omp-superagent 0.1.11 → 0.1.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/DESIGN.md CHANGED
@@ -107,6 +107,19 @@ part of the native build.
107
107
  no `KeepAlive`, immediate activation, or second supervisor. `uninstall` removes
108
108
  only future startup. There is no Linux service installer or Windows support.
109
109
 
110
+ An [in-place package update](docs/OPERATIONS.en.md#update-an-existing-installation)
111
+ requires verified shutdown of every Gateway and resident Host using that installation.
112
+ Capture live identity from the physical socket before stopping. A local lane stop must
113
+ match the selected instance, recorded socket and native session on the connection that
114
+ sends the shutdown. Match the exact process, session and physical journal to a fresh
115
+ Host exit receipt and independently verify process exit.
116
+ Restore only previously running Gateways. A positively sleeping HEAD has no resident
117
+ process to stop; explicit start of its previously running Gateway resumes the same session.
118
+ Starting with 0.1.11, Rust owners verify journal persistence and flushed observations
119
+ in-process. A 0.1.10 owner must finish using its original helper before replacement.
120
+ The new installation cannot authenticate the old helper's `exit` request and does not
121
+ publish a receipt for it. Replacing the files does not release an already-fenced owner.
122
+
110
123
  ### Idle HEAD hibernation
111
124
 
112
125
  `headIdleMs` controls how long a fully idle HEAD stays resident (default 30
package/README.ko.md CHANGED
@@ -45,7 +45,9 @@
45
45
 
46
46
  ## 빠른 시작
47
47
 
48
- ### 1. 설치
48
+ ### 1. 처음 설치
49
+
50
+ **이미 설치했다면** [업데이트 절차](docs/OPERATIONS.md#기존-설치-업데이트)를 따르세요. 실제 소유 정보를 기록하고 해당 프로세스의 정상 종료를 확인한 뒤 파일을 교체하세요. 새 CLI로 업데이트 전 실행 중이던 Gateway만 다시 시작하세요. 종료 요청의 수락 응답만으로는 충분하지 않습니다.
49
51
 
50
52
  macOS 또는 Linux(arm64·x64), [Bun 1.4.4 이상](https://bun.sh), 별도로 설치한 [순정 OMP](https://github.com/can1357/oh-my-pi#install)가 필요합니다. 모델 제공자 인증은 OMP에서 설정하세요.
51
53
 
package/README.md CHANGED
@@ -46,7 +46,9 @@
46
46
 
47
47
  ## Quick start
48
48
 
49
- ### 1. Install
49
+ ### 1. First install
50
+
51
+ **Already installed?** Follow the [update procedure](docs/OPERATIONS.en.md#update-an-existing-installation): capture live owners, stop the verified processes before replacing files, and restart only previously running Gateways using the upgraded CLI. A shutdown ACK alone is not enough.
50
52
 
51
53
  Use macOS or Linux (arm64 or x64), [Bun 1.4.4+](https://bun.sh), and a separately installed [stock OMP](https://github.com/can1357/oh-my-pi#install). Authenticate your model provider in OMP.
52
54
 
@@ -4,7 +4,7 @@
4
4
  [Design](../DESIGN.md) · [Example configuration](../config.example.json) ·
5
5
  [Attribution and license notices](../THIRD_PARTY_NOTICES.md)
6
6
 
7
- [Install](#1-local-preparation--does-not-start-the-bot) · [Platform apps](#2-platform-apps-and-access) · [Configuration](#3-configuration) · [Daily use](#4-commands-and-daily-use) · [Recovery](#5-operational-scope-and-recovery-constraints) · [Developer verification](#6-developer-verification)
7
+ [Install](#1-local-preparation--does-not-start-the-bot) · [Update](#update-an-existing-installation) · [Platform apps](#2-platform-apps-and-access) · [Configuration](#3-configuration) · [Daily use](#4-commands-and-daily-use) · [Recovery](#5-operational-scope-and-recovery-constraints) · [Developer verification](#6-developer-verification)
8
8
 
9
9
  This guide covers installation, configuration, day-to-day operation, and recovery. Unless
10
10
  otherwise noted, file and code paths and shell commands are relative to the **repository root**.
@@ -256,26 +256,201 @@ OMP 19's per-user daemon does not take over services from the previous broker. A
256
256
  in the new daemon is not evidence that you may stop or reclaim work whose completion was
257
257
  never confirmed in the old session.
258
258
 
259
- **Upgrading from the Bun journal verifier:** before replacing an installation in
260
- place, let work settle and gracefully stop its resident lane Hosts (including
261
- remote workers) and its Gateway/HEAD using the old installation. Check their
262
- exit receipts and verify the owners have exited. `stop main` alone does not stop
263
- independent lanes. Old owners still need their original helper files until exit;
264
- the new owners verify their journals in Rust. Keep the state and session files.
265
-
266
259
  The default `command: ["omp"]` looks up OMP on PATH. To use a different installation, put
267
260
  its OMP path in the first entry of `command`. A relative path is resolved against the
268
261
  configuration file's directory, and all lanes use the same path. This repository does not
269
262
  download OMP or build it from source.
270
263
 
264
+ ### Update an Existing Installation
265
+
266
+ **Do not replace files while an affected process can still use them.** Schedule a quiet
267
+ window: hold new work, avoid concurrent starts/restarts or login activation, and let
268
+ active work, approvals, goals, deliveries and owned services settle. Inventory every
269
+ configured instance and enrolled worker account using the copy being replaced, not just
270
+ the currently selected config. In `omp-sa status --config FILE`, `lanes[]` and `workers[]`
271
+ are saved records, not live ownership or exit evidence. On each machine, cross-check the
272
+ inventory against local processes, for example with `ps -axo pid=,ppid=,uid=,comm=` and
273
+ `lsof -nP -a -p PID -d txt` to locate a candidate Gateway or owner executable if needed.
274
+ Do not read process environments or print credential files. If you cannot account for
275
+ an affected process, machine or installation, do not replace that copy.
276
+
277
+ #### Capture before stopping
278
+
279
+ Keep [`upgrade-evidence.mjs`](../scripts/upgrade-evidence.mjs) and its two helpers,
280
+ [`upgrade-host-wire.mjs`](../scripts/upgrade-host-wire.mjs) and
281
+ [`upgrade-evidence-files.mjs`](../scripts/upgrade-evidence-files.mjs), together from the same
282
+ revision as this guide, **outside every directory being replaced**, on each affected
283
+ machine. They use Bun and the installed 0.1.10+ private Gateway/Host protocol; they
284
+ need no package install. `capture`, `recheck` and `verify` are read-only. Only
285
+ `stop-local` requests shutdown, for one verified local lane. Keep captures private.
286
+
287
+ On the Gateway machine, use the account and CLI from the **old installation**.
288
+ Substitute your absolute paths and save the status for each instance:
289
+
290
+ ```sh
291
+ OLD_OMP_SA=/path/to/old/omp-sa
292
+ CONFIG=/path/to/config.local.json
293
+ PROBE=/path/outside/installation/upgrade-evidence.mjs
294
+ umask 077
295
+ EVIDENCE_DIR=$(mktemp -d /tmp/omp-sa-upgrade.XXXXXX) &&
296
+ "$OLD_OMP_SA" status --config "$CONFIG" > "$EVIDENCE_DIR/status-before.json"
297
+ ```
298
+
299
+ For a source installation, use `bun --no-env-file /path/to/old/src/cli.ts` in
300
+ place of `"$OLD_OMP_SA"` for the old CLI commands. From the saved status, take the
301
+ absolute `main.socketPath` and use its sibling `gateway.sock` for the Gateway.
302
+ For each previously running Gateway, capture the Gateway and its HEAD together:
303
+
304
+ ```sh
305
+ GATEWAY_SOCKET=/absolute/state/run/gateway.sock
306
+ bun --no-env-file "$PROBE" capture gateway "$GATEWAY_SOCKET" > "$EVIDENCE_DIR/gateway.json"
307
+ ```
308
+
309
+ - For a resident HEAD the probe matches its native PID and session ID against
310
+ `gateway.head.pid` and `gateway.head.initialization.sessionId`. For a **sleeping**
311
+ HEAD it records `gateway.head.hibernation.sessionId` with no live Host to stop.
312
+ A positive `sleeping` stage from a live Gateway is different from an absent socket,
313
+ `gateway: null`, or a failed probe. Do not wake a sleeping HEAD for evidence.
314
+ - Do not run `stop` or `start` for an instance or lane already confirmed intentionally
315
+ stopped. Use the known prior stop/exit and machine process inventory to establish
316
+ this; a missing socket, saved state, or an unrelated receipt is not proof. An absent
317
+ or unconfirmed owner, an in-progress wake/rotation, or a failed capture is a reason to
318
+ resolve ownership before replacing files, not to mark it stopped or force a start.
319
+
320
+ For each affected resident lane, take `id`, `socketPath` and `sessionId` from the
321
+ corresponding `lanes[]` entry and confirm `placement.target`. On the physical machine
322
+ holding that socket, capture the live identity:
323
+
324
+ ```sh
325
+ LANE_ID=lane-example
326
+ LANE_SOCKET=/absolute/state/run/lane-example.sock
327
+ LANE_SESSION=SESSION_ID_FROM_STATUS
328
+ bun --no-env-file "$PROBE" capture host "$LANE_SOCKET" "$LANE_SESSION" > "$EVIDENCE_DIR/$LANE_ID.json"
329
+ ```
330
+
331
+ For `placement.target: "remote"`, match `placement.workerId` to `workers[].workerId`.
332
+ Use a separate authorized login on that enrolled machine **as the enrolled OS account**.
333
+ Set `PROBE` and create a private `EVIDENCE_DIR` on that machine using the same steps.
334
+ Use the recorded remote socket and add `--worker` to capture and verify the launch
335
+ attempt as well:
336
+
337
+ ```sh
338
+ bun --no-env-file "$PROBE" capture host "$LANE_SOCKET" "$LANE_SESSION" --worker > "$EVIDENCE_DIR/$LANE_ID.json"
339
+ ```
340
+
341
+ The enrolled SSH key's forced command is not a shell; do not loosen it, tunnel the
342
+ socket, or use same-named paths on the HEAD machine. If you lack authorized access
343
+ to the affected worker, cannot correlate all its dependent Hosts to their managing
344
+ HEADs, or cannot prove their ownership, leave that installation intact. A HEAD-only
345
+ update does not replace worker files or require stopping lanes on unchanged
346
+ installations.
347
+
348
+ #### Stop, verify, and replace
349
+
350
+ For a **local** lane, use the private status saved from its managing instance and
351
+ the capture from that host. `stop-local` checks that the lane's recorded socket
352
+ is the one derived from that instance's `main.socketPath` and lane ID. It compares
353
+ the live session and owner to the capture and sends a single shutdown on that
354
+ same connection. Do not substitute the old CLI's `stop LANE_ID`: it reconnects
355
+ by pathname. A refusal or lost reply is not permission to send another stop.
356
+
357
+ ```sh
358
+ bun --no-env-file "$PROBE" stop-local "$EVIDENCE_DIR/$LANE_ID.json" "$EVIDENCE_DIR/status-before.json" "$LANE_ID" &&
359
+ bun --no-env-file "$PROBE" verify "$EVIDENCE_DIR/$LANE_ID.json"
360
+ ```
361
+
362
+ For a remote lane, run `bun --no-env-file "$PROBE" recheck "$EVIDENCE_DIR/$LANE_ID.json"`
363
+ on the worker first. Only if it succeeds, run `"$OLD_OMP_SA" stop "$LANE_ID" --config "$CONFIG"`
364
+ on its managing HEAD machine. Once accepted, run
365
+ `bun --no-env-file "$PROBE" verify "$EVIDENCE_DIR/$LANE_ID.json"` on the worker.
366
+
367
+ After the affected lanes, stop each previously running Gateway using its old CLI
368
+ and saved capture. `stop main` does not stop independent lanes:
369
+
370
+ ```sh
371
+ bun --no-env-file "$PROBE" recheck "$EVIDENCE_DIR/gateway.json" &&
372
+ "$OLD_OMP_SA" stop main --config "$CONFIG" &&
373
+ bun --no-env-file "$PROBE" verify "$EVIDENCE_DIR/gateway.json"
374
+ ```
375
+
376
+ If HEAD hibernates after the first capture, the resident `recheck` fails. Take a fresh
377
+ Gateway capture only after it positively reports `sleeping` with the same session ID
378
+ and resume the stop procedure with that capture.
379
+
380
+ Each capture binds the Gateway PID and each live Host's native PID, adapter owner PID,
381
+ session ID and journal path to the socket's device and inode. The journal's device
382
+ and inode must still match at recheck and verification. An ordinary local journal
383
+ may be an owned symlink to the same owned regular file; a worker journal cannot be
384
+ a symlink. `verify` must report
385
+ `exit-confirmed` on the same machine/account before proceeding. It requires actual
386
+ process absence (`ESRCH`, not a reused PID or a permission error), absent old socket
387
+ paths, and for each formerly resident Host a **new** private `<socketPath>.exit.json`
388
+ inode, matching the captured identity (including the worker attempt where applicable),
389
+ `code: 0`, `signal: null`, `persisted: true`, and `observationsFlushed: true`. For an
390
+ already-sleeping HEAD, stopping Gateway does not create a new Host receipt: its live
391
+ Gateway had already verified the hibernation exit. If shutdown was accepted but still
392
+ completing, run `verify` again after the processes have had time to exit. Do not resend
393
+ stop blindly, delete socket or receipt files, or interpret a stale receipt, a shutdown
394
+ ACK, or a missing socket alone as success. If exit is refused or still unconfirmed,
395
+ leave the old files in place.
396
+
397
+ Only then use `bun add --global --trust omp-superagent@VERSION` or
398
+ `npm install --global omp-superagent@VERSION` with the target version, or rebuild the
399
+ source installation. Replace worker files only on the relevant worker after its
400
+ dependent Hosts have stopped. Keep the same config, state, enrollment and journals;
401
+ do not rerun `setup`.
402
+
403
+ #### Restore only what was running
404
+
405
+ On each Gateway machine, `omp-sa doctor --config FILE` checks local prerequisites
406
+ without starting anything. Run `omp-sa start --config FILE` **only for Gateways that
407
+ were running before the maintenance window**. A running Gateway with a sleeping HEAD
408
+ counts as running: explicit start brings that HEAD up using its saved session, rather
409
+ than returning it to sleep immediately. Do not manually start lanes; they are managed
410
+ by HEAD. Select the **explicit path to the upgraded installation** for all three
411
+ commands, not a different `omp-sa` that happens to be on `PATH`. For a package install:
412
+
413
+ ```sh
414
+ NEW_OMP_SA=/absolute/path/to/upgraded/bin/omp-sa
415
+ "$NEW_OMP_SA" doctor --config "$CONFIG" &&
416
+ "$NEW_OMP_SA" start --config "$CONFIG" &&
417
+ "$NEW_OMP_SA" status --config "$CONFIG"
418
+ ```
419
+
420
+ For a source installation, use the upgraded checkout instead:
421
+
422
+ ```sh
423
+ NEW_CLI=/absolute/path/to/upgraded/checkout/src/cli.ts
424
+ bun --no-env-file "$NEW_CLI" doctor --config "$CONFIG" &&
425
+ bun --no-env-file "$NEW_CLI" start --config "$CONFIG" &&
426
+ bun --no-env-file "$NEW_CLI" status --config "$CONFIG"
427
+ ```
428
+
429
+ In `status`, `gateway.gateway.ready`
430
+ is transport readiness, `gateway.gateway.admissionReady` is the initial approval
431
+ reconciliation barrier for durable intake, and `gateway.head.ready` is live controller
432
+ and preset readiness. `start` can return before all three are true. While HEAD is
433
+ resident, compare `gateway.head.initialization.sessionId` to the captured session
434
+ (using `gateway.head.hibernation.sessionId` as the **before** value if HEAD was asleep).
435
+ Do not force redelivery of held inputs or uncertain outputs.
436
+
437
+ **If 0.1.10 files were already overwritten:** do not use the new helper to finish an
438
+ old owner's shutdown. It cannot authenticate that `exit` request and will not write
439
+ an exit receipt. Preserve the instance, config, journal and logs for recovery; do
440
+ not restart, manufacture a receipt, or repeat an uncertain shutdown. Restoring
441
+ files alone does not release an owner whose verification already failed. Starting
442
+ with 0.1.11, owners verify their own exits in-process in Rust.
443
+
444
+ ### First Installation
445
+
271
446
  ```sh
272
- bun add --global --trust omp-superagent@0.1.11
447
+ bun add --global --trust omp-superagent@0.1.13
273
448
  omp-sa --help
274
449
  ```
275
450
 
276
451
  `--trust` allows package installation scripts, including preparation of the managed
277
452
  omp-superkit. Add the output of `bun pm bin --global` to PATH. If Bun is on PATH, you can
278
- also use `npm install --global omp-superagent@0.1.11`. Create the configuration in your
453
+ also use `npm install --global omp-superagent@0.1.13`. Create the configuration in your
279
454
  own working directory, not the installation directory, with
280
455
  `omp-sa setup --config ./config.local.json`. Installation alone does not activate the bot.
281
456
 
@@ -3,7 +3,7 @@
3
3
  [프로젝트 소개로 돌아가기](../README.ko.md) · [English](OPERATIONS.en.md) · [설계](../DESIGN.md) ·
4
4
  [설정 예제](../config.example.json) · [출처·라이선스 고지](../THIRD_PARTY_NOTICES.md)
5
5
 
6
- [설치](#1-로컬-준비--봇은-시작하지-않음) · [플랫폼별 앱](#2-플랫폼별-앱과-접근-범위) · [설정](#3-설정) · [일상 사용](#4-명령과-일상-사용) · [복구](#5-운영-범위와-복구-제약) · [개발자 검증](#6-개발자-검증)
6
+ [설치](#1-로컬-준비--봇은-시작하지-않음) · [업데이트](#기존-설치-업데이트) · [플랫폼별 앱](#2-플랫폼별-앱과-접근-범위) · [설정](#3-설정) · [일상 사용](#4-명령과-일상-사용) · [복구](#5-운영-범위와-복구-제약) · [개발자 검증](#6-개발자-검증)
7
7
 
8
8
  이 문서는 설치·설정·일상 제어와 복구 절차를 다룬다. 파일·코드 경로와 셸 명령은 별도
9
9
  설명이 없으면 **저장소 루트 기준**이다. npm 설치에서는 같은 관리 명령을
@@ -209,24 +209,189 @@ SUPER 스킬 조회·추가 레인·goal·모델 변경·workflow artifact가
209
209
  데몬은 이전 브로커의 서비스를 인수하지 않는다. 새 데몬의 목록이 비어 있어도 이전 세션에서
210
210
  완료를 확인하지 못한 작업의 종료·회수를 승인하는 증거는 아니다.
211
211
 
212
- **Bun 저널 검증기를 사용하던 설치를 덮어쓸 때:** 기존 설치를 유지한 상태에서 작업 정산을
213
- 기다리고, 상주 레인 Host(원격 워커 포함)와 Gateway/HEAD를 정상 종료한다. 종료 영수증과
214
- 소유 프로세스의 실제 종료를 확인한 뒤 파일을 교체한다. `stop main`만으로는 독립 레인이
215
- 종료되지 않는다. 이전 소유자는 종료 시까지 원래 helper 파일이 필요하고, 새 소유자는 Rust로
216
- 저널을 검증한다. 상태 DB와 세션 파일은 그대로 보존한다.
217
-
218
212
  기본 `command: ["omp"]`는 PATH에서 찾는다. 다른 설치를 쓰려면 `command`의 첫 항목에
219
213
  그 OMP 경로를 넣는다. 상대 경로는 설정 파일의 디렉터리 기준이며 모든 레인이 같은 경로를
220
214
  사용한다. 이 저장소는 OMP를 다운로드하거나 소스에서 빌드하지 않는다.
221
215
 
216
+ ### 기존 설치 업데이트
217
+
218
+ **해당 프로세스가 기존 파일을 사용하는 동안에는 덮어쓰지 않는다.** 점검 시간을 잡고 새 작업을
219
+ 넣지 않는다. 다른 시작·재시작이나 로그인 자동 실행이 겹치지 않게 하고, 실행 중인 작업·승인·goal·
220
+ 전달·소유 서비스가 정리될 때까지 기다린다. 현재 선택한 설정만 보지 말고, 교체할 설치본을 쓰는
221
+ 모든 인스턴스와 등록된 워커 계정을 파악한다. `omp-sa status --config FILE`의 `lanes[]`와
222
+ `workers[]`는 저장된 기록이지 현재 소유권이나 종료 증거가 아니다. 머신별로
223
+ `ps -axo pid=,ppid=,uid=,comm=` 등으로 실행 중인 프로세스를 대조하고, 필요하면
224
+ `lsof -nP -a -p PID -d txt`로 Gateway 또는 소유 프로세스의 실행 파일 위치를 확인한다.
225
+ 프로세스의 환경 변수나 자격 증명 파일을 출력하지 않는다. 해당 프로세스·머신·설치본을 빠짐없이
226
+ 확인할 수 없다면 그 설치본을 교체하지 않는다.
227
+
228
+ #### 중지 전 증거 수집
229
+
230
+ 이 가이드와 같은 리비전의 [`upgrade-evidence.mjs`](../scripts/upgrade-evidence.mjs),
231
+ [`upgrade-host-wire.mjs`](../scripts/upgrade-host-wire.mjs),
232
+ [`upgrade-evidence-files.mjs`](../scripts/upgrade-evidence-files.mjs)를 각 대상 머신의 **교체하지 않을
233
+ 디렉터리에 나란히** 둔다. Bun과 기존 0.1.10 이상의 비공개 Gateway·Host 프로토콜을 사용하며
234
+ 패키지 설치는 필요 없다. `capture`, `recheck`, `verify`는 읽기 전용이다. `stop-local`만
235
+ 검증된 로컬 레인 하나에 종료를 요청한다. 수집 파일은 비공개로 보관한다.
236
+
237
+ Gateway 머신에서 **기존 설치본**의 CLI와 계정을 사용한다. 각 인스턴스의 실제 절대 경로를
238
+ 지정하고 상태를 저장한다.
239
+
240
+ ```sh
241
+ OLD_OMP_SA=/path/to/old/omp-sa
242
+ CONFIG=/path/to/config.local.json
243
+ PROBE=/path/outside/installation/upgrade-evidence.mjs
244
+ umask 077
245
+ EVIDENCE_DIR=$(mktemp -d /tmp/omp-sa-upgrade.XXXXXX) &&
246
+ "$OLD_OMP_SA" status --config "$CONFIG" > "$EVIDENCE_DIR/status-before.json"
247
+ ```
248
+
249
+ 소스 설치라면 기존 CLI 명령의 `"$OLD_OMP_SA"` 대신
250
+ `bun --no-env-file /path/to/old/src/cli.ts`를 사용한다. 저장한 상태의 `main.socketPath`와
251
+ 같은 디렉터리에 있는 `gateway.sock`이 Gateway 소켓이다. 실행 중인 각 Gateway를 HEAD와 함께
252
+ 기록한다.
253
+
254
+ ```sh
255
+ GATEWAY_SOCKET=/absolute/state/run/gateway.sock
256
+ bun --no-env-file "$PROBE" capture gateway "$GATEWAY_SOCKET" > "$EVIDENCE_DIR/gateway.json"
257
+ ```
258
+
259
+ - 상주 HEAD는 실제 OMP PID와 세션 ID가 `gateway.head.pid`,
260
+ `gateway.head.initialization.sessionId`와 일치해야 한다. HEAD가 **절전 중**이면
261
+ `gateway.head.hibernation.sessionId`를 기록하며, 중지할 상주 Host는 없다. 살아 있는
262
+ Gateway가 보고한 `sleeping` 상태는 소켓 부재, `gateway: null`, 조회 실패와 다르다.
263
+ 증거를 얻으려고 절전 중인 HEAD를 깨우지 않는다.
264
+ - 의도적으로 이미 중지됐음이 확인된 인스턴스나 레인에는 `stop`도 `start`도 실행하지 않는다.
265
+ 이전 정상 종료 증거와 머신의 프로세스 목록을 대조한다. 소켓 부재·저장된 상태·다른 종료
266
+ 영수증으로는 충분하지 않다. 소유자가 보이지 않거나 확인되지 않거나, HEAD 복귀·교체가 진행
267
+ 중이거나, 수집에 실패하면 소유 상태를 먼저 확인한다. 중지된 것으로 간주하거나 강제로
268
+ 시작하지 않는다.
269
+
270
+ 교체할 설치본을 쓰는 각 상주 레인은 해당 `lanes[]` 항목의 `id`, `socketPath`, `sessionId`를
271
+ 확인하고 `placement.target`을 확인한다. 소켓이 있는 실제 머신에서 현재 소유권을 기록한다.
272
+
273
+ ```sh
274
+ LANE_ID=lane-example
275
+ LANE_SOCKET=/absolute/state/run/lane-example.sock
276
+ LANE_SESSION=SESSION_ID_FROM_STATUS
277
+ bun --no-env-file "$PROBE" capture host "$LANE_SOCKET" "$LANE_SESSION" > "$EVIDENCE_DIR/$LANE_ID.json"
278
+ ```
279
+
280
+ `placement.target: "remote"`라면 `placement.workerId`를 `workers[].workerId`와 대조한다.
281
+ 그 등록 머신에 **등록된 OS 계정**으로 별도 승인된 관리 접속을 사용한다. 해당 머신에서 같은
282
+ 방법으로 `PROBE`를 지정하고 비공개 `EVIDENCE_DIR`를 만든다. 기록된 원격 소켓 경로를 쓰고,
283
+ `--worker`를 추가해 워커 실행 시도 ID까지 기록한다.
284
+
285
+ ```sh
286
+ bun --no-env-file "$PROBE" capture host "$LANE_SOCKET" "$LANE_SESSION" --worker > "$EVIDENCE_DIR/$LANE_ID.json"
287
+ ```
288
+
289
+ 등록된 SSH 키의 강제 명령은 셸이 아니다. 제한을 풀거나 소켓을 터널링하거나 HEAD 머신의
290
+ 동일한 이름의 경로를 쓰지 않는다. 대상 워커에 승인된 접속 수단이 없거나, 해당 설치본에
291
+ 의존하는 모든 Host를 각 관리 HEAD와 대조할 수 없거나, 소유 상태를 확인할 수 없다면 해당
292
+ 설치본을 그대로 둔다. HEAD 쪽만 업데이트할 때는 바꾸지 않는 설치본의 파일을 교체하거나 그
293
+ 레인을 중지할 필요가 없다.
294
+
295
+ #### 중지·검증·교체
296
+
297
+ **로컬 레인**은 관리 인스턴스에서 비공개로 저장한 상태 파일과 해당 Host의 수집 파일을 함께
298
+ 사용한다. `stop-local`은 레인에 기록된 소켓이 해당 인스턴스의 `main.socketPath`와 레인 ID로
299
+ 계산한 소켓인지 확인한다. 실제 소유자와 세션이 수집 시점과 일치할 때만 **확인한 바로 그 연결**로
300
+ 종료를 한 번 요청한다. 경로만 보고 다시 접속하는 구버전 CLI의 `stop LANE_ID`로 대체하지 않는다.
301
+ 거부되거나 응답을 잃었을 때 종료 요청을 반복하지 않는다.
302
+
303
+ ```sh
304
+ bun --no-env-file "$PROBE" stop-local "$EVIDENCE_DIR/$LANE_ID.json" "$EVIDENCE_DIR/status-before.json" "$LANE_ID" &&
305
+ bun --no-env-file "$PROBE" verify "$EVIDENCE_DIR/$LANE_ID.json"
306
+ ```
307
+
308
+ 원격 레인은 워커에서 먼저
309
+ `bun --no-env-file "$PROBE" recheck "$EVIDENCE_DIR/$LANE_ID.json"`을 실행한다.
310
+ 성공한 경우에만 관리 HEAD 머신에서 `"$OLD_OMP_SA" stop "$LANE_ID" --config "$CONFIG"`를
311
+ 실행한다. 수락되면 워커에서 `bun --no-env-file "$PROBE" verify "$EVIDENCE_DIR/$LANE_ID.json"`을
312
+ 실행한다.
313
+
314
+ 대상 레인을 정리한 뒤, 원래 실행 중이던 각 Gateway를 기존 CLI와 수집 파일로 중지·검증한다.
315
+ `stop main`은 독립 레인을 중지하지 않는다.
316
+
317
+ ```sh
318
+ bun --no-env-file "$PROBE" recheck "$EVIDENCE_DIR/gateway.json" &&
319
+ "$OLD_OMP_SA" stop main --config "$CONFIG" &&
320
+ bun --no-env-file "$PROBE" verify "$EVIDENCE_DIR/gateway.json"
321
+ ```
322
+
323
+ 처음 수집한 뒤 HEAD가 절전에 들어가면 상주 상태의 `recheck`는 실패한다. 동일 세션의
324
+ `sleeping` 상태가 확인된 뒤에만 Gateway를 다시 수집하고, 그 수집 파일로 중지 절차를 이어간다.
325
+
326
+ 수집할 때 Gateway PID와 각 상주 Host의 OMP PID, 어댑터 소유 PID, 세션 ID, 저널 경로를
327
+ 실제 소켓의 장치 번호와 inode에 연결한다. 재확인·종료 검증 때 저널의 장치 번호와 inode도
328
+ 같아야 한다. 일반 로컬 저널은 같은 계정 소유의 일반 파일을 가리키는 소유 링크여도 되지만,
329
+ 워커 저널은 심볼릭 링크일 수 없다. 같은 머신·계정에서 `verify`가 `exit-confirmed`를
330
+ 반환해야 한다. 해당 PID가 실제로 없어야 하고(`ESRCH`만 인정하며 PID 재사용·권한 오류는
331
+ 종료 증거가 아님), 기존 소켓 경로도 없어야 한다. 종료한 상주 Host마다 비공개
332
+ `<socketPath>.exit.json`의 inode가 **새로 생겼는지** 확인하고, 저장한 소유 정보(해당 시
333
+ 워커 실행 시도 ID 포함)와 일치하는지, `code: 0`, `signal: null`, `persisted: true`,
334
+ `observationsFlushed: true`인지 대조한다. HEAD가 이미 절전 중이면 Gateway 중지 시 새 Host
335
+ 영수증이 생기지 않는다. 살아 있던 Gateway가 절전 시 해당 Host 종료를 이미 검증했다.
336
+ 중지 요청이 수락된 뒤 아직 종료 중이라면 프로세스가 끝난 후 `verify`만 다시 실행한다.
337
+ 중지 요청을 무작정 반복하거나 소켓·영수증을 삭제하지 않는다. 오래된 영수증, 요청 수락,
338
+ 소켓 부재만으로는 정상 종료가 아니다. 종료가 거부됐거나 끝내 확인되지 않으면 기존 파일을
339
+ 유지한다.
340
+
341
+ 검증 후에만 `bun add --global --trust omp-superagent@VERSION` 또는
342
+ `npm install --global omp-superagent@VERSION`으로 대상 버전을 설치하거나 소스 설치를
343
+ 다시 빌드한다. 워커 파일은 그 설치본에 의존하는 Host의 종료를 확인한 뒤 해당 워커에서만
344
+ 교체한다. 기존 설정·상태·등록 정보·저널을 보존하고 `setup`은 다시 실행하지 않는다.
345
+
346
+ #### 원래 실행 중이던 Gateway만 복구
347
+
348
+ 각 Gateway 머신에서 `omp-sa doctor --config FILE`로 시작하지 않고 로컬 준비 상태를 확인할
349
+ 수 있다. 점검 전에 **실행 중이던 Gateway에만** `omp-sa start --config FILE`을 실행한다.
350
+ HEAD가 절전 중이었어도 Gateway는 실행 중인 인스턴스다. 명시적 시작은 저장된 동일 세션으로
351
+ HEAD를 올리며, 바로 절전 상태로 돌려놓는 명령은 아니다. 레인은 HEAD가 관리하므로 수동으로
352
+ 시작하지 않는다. 아래 세 명령에는 `PATH`에서 우연히 찾은 `omp-sa`가 아니라 **업데이트한
353
+ 설치본의 절대 경로**를 쓴다. 패키지 설치라면 다음과 같이 실행한다.
354
+
355
+ ```sh
356
+ NEW_OMP_SA=/absolute/path/to/upgraded/bin/omp-sa
357
+ "$NEW_OMP_SA" doctor --config "$CONFIG" &&
358
+ "$NEW_OMP_SA" start --config "$CONFIG" &&
359
+ "$NEW_OMP_SA" status --config "$CONFIG"
360
+ ```
361
+
362
+ 소스 설치라면 대신 업데이트한 체크아웃의 CLI를 직접 실행한다.
363
+
364
+ ```sh
365
+ NEW_CLI=/absolute/path/to/upgraded/checkout/src/cli.ts
366
+ bun --no-env-file "$NEW_CLI" doctor --config "$CONFIG" &&
367
+ bun --no-env-file "$NEW_CLI" start --config "$CONFIG" &&
368
+ bun --no-env-file "$NEW_CLI" status --config "$CONFIG"
369
+ ```
370
+
371
+ `status`에서 `gateway.gateway.ready`는
372
+ 메신저 연결 준비, `gateway.gateway.admissionReady`는 최초 승인 복구를 마쳐 내구성 있는
373
+ 입력 접수가 가능하다는 뜻이고, `gateway.head.ready`는 상주 컨트롤러와 프리셋 준비 상태다.
374
+ `start`는 셋이 모두 참이 되기 전에 반환할 수 있다. HEAD가 상주할 때
375
+ `gateway.head.initialization.sessionId`를 앞서 수집한 세션과 대조한다. 절전 상태를
376
+ 수집했다면 **이전 값**은 `gateway.head.hibernation.sessionId`다. 보류된 입력이나 발송 결과가
377
+ 불확실한 응답을 강제로 재전달하지 않는다.
378
+
379
+ **0.1.10의 파일을 이미 덮어썼다면** 새 helper로 기존 소유 프로세스의 종료를 마무리하지 않는다.
380
+ 새 helper는 구버전의 `exit` 요청 출처를 증명할 수 없어 종료 영수증을 발행하지 않는다.
381
+ 복구를 위해 인스턴스·설정·저널·로그를 보존하고, 재시작하거나 영수증을 직접 작성하거나 불확실한
382
+ 종료 요청을 반복하지 않는다. 이미 검증에 실패한 소유 프로세스는 파일만 되돌려도 풀리지 않는다.
383
+ 0.1.11부터 소유 프로세스는 Rust에서 자신의 종료를 직접 검증한다.
384
+
385
+ ### 처음 설치
386
+
222
387
  ```sh
223
- bun add --global --trust omp-superagent@0.1.11
388
+ bun add --global --trust omp-superagent@0.1.13
224
389
  omp-sa --help
225
390
  ```
226
391
 
227
392
  `--trust`는 관리형 omp-superkit 준비 등 패키지 설치 스크립트를 허용한다.
228
393
  `bun pm bin --global`의 출력 경로를 PATH에 포함한다. Bun이 PATH에 있으면
229
- `npm install --global omp-superagent@0.1.11`도 사용할 수 있다.
394
+ `npm install --global omp-superagent@0.1.13`도 사용할 수 있다.
230
395
  설정은 설치 디렉터리가 아닌 사용자 작업 디렉터리에
231
396
  `omp-sa setup --config ./config.local.json`으로 만든다. 설치만으로 봇을 활성화하지 않는다.
232
397
 
@@ -8,11 +8,13 @@
8
8
 
9
9
  ## Install or upgrade
10
10
 
11
+ **Already running 0.1.10? Stop before installing.** Follow the [current in-place upgrade runbook](https://github.com/dbc-hbin/omp-superagent/blob/main/docs/OPERATIONS.en.md#update-an-existing-installation) to capture and stop the exact local lanes on verified connections, stop any affected remote lanes through their managing instance, and stop the Gateway using the **old installation**. If any shutdown is refused or uncertain, keep the old files in place: the 0.1.10 owner needs them to finish shutdown. A replacement installation cannot certify its exit after the fact. Preserve the config, state and journals.
12
+
11
13
  ```sh
12
14
  bun add --global --trust omp-superagent@0.1.11
13
15
  omp-sa --help
14
16
  ```
15
17
 
16
- Alternatively, use `npm install --global omp-superagent@0.1.11` with Bun 1.4.4 or later on `PATH`. Install OMP separately. Installing does not restart a running Gateway; stop and start it normally so the Gateway and HEAD use the same installation.
18
+ Alternatively, use `npm install --global omp-superagent@0.1.11` with Bun 1.4.4 or later on `PATH`. Install OMP separately. After upgrading, explicitly start only the Gateways that were running before maintenance, including those whose HEAD was sleeping. Check `omp-sa status --config FILE` for the same HEAD session and transport, admission and HEAD readiness. Leave intentionally stopped instances stopped.
17
19
 
18
- [Changes since 0.1.10](https://github.com/dbc-hbin/omp-superagent/compare/v0.1.10...v0.1.11) · [Operations guide](https://github.com/dbc-hbin/omp-superagent/blob/v0.1.11/docs/OPERATIONS.en.md)
20
+ [Changes since 0.1.10](https://github.com/dbc-hbin/omp-superagent/compare/v0.1.10...v0.1.11) · [Current operations guide](https://github.com/dbc-hbin/omp-superagent/blob/main/docs/OPERATIONS.en.md)
@@ -0,0 +1,13 @@
1
+ # omp-superagent 0.1.13
2
+
3
+ **Stop and verify before upgrading.** Follow the [upgrade procedure](https://github.com/dbc-hbin/omp-superagent/blob/v0.1.13/docs/OPERATIONS.en.md#update-an-existing-installation) ([한국어](https://github.com/dbc-hbin/omp-superagent/blob/v0.1.13/docs/OPERATIONS.md#기존-설치-업데이트)) while the original installation is intact. Stop affected resident lanes and the Gateway/HEAD, and verify their exits before replacing files. `stop main` alone does not stop independent lanes. A replacement helper cannot certify a 0.1.10 owner's exit after the fact.
4
+
5
+ - Local lane shutdown checks the configured socket and the live session, PID and journal before sending a single stop on that same connection. A copied state directory or stale lane record no longer authorizes stopping another Host.
6
+ - The packaged upgrade tools capture and recheck live ownership, handle large protocol-v2 state responses, and confirm process exit against a fresh receipt and the original journal file.
7
+ - The package upgrade check runs the real npm installation hooks, resumes the same HEAD journal, and checks that the predecessor's observations survive the upgrade.
8
+
9
+ After confirming shutdown, install `omp-superagent@0.1.13` with `bun add --global --trust` or `npm install --global`. Keep the original config and journals. Use the upgraded CLI to start only Gateways that were running before maintenance.
10
+
11
+ The `v0.1.12` tag did not publish a package: the profile-isolation test assumed a stable directory listing order on Linux. It now compares the same paths regardless of order.
12
+
13
+ [Changes since 0.1.11](https://github.com/dbc-hbin/omp-superagent/compare/v0.1.11...v0.1.13)
Binary file
Binary file
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "omp-superagent",
3
- "version": "0.1.11",
3
+ "version": "0.1.13",
4
4
  "description": "One messenger-connected OMP head with independent work sessions",
5
5
  "license": "MIT",
6
6
  "author": "dbc-hbin",
@@ -17,6 +17,9 @@
17
17
  "scripts/build-host-owner.ts",
18
18
  "scripts/prepare-super.ts",
19
19
  "scripts/setup.sh",
20
+ "scripts/upgrade-evidence-files.mjs",
21
+ "scripts/upgrade-evidence.mjs",
22
+ "scripts/upgrade-host-wire.mjs",
20
23
  "skills/",
21
24
  "host-owner/bin/",
22
25
  "gateway/bin/",
@@ -0,0 +1,100 @@
1
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, realpathSync, statSync } from "node:fs";
2
+ import { hostname } from "node:os";
3
+ import { dirname, isAbsolute } from "node:path";
4
+ import { isDeepStrictEqual } from "node:util";
5
+ import { requireEvidence, Unconfirmed } from "./upgrade-host-wire.mjs";
6
+
7
+ const fileLimit = 16 * 1024;
8
+ export const machine = { hostname: hostname(), platform: process.platform, uid: process.getuid() };
9
+
10
+ export function absolute(path) {
11
+ return typeof path === "string" && isAbsolute(path) && !path.includes("\0");
12
+ }
13
+
14
+ export function readJson(data) {
15
+ try {
16
+ return JSON.parse(data.toString());
17
+ } catch (error) {
18
+ if (error instanceof SyntaxError) throw new Unconfirmed("Invalid JSON evidence");
19
+ throw error;
20
+ }
21
+ }
22
+
23
+ export function entry(path) {
24
+ requireEvidence(absolute(path), "Evidence paths must be absolute");
25
+ return lstatSync(path, { bigint: true, throwIfNoEntry: false });
26
+ }
27
+
28
+ export function inode(stat) {
29
+ return { dev: stat.dev.toString(), ino: stat.ino.toString() };
30
+ }
31
+
32
+ function privateDirectory(stat) {
33
+ return stat?.isDirectory() && stat.uid === BigInt(machine.uid) && (stat.mode & 0o777n) === 0o700n;
34
+ }
35
+
36
+ export function socket(path) {
37
+ requireEvidence(absolute(path) && Buffer.byteLength(path) <= 100, "Invalid private Unix socket path");
38
+ const stat = entry(path);
39
+ requireEvidence(privateDirectory(entry(dirname(path))) && stat?.isSocket() &&
40
+ stat.uid === BigInt(machine.uid) && (stat.mode & 0o777n) === 0o600n,
41
+ `Not a private owned socket: ${path}`);
42
+ return inode(stat);
43
+ }
44
+
45
+ export function ownedFile(stat, path, mode) {
46
+ requireEvidence(stat?.isFile() && stat.uid === BigInt(machine.uid) && (stat.mode & mode) === 0n,
47
+ `Not an owned regular file with the required permissions: ${path}`);
48
+ }
49
+
50
+ function enclosedByPrivateDirectory(path) {
51
+ for (let directory = dirname(path); directory !== dirname(directory); directory = dirname(directory)) {
52
+ if (privateDirectory(entry(directory))) return true;
53
+ }
54
+ return false;
55
+ }
56
+
57
+ export function journal(path, worker) {
58
+ const leaf = entry(path);
59
+ const link = leaf?.isSymbolicLink();
60
+ requireEvidence(leaf?.isFile() || (link && !worker && leaf.uid === BigInt(machine.uid)),
61
+ "Managed journal is not an owned local link or regular file");
62
+ const resolvedPath = realpathSync(path);
63
+ const resolved = entry(resolvedPath);
64
+ ownedFile(resolved, path, 0o022n);
65
+ // Stock OMP can create regular journals with mode 0644 under private session directories.
66
+ requireEvidence((resolved.mode & 0o077n) === 0n || enclosedByPrivateDirectory(resolvedPath),
67
+ "Managed journal is not private");
68
+ const current = entry(path);
69
+ const target = link ? statSync(path, { bigint: true }) : current;
70
+ requireEvidence(current && current.uid === leaf.uid && isDeepStrictEqual(inode(current), inode(leaf)) &&
71
+ target.mode === resolved.mode && target.uid === resolved.uid && isDeepStrictEqual(inode(target), inode(resolved)),
72
+ "Managed journal changed during inspection");
73
+ return { resolvedPath, ...inode(resolved), ...(link ? { link: inode(leaf) } : {}) };
74
+ }
75
+
76
+ export function privateJson(path, stat, limit = fileLimit) {
77
+ ownedFile(stat, path, 0o077n);
78
+ const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
79
+ try {
80
+ const opened = fstatSync(fd, { bigint: true });
81
+ ownedFile(opened, path, 0o077n);
82
+ requireEvidence(isDeepStrictEqual(inode(opened), inode(stat)), `Evidence was replaced: ${path}`);
83
+ requireEvidence(opened.size <= BigInt(limit), "Evidence exceeded size limit");
84
+ const buffer = Buffer.alloc(Number(opened.size) + 1);
85
+ let length = 0;
86
+ while (length < buffer.length) {
87
+ const count = readSync(fd, buffer, length, buffer.length - length, null);
88
+ if (!count) break;
89
+ length += count;
90
+ }
91
+ const after = entry(path);
92
+ requireEvidence(length === buffer.length - 1 && after && after.mode === opened.mode && after.uid === opened.uid &&
93
+ isDeepStrictEqual(inode(after), inode(opened)) && after.size === opened.size &&
94
+ after.mtimeNs === opened.mtimeNs && after.ctimeNs === opened.ctimeNs,
95
+ `Evidence exceeded size limit or changed during read: ${path}`);
96
+ return readJson(buffer.subarray(0, length));
97
+ } finally {
98
+ closeSync(fd);
99
+ }
100
+ }
@@ -0,0 +1,192 @@
1
+ // Dependency-free operator probe for installations using the 0.1.10+ local wire.
2
+ import { request } from "node:http";
3
+ import { basename, dirname, join } from "node:path";
4
+ import { isDeepStrictEqual } from "node:util";
5
+ import { absolute, entry, inode, journal, machine, ownedFile, privateJson, readJson, socket } from "./upgrade-evidence-files.mjs";
6
+ import { logicalLimit, probeTimeoutMs, requireEvidence, Unconfirmed, wireLimit, withHost } from "./upgrade-host-wire.mjs";
7
+
8
+ const usage =
9
+ "Usage: upgrade-evidence.mjs capture gateway SOCKET | capture host SOCKET SESSION_ID [--worker] | recheck CAPTURE.json | stop-local CAPTURE.json STATUS.json LANE_ID | verify CAPTURE.json";
10
+
11
+ function validPid(pid) {
12
+ return Number.isInteger(pid) && pid > 0 && pid <= 0x7fffffff;
13
+ }
14
+
15
+ function text(value) {
16
+ return typeof value === "string" && value.length > 0;
17
+ }
18
+
19
+ function exists(pid) {
20
+ requireEvidence(validPid(pid), "Invalid native PID");
21
+ try {
22
+ process.kill(pid, 0);
23
+ return true;
24
+ } catch (error) {
25
+ if (error instanceof Error && error.code === "ESRCH") return false;
26
+ throw new Unconfirmed(`Cannot establish whether PID ${pid} exists`);
27
+ }
28
+ }
29
+
30
+ async function gatewayStatus(path) {
31
+ return new Promise((resolve, reject) => {
32
+ const req = request({ socketPath: path, path: "/status", signal: AbortSignal.timeout(probeTimeoutMs) }, async res => {
33
+ try {
34
+ requireEvidence(res.statusCode === 200, "Old Gateway did not return status");
35
+ const chunks = [];
36
+ let size = 0;
37
+ for await (const chunk of res) {
38
+ size += chunk.length;
39
+ requireEvidence(size <= wireLimit, "Gateway status exceeded size limit");
40
+ chunks.push(chunk);
41
+ }
42
+ const reply = readJson(Buffer.concat(chunks));
43
+ requireEvidence(reply?.ok === true && reply.value?.gateway && reply.value?.head, "Invalid Gateway status");
44
+ resolve(reply.value);
45
+ } catch (error) {
46
+ res.destroy();
47
+ reject(error);
48
+ }
49
+ });
50
+ req.on("error", reject);
51
+ req.end();
52
+ });
53
+ }
54
+
55
+ function hostEvidence({ socketPath, expectedSession, worker }, before, { state, workerIdentity }) {
56
+ const { hostPid: pid, adapterOwnerPid: ownerPid, sessionId, sessionFile, workerAttempt } = state;
57
+ requireEvidence(state.adapterProtocol === "owned-stock-stdio-v1" && pid !== ownerPid &&
58
+ validPid(pid) && validPid(ownerPid) && exists(pid) && exists(ownerPid) &&
59
+ text(sessionId) && sessionId === expectedSession && absolute(sessionFile), "Live Host did not match the expected native session");
60
+ requireEvidence(worker ? text(workerAttempt) && workerIdentity?.hostPid === pid &&
61
+ workerIdentity.adapterOwnerPid === ownerPid && workerIdentity.sessionId === sessionId &&
62
+ workerIdentity.sessionFile === sessionFile && workerIdentity.workerAttempt === workerAttempt
63
+ : workerAttempt === undefined && workerIdentity === undefined, "Host did not match the expected local/worker placement");
64
+ const journalIdentity = journal(sessionFile, worker);
65
+ const receiptPath = `${socketPath}.exit.json`;
66
+ const prior = entry(receiptPath);
67
+ if (prior) ownedFile(prior, receiptPath, 0o077n);
68
+ requireEvidence(isDeepStrictEqual(before, socket(socketPath)), `Host socket changed during capture: ${socketPath}`);
69
+ return { kind: "host", socketPath, socket: before, pid, ownerPid, sessionId, sessionFile, journal: journalIdentity,
70
+ ...(worker ? { workerAttempt } : {}), priorReceipt: prior ? inode(prior) : null };
71
+ }
72
+
73
+ function captureHost(expectation) {
74
+ const before = socket(expectation.socketPath);
75
+ return withHost(expectation.socketPath, live => hostEvidence(expectation, before, live));
76
+ }
77
+
78
+ async function stopLocal(host, status, laneId) {
79
+ requireEvidence(host.kind === "host" && host.workerAttempt === undefined &&
80
+ text(laneId) && !/[^a-zA-Z0-9_-]/.test(laneId) && laneId !== "main" && laneId !== "gateway",
81
+ "Only local lane captures and exact lane IDs are eligible for shutdown");
82
+ const main = status?.main?.socketPath;
83
+ requireEvidence(absolute(main) && basename(dirname(main)) === "run" && join(dirname(main), "main.sock") === main &&
84
+ Array.isArray(status.lanes), "Expected old managing CLI status with a main socket and lane inventory");
85
+ const lanes = status.lanes.filter(lane => lane?.id === laneId);
86
+ const [lane] = lanes;
87
+ const path = join(dirname(main), `${laneId}.sock`);
88
+ requireEvidence(lanes.length === 1 && isDeepStrictEqual(lane.placement, { target: "local" }) &&
89
+ path === lane.socketPath && lane.socketPath === host.socketPath && lane.sessionId === host.sessionId,
90
+ "Local lane identity or socket does not match the managing CLI target");
91
+ const before = socket(path);
92
+ const mainEntry = entry(main);
93
+ requireEvidence(isDeepStrictEqual(host.socket, before) &&
94
+ (!mainEntry || (mainEntry.isSocket() && !isDeepStrictEqual(inode(mainEntry), before))),
95
+ "Captured socket changed or cannot be distinguished from HEAD");
96
+ await withHost(path, async live => {
97
+ const current = hostEvidence({ socketPath: path, expectedSession: host.sessionId, worker: false }, before, live);
98
+ requireEvidence(isDeepStrictEqual(current, host), "Captured ownership changed; shutdown was not sent");
99
+ await live.shutdown();
100
+ });
101
+ return { result: "shutdown-accepted" };
102
+ }
103
+
104
+ function headAtRest(head) {
105
+ const terminal = [undefined, "complete", "refused"];
106
+ return terminal.includes(head.rotation?.stage) && [...terminal, "sleeping"].includes(head.hibernation?.stage);
107
+ }
108
+
109
+ async function captureGateway(socketPath) {
110
+ const before = socket(socketPath);
111
+ const { gateway, head } = await gatewayStatus(socketPath);
112
+ requireEvidence(gateway.stopping === false && validPid(gateway.pid) && exists(gateway.pid) &&
113
+ absolute(head.socketPath) && headAtRest(head),
114
+ "Gateway is stopping or did not identify live ownership");
115
+ const sleeping = head.hibernation?.stage === "sleeping";
116
+ if (sleeping) {
117
+ requireEvidence(head.pid === null && head.connected === false && head.ready === false && !head.error &&
118
+ text(head.hibernation.sessionId) && !entry(head.socketPath), "HEAD sleep was not confirmed");
119
+ }
120
+ const native = sleeping ? { kind: "sleeping", socketPath: head.socketPath, sessionId: head.hibernation.sessionId }
121
+ : await captureHost({ socketPath: head.socketPath, expectedSession: head.initialization?.sessionId, worker: false });
122
+ const after = await gatewayStatus(socketPath);
123
+ requireEvidence(after.gateway.pid === gateway.pid && after.gateway.stopping === false && headAtRest(after.head) &&
124
+ isDeepStrictEqual(before, socket(socketPath)) && head.socketPath === after.head.socketPath &&
125
+ (sleeping ? after.head.hibernation?.stage === "sleeping" && after.head.hibernation.sessionId === native.sessionId &&
126
+ after.head.pid === null && !after.head.error && !entry(head.socketPath)
127
+ : head.pid === native.pid && after.head.pid === native.pid && after.head.initialization?.sessionId === native.sessionId),
128
+ "Gateway or HEAD identity changed during capture");
129
+ return { kind: "gateway", socketPath, socket: before, pid: gateway.pid, head: native };
130
+ }
131
+
132
+ function exited(pid, path) {
133
+ requireEvidence(!exists(pid) && !entry(path), `PID ${pid} still exists or socket is still present: ${path}`);
134
+ }
135
+
136
+ function verifyHost(host) {
137
+ requireEvidence(host?.kind === "host" && host.pid !== host.ownerPid && text(host.sessionId) &&
138
+ (host.priorReceipt === null || text(host.priorReceipt?.dev) && text(host.priorReceipt?.ino)),
139
+ "Missing captured Host or prior-receipt identity");
140
+ exited(host.pid, host.socketPath);
141
+ requireEvidence(!exists(host.ownerPid), `Host owner PID ${host.ownerPid} still exists`);
142
+ const path = `${host.socketPath}.exit.json`;
143
+ const stat = entry(path);
144
+ ownedFile(stat, path, 0o077n);
145
+ requireEvidence(!isDeepStrictEqual(host.priorReceipt, inode(stat)), `Exit receipt predates capture: ${path}`);
146
+ const receipt = privateJson(path, stat);
147
+ requireEvidence(receipt?.pid === host.pid && receipt.ownerPid === host.ownerPid &&
148
+ receipt.sessionId === host.sessionId && receipt.sessionFile === host.sessionFile &&
149
+ receipt.workerAttempt === host.workerAttempt && receipt.code === 0 && receipt.signal === null &&
150
+ receipt.persisted === true && receipt.observationsFlushed === true, `Exit receipt does not match or prove clean exit: ${path}`);
151
+ requireEvidence(isDeepStrictEqual(journal(host.sessionFile, host.workerAttempt !== undefined), host.journal),
152
+ "Managed journal no longer matches the captured file");
153
+ }
154
+
155
+ async function run(args) {
156
+ const [mode, kind, path, sessionId, worker] = args;
157
+ if (mode === "capture") {
158
+ if (kind === "gateway" && args.length === 3) return { machine, endpoint: await captureGateway(path) };
159
+ if (kind === "host" && (args.length === 4 || (args.length === 5 && worker === "--worker")))
160
+ return { machine, endpoint: await captureHost({ socketPath: path, expectedSession: sessionId, worker: worker === "--worker" }) };
161
+ } else if (((mode === "verify" || mode === "recheck") && args.length === 2) || (mode === "stop-local" && args.length === 4)) {
162
+ const value = privateJson(kind, entry(kind));
163
+ const endpoint = value?.endpoint;
164
+ requireEvidence(isDeepStrictEqual(value?.machine, machine) && ["gateway", "host"].includes(endpoint?.kind),
165
+ "Use the unedited capture on the same machine under the same OS account");
166
+ if (mode === "stop-local") return stopLocal(endpoint, privateJson(path, entry(path), logicalLimit), sessionId);
167
+ if (mode === "recheck") {
168
+ const current = endpoint.kind === "gateway" ? await captureGateway(endpoint.socketPath)
169
+ : await captureHost({ socketPath: endpoint.socketPath, expectedSession: endpoint.sessionId,
170
+ worker: endpoint.workerAttempt !== undefined });
171
+ requireEvidence(isDeepStrictEqual(current, endpoint), "Captured ownership changed; do not stop or replace files");
172
+ } else if (endpoint.kind === "gateway") {
173
+ exited(endpoint.pid, endpoint.socketPath);
174
+ if (endpoint.head.kind === "sleeping") {
175
+ requireEvidence(!entry(endpoint.head.socketPath), "A HEAD socket appeared after sleep was captured");
176
+ } else {
177
+ verifyHost(endpoint.head);
178
+ }
179
+ } else {
180
+ verifyHost(endpoint);
181
+ }
182
+ return { result: mode === "verify" ? "exit-confirmed" : "identity-unchanged", endpoint };
183
+ }
184
+ throw new Unconfirmed(usage);
185
+ }
186
+
187
+ try {
188
+ console.log(JSON.stringify(await run(process.argv.slice(2)), null, 2));
189
+ } catch (error) {
190
+ console.error(error instanceof Unconfirmed ? error.message : "Could not read the private endpoint or evidence file");
191
+ process.exitCode = 1;
192
+ }
@@ -0,0 +1,162 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { createConnection } from "node:net";
3
+
4
+ export const probeTimeoutMs = 5000;
5
+ export const wireLimit = 1024 * 1024;
6
+ // Match the stock output codec used by the v0.1.10 owner, not its input limit.
7
+ const chunkSize = 256 * 1024;
8
+ const chunkCount = 256;
9
+ export const logicalLimit = chunkSize * chunkCount;
10
+ const base64Limit = Math.ceil(chunkSize / 3) * 4;
11
+ const utf8 = new TextDecoder("utf-8", { fatal: true });
12
+
13
+ export class Unconfirmed extends Error {}
14
+
15
+ export function requireEvidence(condition, problem) {
16
+ if (!condition) throw new Unconfirmed(problem);
17
+ }
18
+
19
+ function object(value) {
20
+ return value !== null && typeof value === "object" && !Array.isArray(value);
21
+ }
22
+
23
+ function readFrame(bytes) {
24
+ let frame;
25
+ try {
26
+ frame = JSON.parse(utf8.decode(bytes));
27
+ } catch (error) {
28
+ if (error instanceof SyntaxError || error instanceof TypeError) throw new Unconfirmed("Invalid Host wire JSON");
29
+ throw error;
30
+ }
31
+ requireEvidence(object(frame), "Host wire frame was not an object");
32
+ return frame;
33
+ }
34
+
35
+ class Chunks {
36
+ #pending;
37
+
38
+ accept(frame, version) {
39
+ const pending = this.#pending;
40
+ if (frame.type !== "rpc_chunk") {
41
+ requireEvidence(!pending, "Host chunk sequence interrupted");
42
+ return frame;
43
+ }
44
+ const { chunkId, index, count, byteLength, data } = frame;
45
+ requireEvidence(version === 2 && typeof chunkId === "string" && chunkId.length > 0 && chunkId.length <= 128 &&
46
+ Number.isInteger(count) && count >= 2 && count <= chunkCount && Number.isInteger(index) && index >= 0 && index < count &&
47
+ Number.isInteger(byteLength) && byteLength >= wireLimit && byteLength <= count * chunkSize,
48
+ "Invalid Host chunk metadata");
49
+ requireEvidence(pending
50
+ ? chunkId === pending.chunkId && count === pending.count && byteLength === pending.byteLength && index === pending.parts.length
51
+ : index === 0, "Host chunk sequence mismatch");
52
+ requireEvidence(typeof data === "string" && data.length > 0 && data.length <= base64Limit,
53
+ "Invalid Host chunk payload size");
54
+ const bytes = Buffer.from(data, "base64");
55
+ requireEvidence(bytes.length <= chunkSize && bytes.toString("base64") === data, "Invalid Host chunk base64");
56
+ const received = (pending?.received ?? 0) + bytes.length;
57
+ const remaining = count - index - 1;
58
+ requireEvidence(received + remaining <= byteLength && byteLength <= received + remaining * chunkSize,
59
+ "Host chunk sequence length mismatch");
60
+ const parts = pending?.parts ?? [];
61
+ parts.push(bytes);
62
+ if (remaining > 0) {
63
+ this.#pending = { chunkId, count, byteLength, received, parts };
64
+ return;
65
+ }
66
+ this.#pending = undefined;
67
+ const decoded = readFrame(Buffer.concat(parts, byteLength));
68
+ requireEvidence(decoded.type !== "rpc_chunk", "Nested Host chunks are invalid");
69
+ return decoded;
70
+ }
71
+
72
+ get incomplete() {
73
+ return this.#pending !== undefined;
74
+ }
75
+ }
76
+
77
+ async function* frames(peer, protocol) {
78
+ const line = Buffer.alloc(wireLimit);
79
+ const chunks = new Chunks();
80
+ let length = 0;
81
+ for await (const data of peer) {
82
+ let start = 0;
83
+ while (start < data.length) {
84
+ const newline = data.indexOf(10, start);
85
+ const end = newline < 0 ? data.length : newline;
86
+ requireEvidence(length + end - start < wireLimit, "Host frame exceeded size limit");
87
+ line.set(data.subarray(start, end), length);
88
+ length += end - start;
89
+ if (newline < 0) break;
90
+ const bytes = line.subarray(0, length);
91
+ length = 0;
92
+ start = end + 1;
93
+ if (bytes.every(byte => byte === 32 || byte === 9 || byte === 13)) continue;
94
+ const decoded = chunks.accept(readFrame(bytes), protocol.version);
95
+ if (decoded) yield decoded;
96
+ }
97
+ }
98
+ requireEvidence(length === 0 && !chunks.incomplete, "Host disconnected with an incomplete frame");
99
+ }
100
+
101
+ async function timed(peer, timeout, operation) {
102
+ const timer = setTimeout(() => peer.destroy(new Unconfirmed("Host request timed out")), timeout);
103
+ try {
104
+ return await operation();
105
+ } finally {
106
+ clearTimeout(timer);
107
+ }
108
+ }
109
+
110
+ export async function withHost(path, use) {
111
+ const peer = createConnection(path);
112
+ const protocol = { version: 1 };
113
+ const input = frames(peer, protocol);
114
+ async function read() {
115
+ const next = await input.next();
116
+ requireEvidence(!next.done, "Host disconnected before replying");
117
+ return next.value;
118
+ }
119
+ async function command(type, fields) {
120
+ const id = randomUUID();
121
+ peer.write(JSON.stringify({ type, id, ...fields }) + "\n");
122
+ for (;;) {
123
+ const frame = await read();
124
+ if (frame.type === "response" && frame.id === id) {
125
+ requireEvidence(frame.command === type, "Host returned a mismatched response");
126
+ return frame;
127
+ }
128
+ }
129
+ }
130
+ try {
131
+ const { state, workerIdentity } = await timed(peer, probeTimeoutMs, async () => {
132
+ const ready = await read();
133
+ requireEvidence(ready.type === "ready" && ready.protocolVersion === 1, "Not the old Host JSONL protocol");
134
+ if (Array.isArray(ready.supportedProtocolVersions) && ready.supportedProtocolVersions.includes(2)) {
135
+ const negotiated = await command("negotiate_protocol", { protocolVersion: 2 });
136
+ requireEvidence(negotiated.success === true && negotiated.data?.protocolVersion === 2, "Host did not negotiate protocol v2");
137
+ protocol.version = 2;
138
+ }
139
+ const reply = await command("get_state");
140
+ requireEvidence(reply.success === true && object(reply.data), "Host did not return owned native state");
141
+ return { state: reply.data, workerIdentity: ready.workerIdentity };
142
+ });
143
+ async function shutdown() {
144
+ let ack;
145
+ try {
146
+ // Preserve the old CLI's request deadline, separate from the identity probe.
147
+ ack = await timed(peer, 30_000, () => command("shutdown_host"));
148
+ } catch (error) {
149
+ if (error instanceof Error) throw new Unconfirmed("Host shutdown acknowledgement was lost; do not retry");
150
+ throw error;
151
+ }
152
+ requireEvidence(ack.success !== false, "Host refused graceful shutdown");
153
+ requireEvidence(ack.success === true && ack.data?.shutdown === true &&
154
+ ack.data.sessionId === state.sessionId && ack.data.sessionFile === state.sessionFile,
155
+ "Host shutdown acknowledgement did not confirm the verified session; do not retry");
156
+ }
157
+ return await use({ state, workerIdentity, shutdown });
158
+ } finally {
159
+ peer.destroy();
160
+ await input.return();
161
+ }
162
+ }
package/src/cli.ts CHANGED
@@ -8,7 +8,6 @@ import { inspectInstalledOmp } from "./omp/installed-omp";
8
8
  import { requireHostOwner } from "./omp/host-owner-path";
9
9
  import { loadCredentials } from "./config/credentials";
10
10
  import { WORKFLOW_NAMES, type Lane } from "./contracts";
11
- import type { HostConnection } from "./omp/host";
12
11
  import { readLaneRows } from "./lane/lane-rows";
13
12
 
14
13
  // Keep Host/SDK imports out of setup, doctor and command registration:
@@ -375,28 +374,9 @@ export async function main(args = process.argv.slice(2)): Promise<void> {
375
374
  }
376
375
  const lane = laneRows(config.stateDir).find(record => record.id === target);
377
376
  if (!lane) throw new Error("Unknown managed lane");
378
- const remote = lane.remote;
379
- let host: HostConnection;
380
- if (remote) {
381
- const { lookupWorker, remoteLanePaths, workerConnect, workerRef } = await import("./worker/worker-wire");
382
- const paths = remoteLanePaths(remote, lane.id);
383
- if (lane.pid === null || !lane.sessionId || lane.sessionFile !== paths.sessionFile || lane.socketPath !== paths.socketPath)
384
- throw new Error("Remote lane has no recorded Host identity eligible for shutdown");
385
- host = await workerConnect(await lookupWorker(config.stateDir, remote), workerRef(lane));
386
- } else {
387
- const { connect } = await import("./omp/host");
388
- host = await connect(hostPaths(config, target).socketPath);
389
- }
390
- try {
391
- if (remote) {
392
- const state = await host.client.getState();
393
- if (state.hostPid !== lane.pid || state.sessionId !== lane.sessionId || state.sessionFile !== lane.sessionFile)
394
- throw new Error("Remote Host identity no longer matches the recorded lane; shutdown was not sent");
395
- }
396
- const response = await host.request({ type: "shutdown_host" });
397
- if (!response.success) throw new Error(response.error ?? "Host refused shutdown");
398
- console.log(`Host ${target} accepted graceful shutdown.`);
399
- } finally { await host.close(); }
377
+ const { stopManagedLane } = await import("./operator/stop-lane");
378
+ await stopManagedLane(config, lane);
379
+ console.log(`Host ${target} accepted graceful shutdown.`);
400
380
  return;
401
381
  }
402
382
  if (target !== "main") {
@@ -219,10 +219,14 @@ try {
219
219
  }
220
220
  else if (operation === "prepare") throw new Error("Session preparation follows launch discovery");
221
221
  else if (operation === "inventory" || operation === "fit") {
222
+ if (!path) throw new Error("Host manifest is required");
222
223
  const input = await Bun.stdin.json();
223
- const manifest: Manifest = await Bun.file(path!).json();
224
+ const manifest: Manifest = await Bun.file(path).json();
224
225
  process.stdout.write(JSON.stringify(await run(operation, manifest, input)));
225
- } else throw new Error("Unknown Host SDK operation");
226
+ } else {
227
+ console.error("Unsupported Host SDK operation");
228
+ process.exitCode = 1;
229
+ }
226
230
  } catch {
227
231
  // SDK errors may contain native frames, authorization data or prompt content.
228
232
  console.error("Host SDK operation failed");
@@ -0,0 +1,25 @@
1
+ import { hostPaths, type Config } from "../config/config";
2
+ import type { Lane } from "../contracts";
3
+ import { HostConnection } from "../omp/host";
4
+ import { lookupWorker, remoteLanePaths, workerConnect, workerRef } from "../worker/worker-wire";
5
+
6
+ /** The saved lane and selected instance must agree before contact. Send the
7
+ * stop only over the connection on which its native identity was established. */
8
+ export async function stopManagedLane(config: Config, lane: Lane): Promise<void> {
9
+ const remote = lane.remote;
10
+ const paths = remote ? remoteLanePaths(remote, lane.id) : hostPaths(config, lane.id);
11
+ if (!lane.pid || !lane.sessionId || lane.socketPath !== paths.socketPath || (remote && lane.sessionFile !== paths.sessionFile))
12
+ throw new Error("Lane has no recorded Host identity eligible for shutdown");
13
+
14
+ const endpoint = remote ? {
15
+ connection: await workerConnect(await lookupWorker(config.stateDir, remote), workerRef(lane)),
16
+ } : await HostConnection.open(paths.socketPath);
17
+ try {
18
+ const state = "state" in endpoint ? endpoint.state : await endpoint.connection.client.getState();
19
+ if (state.hostPid !== lane.pid || state.sessionId !== lane.sessionId || state.sessionFile !== lane.sessionFile ||
20
+ (!remote && "workerAttempt" in state))
21
+ throw new Error("Host identity no longer matches the recorded lane; shutdown was not sent");
22
+ const response = await endpoint.connection.request({ type: "shutdown_host" });
23
+ if (!response.success) throw new Error(response.error ?? "Host refused shutdown");
24
+ } finally { await endpoint.connection.close(); }
25
+ }