robisie 0.5.44 → 0.5.46

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.
@@ -0,0 +1,696 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import * as fs from 'node:fs';
3
+ import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
4
+ import { createInterface } from 'node:readline/promises';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { isDeepStrictEqual } from 'node:util';
7
+ import { agentPaths } from './agents.js';
8
+ import { RobisieError } from './context.js';
9
+ import { CONFIG_FILE, parseEngineConfig } from './engine-config.js';
10
+ import { readKey } from './manifest.js';
11
+ import { PlanerClient } from './planer-client.js';
12
+ function refuse(message) {
13
+ throw new RobisieError(message, 'Sprawdź konfigurację i prywatny audyt w <stateDir>/update; usuń przyczynę przed kolejnym wywołaniem update.');
14
+ }
15
+ function code(error) { return error?.code; }
16
+ function object(raw) { return raw !== null && typeof raw === 'object' && !Array.isArray(raw); }
17
+ function json(bytes) {
18
+ const raw = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes).replace(/^\uFEFF/, ''));
19
+ if (!object(raw))
20
+ refuse('Wymagany obiekt JSON.');
21
+ return raw;
22
+ }
23
+ function version(raw) {
24
+ if (typeof raw !== 'string' || !/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(raw))
25
+ refuse('Niepoprawna stabilna wersja npm.');
26
+ const parts = raw.split('.').map(Number);
27
+ if (!parts.every(Number.isSafeInteger))
28
+ refuse('Niepoprawna wersja npm.');
29
+ return parts;
30
+ }
31
+ function newer(candidate, current) {
32
+ const next = version(candidate), old = version(current);
33
+ for (let i = 0; i < 3; i++)
34
+ if (next[i] !== old[i])
35
+ return next[i] > old[i];
36
+ return false;
37
+ }
38
+ async function connectBoard(ctx, config) {
39
+ // Host DB queries remain in the host. Never import DB or execute tick to obtain them.
40
+ if (config.engine.mode === 'host')
41
+ refuse('Brak dostępnej hostowej drogi tablicy poza tick.ts; aktualizacja odmówiona.');
42
+ const token = readKey(agentPaths(ctx).clientDir);
43
+ if (!token)
44
+ refuse('Brak zapisanego klucza instalacji; uruchom npx robisie init.');
45
+ const client = new PlanerClient({ origin: ctx.env.MASZYNISTA_PLANNER_ORIGIN || ctx.origin, token, fetch: ctx.fetch });
46
+ try {
47
+ await client.connect();
48
+ return client;
49
+ }
50
+ catch {
51
+ await client.close();
52
+ refuse('Nie można połączyć tablicy instalacji.');
53
+ }
54
+ }
55
+ export async function runInstallationUpdate(ctx, options, overrides = {}) {
56
+ const runtime = {
57
+ fs, exec: (command, args, cwd, env) => {
58
+ const result = spawnSync(command, args, { cwd, env, encoding: 'utf8', shell: false, timeout: 120_000, maxBuffer: 4 * 1024 * 1024 });
59
+ return { status: result.status, signal: result.signal, stdout: result.stdout };
60
+ }, kill: process.kill, now: Date.now, sleep: ms => new Promise(done => setTimeout(done, ms)),
61
+ interactive: Boolean(process.stdin.isTTY && process.stdout.isTTY),
62
+ ask: async (question) => {
63
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
64
+ try {
65
+ return await rl.question(question);
66
+ }
67
+ finally {
68
+ rl.close();
69
+ }
70
+ }, moduleUrl: import.meta.url, node: process.execPath, pid: process.pid, board: connectBoard, ...overrides,
71
+ };
72
+ const io = runtime.fs;
73
+ let board, serialRelease, tickRelease;
74
+ let mode;
75
+ let result = 2;
76
+ let completed = false;
77
+ const env = { ...ctx.env };
78
+ const command = (name, args, cwd = ctx.cwd) => {
79
+ const outcome = runtime.exec(name, args, cwd, env);
80
+ if (outcome.status !== 0 || outcome.signal !== null)
81
+ refuse('Polecenie aktualizacji nie zakończyło się poprawnie.');
82
+ return outcome.stdout;
83
+ };
84
+ const stat = (path) => {
85
+ try {
86
+ return io.lstatSync(path);
87
+ }
88
+ catch (error) {
89
+ if (code(error) === 'ENOENT')
90
+ return null;
91
+ throw error;
92
+ }
93
+ };
94
+ const regular = (path) => {
95
+ if (!stat(path)?.isFile())
96
+ refuse('Wymagany zwykły czytelny plik instalacji.');
97
+ return io.readFileSync(path);
98
+ };
99
+ const privateDir = (path) => {
100
+ io.mkdirSync(path, { recursive: true, mode: 0o700 });
101
+ if (!stat(path)?.isDirectory())
102
+ refuse('Katalog aktualizacji nie może być dowiązaniem.');
103
+ io.chmodSync(path, 0o700);
104
+ };
105
+ const acquire = (path) => {
106
+ const previous = stat(path);
107
+ if (previous) {
108
+ if (!previous.isFile())
109
+ refuse('Nieczytelna blokada aktualizacji.');
110
+ const bytes = regular(path), token = bytes.toString('utf8');
111
+ if (!/^[1-9]\d*$/.test(token) || !Number.isSafeInteger(Number(token)))
112
+ refuse('Nieczytelny PID blokady; odmowa.');
113
+ try {
114
+ runtime.kill(Number(token), 0);
115
+ return null;
116
+ }
117
+ catch (error) {
118
+ if (code(error) !== 'ESRCH')
119
+ refuse('Nie można ustalić stanu procesu blokady.');
120
+ }
121
+ const fresh = stat(path);
122
+ if (!fresh || fresh.ino !== previous.ino || fresh.dev !== previous.dev || !regular(path).equals(bytes))
123
+ refuse('Blokada zmieniła się podczas kontroli.');
124
+ io.unlinkSync(path);
125
+ }
126
+ let fd;
127
+ try {
128
+ fd = io.openSync(path, 'wx', 0o600);
129
+ }
130
+ catch (error) {
131
+ if (code(error) === 'EEXIST')
132
+ return null;
133
+ throw error;
134
+ }
135
+ let own;
136
+ const token = String(runtime.pid);
137
+ try {
138
+ io.writeFileSync(fd, token);
139
+ io.fsyncSync(fd);
140
+ own = io.fstatSync(fd);
141
+ }
142
+ finally {
143
+ io.closeSync(fd);
144
+ }
145
+ return () => {
146
+ const fresh = stat(path);
147
+ if (!fresh || fresh.ino !== own.ino || fresh.dev !== own.dev || regular(path).toString('utf8') !== token)
148
+ refuse('Własna blokada zmieniła się; nie usunięto cudzej blokady.');
149
+ io.unlinkSync(path);
150
+ };
151
+ };
152
+ try {
153
+ result = await (async () => {
154
+ const selected = options.engineConfig ?? ctx.env.ROBISIE_ENGINE_CONFIG;
155
+ if (selected !== undefined && selected !== null && !selected.trim())
156
+ refuse('Pusta ścieżka konfiguracji silnika.');
157
+ const selectedPath = resolve(ctx.cwd, selected ?? CONFIG_FILE);
158
+ let bytes, configPath;
159
+ try {
160
+ configPath = io.realpathSync(selectedPath);
161
+ bytes = regular(configPath);
162
+ }
163
+ catch (error) {
164
+ if (code(error) !== 'ENOENT' || selected !== undefined && selected !== null || stat(selectedPath))
165
+ throw error;
166
+ command('npm', ['install', 'robisie@latest']);
167
+ ctx.out('Zainstalowano robisie@latest; uruchom npx robisie init.');
168
+ return 0;
169
+ }
170
+ const raw = json(bytes);
171
+ let config = parseEngineConfig(raw, configPath);
172
+ if (!config.update?.enabled) {
173
+ if (!runtime.interactive || config.update?.enabled === false) {
174
+ ctx.out('Aktualizacja pominięta: brak włączonej zgody w konfiguracji.');
175
+ return 0;
176
+ }
177
+ const answer = await runtime.ask('Czy włączyć automatyczne aktualizacje robisie co 120 sekund z kontrolowanym powrotem? [Tak/Nie] ');
178
+ if (!/^(tak|t)$/i.test(answer.trim())) {
179
+ ctx.out('Aktualizacja pominięta bez zmiany zgody.');
180
+ return 0;
181
+ }
182
+ if (!regular(configPath).equals(bytes) || io.realpathSync(selectedPath) !== configPath)
183
+ refuse('Konfiguracja zmieniła się przed zapisem zgody.');
184
+ raw.update = { consentedAt: new Date(runtime.now()).toISOString(), enabled: true };
185
+ const temporary = `${configPath}.update-${runtime.pid}`;
186
+ io.writeFileSync(temporary, JSON.stringify(raw, null, 2) + '\n', { flag: 'wx', mode: 0o600, flush: true });
187
+ if (!regular(configPath).equals(bytes))
188
+ refuse('Konfiguracja zmieniła się przed zapisem zgody.');
189
+ io.renameSync(temporary, configPath);
190
+ bytes = regular(configPath);
191
+ config = parseEngineConfig(json(bytes), configPath);
192
+ }
193
+ if (ctx.platform !== 'linux' && ctx.platform !== 'darwin')
194
+ refuse('Aktualizacja wymaga Linuxa z systemd --user lub macOS z launchd.');
195
+ const repo = io.realpathSync(config.engine.repo), state = io.realpathSync(config.stateDir);
196
+ if (!stat(repo)?.isDirectory() || !stat(state)?.isDirectory())
197
+ refuse('Niepoprawne katalogi repo lub stanu.');
198
+ const host = config.engine.mode === 'host';
199
+ const rel = relative(repo, state);
200
+ if (!host && (rel === '' || rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel)))
201
+ refuse('Stan klienta musi być poza repo.');
202
+ if (host ? config.engine.delivery === 'local' : config.engine.delivery !== 'local')
203
+ refuse('Niepoprawny tryb dostarczenia instalacji.');
204
+ const modePath = join(config.engine.hostPaths?.hostStateDir ?? state, 'HOST-ACTIVATION.mode');
205
+ const modeBytes = stat(modePath) ? regular(modePath) : null;
206
+ if (modeBytes && modeBytes.toString('utf8').trim().split(/\s+/)[0] !== 'live')
207
+ refuse('HOST-ACTIVATION.mode nie ma tokenu live; aktualizacja odmówiona.');
208
+ let attempt;
209
+ let pointerSnapshot;
210
+ const check = () => {
211
+ if (io.realpathSync(selectedPath) !== configPath || !regular(configPath).equals(bytes)
212
+ || io.realpathSync(config.engine.repo) !== repo || io.realpathSync(config.stateDir) !== state)
213
+ refuse('Konfiguracja lub ścieżki zmieniły się podczas aktualizacji.');
214
+ const currentMode = stat(modePath) ? regular(modePath) : null;
215
+ if (modeBytes ? !currentMode?.equals(modeBytes) : currentMode !== null)
216
+ refuse('HOST-ACTIVATION.mode zmienił się podczas aktualizacji.');
217
+ if (attempt && !regular(attempt.path).equals(attempt.saved))
218
+ refuse('Rejestr prób zmienił się podczas aktualizacji.');
219
+ if (pointerSnapshot && (stat(pointerSnapshot.path) ? io.realpathSync(pointerSnapshot.path) : null) !== pointerSnapshot.target)
220
+ refuse('Żywy wskaźnik zmienił się podczas aktualizacji.');
221
+ };
222
+ // Probe manager before any pointer, service, or card mutation.
223
+ const manager = ctx.platform === 'linux' ? 'systemctl' : 'launchctl';
224
+ const domain = `gui/${typeof process.getuid === 'function' ? process.getuid() : 0}`;
225
+ command(manager, ctx.platform === 'linux' ? ['--user', 'show-environment'] : ['print', domain]);
226
+ board = await runtime.board(ctx, config);
227
+ const update = join(state, 'update');
228
+ privateDir(update);
229
+ const auditPath = join(update, 'audit.jsonl');
230
+ const append = (path, value) => {
231
+ if (stat(path) && !stat(path)?.isFile())
232
+ refuse('Plik stanu aktualizacji nie jest zwykłym plikiem.');
233
+ io.appendFileSync(path, JSON.stringify(value) + '\n', { mode: 0o600, flush: true });
234
+ io.chmodSync(path, 0o600);
235
+ };
236
+ const audit = (event, value = {}) => append(auditPath, { at: new Date(runtime.now()).toISOString(), event, ...value });
237
+ const defer = () => {
238
+ if (attempt) {
239
+ if (!regular(attempt.path).equals(attempt.saved))
240
+ refuse('Rejestr prób zmienił się przed odroczeniem.');
241
+ if (attempt.before === null)
242
+ io.unlinkSync(attempt.path);
243
+ else {
244
+ const temporary = `${attempt.path}.${runtime.pid}`;
245
+ io.writeFileSync(temporary, attempt.before, { flag: 'wx', mode: 0o600, flush: true });
246
+ io.renameSync(temporary, attempt.path);
247
+ }
248
+ audit('attempt-deferred');
249
+ attempt = undefined;
250
+ }
251
+ const path = join(update, 'deferred.json');
252
+ const previous = stat(path) ? json(regular(path)) : null;
253
+ if (previous && (typeof previous.since !== 'number' || typeof previous.alarmed !== 'boolean'))
254
+ refuse('Nieczytelny rejestr odroczeń.');
255
+ const since = previous?.since ?? runtime.now();
256
+ const alarmed = previous?.alarmed === true || runtime.now() - since >= 7_200_000;
257
+ if (alarmed && previous?.alarmed !== true) {
258
+ audit('deferred-alarm', { since });
259
+ ctx.err('Alarm: aktualizacja odroczona od co najmniej 7200 sekund.');
260
+ }
261
+ io.writeFileSync(path, JSON.stringify({ since, alarmed }), { mode: 0o600, flush: true });
262
+ ctx.out('Aktualizacja odroczona: trwa praca fabryki.');
263
+ return 0;
264
+ };
265
+ serialRelease = acquire(join(update, '.update.lock')) ?? undefined;
266
+ if (!serialRelease) {
267
+ ctx.out('Aktualizacja odroczona: inny aktualizator już działa.');
268
+ return 0;
269
+ }
270
+ const processBusy = () => {
271
+ const output = command('ps', ['-axo', 'pid=,command=']);
272
+ for (const line of output.split('\n').filter(line => line.trim())) {
273
+ const match = line.match(/^\s*([1-9]\d*)\s+(.+)$/);
274
+ if (!match)
275
+ refuse('Nieustalony stan procesów fabryki.');
276
+ if (Number(match[1]) === runtime.pid)
277
+ continue;
278
+ if (/\bfactory\s+run\b|(?:^|[\/\s])tick\.(?:cjs|ts|js)(?:\s|$)|\bcodex\b[^\n]*\bexec\b/.test(match[2]))
279
+ return true;
280
+ }
281
+ return false;
282
+ };
283
+ const preflight = async () => {
284
+ check();
285
+ const busy = processBusy();
286
+ for (const claim of ['.tester-job.lock', '.tester-job.input.json', '.tester-job.result.json',
287
+ ...['claim.json', 'started', 'wynik.json', 'stop.json', 'ack.json'].map(name => `receiver-jobs/local/${name}`)]) {
288
+ for (const suffix of ['', '.pending'])
289
+ if (stat(join(state, claim + suffix)))
290
+ refuse('Nierozliczony claim testera lub odbiorcy; zachowaj stan.');
291
+ }
292
+ const rows = await board.listTasks({ projectId: config.project, statuses: ['in_progress'], detailsKeys: [] });
293
+ if (!Array.isArray(rows))
294
+ refuse('Nieczytelna lista kart in_progress.');
295
+ const own = [];
296
+ for (const row of rows) {
297
+ if (row.projectId !== config.project || row.status !== 'in_progress' || typeof row.assignee !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._:-]*$/.test(row.assignee))
298
+ refuse('Nieznany właściciel karty in_progress.');
299
+ if (row.assignee !== 'maszynista')
300
+ continue;
301
+ const card = await board.getTask({ id: row.id, include: [], fullDetails: true });
302
+ if (!card || card.id !== row.id || card.projectId !== config.project || card.status !== 'in_progress' || card.assignee !== 'maszynista' || card.details !== null && !object(card.details))
303
+ refuse('Nieczytelny pełny stan własnej karty.');
304
+ if (card.details?.maszynista !== undefined && !object(card.details.maszynista))
305
+ refuse('Nieczytelny stan maszynista na karcie.');
306
+ own.push(card);
307
+ }
308
+ return { busy, own };
309
+ };
310
+ if ((await preflight()).busy)
311
+ return defer();
312
+ const pointer = join(update, 'current');
313
+ if (stat(pointer) && !stat(pointer)?.isSymbolicLink())
314
+ refuse('Żywy wskaźnik musi być dowiązaniem aktualizatora.');
315
+ const previous = stat(pointer) ? io.realpathSync(pointer) : io.realpathSync(fileURLToPath(new URL('../', runtime.moduleUrl)));
316
+ pointerSnapshot = { path: pointer, target: stat(pointer) ? previous : null };
317
+ const oldPackage = json(regular(join(previous, 'package.json')));
318
+ const oldBuild = json(regular(join(previous, 'dist/engine/build-id.json')));
319
+ const validBuild = (build) => {
320
+ if (build.schema !== 1 || build.dirty !== false || typeof build.sha !== 'string' || !/^[a-f0-9]{40}$/.test(build.sha))
321
+ refuse('Niepoprawny build-id wydania.');
322
+ return build.sha;
323
+ };
324
+ const oldSha = validBuild(oldBuild);
325
+ const metadata = JSON.parse(command('npm', ['view', 'robisie@latest', 'version', 'gitHead', 'dist', '--json']));
326
+ if (!object(metadata) || !object(metadata.dist) || typeof metadata.dist.integrity !== 'string' || !/^sha(?:256|384|512)-\S+$/.test(metadata.dist.integrity)
327
+ || typeof metadata.gitHead !== 'string' || !/^[a-f0-9]{40}$/.test(metadata.gitHead))
328
+ refuse('Niepoprawne metadane npm: wymagane gitHead i integralność.');
329
+ const latest = metadata.version;
330
+ if (!newer(latest, oldPackage.version) && (latest !== oldPackage.version || stat(pointer))) {
331
+ ctx.out('Zainstalowana wersja robisie jest aktualna; brak downgrade.');
332
+ return 0;
333
+ }
334
+ const attempts = join(update, 'attempts.jsonl');
335
+ const attemptBytes = stat(attempts) ? regular(attempts) : null;
336
+ if (attemptBytes)
337
+ for (const line of attemptBytes.toString('utf8').split('\n').filter(Boolean)) {
338
+ const entry = JSON.parse(line);
339
+ if (!object(entry) || typeof entry.version !== 'string' || typeof entry.at !== 'string')
340
+ refuse('Nieczytelny rejestr prób aktualizacji.');
341
+ if (entry.version === latest)
342
+ refuse(`Ta wersja była już próbowana; usuń ręcznie jej jedną linię z ${attempts} dopiero po wyjaśnieniu błędu.`);
343
+ }
344
+ // A second precheck under the same lock as tick precedes card writes and the release attempt.
345
+ tickRelease = acquire(join(state, '.tick.lock')) ?? undefined;
346
+ if (!tickRelease)
347
+ return defer();
348
+ const second = await preflight();
349
+ if (second.busy)
350
+ return defer();
351
+ for (const card of second.own) {
352
+ check();
353
+ if (processBusy())
354
+ return defer();
355
+ const echo = await board.updateTask({ id: card.id, status: 'blocked', expected: { status: 'in_progress', details: card.details } });
356
+ if (echo.id !== card.id || echo.status !== 'blocked')
357
+ refuse('Niepotwierdzony CAS blocked; nie ponowiono zapisu.');
358
+ const current = await board.getTask({ id: card.id, include: [], fullDetails: true });
359
+ if (!current || current.status !== 'blocked' || current.assignee !== card.assignee || !isDeepStrictEqual(current.details, card.details))
360
+ refuse('Niepotwierdzony stan po CAS blocked.');
361
+ const machine = object(current.details?.maszynista) ? current.details.maszynista : {};
362
+ const reason = `Aktualizacja instalacji: martwa praca zablokowana ${new Date(runtime.now()).toISOString()}; zachowano WIP.`;
363
+ const echoDetail = await board.appendDetail({ id: card.id, patch: { maszynista: { ...machine, updateReason: reason } } });
364
+ const projected = echoDetail.readback.ok ? echoDetail.readback.task : null;
365
+ if (echoDetail.write.status !== 'blocked' || !projected || projected.status !== 'blocked' || projected.assignee !== card.assignee
366
+ || !object(projected.details?.maszynista) || projected.details.maszynista.updateReason !== reason)
367
+ refuse('Niepotwierdzony powód blokady; nie ponowiono zapisu.');
368
+ const after = await board.getTask({ id: card.id, include: [], fullDetails: true });
369
+ if (!after || after.status !== 'blocked' || after.assignee !== card.assignee
370
+ || !isDeepStrictEqual(after.details, { ...current.details, maszynista: { ...machine, updateReason: reason } }))
371
+ refuse('Niepotwierdzone zachowanie WIP i pól maszynista po dopisaniu powodu.');
372
+ audit('card-blocked', { id: card.id, before: card, after, echo, echoDetail });
373
+ }
374
+ check();
375
+ if (attemptBytes ? !regular(attempts).equals(attemptBytes) : stat(attempts) !== null)
376
+ refuse('Rejestr prób zmienił się podczas aktualizacji.');
377
+ append(attempts, { version: latest, at: new Date(runtime.now()).toISOString() });
378
+ attempt = { path: attempts, before: attemptBytes, saved: regular(attempts) };
379
+ audit('attempt', { version: latest, previous: oldSha });
380
+ const releases = join(update, 'releases');
381
+ privateDir(releases);
382
+ const release = io.mkdtempSync(join(releases, `robisie-${latest}-`));
383
+ io.writeFileSync(join(release, 'package.json'), JSON.stringify({ private: true }) + '\n', { flag: 'wx', mode: 0o600, flush: true });
384
+ command('npm', ['install', `robisie@${latest}`, '--ignore-scripts', '--no-audit', '--no-fund', '--save-exact'], release);
385
+ const next = join(release, 'node_modules/robisie');
386
+ const build = json(regular(join(next, 'dist/engine/build-id.json'))), sha = validBuild(build);
387
+ const lock = json(regular(join(release, 'package-lock.json')));
388
+ const installed = object(lock.packages) ? lock.packages['node_modules/robisie'] : null;
389
+ if (sha !== metadata.gitHead || !object(installed) || installed.integrity !== metadata.dist.integrity
390
+ || json(regular(join(next, 'package.json'))).version !== latest)
391
+ refuse('Weryfikacja wydania npm nie powiodła się.');
392
+ regular(join(next, 'dist/cli.js'));
393
+ regular(join(next, 'dist/engine/tick.cjs'));
394
+ const prepared = await preflight();
395
+ if (prepared.busy)
396
+ return defer();
397
+ if (prepared.own.length)
398
+ return defer();
399
+ const launcher = join(update, 'launch.mjs');
400
+ const launcherText = `// robisie:update-managed
401
+ import {realpathSync} from 'node:fs';
402
+ import {join} from 'node:path';
403
+ import {pathToFileURL} from 'node:url';
404
+ import {spawnSync} from 'node:child_process';
405
+ try {
406
+ const root=realpathSync(${JSON.stringify(pointer)});
407
+ const env={...process.env};
408
+ if(process.argv[2]==='factory') {
409
+ const {readKey}=await import(pathToFileURL(join(root,'dist/manifest.js')).href);
410
+ const dir=${JSON.stringify(agentPaths(ctx).clientDir)};
411
+ env.ROBISIE_KEY=readKey(dir);
412
+ env.ROBISIE_REVIEW_KEY=readKey(dir,'review-key');
413
+ if(!env.ROBISIE_KEY||!env.ROBISIE_REVIEW_KEY) throw new Error('Brak plików kluczy instalacji');
414
+ }
415
+ const r=spawnSync(${JSON.stringify(runtime.node)},[join(root,'dist/cli.js'),...process.argv.slice(2)],{cwd:${JSON.stringify(ctx.cwd)},env,stdio:'inherit',shell:false});
416
+ if(r.status!==0||r.signal!==null) throw new Error('Polecenie robisie nie powiodło się');
417
+ process.exitCode=0;
418
+ } catch { process.stderr.write('Błąd uruchomienia robisie; sprawdź prywatny audyt aktualizacji.\\n'); process.exitCode=2; }
419
+ `;
420
+ const writeManaged = (path, content) => {
421
+ if (stat(path) && !regular(path).toString('utf8').includes('robisie:update-managed'))
422
+ refuse('Obcy plik jednostki lub launchera; odmowa nadpisania.');
423
+ io.writeFileSync(path, content, { mode: 0o600, flush: true });
424
+ };
425
+ const unitDir = ctx.platform === 'linux' ? join(dirname(agentPaths(ctx).clientDir), 'systemd/user') : join(ctx.home, 'Library/LaunchAgents');
426
+ io.mkdirSync(unitDir, { recursive: true, mode: 0o700 });
427
+ const factoryArgs = ['factory', 'run', '--once', '--engine-config', configPath];
428
+ const updateArgs = ['update', '--engine-config', configPath];
429
+ const factoryName = ctx.platform === 'linux' ? 'robisie-factory' : 'com.robisie.factory';
430
+ const ensureOwned = () => {
431
+ if (ctx.platform === 'linux') {
432
+ for (const name of [factoryName, 'robisie-update']) {
433
+ const info = runtime.exec(manager, ['--user', 'show', `${name}.service`, '--property=LoadState,ActiveState,ExecStart', '--value'], ctx.cwd, env);
434
+ if (info.signal !== null || info.status !== 0 && !(info.status === 1 && /^not-found$/m.test(info.stdout)))
435
+ refuse('Nie można potwierdzić właściciela usługi systemd.');
436
+ if (/^(?:active|activating|deactivating)$/m.test(info.stdout) && !info.stdout.includes(launcher))
437
+ refuse('Obca aktywna usługa fabryki lub aktualizacji; nie zatrzymano jej.');
438
+ }
439
+ }
440
+ else {
441
+ for (const name of [factoryName, 'com.robisie.update']) {
442
+ const info = runtime.exec(manager, ['print', `${domain}/${name}`], ctx.cwd, env);
443
+ if (info.signal !== null || info.status !== 0 && info.status !== 113)
444
+ refuse('Nie można potwierdzić właściciela usługi launchd.');
445
+ if (info.status === 0 && !info.stdout.includes(launcher))
446
+ refuse('Obca aktywna usługa fabryki lub aktualizacji; nie zatrzymano jej.');
447
+ }
448
+ }
449
+ };
450
+ ensureOwned();
451
+ writeManaged(launcher, launcherText);
452
+ const xml = (text) => text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&apos;');
453
+ const systemArg = (text, execution = false) => '"' + text.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/%/g, '%%').replace(/\$/g, () => execution ? '$$' : '$').replace(/\n/g, '\\n').replace(/\r/g, '\\r') + '"';
454
+ const unitEnv = Object.entries({ HOME: ctx.home, PATH: ctx.env.PATH, CODEX_HOME: ctx.env.CODEX_HOME, XDG_CONFIG_HOME: ctx.env.XDG_CONFIG_HOME })
455
+ .filter((entry) => entry[1] !== undefined);
456
+ for (const [name, args] of [['factory', factoryArgs], ['update', updateArgs]]) {
457
+ if (ctx.platform === 'linux') {
458
+ // Tick and update own their deadlines, including the separate rollback health window.
459
+ writeManaged(join(unitDir, `robisie-${name}.service`), `# robisie:update-managed\n[Unit]\nDescription=robisie ${name}\n[Service]\nType=oneshot\nTimeoutStartSec=infinity\n${unitEnv.map(([key, value]) => `Environment=${systemArg(`${key}=${value}`)}\n`).join('')}WorkingDirectory=${systemArg(ctx.cwd)}\nExecStart=${[runtime.node, launcher, ...args].map(arg => systemArg(arg, true)).join(' ')}\n`);
460
+ writeManaged(join(unitDir, `robisie-${name}.timer`), `# robisie:update-managed\n[Unit]\nDescription=robisie ${name}\n[Timer]\nOnBootSec=120s\nOnUnitInactiveSec=120s\nUnit=robisie-${name}.service\n[Install]\nWantedBy=timers.target\n`);
461
+ }
462
+ else {
463
+ writeManaged(join(unitDir, `com.robisie.${name}.plist`), `<?xml version="1.0" encoding="UTF-8"?>\n<!-- robisie:update-managed -->\n<plist version="1.0"><dict><key>Label</key><string>com.robisie.${name}</string><key>ProgramArguments</key><array>${[runtime.node, launcher, ...args].map(arg => `<string>${xml(arg)}</string>`).join('')}</array><key>EnvironmentVariables</key><dict>${unitEnv.map(([key, value]) => `<key>${xml(key)}</key><string>${xml(value)}</string>`).join('')}</dict><key>WorkingDirectory</key><string>${xml(ctx.cwd)}</string><key>StartInterval</key><integer>120</integer></dict></plist>\n`);
464
+ }
465
+ }
466
+ const switchPointer = (target) => {
467
+ const temporary = join(update, `.current-${runtime.pid}`);
468
+ io.symlinkSync(target, temporary);
469
+ io.renameSync(temporary, pointer);
470
+ if (io.realpathSync(pointer) !== io.realpathSync(target))
471
+ refuse('Niepotwierdzona wymiana wskaźnika.');
472
+ pointerSnapshot = { path: pointer, target: io.realpathSync(target) };
473
+ };
474
+ const start = () => {
475
+ if (ctx.platform === 'linux') {
476
+ command(manager, ['--user', 'daemon-reload']);
477
+ command(manager, ['--user', 'enable', '--now', 'robisie-factory.timer', 'robisie-update.timer']);
478
+ command(manager, ['--user', 'reset-failed', 'robisie-factory.service']);
479
+ command(manager, ['--user', 'start', '--no-block', 'robisie-factory.service']);
480
+ }
481
+ else {
482
+ for (const name of ['factory', 'update']) {
483
+ const loaded = runtime.exec(manager, ['print', `${domain}/com.robisie.${name}`], ctx.cwd, env);
484
+ if (loaded.signal !== null)
485
+ refuse('Nie można potwierdzić stanu jednostki launchd.');
486
+ if (loaded.status === 0) {
487
+ if (!loaded.stdout.includes(launcher))
488
+ refuse('Obca jednostka launchd; odmowa jej zatrzymania.');
489
+ // Both jobs resolve current at launch; reloading could kill work or the updater itself.
490
+ continue;
491
+ }
492
+ else if (loaded.status !== 113)
493
+ refuse('Nie można potwierdzić stanu jednostki launchd.');
494
+ command(manager, ['bootstrap', domain, join(unitDir, `com.robisie.${name}.plist`)]);
495
+ }
496
+ command(manager, ['kickstart', `${domain}/com.robisie.factory`]);
497
+ }
498
+ };
499
+ const refresh = (root) => {
500
+ // Reuse the package's installer/doctor with file-backed A/B, never a new role installer.
501
+ const key = readKey(agentPaths(ctx).clientDir), reviewKey = readKey(agentPaths(ctx).clientDir, 'review-key');
502
+ const childEnv = { ...env };
503
+ delete childEnv.ROBISIE_KEY;
504
+ delete childEnv.ROBISIE_REVIEW_KEY;
505
+ for (const name of ['init', 'doctor']) {
506
+ if (name === 'doctor') {
507
+ if (key)
508
+ childEnv.ROBISIE_KEY = key;
509
+ if (reviewKey)
510
+ childEnv.ROBISIE_REVIEW_KEY = reviewKey;
511
+ }
512
+ const outcome = runtime.exec(runtime.node, [join(root, 'dist/cli.js'), name, '--engine-config', configPath], ctx.cwd, childEnv);
513
+ if (outcome.status !== 0 || outcome.signal !== null)
514
+ refuse('Odświeżenie ról lub doctor nie powiodło się.');
515
+ }
516
+ };
517
+ const serviceOk = (sha, failureEvent) => {
518
+ if (ctx.platform !== 'linux')
519
+ return true;
520
+ let serviceResult;
521
+ try {
522
+ serviceResult = command(manager, ['--user', 'show', 'robisie-factory.service', '--property=Result', '--value']).trim();
523
+ }
524
+ catch {
525
+ audit(failureEvent, { sha });
526
+ return false;
527
+ }
528
+ // --no-block only queues the start. Result also detects later ExecStart failures.
529
+ if (serviceResult === 'success')
530
+ return true;
531
+ audit(failureEvent, { sha, serviceResult });
532
+ return false;
533
+ };
534
+ const activate = (root, sha, failureEvent) => {
535
+ try {
536
+ refresh(root);
537
+ }
538
+ catch {
539
+ audit(failureEvent, { sha });
540
+ return false;
541
+ }
542
+ finally {
543
+ const release = tickRelease;
544
+ tickRelease = undefined;
545
+ release();
546
+ }
547
+ try {
548
+ start();
549
+ }
550
+ catch {
551
+ audit(failureEvent, { sha });
552
+ return false;
553
+ }
554
+ return serviceOk(sha, failureEvent);
555
+ };
556
+ const priorTicks = new Set();
557
+ let highestTick = BigInt(0);
558
+ const rememberTick = () => {
559
+ try {
560
+ const report = regular(join(state, 'LAST-TICK.md')).toString('utf8');
561
+ const tick = report.match(/^- tick: ([1-9]\d*)$/m)?.[1];
562
+ if (tick) {
563
+ priorTicks.add(tick);
564
+ if (BigInt(tick) > highestTick)
565
+ highestTick = BigInt(tick);
566
+ }
567
+ }
568
+ catch { /* Missing or unreadable baseline provides no health evidence. */ }
569
+ };
570
+ const health = async (expected, switchedAt, event, failureEvent) => {
571
+ const seen = new Set(priorTicks);
572
+ let accepted = 0, lastAt = switchedAt;
573
+ const deadline = switchedAt + 1_200_000;
574
+ while (runtime.now() < deadline) {
575
+ await runtime.sleep(20_000);
576
+ if (runtime.now() > deadline)
577
+ break;
578
+ if (!serviceOk(expected, failureEvent) || runtime.now() > deadline)
579
+ return false;
580
+ let report;
581
+ try {
582
+ report = regular(join(state, 'LAST-TICK.md')).toString('utf8');
583
+ }
584
+ catch {
585
+ continue;
586
+ } // Unreadable evidence never proves health.
587
+ const values = (name) => [...report.matchAll(new RegExp(`^- ${name}: (.+)$`, 'gm'))].map(match => match[1]);
588
+ const ticks = values('tick'), dates = values('at'), loaded = values('loaded');
589
+ if (!/^# LAST TICK — OK\r?\n/.test(report) || ticks.length !== 1 || dates.length !== 1 || loaded.length !== 1
590
+ || !/^[1-9]\d*$/.test(ticks[0]) || loaded[0] !== expected)
591
+ continue;
592
+ const at = Date.parse(dates[0]);
593
+ if (!Number.isFinite(at) || at <= lastAt || at > runtime.now() || seen.has(ticks[0]) || BigInt(ticks[0]) <= highestTick)
594
+ continue;
595
+ seen.add(ticks[0]);
596
+ priorTicks.add(ticks[0]);
597
+ highestTick = BigInt(ticks[0]);
598
+ accepted++;
599
+ lastAt = at;
600
+ audit(event, { tick: ticks[0], sha: expected, reportedAt: dates[0] });
601
+ if (accepted >= 2)
602
+ return true;
603
+ }
604
+ return false;
605
+ };
606
+ if (modeBytes) {
607
+ mode = { path: modePath, bytes: modeBytes };
608
+ const backup = join(update, 'HOST-ACTIVATION.mode.backup');
609
+ if (stat(backup) && !stat(backup)?.isFile())
610
+ refuse('Kopia trybu hosta nie jest zwykłym plikiem.');
611
+ io.writeFileSync(backup, modeBytes, { mode: 0o600, flush: true });
612
+ if (!regular(backup).equals(modeBytes))
613
+ refuse('Niepotwierdzona kopia bajtów HOST-ACTIVATION.mode.');
614
+ }
615
+ ensureOwned();
616
+ const activating = await preflight();
617
+ if (activating.busy)
618
+ return defer();
619
+ if (activating.own.length)
620
+ return defer();
621
+ rememberTick();
622
+ const switchedAt = runtime.now();
623
+ switchPointer(next);
624
+ audit('switched', { sha, previous: oldSha });
625
+ const started = activate(next, sha, 'start-failed');
626
+ if (started && await health(sha, switchedAt, 'new-tick', 'start-failed')) {
627
+ audit('updated', { sha });
628
+ if (stat(join(update, 'deferred.json')))
629
+ io.unlinkSync(join(update, 'deferred.json'));
630
+ completed = true;
631
+ result = 0;
632
+ }
633
+ else {
634
+ // New work prevents rollback, exactly as it prevents forward activation.
635
+ const rollbackPre = await preflight();
636
+ if (rollbackPre.busy || rollbackPre.own.length)
637
+ refuse('Alarm: nowa praca blokuje powrót; poprzednia wersja niepotwierdzona.');
638
+ tickRelease = acquire(join(state, '.tick.lock')) ?? undefined;
639
+ if (!tickRelease)
640
+ refuse('Alarm: blokada taktu uniemożliwia powrót; poprzednia wersja niepotwierdzona.');
641
+ const rollbackLocked = await preflight();
642
+ if (rollbackLocked.busy || rollbackLocked.own.length)
643
+ refuse('Alarm: nowa praca pod blokadą uniemożliwia powrót.');
644
+ ensureOwned();
645
+ rememberTick();
646
+ const restoredAt = runtime.now();
647
+ switchPointer(previous);
648
+ audit('restored', { sha: oldSha, failed: sha });
649
+ const restarted = activate(previous, oldSha, 'rollback-start-failed');
650
+ const confirmed = restarted && await health(oldSha, restoredAt, 'old-tick', 'rollback-start-failed');
651
+ audit(confirmed ? 'rollback-confirmed' : 'rollback-unconfirmed', { sha: oldSha, failed: sha });
652
+ ctx.err(confirmed ? 'Nowa wersja nie wstała; powrót potwierdzony dwoma świeżymi taktami OK.' : 'Alarm: nie potwierdzono zdrowia poprzedniej wersji po powrocie.');
653
+ result = 1;
654
+ }
655
+ return result;
656
+ })();
657
+ }
658
+ catch (error) {
659
+ ctx.err(error instanceof RobisieError ? error.message : 'Odmowa aktualizacji: błąd IO, konfiguracji, transportu lub audytu; nie ponawiaj niepewnego zapisu.');
660
+ result = 2;
661
+ }
662
+ finally {
663
+ if (mode) {
664
+ try {
665
+ io.writeFileSync(mode.path, mode.bytes, { mode: 0o600, flush: true });
666
+ if (!regular(mode.path).equals(mode.bytes))
667
+ throw new Error('mode bytes');
668
+ }
669
+ catch {
670
+ ctx.err('Alarm: nie potwierdzono przywrócenia bajtów HOST-ACTIVATION.mode.');
671
+ result = 2;
672
+ }
673
+ }
674
+ for (const release of [tickRelease, serialRelease])
675
+ if (release) {
676
+ try {
677
+ release();
678
+ }
679
+ catch {
680
+ ctx.err('Alarm: nie udało się bezpiecznie zwolnić własnej blokady aktualizacji.');
681
+ result = 2;
682
+ }
683
+ }
684
+ if (board)
685
+ try {
686
+ await board.close();
687
+ }
688
+ catch {
689
+ ctx.err('Alarm: nie udało się zamknąć transportu tablicy.');
690
+ result = 2;
691
+ }
692
+ }
693
+ if (completed && result === 0)
694
+ ctx.out('Aktualizacja potwierdzona dwoma świeżymi taktami OK.');
695
+ return result;
696
+ }