robisie 0.5.53 → 0.6.1

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.
@@ -1,4 +1,5 @@
1
1
  import { spawnSync } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
2
3
  import * as fs from 'node:fs';
3
4
  import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
4
5
  import { createInterface } from 'node:readline/promises';
@@ -35,10 +36,7 @@ function newer(candidate, current) {
35
36
  return next[i] > old[i];
36
37
  return false;
37
38
  }
38
- async function connectBoard(ctx, config) {
39
- // Host DB queries remain in the host. Never import DB or execute tick to obtain them.
40
- if (config.engine.mode === 'host')
41
- refuse('Brak dostępnej hostowej drogi tablicy poza tick.ts; aktualizacja odmówiona.');
39
+ async function connectBoard(ctx) {
42
40
  const token = readKey(agentPaths(ctx).clientDir);
43
41
  if (!token)
44
42
  refuse('Brak zapisanego klucza instalacji; uruchom npx robisie init.');
@@ -71,7 +69,10 @@ export async function runInstallationUpdate(ctx, options, overrides = {}) {
71
69
  };
72
70
  const io = runtime.fs;
73
71
  let board, serialRelease, tickRelease;
72
+ let sharedRelease, rollback;
73
+ let notifyFailure, afterCleanup, modeRestored;
74
74
  let mode;
75
+ const digest = (bytes) => createHash('sha256').update(bytes).digest('hex');
75
76
  let result = 2;
76
77
  let completed = false;
77
78
  const env = { ...ctx.env };
@@ -99,6 +100,24 @@ export async function runInstallationUpdate(ctx, options, overrides = {}) {
99
100
  refuse('Wymagany zwykły czytelny plik instalacji.');
100
101
  return io.readFileSync(path);
101
102
  };
103
+ const replaceMode = (target) => {
104
+ if (!mode)
105
+ return;
106
+ const directory = io.mkdtempSync(join(dirname(mode.path), '.mode-update-')), temporary = join(directory, 'mode');
107
+ io.writeFileSync(temporary, target, { flag: 'wx', mode: 0o600, flush: true });
108
+ if (!regular(temporary).equals(target) || !regular(mode.path).equals(mode.expected))
109
+ refuse('Obca zmiana mode lub niepotwierdzony zapis; zachowano stan.');
110
+ try {
111
+ io.renameSync(temporary, mode.path);
112
+ }
113
+ finally {
114
+ if (regular(mode.path).equals(target))
115
+ mode.expected = target;
116
+ }
117
+ if (!regular(mode.path).equals(target))
118
+ refuse('Niepotwierdzona wymiana mode.');
119
+ io.rmdirSync(directory);
120
+ };
102
121
  const privateDir = (path) => {
103
122
  io.mkdirSync(path, { recursive: true, mode: 0o700 });
104
123
  if (!stat(path)?.isDirectory())
@@ -152,6 +171,63 @@ export async function runInstallationUpdate(ctx, options, overrides = {}) {
152
171
  io.unlinkSync(path);
153
172
  };
154
173
  };
174
+ const cleanup = async () => {
175
+ if (mode) {
176
+ try {
177
+ if (!regular(mode.path).equals(mode.expected))
178
+ throw new Error('foreign mode');
179
+ replaceMode(mode.bytes);
180
+ if (digest(regular(mode.path)) !== mode.sha)
181
+ throw new Error('mode SHA');
182
+ mode.expected = mode.bytes;
183
+ modeRestored?.();
184
+ }
185
+ catch {
186
+ ctx.err('Alarm: nie potwierdzono przywrócenia bajtów HOST-ACTIVATION.mode.');
187
+ result = 2;
188
+ if (rollback) {
189
+ const restore = rollback;
190
+ rollback = undefined;
191
+ try {
192
+ await restore();
193
+ }
194
+ catch {
195
+ ctx.err('Alarm: niepotwierdzony rollback; zachowano stan i WIP.');
196
+ }
197
+ // A failed write can leave our HOLD in place; only restore bytes still owned by us.
198
+ try {
199
+ if (!regular(mode.path).equals(mode.expected))
200
+ throw new Error('foreign mode');
201
+ replaceMode(mode.bytes);
202
+ if (digest(regular(mode.path)) !== mode.sha)
203
+ throw new Error('mode SHA');
204
+ }
205
+ catch {
206
+ ctx.err('Alarm: nie potwierdzono przywrócenia bajtów HOST-ACTIVATION.mode.');
207
+ }
208
+ }
209
+ }
210
+ }
211
+ for (const release of [tickRelease, serialRelease, sharedRelease])
212
+ if (release) {
213
+ try {
214
+ release();
215
+ }
216
+ catch {
217
+ ctx.err('Alarm: nie udało się bezpiecznie zwolnić własnej blokady aktualizacji.');
218
+ result = 2;
219
+ }
220
+ }
221
+ tickRelease = serialRelease = sharedRelease = undefined;
222
+ if (board)
223
+ try {
224
+ await board.close();
225
+ }
226
+ catch {
227
+ ctx.err('Alarm: nie udało się zamknąć transportu tablicy.');
228
+ result = 2;
229
+ }
230
+ };
155
231
  try {
156
232
  result = await (async () => {
157
233
  const selected = options.engineConfig ?? ctx.env.ROBISIE_ENGINE_CONFIG;
@@ -172,6 +248,12 @@ export async function runInstallationUpdate(ctx, options, overrides = {}) {
172
248
  }
173
249
  const raw = json(bytes);
174
250
  let config = parseEngineConfig(raw, configPath);
251
+ const host = config.engine.mode === 'host';
252
+ const hostHome = resolve(ctx.cwd, env.HU_HOME || dirname(configPath));
253
+ if (host && stat(join(hostHome, 'AUTO-UPDATE.off'))) {
254
+ ctx.out('Aktualizacja pominięta: AUTO-UPDATE.off.');
255
+ return 0;
256
+ }
175
257
  const manager = ctx.platform === 'linux' ? 'systemctl' : 'launchctl';
176
258
  const domain = `gui/${typeof process.getuid === 'function' ? process.getuid() : 0}`;
177
259
  let managerProbed = false;
@@ -198,6 +280,11 @@ export async function runInstallationUpdate(ctx, options, overrides = {}) {
198
280
  }
199
281
  if (ctx.platform !== 'linux' && ctx.platform !== 'darwin')
200
282
  refuse('Aktualizacja wymaga Linuxa z systemd --user lub macOS z launchd.');
283
+ if (host) {
284
+ const path = env.HU_MODE || join(config.engine.hostPaths?.hostStateDir ?? config.stateDir, 'HOST-ACTIVATION.mode');
285
+ if (!stat(path) || regular(path).toString('utf8').trim().split(/\s+/)[0] !== 'live')
286
+ refuse('Host wymaga HOST-ACTIVATION.mode z tokenem live.');
287
+ }
201
288
  probeManager();
202
289
  if (!regular(configPath).equals(bytes) || io.realpathSync(selectedPath) !== configPath)
203
290
  refuse('Konfiguracja zmieniła się przed zapisem zgody.');
@@ -215,14 +302,19 @@ export async function runInstallationUpdate(ctx, options, overrides = {}) {
215
302
  const repo = io.realpathSync(config.engine.repo), state = io.realpathSync(config.stateDir);
216
303
  if (!stat(repo)?.isDirectory() || !stat(state)?.isDirectory())
217
304
  refuse('Niepoprawne katalogi repo lub stanu.');
218
- const host = config.engine.mode === 'host';
219
305
  const rel = relative(repo, state);
220
306
  if (!host && (rel === '' || rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel)))
221
307
  refuse('Stan klienta musi być poza repo.');
222
308
  if (host ? config.engine.delivery === 'local' : config.engine.delivery !== 'local')
223
309
  refuse('Niepoprawny tryb dostarczenia instalacji.');
224
- const modePath = join(config.engine.hostPaths?.hostStateDir ?? state, 'HOST-ACTIVATION.mode');
310
+ const npm = host && env.HU_NPM ? env.HU_NPM : 'npm';
311
+ if (host && ctx.platform !== 'darwin')
312
+ refuse('Host wymaga istniejącego zegara launchd com.robisie.maszynista.');
313
+ const modePath = host && env.HU_MODE ? resolve(ctx.cwd, env.HU_MODE) : join(config.engine.hostPaths?.hostStateDir ?? state, 'HOST-ACTIVATION.mode');
314
+ const lastTick = host && env.HU_LASTTICK ? resolve(ctx.cwd, env.HU_LASTTICK) : join(state, 'LAST-TICK.md');
225
315
  const modeBytes = stat(modePath) ? regular(modePath) : null;
316
+ if (host && !modeBytes)
317
+ refuse('Host wymaga HOST-ACTIVATION.mode z tokenem live.');
226
318
  if (modeBytes && modeBytes.toString('utf8').trim().split(/\s+/)[0] !== 'live')
227
319
  refuse('HOST-ACTIVATION.mode nie ma tokenu live; aktualizacja odmówiona.');
228
320
  let attempt;
@@ -232,7 +324,7 @@ export async function runInstallationUpdate(ctx, options, overrides = {}) {
232
324
  || io.realpathSync(config.engine.repo) !== repo || io.realpathSync(config.stateDir) !== state)
233
325
  refuse('Konfiguracja lub ścieżki zmieniły się podczas aktualizacji.');
234
326
  const currentMode = stat(modePath) ? regular(modePath) : null;
235
- if (modeBytes ? !currentMode?.equals(modeBytes) : currentMode !== null)
327
+ if (modeBytes ? !currentMode?.equals(mode?.expected ?? modeBytes) : currentMode !== null)
236
328
  refuse('HOST-ACTIVATION.mode zmienił się podczas aktualizacji.');
237
329
  if (attempt && !regular(attempt.path).equals(attempt.saved))
238
330
  refuse('Rejestr prób zmienił się podczas aktualizacji.');
@@ -242,10 +334,36 @@ export async function runInstallationUpdate(ctx, options, overrides = {}) {
242
334
  // Probe manager before any pointer, service, or card mutation.
243
335
  if (!managerProbed)
244
336
  probeManager();
245
- board = await runtime.board(ctx, config);
337
+ if (!host)
338
+ board = await runtime.board(ctx, config);
339
+ const acquireShared = () => {
340
+ const path = join(hostHome, 'auto-update.lock.d');
341
+ try {
342
+ io.mkdirSync(path, { mode: 0o700 });
343
+ }
344
+ catch (error) {
345
+ if (code(error) !== 'EEXIST')
346
+ throw error;
347
+ return null;
348
+ }
349
+ const own = io.lstatSync(path);
350
+ return () => {
351
+ const fresh = stat(path);
352
+ if (!fresh?.isDirectory() || fresh.ino !== own.ino || fresh.dev !== own.dev)
353
+ refuse('Wspólna blokada zmieniła właściciela.');
354
+ io.rmdirSync(path);
355
+ };
356
+ };
357
+ if (host) {
358
+ sharedRelease = acquireShared() ?? undefined;
359
+ if (!sharedRelease) {
360
+ ctx.out('Aktualizacja odroczona: inny aktualizator już działa.');
361
+ return 0;
362
+ }
363
+ }
246
364
  const update = join(state, 'update');
247
365
  privateDir(update);
248
- const auditPath = join(update, 'audit.jsonl');
366
+ const auditPath = host && env.HU_LOG ? env.HU_LOG : join(update, 'audit.jsonl');
249
367
  const append = (path, value) => {
250
368
  if (stat(path) && !stat(path)?.isFile())
251
369
  refuse('Plik stanu aktualizacji nie jest zwykłym plikiem.');
@@ -253,7 +371,55 @@ export async function runInstallationUpdate(ctx, options, overrides = {}) {
253
371
  io.chmodSync(path, 0o600);
254
372
  };
255
373
  const audit = (event, value = {}) => append(auditPath, { at: new Date(runtime.now()).toISOString(), event, ...value });
374
+ const hostRepo = resolve(ctx.cwd, env.HU_APP || repo);
375
+ const inbox = env.HU_SK || join(env.HU_REPO || join(dirname(repo), '_reksio'), 'notes/2026-10-21-plan-20h/SKRZYNKA-CEO.txt');
376
+ const skline = (text) => {
377
+ // Finish fallible audit writes before publishing a success line.
378
+ audit('inbox-delivery-attempt');
379
+ try {
380
+ if (!stat(inbox)?.isFile())
381
+ throw new Error('missing inbox');
382
+ io.appendFileSync(inbox, `${new Date(runtime.now()).toISOString()} ${text}\n`, { flush: true });
383
+ return true;
384
+ }
385
+ catch { /* Missing destinations are never created. */ }
386
+ audit('inbox-undelivered');
387
+ return false;
388
+ };
389
+ const alarm = (text) => {
390
+ if (!host)
391
+ return;
392
+ let delivered = false;
393
+ try {
394
+ if (env.HU_ALARM)
395
+ command(env.HU_ALARM, [`HOST-AUTO→CTO: ${text}`]);
396
+ else {
397
+ const address = regular(join(ctx.home, '.robisie/reksio-cto-surface')).toString('utf8').trim();
398
+ if (!address || /\s/.test(address))
399
+ throw new Error('missing address');
400
+ command('bash', [join(hostRepo, 'scripts/ping-window.sh'), '--modal-guard', '--surface-id', address, `HOST-AUTO→CTO: ${text}`]);
401
+ }
402
+ delivered = true;
403
+ }
404
+ catch {
405
+ ctx.err('Alarm hosta nie został dostarczony do CTO.');
406
+ }
407
+ audit(delivered ? 'alarm-delivered' : 'alarm-undelivered');
408
+ skline(`CTO ESKALACJA HOST-AUTO ${text}`);
409
+ };
410
+ notifyFailure = host ? () => alarm('Aktualizacja nieudana; sprawdź prywatny audyt i potwierdzenie powrotu.') : undefined;
411
+ const legacyState = env.HU_STATE || join(hostHome, 'auto-update.state');
412
+ let legacyAttempt;
256
413
  const defer = () => {
414
+ if (legacyAttempt) {
415
+ if (!regular(legacyState).equals(legacyAttempt.saved))
416
+ refuse('Rejestr starego agenta zmienił się przed odroczeniem.');
417
+ if (legacyAttempt.before === null)
418
+ io.unlinkSync(legacyState);
419
+ else
420
+ io.writeFileSync(legacyState, legacyAttempt.before, { mode: 0o600, flush: true });
421
+ legacyAttempt = undefined;
422
+ }
257
423
  if (attempt) {
258
424
  if (!regular(attempt.path).equals(attempt.saved))
259
425
  refuse('Rejestr prób zmienił się przed odroczeniem.');
@@ -273,11 +439,12 @@ export async function runInstallationUpdate(ctx, options, overrides = {}) {
273
439
  refuse('Nieczytelny rejestr odroczeń.');
274
440
  const since = previous?.since ?? runtime.now();
275
441
  const alarmed = previous?.alarmed === true || runtime.now() - since >= 7_200_000;
442
+ io.writeFileSync(path, JSON.stringify({ since, alarmed }), { mode: 0o600, flush: true });
276
443
  if (alarmed && previous?.alarmed !== true) {
277
444
  audit('deferred-alarm', { since });
278
445
  ctx.err('Alarm: aktualizacja odroczona od co najmniej 7200 sekund.');
446
+ alarm('Aktualizacja odroczona od co najmniej 7200 sekund: Worker w toku.');
279
447
  }
280
- io.writeFileSync(path, JSON.stringify({ since, alarmed }), { mode: 0o600, flush: true });
281
448
  ctx.out('Aktualizacja odroczona: trwa praca fabryki.');
282
449
  return 0;
283
450
  };
@@ -308,6 +475,16 @@ export async function runInstallationUpdate(ctx, options, overrides = {}) {
308
475
  if (stat(join(state, claim + suffix)))
309
476
  refuse('Nierozliczony claim testera lub odbiorcy; zachowaj stan.');
310
477
  }
478
+ if (host) {
479
+ const report = stat(lastTick);
480
+ let workerBusy = false;
481
+ if (report && runtime.now() - report.mtimeMs <= 600_000) {
482
+ const lines = regular(lastTick).toString('utf8').match(/^- detail: wykonania .+$/gm);
483
+ const counter = lines?.length === 1 ? lines[0].match(/^- detail: wykonania (0|[1-9]\d*)\/([1-9]\d*)(?:[ ,;].*)?$/) : null;
484
+ workerBusy = !counter || !Number.isSafeInteger(Number(counter[1])) || !Number.isSafeInteger(Number(counter[2])) || Number(counter[1]) !== 0;
485
+ }
486
+ return { busy: busy || workerBusy, own: [] };
487
+ }
311
488
  const rows = await board.listTasks({ projectId: config.project, statuses: ['in_progress'], detailsKeys: [] });
312
489
  if (!Array.isArray(rows))
313
490
  refuse('Nieczytelna lista kart in_progress.');
@@ -328,11 +505,28 @@ export async function runInstallationUpdate(ctx, options, overrides = {}) {
328
505
  };
329
506
  if ((await preflight()).busy)
330
507
  return defer();
508
+ const hostPlist = host ? env.HU_PLIST || join(ctx.home, 'Library/LaunchAgents/com.robisie.maszynista.plist') : null;
509
+ let hostService;
510
+ if (hostPlist) {
511
+ const original = regular(hostPlist);
512
+ const service = json(Buffer.from(command('plutil', ['-convert', 'json', '-o', '-', hostPlist])));
513
+ const args = service.ProgramArguments;
514
+ if (service.Label !== 'com.robisie.maszynista' || !Array.isArray(args) || args.length !== 7
515
+ || !args.every(arg => typeof arg === 'string') || !isAbsolute(args[0]) || !isAbsolute(args[1])
516
+ || !isDeepStrictEqual(args.slice(2, 6), ['factory', 'run', '--once', '--engine-config'])
517
+ || io.realpathSync(args[6]) !== configPath || !args[1].endsWith('/dist/cli.js')
518
+ || object(service.EnvironmentVariables) && service.EnvironmentVariables.ROBISIE_ENGINE_CONFIG !== undefined
519
+ && io.realpathSync(String(service.EnvironmentVariables.ROBISIE_ENGINE_CONFIG)) !== configPath)
520
+ refuse('Niepoprawna tożsamość hostowego plista, paczki lub konfiguracji.');
521
+ hostService = { original, current: original, prepared: Buffer.alloc(0), cli: args[1], originalCli: args[1] };
522
+ }
331
523
  const pointer = join(update, 'current');
332
524
  if (stat(pointer) && !stat(pointer)?.isSymbolicLink())
333
525
  refuse('Żywy wskaźnik musi być dowiązaniem aktualizatora.');
334
- const previous = stat(pointer) ? io.realpathSync(pointer) : io.realpathSync(fileURLToPath(new URL('../', runtime.moduleUrl)));
526
+ const previous = stat(pointer) ? io.realpathSync(pointer) : io.realpathSync(hostService ? join(dirname(hostService.cli), '..') : fileURLToPath(new URL('../', runtime.moduleUrl)));
335
527
  pointerSnapshot = { path: pointer, target: stat(pointer) ? previous : null };
528
+ if (hostService && io.realpathSync(hostService.cli) !== join(previous, 'dist/cli.js'))
529
+ refuse('Wskaźnik nie steruje paczką hostowego zegara.');
336
530
  const oldPackage = json(regular(join(previous, 'package.json')));
337
531
  const oldBuild = json(regular(join(previous, 'dist/engine/build-id.json')));
338
532
  const validBuild = (build) => {
@@ -341,7 +535,7 @@ export async function runInstallationUpdate(ctx, options, overrides = {}) {
341
535
  return build.sha;
342
536
  };
343
537
  const oldSha = validBuild(oldBuild);
344
- const metadata = JSON.parse(command('npm', ['view', 'robisie@latest', 'version', 'gitHead', 'dist', '--json']));
538
+ const metadata = JSON.parse(command(npm, ['view', 'robisie@latest', 'version', 'gitHead', 'dist', '--json']));
345
539
  if (!object(metadata) || !object(metadata.dist) || typeof metadata.dist.integrity !== 'string' || !/^sha(?:256|384|512)-\S+$/.test(metadata.dist.integrity)
346
540
  || typeof metadata.gitHead !== 'string' || !/^[a-f0-9]{40}$/.test(metadata.gitHead))
347
541
  refuse('Niepoprawne metadane npm: wymagane gitHead i integralność.');
@@ -350,6 +544,13 @@ export async function runInstallationUpdate(ctx, options, overrides = {}) {
350
544
  ctx.out('Zainstalowana wersja robisie jest aktualna; brak downgrade.');
351
545
  return 0;
352
546
  }
547
+ if (host && stat(legacyState)) {
548
+ const lines = regular(legacyState).toString('utf8').split('\n').filter(Boolean);
549
+ if (lines.some(line => !/^\d+\.\d+\.\d+ \S+ .+$/.test(line)))
550
+ refuse('Nieczytelny rejestr prób starego agenta.');
551
+ if (lines.some(line => line.split(' ')[0] === latest))
552
+ refuse('Ta wersja była już próbowana przez starego agenta; wyjaśnij wpis auto-update.state.');
553
+ }
353
554
  const attempts = join(update, 'attempts.jsonl');
354
555
  const attemptBytes = stat(attempts) ? regular(attempts) : null;
355
556
  if (attemptBytes)
@@ -393,6 +594,11 @@ export async function runInstallationUpdate(ctx, options, overrides = {}) {
393
594
  check();
394
595
  if (attemptBytes ? !regular(attempts).equals(attemptBytes) : stat(attempts) !== null)
395
596
  refuse('Rejestr prób zmienił się podczas aktualizacji.');
597
+ if (host) {
598
+ const before = stat(legacyState) ? regular(legacyState) : null;
599
+ io.appendFileSync(legacyState, `${latest} ATTEMPT ${new Date(runtime.now()).toISOString()}\n`, { mode: 0o600, flush: true });
600
+ legacyAttempt = { before, saved: regular(legacyState) };
601
+ }
396
602
  append(attempts, { version: latest, at: new Date(runtime.now()).toISOString() });
397
603
  attempt = { path: attempts, before: attemptBytes, saved: regular(attempts) };
398
604
  audit('attempt', { version: latest, previous: oldSha });
@@ -400,7 +606,7 @@ export async function runInstallationUpdate(ctx, options, overrides = {}) {
400
606
  privateDir(releases);
401
607
  const release = io.mkdtempSync(join(releases, `robisie-${latest}-`));
402
608
  io.writeFileSync(join(release, 'package.json'), JSON.stringify({ private: true }) + '\n', { flag: 'wx', mode: 0o600, flush: true });
403
- command('npm', ['install', `robisie@${latest}`, '--ignore-scripts', '--no-audit', '--no-fund', '--save-exact'], release);
609
+ command(npm, ['install', `robisie@${latest}`, '--ignore-scripts', '--no-audit', '--no-fund', '--save-exact'], release);
404
610
  const next = join(release, 'node_modules/robisie');
405
611
  const build = json(regular(join(next, 'dist/engine/build-id.json'))), sha = validBuild(build);
406
612
  const lock = json(regular(join(release, 'package-lock.json')));
@@ -424,7 +630,7 @@ import {spawnSync} from 'node:child_process';
424
630
  try {
425
631
  const root=realpathSync(${JSON.stringify(pointer)});
426
632
  const env={...process.env};
427
- if(process.argv[2]==='factory') {
633
+ if(process.argv[2]==='factory' && ${JSON.stringify(!host)}) {
428
634
  const {readKey}=await import(pathToFileURL(join(root,'dist/manifest.js')).href);
429
635
  const dir=${JSON.stringify(agentPaths(ctx).clientDir)};
430
636
  env.ROBISIE_KEY=readKey(dir);
@@ -445,9 +651,17 @@ try {
445
651
  io.mkdirSync(unitDir, { recursive: true, mode: 0o700 });
446
652
  const factoryArgs = ['factory', 'run', '--once', '--engine-config', configPath];
447
653
  const updateArgs = ['update', '--engine-config', configPath];
448
- const factoryName = ctx.platform === 'linux' ? 'robisie-factory' : 'com.robisie.factory';
654
+ const factoryName = ctx.platform === 'linux' ? 'robisie-factory' : host ? 'com.robisie.maszynista' : 'com.robisie.factory';
449
655
  const ensureOwned = () => {
450
- if (ctx.platform === 'linux') {
656
+ if (hostService && hostPlist) {
657
+ if (!regular(hostPlist).equals(hostService.current))
658
+ refuse('Hostowy plist zmienił się podczas aktualizacji.');
659
+ const loaded = runtime.exec(manager, ['print', `${domain}/${factoryName}`], ctx.cwd, env);
660
+ if (loaded.signal !== null || loaded.status !== 113 && (loaded.status !== 0 || !loaded.stdout.includes(configPath)
661
+ || !loaded.stdout.includes(hostService.cli)))
662
+ refuse('Niepotwierdzona tożsamość załadowanego zegara hosta.');
663
+ }
664
+ else if (ctx.platform === 'linux') {
451
665
  for (const name of [factoryName, 'robisie-update']) {
452
666
  const info = runtime.exec(manager, ['--user', 'show', `${name}.service`, '--property=LoadState,ActiveState,ExecStart', '--value'], ctx.cwd, env);
453
667
  if (info.signal !== null || info.status !== 0 && !(info.status === 1 && /^not-found$/m.test(info.stdout)))
@@ -468,30 +682,69 @@ try {
468
682
  };
469
683
  ensureOwned();
470
684
  writeManaged(launcher, launcherText);
685
+ if (hostService && hostPlist) {
686
+ const service = json(Buffer.from(command('plutil', ['-convert', 'json', '-o', '-', hostPlist])));
687
+ const args = service.ProgramArguments;
688
+ service.ProgramArguments = [args[0], join(pointer, 'dist/cli.js'), ...args.slice(2)];
689
+ const preparedPath = join(update, 'host.prepared.plist');
690
+ io.writeFileSync(preparedPath, JSON.stringify(service), { mode: 0o600, flush: true });
691
+ command('plutil', ['-convert', 'xml1', preparedPath]);
692
+ hostService.prepared = regular(preparedPath);
693
+ const backup = join(update, 'host.plist.backup');
694
+ io.writeFileSync(backup, hostService.original, { mode: 0o600, flush: true });
695
+ io.chmodSync(backup, 0o600);
696
+ if (!regular(backup).equals(hostService.original))
697
+ refuse('Niepotwierdzona kopia hostowego plista.');
698
+ }
471
699
  const xml = (text) => text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&apos;');
472
700
  const systemArg = (text, execution = false) => '"' + text.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/%/g, '%%').replace(/\$/g, () => execution ? '$$' : '$').replace(/\n/g, '\\n').replace(/\r/g, '\\r') + '"';
473
- const unitEnv = Object.entries({ HOME: ctx.home, PATH: ctx.env.PATH, CODEX_HOME: ctx.env.CODEX_HOME, XDG_CONFIG_HOME: ctx.env.XDG_CONFIG_HOME })
701
+ const unitEnv = Object.entries({ ...(host ? Object.fromEntries(Object.entries(env).filter(([key]) => /^HU_(?:HOME|MODE|LASTTICK|SK|REPO|APP|PLIST|CHECKOUT|LOG|STATE|NPM|ALARM)$/.test(key))) : {}), HOME: ctx.home, PATH: ctx.env.PATH, CODEX_HOME: ctx.env.CODEX_HOME, XDG_CONFIG_HOME: ctx.env.XDG_CONFIG_HOME })
474
702
  .filter((entry) => entry[1] !== undefined);
703
+ let hostUpdateUnit;
475
704
  for (const [name, args] of [['factory', factoryArgs], ['update', updateArgs]]) {
705
+ if (host && name === 'factory')
706
+ continue;
476
707
  if (ctx.platform === 'linux') {
477
708
  // Tick and update own their deadlines, including the separate rollback health window.
478
709
  writeManaged(join(unitDir, `robisie-${name}.service`), `# robisie:update-managed\n[Unit]\nDescription=robisie ${name}\n[Service]\nType=oneshot\nTimeoutStartSec=infinity\n${unitEnv.map(([key, value]) => `Environment=${systemArg(`${key}=${value}`)}\n`).join('')}WorkingDirectory=${systemArg(ctx.cwd)}\nExecStart=${[runtime.node, launcher, ...args].map(arg => systemArg(arg, true)).join(' ')}\n`);
479
710
  writeManaged(join(unitDir, `robisie-${name}.timer`), `# robisie:update-managed\n[Unit]\nDescription=robisie ${name}\n[Timer]\nOnBootSec=120s\nOnUnitInactiveSec=120s\nUnit=robisie-${name}.service\n[Install]\nWantedBy=timers.target\n`);
480
711
  }
481
712
  else {
482
- writeManaged(join(unitDir, `com.robisie.${name}.plist`), `<?xml version="1.0" encoding="UTF-8"?>\n<!-- robisie:update-managed -->\n<plist version="1.0"><dict><key>Label</key><string>com.robisie.${name}</string><key>ProgramArguments</key><array>${[runtime.node, launcher, ...args].map(arg => `<string>${xml(arg)}</string>`).join('')}</array><key>EnvironmentVariables</key><dict>${unitEnv.map(([key, value]) => `<key>${xml(key)}</key><string>${xml(value)}</string>`).join('')}</dict><key>WorkingDirectory</key><string>${xml(ctx.cwd)}</string><key>StartInterval</key><integer>120</integer></dict></plist>\n`);
713
+ const path = join(unitDir, `com.robisie.${name}.plist`);
714
+ const content = `<?xml version="1.0" encoding="UTF-8"?>\n<!-- robisie:update-managed -->\n<plist version="1.0"><dict><key>Label</key><string>com.robisie.${name}</string><key>ProgramArguments</key><array>${[runtime.node, launcher, ...args].map(arg => `<string>${xml(arg)}</string>`).join('')}</array><key>EnvironmentVariables</key><dict>${unitEnv.map(([key, value]) => `<key>${xml(key)}</key><string>${xml(value)}</string>`).join('')}</dict><key>WorkingDirectory</key><string>${xml(ctx.cwd)}</string><key>StartInterval</key><integer>120</integer></dict></plist>\n`;
715
+ if (host)
716
+ hostUpdateUnit = { path, content };
717
+ else
718
+ writeManaged(path, content);
483
719
  }
484
720
  }
485
721
  const switchPointer = (target) => {
486
- const temporary = join(update, `.current-${runtime.pid}`);
722
+ const directory = io.mkdtempSync(join(update, '.pointer-')), temporary = join(directory, 'current');
487
723
  io.symlinkSync(target, temporary);
488
- io.renameSync(temporary, pointer);
724
+ try {
725
+ io.renameSync(temporary, pointer);
726
+ }
727
+ finally {
728
+ if (stat(pointer) && io.realpathSync(pointer) === io.realpathSync(target))
729
+ pointerSnapshot = { path: pointer, target: io.realpathSync(target) };
730
+ }
489
731
  if (io.realpathSync(pointer) !== io.realpathSync(target))
490
732
  refuse('Niepotwierdzona wymiana wskaźnika.');
491
- pointerSnapshot = { path: pointer, target: io.realpathSync(target) };
733
+ io.rmdirSync(directory);
492
734
  };
493
735
  const start = () => {
494
- if (ctx.platform === 'linux') {
736
+ if (host && hostPlist) {
737
+ command(manager, ['bootstrap', domain, hostPlist]);
738
+ const loaded = runtime.exec(manager, ['print', `${domain}/com.robisie.update`], ctx.cwd, env);
739
+ if (loaded.signal !== null || loaded.status !== 0 && loaded.status !== 113)
740
+ refuse('Nieustalony stan zegara aktualizacji.');
741
+ if (loaded.status === 113)
742
+ command(manager, ['bootstrap', domain, join(unitDir, 'com.robisie.update.plist')]);
743
+ else if (!loaded.stdout.includes(launcher))
744
+ refuse('Obcy zegar aktualizacji hosta.');
745
+ command(manager, ['kickstart', `${domain}/${factoryName}`]);
746
+ }
747
+ else if (ctx.platform === 'linux') {
495
748
  command(manager, ['--user', 'daemon-reload']);
496
749
  command(manager, ['--user', 'enable', '--now', 'robisie-factory.timer', 'robisie-update.timer']);
497
750
  command(manager, ['--user', 'reset-failed', 'robisie-factory.service']);
@@ -516,6 +769,8 @@ try {
516
769
  }
517
770
  };
518
771
  const refresh = (root) => {
772
+ if (host)
773
+ return;
519
774
  // Reuse the package's installer/doctor with file-backed A/B, never a new role installer.
520
775
  const key = readKey(agentPaths(ctx).clientDir), reviewKey = readKey(agentPaths(ctx).clientDir, 'review-key');
521
776
  const childEnv = { ...env };
@@ -576,7 +831,7 @@ try {
576
831
  let highestTick = BigInt(0);
577
832
  const rememberTick = () => {
578
833
  try {
579
- const report = regular(join(state, 'LAST-TICK.md')).toString('utf8');
834
+ const report = regular(lastTick).toString('utf8');
580
835
  const tick = report.match(/^- tick: ([1-9]\d*)$/m)?.[1];
581
836
  if (tick) {
582
837
  priorTicks.add(tick);
@@ -598,7 +853,7 @@ try {
598
853
  return false;
599
854
  let report;
600
855
  try {
601
- report = regular(join(state, 'LAST-TICK.md')).toString('utf8');
856
+ report = regular(lastTick).toString('utf8');
602
857
  }
603
858
  catch {
604
859
  continue;
@@ -623,22 +878,100 @@ try {
623
878
  return false;
624
879
  };
625
880
  if (modeBytes) {
626
- mode = { path: modePath, bytes: modeBytes };
881
+ mode = { path: modePath, bytes: modeBytes, expected: modeBytes, sha: digest(modeBytes) };
627
882
  const backup = join(update, 'HOST-ACTIVATION.mode.backup');
628
883
  if (stat(backup) && !stat(backup)?.isFile())
629
884
  refuse('Kopia trybu hosta nie jest zwykłym plikiem.');
630
885
  io.writeFileSync(backup, modeBytes, { mode: 0o600, flush: true });
886
+ io.chmodSync(backup, 0o600);
887
+ if (host)
888
+ modeRestored = () => audit('mode-restored', { sha256: digest(modeBytes), matching: true });
631
889
  if (!regular(backup).equals(modeBytes))
632
890
  refuse('Niepotwierdzona kopia bajtów HOST-ACTIVATION.mode.');
633
891
  }
892
+ const replaceHostService = (restoring) => {
893
+ if (!hostService || !hostPlist)
894
+ return;
895
+ const target = restoring ? hostService.original : hostService.prepared;
896
+ const temporary = `${hostPlist}.${restoring ? 'return' : 'update'}-${runtime.pid}`;
897
+ io.writeFileSync(temporary, target, { flag: 'wx', mode: 0o600, flush: true });
898
+ if (!regular(temporary).equals(target))
899
+ refuse('Niepotwierdzony przygotowany plist hosta.');
900
+ ensureOwned();
901
+ const loaded = runtime.exec(manager, ['print', `${domain}/${factoryName}`], ctx.cwd, env);
902
+ if (loaded.signal !== null || loaded.status !== 0 && loaded.status !== 113)
903
+ refuse('Nieustalony stan hosta przed wymianą usługi.');
904
+ if (loaded.status === 0)
905
+ command(manager, ['bootout', `${domain}/${factoryName}`]);
906
+ try {
907
+ io.renameSync(temporary, hostPlist);
908
+ }
909
+ finally {
910
+ if (regular(hostPlist).equals(target)) {
911
+ hostService.current = target;
912
+ hostService.cli = restoring ? hostService.originalCli : join(pointer, 'dist/cli.js');
913
+ }
914
+ }
915
+ if (!regular(hostPlist).equals(target))
916
+ refuse('Niepotwierdzony zapis hostowego plista.');
917
+ };
918
+ const rollbackAudit = (event, value = {}) => {
919
+ try {
920
+ audit(event, value);
921
+ }
922
+ catch {
923
+ ctx.err('Alarm: błąd audytu powrotu.');
924
+ }
925
+ };
926
+ const restorePrevious = async () => {
927
+ // Final confirmation runs after cleanup, so regain serialization before attempting a return.
928
+ if (host && !sharedRelease) {
929
+ sharedRelease = acquireShared() ?? undefined;
930
+ if (!sharedRelease)
931
+ refuse('Alarm: inny aktualizator uniemożliwia powrót; poprzednia wersja niepotwierdzona.');
932
+ }
933
+ if (!serialRelease)
934
+ serialRelease = acquire(join(update, '.update.lock')) ?? undefined;
935
+ if (!serialRelease)
936
+ refuse('Alarm: blokada aktualizacji uniemożliwia powrót; poprzednia wersja niepotwierdzona.');
937
+ if (!tickRelease)
938
+ tickRelease = acquire(join(state, '.tick.lock')) ?? undefined;
939
+ if (!tickRelease)
940
+ refuse('Alarm: blokada taktu uniemożliwia powrót; poprzednia wersja niepotwierdzona.');
941
+ if (host && mode && mode.expected.equals(mode.bytes))
942
+ replaceMode(Buffer.from(`off # robisie update HOLD ${runtime.pid}\n`));
943
+ const locked = await preflight();
944
+ if (locked.busy || locked.own.length)
945
+ refuse('Alarm: nowa praca pod blokadą uniemożliwia powrót.');
946
+ ensureOwned();
947
+ rememberTick();
948
+ replaceHostService(true);
949
+ const restoredAt = runtime.now();
950
+ switchPointer(previous);
951
+ rollbackAudit('restored', { sha: oldSha, failed: sha });
952
+ const restarted = activate(previous, oldSha, 'rollback-start-failed');
953
+ const confirmed = restarted && await health(oldSha, restoredAt, 'old-tick', 'rollback-start-failed');
954
+ rollbackAudit(confirmed ? 'rollback-confirmed' : 'rollback-unconfirmed', { sha: oldSha, failed: sha });
955
+ ctx.err(confirmed ? 'Nowa wersja nie wstała; powrót potwierdzony dwoma świeżymi taktami OK.' : 'Alarm: nie potwierdzono zdrowia poprzedniej wersji po powrocie.');
956
+ };
634
957
  ensureOwned();
958
+ if (host && mode) {
959
+ replaceMode(Buffer.from(`off # robisie update HOLD ${runtime.pid}\n`));
960
+ if (!regular(mode.path).equals(mode.expected))
961
+ refuse('Niepotwierdzony HOLD aktywacji.');
962
+ audit('activation-held', { sha256: mode.sha });
963
+ }
635
964
  const activating = await preflight();
636
- if (activating.busy)
637
- return defer();
638
- if (activating.own.length)
965
+ if (activating.busy || activating.own.length) {
966
+ rollback = undefined;
639
967
  return defer();
968
+ }
640
969
  rememberTick();
641
970
  const switchedAt = runtime.now();
971
+ rollback = restorePrevious;
972
+ if (hostUpdateUnit)
973
+ writeManaged(hostUpdateUnit.path, hostUpdateUnit.content);
974
+ replaceHostService(false);
642
975
  switchPointer(next);
643
976
  audit('switched', { sha, previous: oldSha });
644
977
  const started = activate(next, sha, 'start-failed');
@@ -648,67 +981,82 @@ try {
648
981
  io.unlinkSync(join(update, 'deferred.json'));
649
982
  completed = true;
650
983
  result = 0;
984
+ if (host)
985
+ afterCleanup = async () => {
986
+ const checkout = env.HU_CHECKOUT || repo, deadline = runtime.now() + 480_000;
987
+ const checkoutHead = () => {
988
+ try {
989
+ return command('git', ['-C', checkout, 'rev-parse', 'HEAD']).trim();
990
+ }
991
+ catch {
992
+ return null;
993
+ } // Checkout convergence is advisory; this command never applies the FF.
994
+ };
995
+ let head = checkoutHead();
996
+ while (head !== sha && runtime.now() < deadline) {
997
+ await runtime.sleep(20_000);
998
+ head = checkoutHead();
999
+ }
1000
+ audit('checkout-observed', { matches: head === sha });
1001
+ if (!skline(`CTO GOTOWE/DO-CEO HOST-AUTO aktualizacja ${latest}; dwa świeże takty OK; mode SHA ZGODNA; ${head === sha ? 'checkout zgodny z gitHead' : 'UWAGA checkout jeszcze niezgodny z gitHead'}`))
1002
+ refuse('Nie dostarczono potwierdzenia aktualizacji do skrzynki hosta.');
1003
+ };
651
1004
  }
652
1005
  else {
653
- // New work prevents rollback, exactly as it prevents forward activation.
654
- const rollbackPre = await preflight();
655
- if (rollbackPre.busy || rollbackPre.own.length)
656
- refuse('Alarm: nowa praca blokuje powrót; poprzednia wersja niepotwierdzona.');
657
- tickRelease = acquire(join(state, '.tick.lock')) ?? undefined;
658
- if (!tickRelease)
659
- refuse('Alarm: blokada taktu uniemożliwia powrót; poprzednia wersja niepotwierdzona.');
660
- const rollbackLocked = await preflight();
661
- if (rollbackLocked.busy || rollbackLocked.own.length)
662
- refuse('Alarm: nowa praca pod blokadą uniemożliwia powrót.');
663
- ensureOwned();
664
- rememberTick();
665
- const restoredAt = runtime.now();
666
- switchPointer(previous);
667
- audit('restored', { sha: oldSha, failed: sha });
668
- const restarted = activate(previous, oldSha, 'rollback-start-failed');
669
- const confirmed = restarted && await health(oldSha, restoredAt, 'old-tick', 'rollback-start-failed');
670
- audit(confirmed ? 'rollback-confirmed' : 'rollback-unconfirmed', { sha: oldSha, failed: sha });
671
- ctx.err(confirmed ? 'Nowa wersja nie wstała; powrót potwierdzony dwoma świeżymi taktami OK.' : 'Alarm: nie potwierdzono zdrowia poprzedniej wersji po powrocie.');
1006
+ const restore = rollback;
1007
+ rollback = undefined;
1008
+ await restore();
672
1009
  result = 1;
673
1010
  }
674
1011
  return result;
675
1012
  })();
676
1013
  }
677
1014
  catch (error) {
678
- ctx.err(error instanceof RobisieError ? error.message : 'Odmowa aktualizacji: błąd IO, konfiguracji, transportu lub audytu; nie ponawiaj niepewnego zapisu.');
679
- result = 2;
680
- }
681
- finally {
682
- if (mode) {
1015
+ if (rollback) {
1016
+ const restore = rollback;
1017
+ rollback = undefined;
683
1018
  try {
684
- io.writeFileSync(mode.path, mode.bytes, { mode: 0o600, flush: true });
685
- if (!regular(mode.path).equals(mode.bytes))
686
- throw new Error('mode bytes');
1019
+ await restore();
687
1020
  }
688
1021
  catch {
689
- ctx.err('Alarm: nie potwierdzono przywrócenia bajtów HOST-ACTIVATION.mode.');
690
- result = 2;
1022
+ ctx.err('Alarm: niepotwierdzony rollback; zachowano stan i WIP.');
691
1023
  }
692
1024
  }
693
- for (const release of [tickRelease, serialRelease])
694
- if (release) {
1025
+ ctx.err(error instanceof RobisieError ? error.message : 'Odmowa aktualizacji: błąd IO, konfiguracji, transportu lub audytu; nie ponawiaj niepewnego zapisu.');
1026
+ result = 2;
1027
+ }
1028
+ finally {
1029
+ await cleanup();
1030
+ }
1031
+ if (completed && result === 0 && afterCleanup) {
1032
+ try {
1033
+ await afterCleanup();
1034
+ }
1035
+ catch {
1036
+ result = 2;
1037
+ ctx.err('Alarm: błąd potwierdzenia lub audytu hosta po cleanup.');
1038
+ if (rollback) {
1039
+ const restore = rollback;
1040
+ rollback = undefined;
695
1041
  try {
696
- release();
1042
+ await restore();
697
1043
  }
698
1044
  catch {
699
- ctx.err('Alarm: nie udało się bezpiecznie zwolnić własnej blokady aktualizacji.');
700
- result = 2;
1045
+ ctx.err('Alarm: niepotwierdzony rollback; zachowano stan i WIP.');
1046
+ }
1047
+ finally {
1048
+ await cleanup();
701
1049
  }
702
1050
  }
703
- if (board)
704
- try {
705
- await board.close();
706
- }
707
- catch {
708
- ctx.err('Alarm: nie udało się zamknąć transportu tablicy.');
709
- result = 2;
710
- }
1051
+ }
711
1052
  }
1053
+ if (result !== 0 && notifyFailure)
1054
+ try {
1055
+ notifyFailure();
1056
+ }
1057
+ catch {
1058
+ ctx.err('Alarm: błąd dostawy lub audytu alarmu hosta.');
1059
+ }
712
1060
  if (completed && result === 0)
713
1061
  ctx.out('Aktualizacja potwierdzona dwoma świeżymi taktami OK.');
714
1062
  return result;