robisie 0.8.0 → 0.9.0

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.
@@ -37652,7 +37652,7 @@ var init_constants = __esm({
37652
37652
  "packages/client/src/constants.ts"() {
37653
37653
  "use strict";
37654
37654
  PACKAGE_NAME = "robisie";
37655
- PACKAGE_VERSION = "0.8.0";
37655
+ PACKAGE_VERSION = "0.9.0";
37656
37656
  SUPPORTED_CONTRACT_MAJOR = 1;
37657
37657
  DEFAULT_ORIGIN = "https://robisie.app";
37658
37658
  MCP_SERVER_NAME = "robisie";
@@ -82183,6 +82183,343 @@ var init_done_when_roles = __esm({
82183
82183
  }
82184
82184
  });
82185
82185
 
82186
+ // maszynista/enabled-auto.ts
82187
+ function processRun(file3, args, cwd, timeoutMs = 1e4) {
82188
+ const result = (0, import_node_child_process13.spawnSync)(file3, args, { cwd, encoding: "utf8", timeout: Math.min(1e4, timeoutMs), maxBuffer: 1024 * 1024, shell: false, env: { ...process.env, LC_ALL: "C" } });
82189
+ if (result.error || result.signal || result.status === null) throw new Error(`${file3}: ${result.error?.message ?? result.signal ?? "UNKNOWN status"}`);
82190
+ return { status: result.status, stdout: result.stdout ?? "", stderr: result.stderr ?? "" };
82191
+ }
82192
+ function tail(file3) {
82193
+ let fd;
82194
+ try {
82195
+ fd = (0, import_node_fs31.openSync)(file3, "r");
82196
+ const size = (0, import_node_fs31.fstatSync)(fd).size, length = Math.min(size, MAX_TAIL), bytes = Buffer.alloc(length);
82197
+ const count = (0, import_node_fs31.readSync)(fd, bytes, 0, length, size - length);
82198
+ return bytes.toString("utf8", 0, count);
82199
+ } finally {
82200
+ if (fd !== void 0) (0, import_node_fs31.closeSync)(fd);
82201
+ }
82202
+ }
82203
+ function validCheck(raw) {
82204
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return false;
82205
+ const c = raw;
82206
+ if (typeof c.id !== "string" || c.v !== ENABLED_CHECKS[c.id]) return false;
82207
+ const args = c.args;
82208
+ if (c.id === "tick-loaded") return args === void 0;
82209
+ if (!args || typeof args !== "object" || Array.isArray(args)) return false;
82210
+ const a = args;
82211
+ if (c.id === "service-fresh") return Object.keys(a).length === 1 && SERVICE_ALLOWLIST.has(String(a.label));
82212
+ return c.id === "log-marker" && Object.keys(a).length === 2 && LOG_ALLOWLIST.has(String(a.log)) && a.marker === "ENABLED auto:";
82213
+ }
82214
+ function ancestor2(landed, target, repo, run) {
82215
+ const result = run("git", ["merge-base", "--is-ancestor", landed, target], repo);
82216
+ if (result.status === 0) return true;
82217
+ if (result.status === 1) return false;
82218
+ throw new Error(`git merge-base: ${result.stderr || result.status}`);
82219
+ }
82220
+ function elapsedSeconds(raw) {
82221
+ const match = raw.trim().match(/^(?:(\d+)-)?(?:(\d+):)?(\d{1,2}):(\d{2})$/);
82222
+ if (!match) return null;
82223
+ const days = Number(match[1] ?? 0), hours = Number(match[2] ?? 0), minutes = Number(match[3]), seconds = Number(match[4]);
82224
+ if (minutes > 59 || seconds > 59 || match[1] && hours > 23) return null;
82225
+ return days * 86400 + hours * 3600 + minutes * 60 + seconds;
82226
+ }
82227
+ function checkEnabled(input) {
82228
+ const { id: id2, v } = input;
82229
+ if (!validCheck(input)) return { id: id2, v, verdict: "UNKNOWN_CHECK", observed: "nieznany check lub argument", ref: "ENABLED_CHECKS" };
82230
+ const execute = input.runProcess ?? processRun, readTail = input.readTail ?? tail;
82231
+ const run = (...args) => {
82232
+ const value = execute(...args);
82233
+ if (value.error || value.signal || value.status === null) throw new Error(`${args[0]}: ${value.error?.message ?? value.signal ?? "UNKNOWN status"}`);
82234
+ return value;
82235
+ };
82236
+ const result = (verdict, observed, ref) => ({ id: id2, v, verdict, observed: observed.slice(0, 500), ref });
82237
+ try {
82238
+ if (id2 === "tick-loaded") {
82239
+ const lines2 = readTail(input.logPath).split("\n");
82240
+ for (const line2 of lines2) {
82241
+ const match = line2.match(/\btick_finished\b.*\bat=(\S+).*\boutcome=ok\b.*\bloaded=([a-f0-9]{40})(?!\+dirty)\b/i);
82242
+ if (!match || Number.isNaN(Date.parse(match[1])) || Date.parse(match[1]) < Date.parse(input.activationAt) || !SHA2.test(match[2])) continue;
82243
+ if (ancestor2(input.landedSha, match[2], input.repo, run)) return result("PASS", `tick_finished loaded=${match[2]}`, input.logPath);
82244
+ }
82245
+ const due = lines2.some((line2) => {
82246
+ if (!/\btick_finished\b/.test(line2)) return false;
82247
+ const at3 = Date.parse(line2.match(/\bat=(\S+)/)?.[1] ?? "");
82248
+ if (Number.isFinite(at3) && at3 < Date.parse(input.activationAt)) return false;
82249
+ if (Number.isFinite(at3) && at3 >= Date.parse(input.confirmedAt ?? "")) return true;
82250
+ const loaded = line2.match(/\bloaded=([a-f0-9]{40})(?:\+dirty)?(?=\s|$)/i)?.[1];
82251
+ return !!loaded && ancestor2(input.landedSha, loaded, input.repo, run);
82252
+ });
82253
+ return due ? result("FAIL", "brak poprawnego tick_finished outcome=ok po aktywacji dla landed", input.logPath) : result("CZEKA", "czeka na p\xF3\u017Aniejszy terminal taktu po aktywacji", input.logPath);
82254
+ }
82255
+ if (id2 === "log-marker") {
82256
+ if (!input.cardId || !input.runId) return result("ERROR", "brak wi\u0105zania karty i przebiegu", input.logPath);
82257
+ const lines2 = readTail(input.logPath).split("\n");
82258
+ const checked = `ENABLED auto: karta=${input.cardId} FAIL run=${input.runId} checks=`;
82259
+ return lines2.some((line2) => {
82260
+ const date10 = line2.match(/^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z)\b/);
82261
+ return date10 && Date.parse(date10[1]) >= Date.parse(input.activationAt) && line2.slice(date10[0].length).trimStart().startsWith(checked) && line2.includes("log-marker@1:FAIL");
82262
+ }) ? result("PASS", `faza ENABLED oceni\u0142a kart\u0119 ${input.cardId}`, input.logPath) : result("FAIL", `brak sprawdzianu ENABLED karty ${input.cardId} po aktywacji`, input.logPath);
82263
+ }
82264
+ const printed = run("launchctl", ["print", `gui/${process.getuid?.() ?? 0}/${String(input.args?.label)}`]);
82265
+ if (printed.error || printed.signal || printed.status === null) return result("ERROR", "niepewny odczyt us\u0142ugi", String(input.args?.label));
82266
+ if (printed.status !== 0 && !/Could not find service|service not found/i.test(printed.stderr)) return result("ERROR", `launchctl: ${printed.stderr}`, String(input.args?.label));
82267
+ if (printed.status !== 0) return result("FAIL", `us\u0142uga nie dzia\u0142a: ${printed.stderr}`, String(input.args?.label));
82268
+ const running = /^\s*state\s*=\s*running\s*$/m.test(printed.stdout);
82269
+ const pid = Number(printed.stdout.match(/^\s*pid\s*=\s*(\d+)\s*$/m)?.[1] ?? 0);
82270
+ if (!running || !Number.isSafeInteger(pid) || pid <= 0) return result("FAIL", "us\u0142uga nie dzia\u0142a lub brak pid", String(input.args?.label));
82271
+ const ps = run("ps", ["-o", "etime=", "-p", String(pid)]);
82272
+ if (ps.status !== 0) return result("ERROR", `ps: ${ps.stderr}`, String(pid));
82273
+ const seconds = elapsedSeconds(ps.stdout);
82274
+ if (seconds === null) return result("ERROR", `niepoprawne etime: ${ps.stdout}`, String(pid));
82275
+ const started = Date.parse(input.now) - seconds * 1e3;
82276
+ if (started < Date.parse(input.activationAt)) return result("FAIL", `pid=${pid} sprzed aktywacji`, String(pid));
82277
+ if (!trustedServiceReceipt(input.serviceReload))
82278
+ return result("UNKNOWN", "brak zaufanego receiptu kickstart; owner=CEO; wymagany jawny --bootstrap", "host-activation.json");
82279
+ if (pid !== input.serviceReload.process.pid) return result("UNKNOWN", "obcy PID wzgl\u0119dem receiptu; owner=CEO", String(pid));
82280
+ const command = run("ps", ["-o", "command=", "-p", String(pid)]);
82281
+ if (command.status !== 0 || command.error || command.signal) return result("ERROR", "brak pewnej komendy procesu", String(pid));
82282
+ if (!/(?:^|[\s/])services\/buzz-wake\/main\.ts(?:\s|$)/.test(command.stdout)) return result("FAIL", "b\u0142\u0119dny proces us\u0142ugi", String(pid));
82283
+ const lsof = run("lsof", ["-a", "-d", "cwd", "-p", String(pid), "-Fn"]);
82284
+ if (lsof.status !== 0) return result("ERROR", `lsof: ${lsof.stderr}`, String(pid));
82285
+ const cwd = lsof.stdout.split("\n").find((line2) => line2.startsWith("n"))?.slice(1);
82286
+ if (!cwd) return result("ERROR", "brak cwd z lsof", String(pid));
82287
+ if ((0, import_node_fs31.realpathSync)(cwd) !== (0, import_node_fs31.realpathSync)(input.repo)) return result("FAIL", `cwd=${cwd}`, String(pid));
82288
+ const again = run("launchctl", ["print", `gui/${process.getuid?.() ?? 0}/${String(input.args?.label)}`]);
82289
+ if (again.status !== 0 || again.error || again.signal || Number(again.stdout.match(/^\s*pid\s*=\s*(\d+)\s*$/m)?.[1]) !== pid)
82290
+ return result("ERROR", "proces zmieni\u0142 si\u0119 podczas obserwacji", String(pid));
82291
+ if (input.serviceReload) {
82292
+ const receipt = input.serviceReload, process3 = receipt.process;
82293
+ if (receipt.result !== "PASS" || !process3) return result("ERROR", "nierozliczony reload procesu; owner=CEO", String(pid));
82294
+ const start = run("ps", ["-o", "lstart=", "-p", String(pid)]);
82295
+ if (start.status !== 0 || start.error || start.signal) return result("ERROR", "niepewny start procesu", String(pid));
82296
+ if (process3.pid !== pid || process3.started_at !== start.stdout.trim() || !SHA2.test(process3.code_sha) || !ancestor2(input.landedSha, process3.code_sha, input.repo, run)) return result("UNKNOWN", "proces nie odpowiada receiptowi kodu; owner=CEO", String(pid));
82297
+ }
82298
+ return result("PASS", `pid=${pid} start=${new Date(started).toISOString()} cwd=${cwd}`, String(pid));
82299
+ } catch (error48) {
82300
+ return result("ERROR", error48 instanceof Error ? error48.message : String(error48), id2);
82301
+ }
82302
+ }
82303
+ function details(value) {
82304
+ return value?.details ?? {};
82305
+ }
82306
+ function landedSha3(card) {
82307
+ const value = details(card).landed;
82308
+ const sha5 = value && typeof value === "object" && "sha" in value ? value.sha : null;
82309
+ return typeof sha5 === "string" && SHA2.test(sha5) ? sha5 : null;
82310
+ }
82311
+ function checks(card) {
82312
+ const raw = details(card).enabled_check;
82313
+ return Array.isArray(raw) && raw.length >= 1 && raw.length <= 3 ? raw : null;
82314
+ }
82315
+ function eligible2(card) {
82316
+ return card.status === "delivered" && details(card).card_class === "executable" && landedSha3(card) !== null && checks(card) !== null && details(card).enabled_evidence === void 0;
82317
+ }
82318
+ function activationAt(landed, input, run) {
82319
+ const confirmed = input.activation.confirmed;
82320
+ if (confirmed && SHA2.test(confirmed.target) && ancestor2(landed, confirmed.target, input.repo, run)) {
82321
+ return reflogMoment(landed, input.repo, run) ?? (Number.isFinite(Date.parse(confirmed.at)) ? confirmed.at : null);
82322
+ }
82323
+ return reflogMoment(landed, input.repo, run);
82324
+ }
82325
+ function reflogMoment(landed, repo, run) {
82326
+ const result = run("git", ["reflog", "show", "--date=iso-strict", "--format=%H%x09%gd", "HEAD"], repo);
82327
+ if (result.status !== 0) throw new Error(`git reflog: ${result.stderr}`);
82328
+ const descendants = run("git", ["rev-list", "--ancestry-path", `${landed}..HEAD`], repo);
82329
+ if (descendants.status !== 0) throw new Error(`git rev-list: ${descendants.stderr || descendants.status}`);
82330
+ if (!ancestor2(landed, "HEAD", repo, run)) return null;
82331
+ const onHead = new Set(descendants.stdout.trim().split("\n"));
82332
+ onHead.add(landed);
82333
+ let earliest = null;
82334
+ for (const line2 of result.stdout.split("\n")) {
82335
+ const [sha5, selector] = line2.split(" ");
82336
+ const at3 = selector?.match(/@\{([^}]+)\}/)?.[1];
82337
+ if (SHA2.test(sha5 ?? "") && at3 && !Number.isNaN(Date.parse(at3)) && onHead.has(sha5)) earliest = new Date(at3).toISOString();
82338
+ }
82339
+ return earliest;
82340
+ }
82341
+ function runId(cardId, landed, checkList, at3) {
82342
+ return (0, import_node_crypto20.createHash)("sha256").update(`${cardId}${landed}${checkList.map((c) => validCheck(c) ? `${c.id}@${c.v}` : `INVALID:${JSON.stringify(c) ?? "undefined"}`).join(",")}${at3}`).digest("hex").slice(0, 16);
82343
+ }
82344
+ async function runEnabledAuto(input, deps) {
82345
+ if (!SHA2.test(input.loadedSha)) {
82346
+ deps.log(`ENABLED auto: UNKNOWN owner=CEO loaded=${input.loadedSha}; potrzebny czysty observed loaded`);
82347
+ return;
82348
+ }
82349
+ const confirmed = input.activation.confirmed;
82350
+ const waiting = !confirmed ? "brak confirmed; czeka na potwierdzenie loaded" : (confirmed.observed_loaded ?? confirmed.target) !== input.loadedSha ? `confirmed=${confirmed.target} != loaded=${input.loadedSha}; czeka na potwierdzenie` : void 0;
82351
+ const started = Date.now();
82352
+ const rawRun = deps.runProcess ?? processRun, readTail = deps.readTail ?? tail;
82353
+ const run = (file3, args, cwd) => {
82354
+ const remaining = 3e4 - (Date.now() - started);
82355
+ if (remaining <= 0) throw new Error("bud\u017Cet ENABLED auto 30 s przekroczony");
82356
+ return rawRun(file3, args, cwd, Math.min(1e4, remaining));
82357
+ };
82358
+ const cards = (await deps.listCards()).filter(eligible2).sort((a, b) => String(input.state.enabledAuto?.[a.id]?.lastAt ?? "").localeCompare(String(input.state.enabledAuto?.[b.id]?.lastAt ?? "")) || String(details(a).landed.at ?? "").localeCompare(String(details(b).landed.at ?? "")) || a.id.localeCompare(b.id));
82359
+ let evaluated = 0;
82360
+ for (const card of cards) {
82361
+ if (Date.now() - started >= 3e4 || evaluated >= 5) break;
82362
+ const landed = landedSha3(card);
82363
+ let isLoaded = false;
82364
+ let at3 = null;
82365
+ try {
82366
+ isLoaded = ancestor2(landed, input.loadedSha, input.repo, run);
82367
+ if (isLoaded) at3 = activationAt(landed, input, run);
82368
+ } catch (error48) {
82369
+ evaluated++;
82370
+ const id3 = runId(card.id, landed, checks(card), "OBJECT_ERROR");
82371
+ const previous2 = input.state.enabledAuto?.[card.id];
82372
+ const checkDigest = error48 instanceof Error ? error48.message : String(error48);
82373
+ const changed2 = previous2?.run_id !== id3 || previous2.lastVerdict !== "ERROR" || previous2.checkDigest !== checkDigest;
82374
+ if (changed2) deps.log(`${input.dryRun ? "[dry-run] " : ""}ENABLED auto: karta=${card.id.slice(0, 8)} ERROR run=${id3} checks=git:${checkDigest}`);
82375
+ const full2 = await deps.getTask(card.id);
82376
+ if (!input.dryRun && full2?.status === "delivered" && details(full2).enabled_evidence === void 0) {
82377
+ input.state.enabledAuto ??= {};
82378
+ const entry3 = {
82379
+ run_id: id3,
82380
+ phase: "checking",
82381
+ attempts: (previous2?.run_id === id3 ? previous2.attempts : 0) + 1,
82382
+ firstAt: previous2?.run_id === id3 ? previous2.firstAt : input.now,
82383
+ lastAt: input.now,
82384
+ lastVerdict: "ERROR",
82385
+ checkDigest
82386
+ };
82387
+ if (changed2) await deps.appendDetail(card.id, { enabled_auto: { verdict: "ERROR", run_id: id3, at: input.now } });
82388
+ input.state.enabledAuto[card.id] = entry3;
82389
+ }
82390
+ continue;
82391
+ }
82392
+ if (!isLoaded) continue;
82393
+ const checkList = checks(card);
82394
+ const id2 = runId(card.id, landed, checkList, at3 ?? "NO_ACTIVATION_MOMENT");
82395
+ let previous = input.state.enabledAuto?.[card.id];
82396
+ const full = await deps.getTask(card.id);
82397
+ if (!full || full.status !== "delivered") continue;
82398
+ if (details(full).enabled_evidence !== void 0) {
82399
+ if (!input.dryRun && previous?.run_id === id2) input.state.enabledAuto[card.id] = { ...previous, phase: "written" };
82400
+ continue;
82401
+ }
82402
+ if (previous?.run_id === id2 && previous.phase === "written") previous = void 0;
82403
+ evaluated++;
82404
+ const outputs = [];
82405
+ const checkListValid = checkList.every(validCheck);
82406
+ let verdict;
82407
+ if (waiting) {
82408
+ verdict = "CZEKA";
82409
+ outputs.push({ id: "tick-loaded", v: 1, verdict, observed: waiting, ref: "host-activation.json" });
82410
+ } else if (!at3) {
82411
+ verdict = "NO_ACTIVATION_MOMENT";
82412
+ outputs.push({ id: "tick-loaded", v: 1, verdict, observed: "brak wiarygodnego czasu aktywacji; owner=CEO; potrzebny receipt lub reflog", ref: "host-activation.json" });
82413
+ } else if (!checkListValid) verdict = "UNKNOWN_CHECK";
82414
+ else {
82415
+ for (const c of checkList) {
82416
+ outputs.push(checkEnabled({
82417
+ ...c,
82418
+ repo: input.repo,
82419
+ landedSha: landed,
82420
+ loadedSha: input.loadedSha,
82421
+ activationAt: at3,
82422
+ confirmedAt: confirmed?.confirmed_at,
82423
+ now: input.now,
82424
+ logPath: input.logPath,
82425
+ cardId: card.id,
82426
+ runId: id2,
82427
+ runProcess: run,
82428
+ readTail,
82429
+ serviceReload: input.activation.service_reload
82430
+ }));
82431
+ }
82432
+ verdict = outputs.some((c) => c.verdict === "ERROR") ? "ERROR" : outputs.some((c) => c.verdict === "FAIL") ? "FAIL" : outputs.some((c) => c.verdict === "UNKNOWN") ? "UNKNOWN" : outputs.every((c) => c.verdict === "PASS") ? "PASS" : "CZEKA";
82433
+ }
82434
+ const digest5 = (0, import_node_crypto20.createHash)("sha256").update(JSON.stringify(outputs)).digest("hex");
82435
+ const changed = previous?.run_id !== id2 || previous.lastVerdict !== verdict || previous.checkDigest !== digest5;
82436
+ if (changed) deps.log(`${input.dryRun ? "[dry-run] " : ""}ENABLED auto: karta=${card.id} ${verdict} run=${id2} checks=${outputs.map((c) => `${c.id}@${c.v}:${c.verdict}:${c.observed}`).join(",")}`);
82437
+ if (input.dryRun) continue;
82438
+ const current = await deps.getTask(card.id);
82439
+ if (!current || current.status !== "delivered" || details(current).enabled_evidence !== void 0) continue;
82440
+ const uncertainService = outputs.find((c) => c.id === "service-fresh" && ["UNKNOWN", "ERROR"].includes(c.verdict));
82441
+ if (uncertainService) await persistServiceAlarm(
82442
+ {
82443
+ stateDir: input.stateDir ?? import_node_path31.default.dirname(input.logPath),
82444
+ target: input.loadedSha,
82445
+ previous: confirmed?.previous ?? input.loadedSha,
82446
+ detail: uncertainService.observed,
82447
+ cause: !trustedServiceReceipt(input.activation.service_reload) ? "untrusted-receipt" : uncertainService.observed === "obcy PID wzgl\u0119dem receiptu; owner=CEO" ? "foreign-pid" : uncertainService.observed
82448
+ },
82449
+ { alarm: deps.alarm, log: deps.log, now: () => input.now }
82450
+ );
82451
+ const now = input.now;
82452
+ if (verdict !== "PASS" && at3 && Date.parse(now) - Date.parse(at3) >= 24 * 60 * 6e4) {
82453
+ if (previous?.run_id !== id2 || previous.phase !== "undecided") deps.log(`ENABLED auto: karta=${card.id} nieodebrane po 24 h (${verdict})`);
82454
+ const entry3 = {
82455
+ run_id: id2,
82456
+ phase: "undecided",
82457
+ attempts: (previous?.run_id === id2 ? previous.attempts : 0) + 1,
82458
+ firstAt: previous?.run_id === id2 ? previous.firstAt : now,
82459
+ lastAt: now,
82460
+ lastVerdict: verdict,
82461
+ checkDigest: digest5
82462
+ };
82463
+ if (previous?.run_id !== id2 || previous.phase !== "undecided" || changed)
82464
+ await deps.appendDetail(card.id, { enabled_auto: { verdict: "UNDECIDED_24H", run_id: id2, at: now, checks: outputs } });
82465
+ input.state.enabledAuto ??= {};
82466
+ input.state.enabledAuto[card.id] = entry3;
82467
+ continue;
82468
+ }
82469
+ const entry2 = {
82470
+ run_id: id2,
82471
+ phase: verdict === "PASS" ? "writing" : "checking",
82472
+ attempts: (previous?.run_id === id2 ? previous.attempts : 0) + 1,
82473
+ firstAt: previous?.run_id === id2 ? previous.firstAt : now,
82474
+ lastAt: now,
82475
+ lastVerdict: verdict,
82476
+ checkDigest: digest5
82477
+ };
82478
+ input.state.enabledAuto ??= {};
82479
+ if (verdict === "PASS") {
82480
+ const evidence2 = {
82481
+ what: `ENABLED automatem: ${checkList.map((c) => `${c.id}@${c.v}`).join(", ")} PASS dla landed=${landed.slice(0, 8)} na loaded=${input.loadedSha.slice(0, 8)}; ${outputs[0]?.observed.slice(0, 300) ?? ""}`,
82482
+ when: now,
82483
+ ref: `maszynista/ticks.log tick=${input.tick}; maszynista/state.json enabledAuto[${card.id}]; run=${id2}`,
82484
+ source: "maszynista/enabled-auto",
82485
+ card_id: card.id,
82486
+ run_id: id2,
82487
+ activation_at: at3,
82488
+ landed_sha: landed,
82489
+ loaded_sha: input.loadedSha,
82490
+ checks: outputs
82491
+ };
82492
+ entry2.evidence = evidence2;
82493
+ input.state.enabledAuto[card.id] = entry2;
82494
+ deps.saveState(input.state);
82495
+ await deps.appendDetail(card.id, { enabled_evidence: evidence2, enabled_auto: { verdict: "PASS", run_id: id2, at: now } });
82496
+ const read = await deps.getTask(card.id);
82497
+ if (details(read).enabled_evidence?.run_id !== id2) throw new Error(`read-after ENABLED ${card.id}: run_id niezgodny`);
82498
+ input.state.enabledAuto[card.id] = { ...entry2, phase: "written" };
82499
+ } else {
82500
+ if (changed) await deps.appendDetail(card.id, { enabled_auto: { verdict, run_id: id2, at: now, checks: outputs } });
82501
+ input.state.enabledAuto[card.id] = entry2;
82502
+ }
82503
+ }
82504
+ }
82505
+ var import_node_crypto20, import_node_child_process13, import_node_fs31, import_node_path31, SHA2, SERVICE_ALLOWLIST, LOG_ALLOWLIST, ENABLED_CHECKS, MAX_TAIL;
82506
+ var init_enabled_auto = __esm({
82507
+ "maszynista/enabled-auto.ts"() {
82508
+ "use strict";
82509
+ import_node_crypto20 = require("node:crypto");
82510
+ import_node_child_process13 = require("node:child_process");
82511
+ import_node_fs31 = require("node:fs");
82512
+ import_node_path31 = __toESM(require("node:path"));
82513
+ init_host_activation();
82514
+ init_service_reload();
82515
+ SHA2 = /^[a-f0-9]{40}$/i;
82516
+ SERVICE_ALLOWLIST = /* @__PURE__ */ new Set(["com.robisie.buzz-wake"]);
82517
+ LOG_ALLOWLIST = /* @__PURE__ */ new Set(["ticks"]);
82518
+ ENABLED_CHECKS = Object.freeze({ "tick-loaded": 1, "service-fresh": 1, "log-marker": 1 });
82519
+ MAX_TAIL = 4 * 1024 * 1024;
82520
+ }
82521
+ });
82522
+
82186
82523
  // maszynista/seed-bridge.ts
82187
82524
  function authorsFromIntention(intention) {
82188
82525
  const authors = {};
@@ -82222,14 +82559,14 @@ function isCandidate(card) {
82222
82559
  }
82223
82560
  function locate(cardsRoot, id2, generation) {
82224
82561
  const suffix = `-${id2.slice(0, 8)}`;
82225
- const probes = (0, import_node_fs31.readdirSync)(cardsRoot).filter((name3) => name3.endsWith(suffix)).flatMap((name3) => {
82226
- const cardDir = import_node_path31.default.join(cardsRoot, name3);
82227
- return (0, import_node_fs31.readdirSync)(cardDir).filter((entry2) => entry2.startsWith("proba-")).map((entry2) => import_node_path31.default.join(cardDir, entry2));
82228
- }).sort((a, b) => import_node_path31.default.basename(b).localeCompare(import_node_path31.default.basename(a)));
82562
+ const probes = (0, import_node_fs32.readdirSync)(cardsRoot).filter((name3) => name3.endsWith(suffix)).flatMap((name3) => {
82563
+ const cardDir = import_node_path32.default.join(cardsRoot, name3);
82564
+ return (0, import_node_fs32.readdirSync)(cardDir).filter((entry2) => entry2.startsWith("proba-")).map((entry2) => import_node_path32.default.join(cardDir, entry2));
82565
+ }).sort((a, b) => import_node_path32.default.basename(b).localeCompare(import_node_path32.default.basename(a)));
82229
82566
  for (const dir of probes) {
82230
82567
  let odbior;
82231
82568
  try {
82232
- odbior = JSON.parse((0, import_node_fs31.readFileSync)(import_node_path31.default.join(dir, "50-odbior.json"), "utf8"));
82569
+ odbior = JSON.parse((0, import_node_fs32.readFileSync)(import_node_path32.default.join(dir, "50-odbior.json"), "utf8"));
82233
82570
  } catch {
82234
82571
  continue;
82235
82572
  }
@@ -82238,20 +82575,35 @@ function locate(cardsRoot, id2, generation) {
82238
82575
  }
82239
82576
  return { kind: "none" };
82240
82577
  }
82578
+ function appendEnabledCheck(details2, proposal, patch) {
82579
+ if (Object.hasOwn(details2, "enabled_check")) return "zachowany-istniej\u0105cy";
82580
+ if (proposal === void 0) return "pomini\u0119ty:brak-propozycji";
82581
+ if (!Array.isArray(proposal)) return "pomini\u0119ty:nie-tablica";
82582
+ if (proposal.length < 1 || proposal.length > 3) return "pomini\u0119ty:liczba-poza-1\u20133";
82583
+ try {
82584
+ if (!proposal.every(validCheck) || proposal.some(
82585
+ ({ id: id2, args }) => id2 === "service-fresh" && typeof args?.label !== "string" || id2 === "log-marker" && typeof args?.log !== "string"
82586
+ )) return "pomini\u0119ty:niepoprawna-pozycja";
82587
+ } catch {
82588
+ return "pomini\u0119ty:niepoprawna-pozycja";
82589
+ }
82590
+ patch.enabled_check = proposal;
82591
+ return `przeniesiony:${proposal.map(({ id: id2, v }) => `${id2}@${v}`).join(",")}`;
82592
+ }
82241
82593
  function verify(cardsRoot, card, dir, odbior, log3) {
82242
82594
  const details2 = card.details ?? {};
82243
- const real2 = (0, import_node_fs31.realpathSync)(dir);
82244
- if (!real2.startsWith(`${(0, import_node_fs31.realpathSync)(cardsRoot)}${import_node_path31.default.sep}`)) return "pr\xF3ba poza katalogiem kart";
82595
+ const real2 = (0, import_node_fs32.realpathSync)(dir);
82596
+ if (!real2.startsWith(`${(0, import_node_fs32.realpathSync)(cardsRoot)}${import_node_path32.default.sep}`)) return "pr\xF3ba poza katalogiem kart";
82245
82597
  const hashes = record15(odbior.file_sha256) ? odbior.file_sha256 : {};
82246
82598
  const text9 = {};
82247
82599
  for (const name3 of PACKET_FILES) {
82248
- const file3 = import_node_path31.default.join(dir, name3);
82249
- if ((0, import_node_fs31.lstatSync)(file3).isSymbolicLink()) return `${name3} jest symlinkiem`;
82250
- const body = (0, import_node_fs31.readFileSync)(file3);
82600
+ const file3 = import_node_path32.default.join(dir, name3);
82601
+ if ((0, import_node_fs32.lstatSync)(file3).isSymbolicLink()) return `${name3} jest symlinkiem`;
82602
+ const body = (0, import_node_fs32.readFileSync)(file3);
82251
82603
  if (body.toString("utf8").trim() === "" || sha3(body) !== hashes[name3]) return `${name3} nie zgadza si\u0119 z odbiorem siewcy (sha256)`;
82252
82604
  text9[name3] = body.toString("utf8");
82253
82605
  }
82254
- const kontraktBytes = (0, import_node_fs31.readFileSync)(import_node_path31.default.join(dir, "40-kontrakt.json"));
82606
+ const kontraktBytes = (0, import_node_fs32.readFileSync)(import_node_path32.default.join(dir, "40-kontrakt.json"));
82255
82607
  if (sha3(kontraktBytes) !== odbior.contract_sha256) return "40-kontrakt.json nie zgadza si\u0119 z odbiorem siewcy (sha256)";
82256
82608
  const k = JSON.parse(kontraktBytes.toString("utf8"));
82257
82609
  if (!record15(k) || k.verdict !== "PAKIET" || k.card_id !== card.id || odbior.card_id !== card.id) return "kontrakt/odbi\xF3r dotyczy innej karty";
@@ -82265,8 +82617,9 @@ function verify(cardsRoot, card, dir, odbior, log3) {
82265
82617
  if (k.card_class !== "executable" && k.card_class !== "non_executable") return "kontrakt: card_class";
82266
82618
  if (!["low", "medium", "high"].includes(String(k.codex_effort))) return "kontrakt: codex_effort";
82267
82619
  let provenance;
82620
+ let family;
82268
82621
  try {
82269
- localEffectCheck({ id: card.id, title: card.title, details: { done_when: k.done_when, effect_check: k.effect_check } });
82622
+ ({ family } = localEffectCheck({ id: card.id, title: card.title, details: { done_when: k.done_when, effect_check: k.effect_check } }));
82270
82623
  const effect = JSON.parse(String(k.effect_check));
82271
82624
  if (!record15(effect) || effect.source !== `produkt/${card.id}/usage.jsonl`) throw new Error("effect_check: obcy source");
82272
82625
  const authors = { ...record15(k.seed_provenance) && record15(k.seed_provenance.authoring_providers) ? k.seed_provenance.authoring_providers : {} };
@@ -82296,7 +82649,7 @@ function verify(cardsRoot, card, dir, odbior, log3) {
82296
82649
  }
82297
82650
  const declared = details2.card_class;
82298
82651
  if (nonempty2(declared) && declared !== k.card_class) return `card_class rozbie\u017Cny (karta ${declared}, kontrakt ${k.card_class}) \u2014 zadeklarowanego nie zmieniam`;
82299
- const odbiorPath = import_node_path31.default.join(dir, "50-odbior.json");
82652
+ const odbiorPath = import_node_path32.default.join(dir, "50-odbior.json");
82300
82653
  const patch = {
82301
82654
  seed_scope: text9["20-scope.md"],
82302
82655
  seed_scope_sha256: sha3(text9["20-scope.md"]),
@@ -82316,11 +82669,13 @@ function verify(cardsRoot, card, dir, odbior, log3) {
82316
82669
  ...typeof k.servesGoal === "string" && /^#[123]$/.test(k.servesGoal) ? { servesGoal: k.servesGoal } : {},
82317
82670
  ...nonempty2(declared) ? {} : { card_class: k.card_class }
82318
82671
  };
82672
+ const enabledCheckOutcome = family ? appendEnabledCheck(details2, k.enabled_check, patch) : void 0;
82319
82673
  return {
82320
- briefPath: import_node_path31.default.join(dir, "30-brief.md"),
82674
+ briefPath: import_node_path32.default.join(dir, "30-brief.md"),
82321
82675
  patch,
82322
82676
  odbiorPath,
82323
- odbiorSha: sha3((0, import_node_fs31.readFileSync)(odbiorPath))
82677
+ odbiorSha: sha3((0, import_node_fs32.readFileSync)(odbiorPath)),
82678
+ enabledCheckOutcome
82324
82679
  };
82325
82680
  }
82326
82681
  async function bridgeNextPacket(deps) {
@@ -82346,7 +82701,7 @@ async function bridgeNextPacket(deps) {
82346
82701
  const fresh = await deps.readCard(candidate.id);
82347
82702
  if (!fresh || !isCandidate(fresh) || generationOf(fresh.details ?? {}) !== generation) continue;
82348
82703
  const embed = verify(deps.cardsRoot, fresh, located.dir, located.odbior, deps.log);
82349
- const proba = import_node_path31.default.relative(import_node_path31.default.dirname(import_node_path31.default.dirname(deps.cardsRoot)), located.dir);
82704
+ const proba = import_node_path32.default.relative(import_node_path32.default.dirname(import_node_path32.default.dirname(deps.cardsRoot)), located.dir);
82350
82705
  if (typeof embed === "string") {
82351
82706
  deps.log(`most zasiewu: odmowa ${short} g${generation}: ${embed}`);
82352
82707
  continue;
@@ -82356,8 +82711,17 @@ async function bridgeNextPacket(deps) {
82356
82711
  processed ??= { kind: "dry-run", cardId: candidate.id, detail: proba };
82357
82712
  continue;
82358
82713
  }
82714
+ const changed = () => {
82715
+ const detail = `zlecenie zmienione w trakcie zapisu ${short} g${generation} \u2014 bez potwierdzenia`;
82716
+ deps.log(`most zasiewu: ${detail}`);
82717
+ stale = { kind: "none", cardId: candidate.id, detail };
82718
+ };
82359
82719
  await deps.setSpecRef(candidate.id, embed.briefPath);
82360
- await deps.appendDetail(candidate.id, embed.patch);
82720
+ const guard2 = Object.hasOwn(embed.patch, "enabled_check") ? { key: "seed_obligation", expected: fresh.details?.seed_obligation, details: fresh.details ?? {} } : void 0;
82721
+ if (await deps.appendDetail(candidate.id, embed.patch, guard2) === false) {
82722
+ changed();
82723
+ continue;
82724
+ }
82361
82725
  const after2 = await deps.readCard(candidate.id);
82362
82726
  const afterDetails = after2?.details ?? {};
82363
82727
  const mismatched = Object.keys(embed.patch).filter((key) => !(0, import_node_util9.isDeepStrictEqual)(afterDetails[key], embed.patch[key]));
@@ -82368,12 +82732,6 @@ async function bridgeNextPacket(deps) {
82368
82732
  continue;
82369
82733
  }
82370
82734
  const obligation = afterDetails.seed_obligation;
82371
- const changed = () => {
82372
- const detail = `zlecenie zmienione w trakcie zapisu ${short} g${generation} \u2014 bez potwierdzenia`;
82373
- deps.log(`most zasiewu: ${detail}`);
82374
- stale = { kind: "none", cardId: candidate.id, detail };
82375
- return stale;
82376
- };
82377
82735
  if (!isCandidate(after2) || !(0, import_node_util9.isDeepStrictEqual)(obligation, fresh.details?.seed_obligation)) {
82378
82736
  changed();
82379
82737
  continue;
@@ -82382,7 +82740,7 @@ async function bridgeNextPacket(deps) {
82382
82740
  ...record15(obligation) ? obligation : {},
82383
82741
  status: "embedded",
82384
82742
  result: "PAKIET",
82385
- result_ref: import_node_path31.default.relative(import_node_path31.default.dirname(import_node_path31.default.dirname(deps.cardsRoot)), embed.odbiorPath),
82743
+ result_ref: import_node_path32.default.relative(import_node_path32.default.dirname(import_node_path32.default.dirname(deps.cardsRoot)), embed.odbiorPath),
82386
82744
  result_sha256: embed.odbiorSha,
82387
82745
  embedded_at: (/* @__PURE__ */ new Date()).toISOString(),
82388
82746
  embedded_by: "maszynista/seed-bridge.ts"
@@ -82392,7 +82750,8 @@ async function bridgeNextPacket(deps) {
82392
82750
  continue;
82393
82751
  }
82394
82752
  const verdict = czyPromowalny({ ...after2, details: { ...afterDetails, seed_obligation: settled } });
82395
- deps.log(`most zasiewu: ${short} g${generation} pakiet osadzony z ${proba} (seed_brief ${briefSha(afterDetails)?.slice(0, 12)}) \u2192 karta ${verdict.promowalny ? "promowalna" : `nadal wstrzymana: ${verdict.powod}`}`);
82753
+ const enabledCheckSuffix = embed.enabledCheckOutcome ? ` enabled_check=${embed.enabledCheckOutcome}` : "";
82754
+ deps.log(`most zasiewu: ${short} g${generation} pakiet osadzony z ${proba} (seed_brief ${briefSha(afterDetails)?.slice(0, 12)}) \u2192 karta ${verdict.promowalny ? "promowalna" : `nadal wstrzymana: ${verdict.powod}`}${enabledCheckSuffix}`);
82396
82755
  processed ??= { kind: "bridged", cardId: candidate.id, detail: proba };
82397
82756
  } catch (error48) {
82398
82757
  const detail = `FAIL ${short}: ${errorText3(error48)}`;
@@ -82402,20 +82761,21 @@ async function bridgeNextPacket(deps) {
82402
82761
  }
82403
82762
  return failed2 ?? processed ?? stale ?? { kind: "none", detail: "brak gotowego pakietu na dysku" };
82404
82763
  }
82405
- var import_node_crypto20, import_node_fs31, import_node_path31, import_node_util9, BRIDGE_DETAILS_KEYS, PACKET_FILES, sha3, record15, nonempty2, errorText3, PROVIDERS2;
82764
+ var import_node_crypto21, import_node_fs32, import_node_path32, import_node_util9, BRIDGE_DETAILS_KEYS, PACKET_FILES, sha3, record15, nonempty2, errorText3, PROVIDERS2;
82406
82765
  var init_seed_bridge = __esm({
82407
82766
  "maszynista/seed-bridge.ts"() {
82408
82767
  "use strict";
82409
- import_node_crypto20 = require("node:crypto");
82410
- import_node_fs31 = require("node:fs");
82411
- import_node_path31 = __toESM(require("node:path"));
82768
+ import_node_crypto21 = require("node:crypto");
82769
+ import_node_fs32 = require("node:fs");
82770
+ import_node_path32 = __toESM(require("node:path"));
82412
82771
  import_node_util9 = require("node:util");
82413
82772
  init_local_receiver();
82414
82773
  init_done_when_roles();
82415
82774
  init_lib();
82775
+ init_enabled_auto();
82416
82776
  BRIDGE_DETAILS_KEYS = ["seed_obligation", "reksio_withheld", "hold", "superseded_by"];
82417
82777
  PACKET_FILES = ["20-scope.md", "25-spec.md", "30-brief.md"];
82418
- sha3 = (data) => (0, import_node_crypto20.createHash)("sha256").update(data).digest("hex");
82778
+ sha3 = (data) => (0, import_node_crypto21.createHash)("sha256").update(data).digest("hex");
82419
82779
  record15 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
82420
82780
  nonempty2 = (value) => typeof value === "string" && value.trim().length > 0;
82421
82781
  errorText3 = (error48) => error48 instanceof Error ? error48.message : String(error48);
@@ -82425,12 +82785,12 @@ var init_seed_bridge = __esm({
82425
82785
 
82426
82786
  // maszynista/select-fingerprint.ts
82427
82787
  function selectFingerprint(model, prompt2) {
82428
- return (0, import_node_crypto21.createHash)("sha256").update(`${model}
82788
+ return (0, import_node_crypto22.createHash)("sha256").update(`${model}
82429
82789
  ${prompt2}`).digest("hex");
82430
82790
  }
82431
82791
  function readSelectFingerprint(file3) {
82432
82792
  try {
82433
- return (0, import_node_fs32.readFileSync)(file3, "utf8").trim();
82793
+ return (0, import_node_fs33.readFileSync)(file3, "utf8").trim();
82434
82794
  } catch (error48) {
82435
82795
  if (error48.code === "ENOENT") return null;
82436
82796
  throw error48;
@@ -82439,11 +82799,11 @@ function readSelectFingerprint(file3) {
82439
82799
  function writeSelectFingerprint(file3, fingerprint) {
82440
82800
  const temporary = `${file3}.${process.pid}.tmp`;
82441
82801
  try {
82442
- (0, import_node_fs32.writeFileSync)(temporary, fingerprint);
82443
- (0, import_node_fs32.renameSync)(temporary, file3);
82802
+ (0, import_node_fs33.writeFileSync)(temporary, fingerprint);
82803
+ (0, import_node_fs33.renameSync)(temporary, file3);
82444
82804
  } catch (error48) {
82445
82805
  try {
82446
- (0, import_node_fs32.unlinkSync)(temporary);
82806
+ (0, import_node_fs33.unlinkSync)(temporary);
82447
82807
  } catch (cleanupError) {
82448
82808
  if (cleanupError.code !== "ENOENT") throw cleanupError;
82449
82809
  }
@@ -82464,12 +82824,12 @@ async function askUnlessUnchanged(opts) {
82464
82824
  commit: () => writeSelectFingerprint(opts.file, fingerprint)
82465
82825
  };
82466
82826
  }
82467
- var import_node_crypto21, import_node_fs32;
82827
+ var import_node_crypto22, import_node_fs33;
82468
82828
  var init_select_fingerprint = __esm({
82469
82829
  "maszynista/select-fingerprint.ts"() {
82470
82830
  "use strict";
82471
- import_node_crypto21 = require("node:crypto");
82472
- import_node_fs32 = require("node:fs");
82831
+ import_node_crypto22 = require("node:crypto");
82832
+ import_node_fs33 = require("node:fs");
82473
82833
  }
82474
82834
  });
82475
82835
 
@@ -82478,18 +82838,18 @@ function readTickSignals(file3, cards, now) {
82478
82838
  let fd;
82479
82839
  let result;
82480
82840
  try {
82481
- fd = (0, import_node_fs33.openSync)(file3, "r");
82482
- const size = (0, import_node_fs33.fstatSync)(fd).size;
82841
+ fd = (0, import_node_fs34.openSync)(file3, "r");
82842
+ const size = (0, import_node_fs34.fstatSync)(fd).size;
82483
82843
  const bytes = Math.min(size, TICK_TAIL_BYTES);
82484
82844
  const buffer = Buffer.alloc(bytes);
82485
- const read = (0, import_node_fs33.readSync)(fd, buffer, 0, bytes, size - bytes);
82845
+ const read = (0, import_node_fs34.readSync)(fd, buffer, 0, bytes, size - bytes);
82486
82846
  result = { signals: defectSignalsFromTicks(buffer.toString("utf8", 0, read), cards, now), source: "ticks.log" };
82487
82847
  } catch (error48) {
82488
82848
  result = { signals: [], source: `ticks.log UNKNOWN: ${error48 instanceof Error ? error48.message.slice(0, 120) : String(error48).slice(0, 120)}` };
82489
82849
  }
82490
82850
  if (fd !== void 0) {
82491
82851
  try {
82492
- (0, import_node_fs33.closeSync)(fd);
82852
+ (0, import_node_fs34.closeSync)(fd);
82493
82853
  } catch (error48) {
82494
82854
  return { signals: [], source: `ticks.log UNKNOWN: zamkni\u0119cie odczytu: ${error48 instanceof Error ? error48.message.slice(0, 100) : String(error48).slice(0, 100)}` };
82495
82855
  }
@@ -82501,7 +82861,7 @@ function tickSignalReport(input) {
82501
82861
  }
82502
82862
  function readMachineWip(file3, limit2, now = /* @__PURE__ */ new Date()) {
82503
82863
  try {
82504
- return machineWipFromSnapshot(JSON.parse((0, import_node_fs33.readFileSync)(file3, "utf8")), limit2, now);
82864
+ return machineWipFromSnapshot(JSON.parse((0, import_node_fs34.readFileSync)(file3, "utf8")), limit2, now);
82505
82865
  } catch (error48) {
82506
82866
  return { unknown: `state.json niedost\u0119pny: ${error48 instanceof Error ? error48.message.slice(0, 120) : String(error48).slice(0, 120)}` };
82507
82867
  }
@@ -82510,7 +82870,7 @@ function selectFingerprintPrompt(prompt2) {
82510
82870
  return prompt2.replace(/(WIP maszyny: \d+\/\d+ \(snapshot at )\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z(; źródło state\.actives\))/u, "$1fresh$2");
82511
82871
  }
82512
82872
  function selectRunPlan(dry, env) {
82513
- return dry ? { mode: "dry", reportFile: import_node_path32.default.join(DIR, "SELECT-LAST-DRY.md"), commitFingerprint: false, force: true } : { mode: "live", reportFile: LAST, commitFingerprint: true, force: env.SELECTOR_FORCE === "1" };
82873
+ return dry ? { mode: "dry", reportFile: import_node_path33.default.join(DIR, "SELECT-LAST-DRY.md"), commitFingerprint: false, force: true } : { mode: "live", reportFile: LAST, commitFingerprint: true, force: env.SELECTOR_FORCE === "1" };
82514
82874
  }
82515
82875
  function formatSelectReport(ok, at3, trigger, mode, body) {
82516
82876
  return `# SELECT \u2014 ${ok ? "OK" : "FAIL"}
@@ -82529,10 +82889,10 @@ function formatZeroReasonLine(emptyReason, prose) {
82529
82889
  return cutAt > 0 ? `${singleLine.slice(0, cutAt)} ${marker}` : marker;
82530
82890
  }
82531
82891
  function selectLockAlive() {
82532
- if (!(0, import_node_fs33.existsSync)(SELECT_LOCK)) return false;
82892
+ if (!(0, import_node_fs34.existsSync)(SELECT_LOCK)) return false;
82533
82893
  let raw;
82534
82894
  try {
82535
- raw = (0, import_node_fs33.readFileSync)(SELECT_LOCK, "utf8");
82895
+ raw = (0, import_node_fs34.readFileSync)(SELECT_LOCK, "utf8");
82536
82896
  } catch (error48) {
82537
82897
  if (error48.code === "ENOENT") return false;
82538
82898
  throw error48;
@@ -82549,8 +82909,8 @@ function selectLockAlive() {
82549
82909
  }
82550
82910
  }
82551
82911
  try {
82552
- if ((0, import_node_fs33.readFileSync)(SELECT_LOCK, "utf8") !== raw) return true;
82553
- (0, import_node_fs33.unlinkSync)(SELECT_LOCK);
82912
+ if ((0, import_node_fs34.readFileSync)(SELECT_LOCK, "utf8") !== raw) return true;
82913
+ (0, import_node_fs34.unlinkSync)(SELECT_LOCK);
82554
82914
  } catch (error48) {
82555
82915
  if (error48.code !== "ENOENT") throw error48;
82556
82916
  }
@@ -82559,16 +82919,16 @@ function selectLockAlive() {
82559
82919
  function log(msg) {
82560
82920
  const line2 = `${(/* @__PURE__ */ new Date()).toISOString()} ${DRY ? "[dry] " : ""}${msg.replace(/[\r\n]+/g, " ")}`;
82561
82921
  console.log(line2);
82562
- (0, import_node_fs33.appendFileSync)(LOG, line2 + "\n");
82922
+ (0, import_node_fs34.appendFileSync)(LOG, line2 + "\n");
82563
82923
  }
82564
82924
  function last(plan, ok, body) {
82565
- (0, import_node_fs33.writeFileSync)(plan.reportFile, formatSelectReport(ok, (/* @__PURE__ */ new Date()).toISOString(), TRIGGER, plan.mode, body));
82925
+ (0, import_node_fs34.writeFileSync)(plan.reportFile, formatSelectReport(ok, (/* @__PURE__ */ new Date()).toISOString(), TRIGGER, plan.mode, body));
82566
82926
  }
82567
82927
  function askClaude(prompt2) {
82568
82928
  return new Promise((resolve7, reject) => {
82569
82929
  const args = headlessClaudeArgs(MODEL);
82570
82930
  const user = process.env.USER ?? import_node_os7.default.userInfo().username;
82571
- const child = (0, import_node_child_process13.spawn)("claude", args, {
82931
+ const child = (0, import_node_child_process14.spawn)("claude", args, {
82572
82932
  cwd: REPO,
82573
82933
  stdio: ["pipe", "pipe", "pipe"],
82574
82934
  env: { ...process.env, ...HEADLESS_CLAUDE_ENV, ANTHROPIC_API_KEY: void 0, USER: user, LOGNAME: process.env.LOGNAME ?? user }
@@ -82631,7 +82991,7 @@ async function main() {
82631
82991
  return 0;
82632
82992
  }
82633
82993
  try {
82634
- (0, import_node_fs33.writeFileSync)(SELECT_LOCK, String(process.pid), { flag: "wx" });
82994
+ (0, import_node_fs34.writeFileSync)(SELECT_LOCK, String(process.pid), { flag: "wx" });
82635
82995
  locked = true;
82636
82996
  } catch (error49) {
82637
82997
  if (error49.code === "EEXIST") return 0;
@@ -82653,20 +83013,20 @@ async function main() {
82653
83013
  }
82654
83014
  let irreversiblePatterns = null;
82655
83015
  try {
82656
- irreversiblePatterns = (0, import_node_fs33.readFileSync)(import_node_path32.default.join(REPO, "scripts/lib/irreversible-patterns.txt"), "utf8");
83016
+ irreversiblePatterns = (0, import_node_fs34.readFileSync)(import_node_path33.default.join(REPO, "scripts/lib/irreversible-patterns.txt"), "utf8");
82657
83017
  } catch (error49) {
82658
83018
  log(`quality_lane: lista nieodwracalnych niedost\u0119pna (${error49 instanceof Error ? error49.message : String(error49)})`);
82659
83019
  }
82660
83020
  let trackedFiles = null;
82661
83021
  try {
82662
- trackedFiles = (0, import_node_child_process13.execFileSync)("git", ["ls-files", "-z"], { cwd: REPO, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 }).split("\0").filter(Boolean);
83022
+ trackedFiles = (0, import_node_child_process14.execFileSync)("git", ["ls-files", "-z"], { cwd: REPO, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 }).split("\0").filter(Boolean);
82663
83023
  } catch (error49) {
82664
83024
  log(`quality_lane: lista plik\xF3w repo niedost\u0119pna \u2014 katalogi w scope b\u0119d\u0105 CAREFUL (${error49 instanceof Error ? error49.message : String(error49)})`);
82665
83025
  }
82666
- const agentsMd = (0, import_node_fs33.existsSync)(import_node_path32.default.join(REPO, "AGENTS.md")) ? (0, import_node_fs33.readFileSync)(import_node_path32.default.join(REPO, "AGENTS.md"), "utf-8") : "";
82667
- const tickInput = readTickSignals(import_node_path32.default.join(DIR, "ticks.log"), cr.cards, /* @__PURE__ */ new Date());
83026
+ const agentsMd = (0, import_node_fs34.existsSync)(import_node_path33.default.join(REPO, "AGENTS.md")) ? (0, import_node_fs34.readFileSync)(import_node_path33.default.join(REPO, "AGENTS.md"), "utf-8") : "";
83027
+ const tickInput = readTickSignals(import_node_path33.default.join(DIR, "ticks.log"), cr.cards, /* @__PURE__ */ new Date());
82668
83028
  if (tickInput.source !== "ticks.log") log(tickInput.source);
82669
- const machineWip = readMachineWip(import_node_path32.default.join(DIR, "state.json"), configuredWip(process.env.MASZYNISTA_WIP));
83029
+ const machineWip = readMachineWip(import_node_path33.default.join(DIR, "state.json"), configuredWip(process.env.MASZYNISTA_WIP));
82670
83030
  if ("unknown" in machineWip) log(`WIP maszyny UNKNOWN: ${machineWip.unknown}`);
82671
83031
  const prompt2 = buildSelectPrompt({ judgment, goals, cards: cr.cards, agentsMdHead: agentsMd, tickSignals: tickInput.signals, tickSource: tickInput.source, machineWip });
82672
83032
  const gate = await askUnlessUnchanged({
@@ -82763,21 +83123,21 @@ async function main() {
82763
83123
  } finally {
82764
83124
  if (locked) {
82765
83125
  try {
82766
- (0, import_node_fs33.unlinkSync)(SELECT_LOCK);
83126
+ (0, import_node_fs34.unlinkSync)(SELECT_LOCK);
82767
83127
  } catch (error48) {
82768
83128
  if (error48.code !== "ENOENT") throw error48;
82769
83129
  }
82770
83130
  }
82771
83131
  }
82772
83132
  }
82773
- var import_node_fs33, import_node_child_process13, import_node_os7, import_node_path32, DRY, SELECT_DEFAULT_MODEL, MODEL, LAST, LOG, FINGERPRINT, SELECT_LOCK, TRIGGER, MAX_ZERO_REASON_LEN, TICK_TAIL_BYTES, TIMEOUT_MS2;
83133
+ var import_node_fs34, import_node_child_process14, import_node_os7, import_node_path33, DRY, SELECT_DEFAULT_MODEL, MODEL, LAST, LOG, FINGERPRINT, SELECT_LOCK, TRIGGER, MAX_ZERO_REASON_LEN, TICK_TAIL_BYTES, TIMEOUT_MS2;
82774
83134
  var init_select3 = __esm({
82775
83135
  "maszynista/select.ts"() {
82776
83136
  "use strict";
82777
- import_node_fs33 = require("node:fs");
82778
- import_node_child_process13 = require("node:child_process");
83137
+ import_node_fs34 = require("node:fs");
83138
+ import_node_child_process14 = require("node:child_process");
82779
83139
  import_node_os7 = __toESM(require("node:os"));
82780
- import_node_path32 = __toESM(require("node:path"));
83140
+ import_node_path33 = __toESM(require("node:path"));
82781
83141
  init_queries();
82782
83142
  init_env();
82783
83143
  init_board();
@@ -82789,10 +83149,10 @@ var init_select3 = __esm({
82789
83149
  DRY = process.argv.includes("--dry-run");
82790
83150
  SELECT_DEFAULT_MODEL = "sonnet";
82791
83151
  MODEL = process.env.MASZYNISTA_SELECT_MODEL ?? SELECT_DEFAULT_MODEL;
82792
- LAST = import_node_path32.default.join(DIR, "SELECT-LAST.md");
82793
- LOG = import_node_path32.default.join(DIR, "select.log");
82794
- FINGERPRINT = import_node_path32.default.join(DIR, ".select-fingerprint");
82795
- SELECT_LOCK = import_node_path32.default.join(DIR, ".select.lock");
83152
+ LAST = import_node_path33.default.join(DIR, "SELECT-LAST.md");
83153
+ LOG = import_node_path33.default.join(DIR, "select.log");
83154
+ FINGERPRINT = import_node_path33.default.join(DIR, ".select-fingerprint");
83155
+ SELECT_LOCK = import_node_path33.default.join(DIR, ".select.lock");
82796
83156
  TRIGGER = process.argv.find((a) => a.startsWith("--trigger="))?.split("=")[1] ?? process.env.MASZYNISTA_SELECT_TRIGGER ?? "launchd";
82797
83157
  MAX_ZERO_REASON_LEN = 4e3;
82798
83158
  TICK_TAIL_BYTES = 128 * 1024;
@@ -90802,7 +91162,7 @@ async function createBuzzBridge(options2) {
90802
91162
  throw new BuzzToolError(`Buzz state directory is unavailable: ${safeError(error48)}`);
90803
91163
  }
90804
91164
  try {
90805
- const store = await SeenStore.open((0, import_node_path33.join)(options2.stateDir, `mcp-${options2.role}.db`));
91165
+ const store = await SeenStore.open((0, import_node_path34.join)(options2.stateDir, `mcp-${options2.role}.db`));
90806
91166
  return new BuzzBridge(options2, secret, derivedPublicKey, store);
90807
91167
  } catch (error48) {
90808
91168
  if (error48 instanceof BuzzToolError) throw error48;
@@ -90828,7 +91188,7 @@ async function loadBuzzConfig(path34) {
90828
91188
  }
90829
91189
  }
90830
91190
  function defaultStateDir() {
90831
- return (0, import_node_path33.join)((0, import_node_os8.homedir)(), ".robisie", "buzz");
91191
+ return (0, import_node_path34.join)((0, import_node_os8.homedir)(), ".robisie", "buzz");
90832
91192
  }
90833
91193
  async function readIdentityFile(path34) {
90834
91194
  let contents;
@@ -90892,7 +91252,7 @@ function parseBuzzAdminMembers(output) {
90892
91252
  }
90893
91253
  function runRosterCommand(command, args) {
90894
91254
  return new Promise((resolve7, reject) => {
90895
- (0, import_node_child_process14.execFile)(command, args, { encoding: "utf8" }, (error48, stdout) => {
91255
+ (0, import_node_child_process15.execFile)(command, args, { encoding: "utf8" }, (error48, stdout) => {
90896
91256
  if (error48) reject(error48);
90897
91257
  else resolve7(stdout);
90898
91258
  });
@@ -90938,15 +91298,15 @@ async function loadDatabaseSync() {
90938
91298
  throw new BuzzToolError("Buzz requires Node 22 or newer with node:sqlite available");
90939
91299
  }
90940
91300
  }
90941
- var import_node_child_process14, import_promises2, import_node_module, import_node_os8, import_node_path33, PAGE_EOSE_DEADLINE_MS, ZERO_EVENT_ID, BuzzToolError, RelayWebSocket, SeenStore, BuzzBridge;
91301
+ var import_node_child_process15, import_promises2, import_node_module, import_node_os8, import_node_path34, PAGE_EOSE_DEADLINE_MS, ZERO_EVENT_ID, BuzzToolError, RelayWebSocket, SeenStore, BuzzBridge;
90942
91302
  var init_bridge = __esm({
90943
91303
  "services/buzz-mcp/src/bridge.ts"() {
90944
91304
  "use strict";
90945
- import_node_child_process14 = require("node:child_process");
91305
+ import_node_child_process15 = require("node:child_process");
90946
91306
  import_promises2 = require("node:fs/promises");
90947
91307
  import_node_module = require("node:module");
90948
91308
  import_node_os8 = require("node:os");
90949
- import_node_path33 = require("node:path");
91309
+ import_node_path34 = require("node:path");
90950
91310
  init_pure();
90951
91311
  init_relay();
90952
91312
  init_wrapper();
@@ -91387,7 +91747,7 @@ function canonical3(value) {
91387
91747
  return JSON.stringify(value) ?? "null";
91388
91748
  }
91389
91749
  function hostHash(value) {
91390
- return (0, import_node_crypto22.createHash)("sha256").update(canonical3(value)).digest("hex");
91750
+ return (0, import_node_crypto23.createHash)("sha256").update(canonical3(value)).digest("hex");
91391
91751
  }
91392
91752
  function sealHostResult(value) {
91393
91753
  const body = Object.fromEntries(Object.entries(value).filter(([key]) => key !== "result_hash"));
@@ -91399,11 +91759,11 @@ function parseHostResult(value) {
91399
91759
  if (result.status === "succeeded" && (result.exit_code !== 0 || !result.checks.length || result.checks.some((check5) => check5.status !== "PASS" || check5.rc !== 0 || !check5.raw_ref))) throw new Error("Incomplete host success");
91400
91760
  return result;
91401
91761
  }
91402
- var import_node_crypto22, id, sha4, hash7, base, brief, launchParams, checkParams, cleanupParams, hostToolSchema, hostIntentSchema, hostPolicySchema, hostOriginSchema, hostResultSchema, hostBindingSchema, hostOperationSchema, HostAdmissionError;
91762
+ var import_node_crypto23, id, sha4, hash7, base, brief, launchParams, checkParams, cleanupParams, hostToolSchema, hostIntentSchema, hostPolicySchema, hostOriginSchema, hostResultSchema, hostBindingSchema, hostOperationSchema, HostAdmissionError;
91403
91763
  var init_contract = __esm({
91404
91764
  "maszynista/host-ops/contract.ts"() {
91405
91765
  "use strict";
91406
- import_node_crypto22 = require("node:crypto");
91766
+ import_node_crypto23 = require("node:crypto");
91407
91767
  init_zod();
91408
91768
  id = external_exports.string().min(1).max(160).regex(/^[a-zA-Z0-9][a-zA-Z0-9_.:-]*$/);
91409
91769
  sha4 = external_exports.string().regex(/^[a-f0-9]{40}$/);
@@ -91527,14 +91887,14 @@ function unknownProbeAlive(pid) {
91527
91887
  function openStore(path34) {
91528
91888
  return new WakeStore(path34);
91529
91889
  }
91530
- var import_node_fs34, import_node_path34, import_node_sqlite2, import_node_crypto23, GBOT_COPY_MARKER, MAX_QUEUE_ATTEMPTS, QUEUE_RETRY_DELAYS_MS, UNKNOWN_RELEASE_MS, UNKNOWN_BLIND_RELEASE_MS, WakeStore;
91890
+ var import_node_fs35, import_node_path35, import_node_sqlite2, import_node_crypto24, GBOT_COPY_MARKER, MAX_QUEUE_ATTEMPTS, QUEUE_RETRY_DELAYS_MS, UNKNOWN_RELEASE_MS, UNKNOWN_BLIND_RELEASE_MS, WakeStore;
91531
91891
  var init_store = __esm({
91532
91892
  "services/buzz-wake/store.ts"() {
91533
91893
  "use strict";
91534
- import_node_fs34 = require("node:fs");
91535
- import_node_path34 = require("node:path");
91894
+ import_node_fs35 = require("node:fs");
91895
+ import_node_path35 = require("node:path");
91536
91896
  import_node_sqlite2 = require("node:sqlite");
91537
- import_node_crypto23 = require("node:crypto");
91897
+ import_node_crypto24 = require("node:crypto");
91538
91898
  init_contract();
91539
91899
  init_protocol2();
91540
91900
  GBOT_COPY_MARKER = /\n\[\[BUZZ_GBOT_REPLY:([a-f0-9]{64}):([^\]\r\n]+)\]\]$/;
@@ -91547,7 +91907,7 @@ var init_store = __esm({
91547
91907
  path;
91548
91908
  constructor(path34) {
91549
91909
  this.path = path34;
91550
- (0, import_node_fs34.mkdirSync)((0, import_node_path34.dirname)(path34), { recursive: true, mode: 448 });
91910
+ (0, import_node_fs35.mkdirSync)((0, import_node_path35.dirname)(path34), { recursive: true, mode: 448 });
91551
91911
  this.database = new import_node_sqlite2.DatabaseSync(path34);
91552
91912
  this.database.exec(`
91553
91913
  PRAGMA busy_timeout=5000;
@@ -92152,7 +92512,7 @@ var init_store = __esm({
92152
92512
  origin,
92153
92513
  event_id: eventId,
92154
92514
  input_hash: inputHash,
92155
- attempt_id: (0, import_node_crypto23.randomUUID)(),
92515
+ attempt_id: (0, import_node_crypto24.randomUUID)(),
92156
92516
  lane: intent.operation === "launch_role" && intent.params.workspace === "none" ? "agent" : "maszynista",
92157
92517
  state: "accepted",
92158
92518
  fence: 0,
@@ -92486,14 +92846,14 @@ var init_lead_admission = __esm({
92486
92846
  // services/buzz-wake/agent-route.ts
92487
92847
  function isAgentRoute(value) {
92488
92848
  const strings2 = ["executable", "model", "effort", "profile", "cwd", "roleFile"];
92489
- return value.type === "agent" && Object.keys(value).length === 8 && strings2.every((key) => typeof value[key] === "string" && value[key].trim().length > 0 && !value[key].includes("\0")) && [value.executable, value.cwd, value.roleFile].every((path34) => (0, import_node_path35.isAbsolute)(path34)) && Array.isArray(value.argv) && value.argv.every((arg) => typeof arg === "string" && !arg.includes("\0"));
92849
+ return value.type === "agent" && Object.keys(value).length === 8 && strings2.every((key) => typeof value[key] === "string" && value[key].trim().length > 0 && !value[key].includes("\0")) && [value.executable, value.cwd, value.roleFile].every((path34) => (0, import_node_path36.isAbsolute)(path34)) && Array.isArray(value.argv) && value.argv.every((arg) => typeof arg === "string" && !arg.includes("\0"));
92490
92850
  }
92491
92851
  async function validateRoute(route) {
92492
92852
  let part = "config";
92493
92853
  try {
92494
92854
  if (!isAgentRoute(route)) throw Error("invalid_agent_config");
92495
92855
  part = "executable";
92496
- await (0, import_promises3.access)(route.executable, import_node_fs35.constants.X_OK);
92856
+ await (0, import_promises3.access)(route.executable, import_node_fs36.constants.X_OK);
92497
92857
  if (!(await (0, import_promises3.lstat)(route.executable)).isFile() && !(await (0, import_promises3.lstat)(route.executable)).isSymbolicLink()) throw Error("invalid_executable");
92498
92858
  part = "cwd";
92499
92859
  if (!(await (0, import_promises3.lstat)(route.cwd)).isDirectory()) throw Error("invalid_cwd");
@@ -92507,7 +92867,7 @@ async function validateRoute(route) {
92507
92867
  async function enqueueAgent(message3, route, routeDirectory) {
92508
92868
  try {
92509
92869
  await validateRoute(route);
92510
- const store = openStore((0, import_node_path35.join)((0, import_node_path35.dirname)(routeDirectory), "wake.db"));
92870
+ const store = openStore((0, import_node_path36.join)((0, import_node_path36.dirname)(routeDirectory), "wake.db"));
92511
92871
  try {
92512
92872
  store.enqueueAgent(message3, serializeRoute(route), Date.now());
92513
92873
  } finally {
@@ -92617,7 +92977,7 @@ async function measureInherited(bytes, receipt) {
92617
92977
  const sources = [];
92618
92978
  for (const value of audit.sources) {
92619
92979
  const source = object6(value);
92620
- if (typeof source?.path !== "string" || !(0, import_node_path35.isAbsolute)(source.path) || typeof source.bytes !== "number" || typeof source.sha256 !== "string" || sources.some((item) => item.path === source.path)) throw Error("input_audit_invalid");
92980
+ if (typeof source?.path !== "string" || !(0, import_node_path36.isAbsolute)(source.path) || typeof source.bytes !== "number" || typeof source.sha256 !== "string" || sources.some((item) => item.path === source.path)) throw Error("input_audit_invalid");
92621
92981
  const content = await (0, import_promises3.readFile)(source.path);
92622
92982
  if (content.length !== source.bytes || hash8(content) !== source.sha256) throw Error("input_audit_mismatch");
92623
92983
  sources.push({ path: source.path, bytes: source.bytes, sha256: source.sha256 });
@@ -92707,19 +93067,19 @@ async function processAgent(message3, store, errorPath, dependencies) {
92707
93067
  return;
92708
93068
  }
92709
93069
  const { input, bytes } = agentInput(message3, route, role3, store.path);
92710
- const output = (0, import_node_path35.join)((0, import_node_path35.dirname)(store.path), "agent-output", `${hash8(message3.id)}.stdout`);
93070
+ const output = (0, import_node_path36.join)((0, import_node_path36.dirname)(store.path), "agent-output", `${hash8(message3.id)}.stdout`);
92711
93071
  if (!store.startAgent(message3.id, output, JSON.stringify(bytes), Date.now())) {
92712
93072
  store.deferAgent(message3.id, Date.now());
92713
93073
  return;
92714
93074
  }
92715
93075
  let childLaunched = false;
92716
93076
  try {
92717
- await (0, import_promises3.mkdir)((0, import_node_path35.dirname)(output), { recursive: true, mode: 448 });
93077
+ await (0, import_promises3.mkdir)((0, import_node_path36.dirname)(output), { recursive: true, mode: 448 });
92718
93078
  const out = await (0, import_promises3.open)(output, "wx", 384);
92719
93079
  try {
92720
93080
  const err = await (0, import_promises3.open)(`${output}.stderr`, "wx", 384);
92721
93081
  try {
92722
- const child = (0, import_node_child_process15.spawn)(route.executable, [
93082
+ const child = (0, import_node_child_process16.spawn)(route.executable, [
92723
93083
  ...route.argv,
92724
93084
  "exec",
92725
93085
  "--json",
@@ -92740,7 +93100,7 @@ async function processAgent(message3, store, errorPath, dependencies) {
92740
93100
  env: {
92741
93101
  PATH: process.env.PATH ?? "",
92742
93102
  HOME: (0, import_node_os9.homedir)(),
92743
- CODEX_HOME: process.env.CODEX_HOME ?? (0, import_node_path35.join)((0, import_node_os9.homedir)(), ".codex"),
93103
+ CODEX_HOME: process.env.CODEX_HOME ?? (0, import_node_path36.join)((0, import_node_os9.homedir)(), ".codex"),
92744
93104
  TMPDIR: process.env.TMPDIR,
92745
93105
  LANG: process.env.LANG,
92746
93106
  NODE_ENV: process.env.NODE_ENV
@@ -92789,21 +93149,21 @@ async function processAgent(message3, store, errorPath, dependencies) {
92789
93149
  }
92790
93150
  }
92791
93151
  }
92792
- var import_node_fs35, import_promises3, import_node_path35, import_node_crypto24, import_node_child_process15, import_node_os9, AGENT_INSTRUCTIONS, hash8, AGENT_DEADLINE_MS, AGENT_RECORD_RESOLUTION;
93152
+ var import_node_fs36, import_promises3, import_node_path36, import_node_crypto25, import_node_child_process16, import_node_os9, AGENT_INSTRUCTIONS, hash8, AGENT_DEADLINE_MS, AGENT_RECORD_RESOLUTION;
92793
93153
  var init_agent_route = __esm({
92794
93154
  "services/buzz-wake/agent-route.ts"() {
92795
93155
  "use strict";
92796
- import_node_fs35 = require("node:fs");
93156
+ import_node_fs36 = require("node:fs");
92797
93157
  import_promises3 = require("node:fs/promises");
92798
- import_node_path35 = require("node:path");
92799
- import_node_crypto24 = require("node:crypto");
92800
- import_node_child_process15 = require("node:child_process");
93158
+ import_node_path36 = require("node:path");
93159
+ import_node_crypto25 = require("node:crypto");
93160
+ import_node_child_process16 = require("node:child_process");
92801
93161
  import_node_os9 = require("node:os");
92802
93162
  init_delivery();
92803
93163
  init_store();
92804
93164
  init_lead_admission();
92805
93165
  AGENT_INSTRUCTIONS = `Rozstrzygnij t\u0119 spraw\u0119 RAZ, na podstawie zamro\u017Conego materia\u0142u poni\u017Cej (MESSAGE_JSON i wska\u017Anik WAKE_STORE). NIE zapisuj niczego: nie zmieniaj kart ani ich details, nie zapisuj do WakeStore ani plik\xF3w i nie wo\u0142aj narz\u0119dzi zapisu; trwa\u0142y zapis decyzji wykonuje demon. Jako OSTATNI\u0104 wiadomo\u015B\u0107 zwr\xF3\u0107 dok\u0142adnie jeden obiekt JSON {message_id,decision,action,note,card_id?,card_ids?}: message_id to pe\u0142ne id tej wiadomo\u015Bci, decision to niepuste merytoryczne rozstrzygni\u0119cie. Je\u015Bli wiadomo\u015B\u0107 wskazuje wiele kart, wystarczy jedna ze zbioru, a card_ids zawiera karty z tego zbioru, kt\xF3rych dotyczy decyzja; card_id to karta sprawy, je\u015Bli wiadomo\u015B\u0107 j\u0105 wskazuje. Klas\u0119 sprawy znasz z tokenu lead_class=\u2026 w pierwszej linii tekstu wiadomo\u015Bci (pole text w MESSAGE_JSON); bez tokenu klasa jest inna. Pole action jest jednym z trzech s\u0142\xF3w: unblock_worker, resume_land, to_owner; \u017Cadnych innych warto\u015Bci action. unblock_worker WY\u0141\u0104CZNIE gdy wiadomo\u015B\u0107 ma lead_class=blocker: note to niepusta odpowied\u017A dla Workera, kt\xF3r\u0105 automat wpisze do jego briefu. resume_land WY\u0141\u0104CZNIE gdy wiadomo\u015B\u0107 ma lead_class=ci_hold: wznowienie landu po wstrzymaniu CI. Dla lead_class=escalation poprawn\u0105 akcj\u0105 jest zawsze to_owner. to_owner tak\u017Ce gdy decyzja wymaga cz\u0142owieka, jest niepewna albo klasa jest inna ni\u017C powy\u017Csze. note jest wymagana tylko dla unblock_worker; przy pozosta\u0142ych akcjach mo\u017Cesz j\u0105 poda\u0107 jako uzasadnienie. Demon zapisze obiekt bez zmian i nie interpretuje action ani innych p\xF3l. Je\u015Bli nie mo\u017Cesz rozstrzygn\u0105\u0107, zwr\xF3\u0107 decision "NOT_READY". Stdout bez tego obiektu, event_id sprawy, rc=0, wakes.sent i closedAt nie s\u0105 decyzj\u0105. Adapter mo\u017Ce doda\u0107 input_audit:{sources:[{path,bytes,sha256}],unknownSources:[]} wy\u0142\u0105cznie dla faktycznie za\u0142adowanych instrukcji cwd/profilu; niewiadome wymienia jawnie.`;
92806
- hash8 = (value) => (0, import_node_crypto24.createHash)("sha256").update(value).digest("hex");
93166
+ hash8 = (value) => (0, import_node_crypto25.createHash)("sha256").update(value).digest("hex");
92807
93167
  AGENT_DEADLINE_MS = 30 * 6e4;
92808
93168
  AGENT_RECORD_RESOLUTION = "rekord wiadomo\u015Bci w WakeStore";
92809
93169
  }
@@ -92812,7 +93172,7 @@ var init_agent_route = __esm({
92812
93172
  // services/buzz-wake/delivery.ts
92813
93173
  function codexHome() {
92814
93174
  const configured = process.env.CODEX_HOME;
92815
- return configured && (0, import_node_path36.isAbsolute)(configured) ? configured : (0, import_node_path36.join)((0, import_node_os10.homedir)(), ".codex");
93175
+ return configured && (0, import_node_path37.isAbsolute)(configured) ? configured : (0, import_node_path37.join)((0, import_node_os10.homedir)(), ".codex");
92816
93176
  }
92817
93177
  function safeStderr(value, external = false) {
92818
93178
  const source = value instanceof Error ? value.message : typeof value === "string" ? value : "";
@@ -92840,7 +93200,7 @@ function safeStderr(value, external = false) {
92840
93200
  return redacted.slice(0, 4096);
92841
93201
  }
92842
93202
  async function appendSecure(path34, content) {
92843
- await (0, import_promises4.mkdir)((0, import_node_path36.dirname)(path34), { recursive: true, mode: 448 });
93203
+ await (0, import_promises4.mkdir)((0, import_node_path37.dirname)(path34), { recursive: true, mode: 448 });
92844
93204
  try {
92845
93205
  if ((await (0, import_promises4.lstat)(path34)).isSymbolicLink()) throw new Error("Refusing symlink delivery target");
92846
93206
  } catch (error48) {
@@ -92935,10 +93295,10 @@ async function notifySenderRefusal(toRole, text9, eventId) {
92935
93295
  if (refusalBridge === void 0) {
92936
93296
  const { createBuzzBridge: createBuzzBridge2, loadBuzzConfig: loadBuzzConfig2 } = await Promise.resolve().then(() => (init_bridge(), bridge_exports));
92937
93297
  refusalBridge = await createBuzzBridge2({
92938
- config: await loadBuzzConfig2((0, import_node_path36.join)(process.cwd(), "services/buzz-mcp/config/buzz-roles.json")),
92939
- identitiesFile: process.env.BUZZ_IDENTITIES_FILE ?? (0, import_node_path36.join)((0, import_node_os10.homedir)(), "Library/Application Support/Robisie/Buzz G4/agents.env"),
93298
+ config: await loadBuzzConfig2((0, import_node_path37.join)(process.cwd(), "services/buzz-mcp/config/buzz-roles.json")),
93299
+ identitiesFile: process.env.BUZZ_IDENTITIES_FILE ?? (0, import_node_path37.join)((0, import_node_os10.homedir)(), "Library/Application Support/Robisie/Buzz G4/agents.env"),
92940
93300
  role: "control-room",
92941
- stateDir: (0, import_node_path36.join)((0, import_node_os10.homedir)(), ".robisie/buzz")
93301
+ stateDir: (0, import_node_path37.join)((0, import_node_os10.homedir)(), ".robisie/buzz")
92942
93302
  });
92943
93303
  }
92944
93304
  await refusalBridge.send({ to_role: toRole, kind: "chat", text: text9, pointer: eventId });
@@ -93083,7 +93443,7 @@ async function checkQueuePickup(message3, dependencies) {
93083
93443
  let pickedUp = false;
93084
93444
  let inactive = false;
93085
93445
  try {
93086
- const db = new import_node_sqlite3.DatabaseSync(dependencies.codexQueuePath ?? (0, import_node_path36.join)(codexHome(), "queue_1.sqlite"), { readOnly: true });
93446
+ const db = new import_node_sqlite3.DatabaseSync(dependencies.codexQueuePath ?? (0, import_node_path37.join)(codexHome(), "queue_1.sqlite"), { readOnly: true });
93087
93447
  try {
93088
93448
  const row = db.prepare("SELECT thread_id FROM queued_items WHERE id = ?").get(pickup.id);
93089
93449
  seen ||= row !== void 0;
@@ -93435,7 +93795,7 @@ function publishedRoute(source, role3) {
93435
93795
  }
93436
93796
  function probeCrProcess(pid) {
93437
93797
  return new Promise((resolve7) => {
93438
- (0, import_node_child_process16.execFile)(
93798
+ (0, import_node_child_process17.execFile)(
93439
93799
  "ps",
93440
93800
  ["-p", String(pid), "-o", "lstart=,pid=,args="],
93441
93801
  { encoding: "utf8", timeout: 5e3, maxBuffer: 64 * 1024, env: { ...process.env, LC_ALL: "C" } },
@@ -93447,9 +93807,9 @@ function resolveCrRuntime(deps = {}) {
93447
93807
  return resolveCodexRuntime("control-room", deps);
93448
93808
  }
93449
93809
  async function resolveCodexRuntime(role3, deps) {
93450
- const cwd = role3 === "control-room" ? CR_RUNTIME_CWD : (0, import_node_path36.join)((0, import_node_os10.homedir)(), "Documents/PersonalHQ/Projects/Robisie/_reksio");
93810
+ const cwd = role3 === "control-room" ? CR_RUNTIME_CWD : (0, import_node_path37.join)((0, import_node_os10.homedir)(), "Documents/PersonalHQ/Projects/Robisie/_reksio");
93451
93811
  const label2 = role3 === "control-room" ? "CR" : role3;
93452
- const file3 = (0, import_node_path36.join)(deps.routeDirectory ?? (0, import_node_path36.join)((0, import_node_os10.homedir)(), ".robisie/buzz/wake-routes"), `${role3}.json`);
93812
+ const file3 = (0, import_node_path37.join)(deps.routeDirectory ?? (0, import_node_path37.join)((0, import_node_os10.homedir)(), ".robisie/buzz/wake-routes"), `${role3}.json`);
93453
93813
  try {
93454
93814
  const stat = await (0, import_promises4.lstat)(file3);
93455
93815
  if (!stat.isFile() || stat.isSymbolicLink()) return { kind: "unknown", reason: `runtime ${label2} nie jest zwyk\u0142ym plikiem` };
@@ -93510,7 +93870,7 @@ function queueRevision(db, threadId) {
93510
93870
  async function queueCodex(threadId, notice, dependencies) {
93511
93871
  let queueRevisionPre = null;
93512
93872
  try {
93513
- const db = new import_node_sqlite3.DatabaseSync(dependencies.codexQueuePath ?? (0, import_node_path36.join)(codexHome(), "queue_1.sqlite"), { readOnly: true });
93873
+ const db = new import_node_sqlite3.DatabaseSync(dependencies.codexQueuePath ?? (0, import_node_path37.join)(codexHome(), "queue_1.sqlite"), { readOnly: true });
93514
93874
  try {
93515
93875
  const revision = queueRevision(db, threadId);
93516
93876
  if (revision !== null) queueRevisionPre = { threadId, revision };
@@ -93574,7 +93934,7 @@ async function dispatchWake(message3, dependencies) {
93574
93934
  if (!ROLE3.test(role3)) return noRoute(role3, "nazwa roli nie mo\u017Ce utworzy\u0107 bezpiecznej \u015Bcie\u017Cki", dependencies);
93575
93935
  let source;
93576
93936
  try {
93577
- source = await dependencies.readRoute((0, import_node_path36.join)(dependencies.routeDirectory, `${role3}.json`));
93937
+ source = await dependencies.readRoute((0, import_node_path37.join)(dependencies.routeDirectory, `${role3}.json`));
93578
93938
  } catch {
93579
93939
  return noRoute(role3, "opublikowany adres jest niedost\u0119pny", dependencies);
93580
93940
  }
@@ -93607,16 +93967,16 @@ async function dispatchWake(message3, dependencies) {
93607
93967
  const result = await dependencies.run(dependencies.guardedSendBin, ["--modal-guard", ...role3 === "hermes" ? ["--hermes-safe"] : [], ...mode.mode === "steer" ? ["--steer"] : [], "--surface-id", matches2[0].id, panelNotice]);
93608
93968
  return { rc: result.rc, stderr: result.stderr };
93609
93969
  }
93610
- var import_promises4, import_node_child_process16, import_node_os10, import_node_sqlite3, import_node_path36, SAFE_DIAGNOSTIC_CATEGORY, refusalBridge, GBOT_READ_INTERVAL_MS, UUID, ROLE3, CR_RUNTIME_CWD;
93970
+ var import_promises4, import_node_child_process17, import_node_os10, import_node_sqlite3, import_node_path37, SAFE_DIAGNOSTIC_CATEGORY, refusalBridge, GBOT_READ_INTERVAL_MS, UUID, ROLE3, CR_RUNTIME_CWD;
93611
93971
  var init_delivery = __esm({
93612
93972
  "services/buzz-wake/delivery.ts"() {
93613
93973
  "use strict";
93614
93974
  import_promises4 = require("node:fs/promises");
93615
- import_node_child_process16 = require("node:child_process");
93975
+ import_node_child_process17 = require("node:child_process");
93616
93976
  import_node_os10 = require("node:os");
93617
93977
  import_node_sqlite3 = require("node:sqlite");
93618
93978
  init_lib();
93619
- import_node_path36 = require("node:path");
93979
+ import_node_path37 = require("node:path");
93620
93980
  init_store();
93621
93981
  init_agent_route();
93622
93982
  init_protocol2();
@@ -93625,344 +93985,7 @@ var init_delivery = __esm({
93625
93985
  GBOT_READ_INTERVAL_MS = 5e3;
93626
93986
  UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
93627
93987
  ROLE3 = /^[a-z0-9-]+$/;
93628
- CR_RUNTIME_CWD = (0, import_node_path36.join)((0, import_node_os10.homedir)(), "Documents/PersonalHQ/Projects/Robisie Control Room");
93629
- }
93630
- });
93631
-
93632
- // maszynista/enabled-auto.ts
93633
- function processRun(file3, args, cwd, timeoutMs = 1e4) {
93634
- const result = (0, import_node_child_process17.spawnSync)(file3, args, { cwd, encoding: "utf8", timeout: Math.min(1e4, timeoutMs), maxBuffer: 1024 * 1024, shell: false, env: { ...process.env, LC_ALL: "C" } });
93635
- if (result.error || result.signal || result.status === null) throw new Error(`${file3}: ${result.error?.message ?? result.signal ?? "UNKNOWN status"}`);
93636
- return { status: result.status, stdout: result.stdout ?? "", stderr: result.stderr ?? "" };
93637
- }
93638
- function tail(file3) {
93639
- let fd;
93640
- try {
93641
- fd = (0, import_node_fs36.openSync)(file3, "r");
93642
- const size = (0, import_node_fs36.fstatSync)(fd).size, length = Math.min(size, MAX_TAIL), bytes = Buffer.alloc(length);
93643
- const count = (0, import_node_fs36.readSync)(fd, bytes, 0, length, size - length);
93644
- return bytes.toString("utf8", 0, count);
93645
- } finally {
93646
- if (fd !== void 0) (0, import_node_fs36.closeSync)(fd);
93647
- }
93648
- }
93649
- function validCheck(raw) {
93650
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) return false;
93651
- const c = raw;
93652
- if (typeof c.id !== "string" || c.v !== ENABLED_CHECKS[c.id]) return false;
93653
- const args = c.args;
93654
- if (c.id === "tick-loaded") return args === void 0;
93655
- if (!args || typeof args !== "object" || Array.isArray(args)) return false;
93656
- const a = args;
93657
- if (c.id === "service-fresh") return Object.keys(a).length === 1 && SERVICE_ALLOWLIST.has(String(a.label));
93658
- return c.id === "log-marker" && Object.keys(a).length === 2 && LOG_ALLOWLIST.has(String(a.log)) && a.marker === "ENABLED auto:";
93659
- }
93660
- function ancestor2(landed, target, repo, run) {
93661
- const result = run("git", ["merge-base", "--is-ancestor", landed, target], repo);
93662
- if (result.status === 0) return true;
93663
- if (result.status === 1) return false;
93664
- throw new Error(`git merge-base: ${result.stderr || result.status}`);
93665
- }
93666
- function elapsedSeconds(raw) {
93667
- const match = raw.trim().match(/^(?:(\d+)-)?(?:(\d+):)?(\d{1,2}):(\d{2})$/);
93668
- if (!match) return null;
93669
- const days = Number(match[1] ?? 0), hours = Number(match[2] ?? 0), minutes = Number(match[3]), seconds = Number(match[4]);
93670
- if (minutes > 59 || seconds > 59 || match[1] && hours > 23) return null;
93671
- return days * 86400 + hours * 3600 + minutes * 60 + seconds;
93672
- }
93673
- function checkEnabled(input) {
93674
- const { id: id2, v } = input;
93675
- if (!validCheck(input)) return { id: id2, v, verdict: "UNKNOWN_CHECK", observed: "nieznany check lub argument", ref: "ENABLED_CHECKS" };
93676
- const execute = input.runProcess ?? processRun, readTail = input.readTail ?? tail;
93677
- const run = (...args) => {
93678
- const value = execute(...args);
93679
- if (value.error || value.signal || value.status === null) throw new Error(`${args[0]}: ${value.error?.message ?? value.signal ?? "UNKNOWN status"}`);
93680
- return value;
93681
- };
93682
- const result = (verdict, observed, ref) => ({ id: id2, v, verdict, observed: observed.slice(0, 500), ref });
93683
- try {
93684
- if (id2 === "tick-loaded") {
93685
- const lines2 = readTail(input.logPath).split("\n");
93686
- for (const line2 of lines2) {
93687
- const match = line2.match(/\btick_finished\b.*\bat=(\S+).*\boutcome=ok\b.*\bloaded=([a-f0-9]{40})(?!\+dirty)\b/i);
93688
- if (!match || Number.isNaN(Date.parse(match[1])) || Date.parse(match[1]) < Date.parse(input.activationAt) || !SHA2.test(match[2])) continue;
93689
- if (ancestor2(input.landedSha, match[2], input.repo, run)) return result("PASS", `tick_finished loaded=${match[2]}`, input.logPath);
93690
- }
93691
- const due = lines2.some((line2) => {
93692
- if (!/\btick_finished\b/.test(line2)) return false;
93693
- const at3 = Date.parse(line2.match(/\bat=(\S+)/)?.[1] ?? "");
93694
- if (Number.isFinite(at3) && at3 < Date.parse(input.activationAt)) return false;
93695
- if (Number.isFinite(at3) && at3 >= Date.parse(input.confirmedAt ?? "")) return true;
93696
- const loaded = line2.match(/\bloaded=([a-f0-9]{40})(?:\+dirty)?(?=\s|$)/i)?.[1];
93697
- return !!loaded && ancestor2(input.landedSha, loaded, input.repo, run);
93698
- });
93699
- return due ? result("FAIL", "brak poprawnego tick_finished outcome=ok po aktywacji dla landed", input.logPath) : result("CZEKA", "czeka na p\xF3\u017Aniejszy terminal taktu po aktywacji", input.logPath);
93700
- }
93701
- if (id2 === "log-marker") {
93702
- if (!input.cardId || !input.runId) return result("ERROR", "brak wi\u0105zania karty i przebiegu", input.logPath);
93703
- const lines2 = readTail(input.logPath).split("\n");
93704
- const checked = `ENABLED auto: karta=${input.cardId} FAIL run=${input.runId} checks=`;
93705
- return lines2.some((line2) => {
93706
- const date10 = line2.match(/^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z)\b/);
93707
- return date10 && Date.parse(date10[1]) >= Date.parse(input.activationAt) && line2.slice(date10[0].length).trimStart().startsWith(checked) && line2.includes("log-marker@1:FAIL");
93708
- }) ? result("PASS", `faza ENABLED oceni\u0142a kart\u0119 ${input.cardId}`, input.logPath) : result("FAIL", `brak sprawdzianu ENABLED karty ${input.cardId} po aktywacji`, input.logPath);
93709
- }
93710
- const printed = run("launchctl", ["print", `gui/${process.getuid?.() ?? 0}/${String(input.args?.label)}`]);
93711
- if (printed.error || printed.signal || printed.status === null) return result("ERROR", "niepewny odczyt us\u0142ugi", String(input.args?.label));
93712
- if (printed.status !== 0 && !/Could not find service|service not found/i.test(printed.stderr)) return result("ERROR", `launchctl: ${printed.stderr}`, String(input.args?.label));
93713
- if (printed.status !== 0) return result("FAIL", `us\u0142uga nie dzia\u0142a: ${printed.stderr}`, String(input.args?.label));
93714
- const running = /^\s*state\s*=\s*running\s*$/m.test(printed.stdout);
93715
- const pid = Number(printed.stdout.match(/^\s*pid\s*=\s*(\d+)\s*$/m)?.[1] ?? 0);
93716
- if (!running || !Number.isSafeInteger(pid) || pid <= 0) return result("FAIL", "us\u0142uga nie dzia\u0142a lub brak pid", String(input.args?.label));
93717
- const ps = run("ps", ["-o", "etime=", "-p", String(pid)]);
93718
- if (ps.status !== 0) return result("ERROR", `ps: ${ps.stderr}`, String(pid));
93719
- const seconds = elapsedSeconds(ps.stdout);
93720
- if (seconds === null) return result("ERROR", `niepoprawne etime: ${ps.stdout}`, String(pid));
93721
- const started = Date.parse(input.now) - seconds * 1e3;
93722
- if (started < Date.parse(input.activationAt)) return result("FAIL", `pid=${pid} sprzed aktywacji`, String(pid));
93723
- if (!trustedServiceReceipt(input.serviceReload))
93724
- return result("UNKNOWN", "brak zaufanego receiptu kickstart; owner=CEO; wymagany jawny --bootstrap", "host-activation.json");
93725
- if (pid !== input.serviceReload.process.pid) return result("UNKNOWN", "obcy PID wzgl\u0119dem receiptu; owner=CEO", String(pid));
93726
- const command = run("ps", ["-o", "command=", "-p", String(pid)]);
93727
- if (command.status !== 0 || command.error || command.signal) return result("ERROR", "brak pewnej komendy procesu", String(pid));
93728
- if (!/(?:^|[\s/])services\/buzz-wake\/main\.ts(?:\s|$)/.test(command.stdout)) return result("FAIL", "b\u0142\u0119dny proces us\u0142ugi", String(pid));
93729
- const lsof = run("lsof", ["-a", "-d", "cwd", "-p", String(pid), "-Fn"]);
93730
- if (lsof.status !== 0) return result("ERROR", `lsof: ${lsof.stderr}`, String(pid));
93731
- const cwd = lsof.stdout.split("\n").find((line2) => line2.startsWith("n"))?.slice(1);
93732
- if (!cwd) return result("ERROR", "brak cwd z lsof", String(pid));
93733
- if ((0, import_node_fs36.realpathSync)(cwd) !== (0, import_node_fs36.realpathSync)(input.repo)) return result("FAIL", `cwd=${cwd}`, String(pid));
93734
- const again = run("launchctl", ["print", `gui/${process.getuid?.() ?? 0}/${String(input.args?.label)}`]);
93735
- if (again.status !== 0 || again.error || again.signal || Number(again.stdout.match(/^\s*pid\s*=\s*(\d+)\s*$/m)?.[1]) !== pid)
93736
- return result("ERROR", "proces zmieni\u0142 si\u0119 podczas obserwacji", String(pid));
93737
- if (input.serviceReload) {
93738
- const receipt = input.serviceReload, process3 = receipt.process;
93739
- if (receipt.result !== "PASS" || !process3) return result("ERROR", "nierozliczony reload procesu; owner=CEO", String(pid));
93740
- const start = run("ps", ["-o", "lstart=", "-p", String(pid)]);
93741
- if (start.status !== 0 || start.error || start.signal) return result("ERROR", "niepewny start procesu", String(pid));
93742
- if (process3.pid !== pid || process3.started_at !== start.stdout.trim() || !SHA2.test(process3.code_sha) || !ancestor2(input.landedSha, process3.code_sha, input.repo, run)) return result("UNKNOWN", "proces nie odpowiada receiptowi kodu; owner=CEO", String(pid));
93743
- }
93744
- return result("PASS", `pid=${pid} start=${new Date(started).toISOString()} cwd=${cwd}`, String(pid));
93745
- } catch (error48) {
93746
- return result("ERROR", error48 instanceof Error ? error48.message : String(error48), id2);
93747
- }
93748
- }
93749
- function details(value) {
93750
- return value?.details ?? {};
93751
- }
93752
- function landedSha3(card) {
93753
- const value = details(card).landed;
93754
- const sha5 = value && typeof value === "object" && "sha" in value ? value.sha : null;
93755
- return typeof sha5 === "string" && SHA2.test(sha5) ? sha5 : null;
93756
- }
93757
- function checks(card) {
93758
- const raw = details(card).enabled_check;
93759
- return Array.isArray(raw) && raw.length >= 1 && raw.length <= 3 ? raw : null;
93760
- }
93761
- function eligible2(card) {
93762
- return card.status === "delivered" && details(card).card_class === "executable" && landedSha3(card) !== null && checks(card) !== null && details(card).enabled_evidence === void 0;
93763
- }
93764
- function activationAt(landed, input, run) {
93765
- const confirmed = input.activation.confirmed;
93766
- if (confirmed && SHA2.test(confirmed.target) && ancestor2(landed, confirmed.target, input.repo, run)) {
93767
- return reflogMoment(landed, input.repo, run) ?? (Number.isFinite(Date.parse(confirmed.at)) ? confirmed.at : null);
93768
- }
93769
- return reflogMoment(landed, input.repo, run);
93770
- }
93771
- function reflogMoment(landed, repo, run) {
93772
- const result = run("git", ["reflog", "show", "--date=iso-strict", "--format=%H%x09%gd", "HEAD"], repo);
93773
- if (result.status !== 0) throw new Error(`git reflog: ${result.stderr}`);
93774
- const descendants = run("git", ["rev-list", "--ancestry-path", `${landed}..HEAD`], repo);
93775
- if (descendants.status !== 0) throw new Error(`git rev-list: ${descendants.stderr || descendants.status}`);
93776
- if (!ancestor2(landed, "HEAD", repo, run)) return null;
93777
- const onHead = new Set(descendants.stdout.trim().split("\n"));
93778
- onHead.add(landed);
93779
- let earliest = null;
93780
- for (const line2 of result.stdout.split("\n")) {
93781
- const [sha5, selector] = line2.split(" ");
93782
- const at3 = selector?.match(/@\{([^}]+)\}/)?.[1];
93783
- if (SHA2.test(sha5 ?? "") && at3 && !Number.isNaN(Date.parse(at3)) && onHead.has(sha5)) earliest = new Date(at3).toISOString();
93784
- }
93785
- return earliest;
93786
- }
93787
- function runId(cardId, landed, checkList, at3) {
93788
- return (0, import_node_crypto25.createHash)("sha256").update(`${cardId}${landed}${checkList.map((c) => validCheck(c) ? `${c.id}@${c.v}` : `INVALID:${JSON.stringify(c) ?? "undefined"}`).join(",")}${at3}`).digest("hex").slice(0, 16);
93789
- }
93790
- async function runEnabledAuto(input, deps) {
93791
- if (!SHA2.test(input.loadedSha)) {
93792
- deps.log(`ENABLED auto: UNKNOWN owner=CEO loaded=${input.loadedSha}; potrzebny czysty observed loaded`);
93793
- return;
93794
- }
93795
- const confirmed = input.activation.confirmed;
93796
- const waiting = !confirmed ? "brak confirmed; czeka na potwierdzenie loaded" : (confirmed.observed_loaded ?? confirmed.target) !== input.loadedSha ? `confirmed=${confirmed.target} != loaded=${input.loadedSha}; czeka na potwierdzenie` : void 0;
93797
- const started = Date.now();
93798
- const rawRun = deps.runProcess ?? processRun, readTail = deps.readTail ?? tail;
93799
- const run = (file3, args, cwd) => {
93800
- const remaining = 3e4 - (Date.now() - started);
93801
- if (remaining <= 0) throw new Error("bud\u017Cet ENABLED auto 30 s przekroczony");
93802
- return rawRun(file3, args, cwd, Math.min(1e4, remaining));
93803
- };
93804
- const cards = (await deps.listCards()).filter(eligible2).sort((a, b) => String(input.state.enabledAuto?.[a.id]?.lastAt ?? "").localeCompare(String(input.state.enabledAuto?.[b.id]?.lastAt ?? "")) || String(details(a).landed.at ?? "").localeCompare(String(details(b).landed.at ?? "")) || a.id.localeCompare(b.id));
93805
- let evaluated = 0;
93806
- for (const card of cards) {
93807
- if (Date.now() - started >= 3e4 || evaluated >= 5) break;
93808
- const landed = landedSha3(card);
93809
- let isLoaded = false;
93810
- let at3 = null;
93811
- try {
93812
- isLoaded = ancestor2(landed, input.loadedSha, input.repo, run);
93813
- if (isLoaded) at3 = activationAt(landed, input, run);
93814
- } catch (error48) {
93815
- evaluated++;
93816
- const id3 = runId(card.id, landed, checks(card), "OBJECT_ERROR");
93817
- const previous2 = input.state.enabledAuto?.[card.id];
93818
- const checkDigest = error48 instanceof Error ? error48.message : String(error48);
93819
- const changed2 = previous2?.run_id !== id3 || previous2.lastVerdict !== "ERROR" || previous2.checkDigest !== checkDigest;
93820
- if (changed2) deps.log(`${input.dryRun ? "[dry-run] " : ""}ENABLED auto: karta=${card.id.slice(0, 8)} ERROR run=${id3} checks=git:${checkDigest}`);
93821
- const full2 = await deps.getTask(card.id);
93822
- if (!input.dryRun && full2?.status === "delivered" && details(full2).enabled_evidence === void 0) {
93823
- input.state.enabledAuto ??= {};
93824
- const entry3 = {
93825
- run_id: id3,
93826
- phase: "checking",
93827
- attempts: (previous2?.run_id === id3 ? previous2.attempts : 0) + 1,
93828
- firstAt: previous2?.run_id === id3 ? previous2.firstAt : input.now,
93829
- lastAt: input.now,
93830
- lastVerdict: "ERROR",
93831
- checkDigest
93832
- };
93833
- if (changed2) await deps.appendDetail(card.id, { enabled_auto: { verdict: "ERROR", run_id: id3, at: input.now } });
93834
- input.state.enabledAuto[card.id] = entry3;
93835
- }
93836
- continue;
93837
- }
93838
- if (!isLoaded) continue;
93839
- const checkList = checks(card);
93840
- const id2 = runId(card.id, landed, checkList, at3 ?? "NO_ACTIVATION_MOMENT");
93841
- let previous = input.state.enabledAuto?.[card.id];
93842
- const full = await deps.getTask(card.id);
93843
- if (!full || full.status !== "delivered") continue;
93844
- if (details(full).enabled_evidence !== void 0) {
93845
- if (!input.dryRun && previous?.run_id === id2) input.state.enabledAuto[card.id] = { ...previous, phase: "written" };
93846
- continue;
93847
- }
93848
- if (previous?.run_id === id2 && previous.phase === "written") previous = void 0;
93849
- evaluated++;
93850
- const outputs = [];
93851
- const checkListValid = checkList.every(validCheck);
93852
- let verdict;
93853
- if (waiting) {
93854
- verdict = "CZEKA";
93855
- outputs.push({ id: "tick-loaded", v: 1, verdict, observed: waiting, ref: "host-activation.json" });
93856
- } else if (!at3) {
93857
- verdict = "NO_ACTIVATION_MOMENT";
93858
- outputs.push({ id: "tick-loaded", v: 1, verdict, observed: "brak wiarygodnego czasu aktywacji; owner=CEO; potrzebny receipt lub reflog", ref: "host-activation.json" });
93859
- } else if (!checkListValid) verdict = "UNKNOWN_CHECK";
93860
- else {
93861
- for (const c of checkList) {
93862
- outputs.push(checkEnabled({
93863
- ...c,
93864
- repo: input.repo,
93865
- landedSha: landed,
93866
- loadedSha: input.loadedSha,
93867
- activationAt: at3,
93868
- confirmedAt: confirmed?.confirmed_at,
93869
- now: input.now,
93870
- logPath: input.logPath,
93871
- cardId: card.id,
93872
- runId: id2,
93873
- runProcess: run,
93874
- readTail,
93875
- serviceReload: input.activation.service_reload
93876
- }));
93877
- }
93878
- verdict = outputs.some((c) => c.verdict === "ERROR") ? "ERROR" : outputs.some((c) => c.verdict === "FAIL") ? "FAIL" : outputs.some((c) => c.verdict === "UNKNOWN") ? "UNKNOWN" : outputs.every((c) => c.verdict === "PASS") ? "PASS" : "CZEKA";
93879
- }
93880
- const digest5 = (0, import_node_crypto25.createHash)("sha256").update(JSON.stringify(outputs)).digest("hex");
93881
- const changed = previous?.run_id !== id2 || previous.lastVerdict !== verdict || previous.checkDigest !== digest5;
93882
- if (changed) deps.log(`${input.dryRun ? "[dry-run] " : ""}ENABLED auto: karta=${card.id} ${verdict} run=${id2} checks=${outputs.map((c) => `${c.id}@${c.v}:${c.verdict}:${c.observed}`).join(",")}`);
93883
- if (input.dryRun) continue;
93884
- const current = await deps.getTask(card.id);
93885
- if (!current || current.status !== "delivered" || details(current).enabled_evidence !== void 0) continue;
93886
- const uncertainService = outputs.find((c) => c.id === "service-fresh" && ["UNKNOWN", "ERROR"].includes(c.verdict));
93887
- if (uncertainService) await persistServiceAlarm(
93888
- {
93889
- stateDir: input.stateDir ?? import_node_path37.default.dirname(input.logPath),
93890
- target: input.loadedSha,
93891
- previous: confirmed?.previous ?? input.loadedSha,
93892
- detail: uncertainService.observed,
93893
- cause: !trustedServiceReceipt(input.activation.service_reload) ? "untrusted-receipt" : uncertainService.observed === "obcy PID wzgl\u0119dem receiptu; owner=CEO" ? "foreign-pid" : uncertainService.observed
93894
- },
93895
- { alarm: deps.alarm, log: deps.log, now: () => input.now }
93896
- );
93897
- const now = input.now;
93898
- if (verdict !== "PASS" && at3 && Date.parse(now) - Date.parse(at3) >= 24 * 60 * 6e4) {
93899
- if (previous?.run_id !== id2 || previous.phase !== "undecided") deps.log(`ENABLED auto: karta=${card.id} nieodebrane po 24 h (${verdict})`);
93900
- const entry3 = {
93901
- run_id: id2,
93902
- phase: "undecided",
93903
- attempts: (previous?.run_id === id2 ? previous.attempts : 0) + 1,
93904
- firstAt: previous?.run_id === id2 ? previous.firstAt : now,
93905
- lastAt: now,
93906
- lastVerdict: verdict,
93907
- checkDigest: digest5
93908
- };
93909
- if (previous?.run_id !== id2 || previous.phase !== "undecided" || changed)
93910
- await deps.appendDetail(card.id, { enabled_auto: { verdict: "UNDECIDED_24H", run_id: id2, at: now, checks: outputs } });
93911
- input.state.enabledAuto ??= {};
93912
- input.state.enabledAuto[card.id] = entry3;
93913
- continue;
93914
- }
93915
- const entry2 = {
93916
- run_id: id2,
93917
- phase: verdict === "PASS" ? "writing" : "checking",
93918
- attempts: (previous?.run_id === id2 ? previous.attempts : 0) + 1,
93919
- firstAt: previous?.run_id === id2 ? previous.firstAt : now,
93920
- lastAt: now,
93921
- lastVerdict: verdict,
93922
- checkDigest: digest5
93923
- };
93924
- input.state.enabledAuto ??= {};
93925
- if (verdict === "PASS") {
93926
- const evidence2 = {
93927
- what: `ENABLED automatem: ${checkList.map((c) => `${c.id}@${c.v}`).join(", ")} PASS dla landed=${landed.slice(0, 8)} na loaded=${input.loadedSha.slice(0, 8)}; ${outputs[0]?.observed.slice(0, 300) ?? ""}`,
93928
- when: now,
93929
- ref: `maszynista/ticks.log tick=${input.tick}; maszynista/state.json enabledAuto[${card.id}]; run=${id2}`,
93930
- source: "maszynista/enabled-auto",
93931
- card_id: card.id,
93932
- run_id: id2,
93933
- activation_at: at3,
93934
- landed_sha: landed,
93935
- loaded_sha: input.loadedSha,
93936
- checks: outputs
93937
- };
93938
- entry2.evidence = evidence2;
93939
- input.state.enabledAuto[card.id] = entry2;
93940
- deps.saveState(input.state);
93941
- await deps.appendDetail(card.id, { enabled_evidence: evidence2, enabled_auto: { verdict: "PASS", run_id: id2, at: now } });
93942
- const read = await deps.getTask(card.id);
93943
- if (details(read).enabled_evidence?.run_id !== id2) throw new Error(`read-after ENABLED ${card.id}: run_id niezgodny`);
93944
- input.state.enabledAuto[card.id] = { ...entry2, phase: "written" };
93945
- } else {
93946
- if (changed) await deps.appendDetail(card.id, { enabled_auto: { verdict, run_id: id2, at: now, checks: outputs } });
93947
- input.state.enabledAuto[card.id] = entry2;
93948
- }
93949
- }
93950
- }
93951
- var import_node_crypto25, import_node_child_process17, import_node_fs36, import_node_path37, SHA2, SERVICE_ALLOWLIST, LOG_ALLOWLIST, ENABLED_CHECKS, MAX_TAIL;
93952
- var init_enabled_auto = __esm({
93953
- "maszynista/enabled-auto.ts"() {
93954
- "use strict";
93955
- import_node_crypto25 = require("node:crypto");
93956
- import_node_child_process17 = require("node:child_process");
93957
- import_node_fs36 = require("node:fs");
93958
- import_node_path37 = __toESM(require("node:path"));
93959
- init_host_activation();
93960
- init_service_reload();
93961
- SHA2 = /^[a-f0-9]{40}$/i;
93962
- SERVICE_ALLOWLIST = /* @__PURE__ */ new Set(["com.robisie.buzz-wake"]);
93963
- LOG_ALLOWLIST = /* @__PURE__ */ new Set(["ticks"]);
93964
- ENABLED_CHECKS = Object.freeze({ "tick-loaded": 1, "service-fresh": 1, "log-marker": 1 });
93965
- MAX_TAIL = 4 * 1024 * 1024;
93988
+ CR_RUNTIME_CWD = (0, import_node_path37.join)((0, import_node_os10.homedir)(), "Documents/PersonalHQ/Projects/Robisie Control Room");
93966
93989
  }
93967
93990
  });
93968
93991