omp-superagent 0.1.11 → 0.1.15

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.
Files changed (82) hide show
  1. package/DESIGN.md +21 -5
  2. package/README.ko.md +3 -1
  3. package/README.md +3 -1
  4. package/THIRD_PARTY_NOTICES.md +6 -0
  5. package/assets/architecture-dark.svg +4 -4
  6. package/assets/architecture.ko-dark.svg +4 -4
  7. package/assets/architecture.ko.svg +4 -4
  8. package/assets/architecture.mmd +5 -5
  9. package/assets/architecture.svg +4 -4
  10. package/config.example.json +1 -0
  11. package/docs/OPERATIONS.en.md +242 -31
  12. package/docs/OPERATIONS.md +225 -25
  13. package/docs/design/execution.md +161 -43
  14. package/docs/design/messaging.md +45 -9
  15. package/docs/releases/0.1.11.md +4 -2
  16. package/docs/releases/0.1.13.md +13 -0
  17. package/docs/releases/0.1.15.md +13 -0
  18. package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
  19. package/gateway/bin/omp-gateway-darwin-x64 +0 -0
  20. package/gateway/bin/omp-gateway-linux-arm64 +0 -0
  21. package/gateway/bin/omp-gateway-linux-x64 +0 -0
  22. package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
  23. package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
  24. package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
  25. package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
  26. package/package.json +9 -3
  27. package/scripts/prepare-worker-memory.ts +37 -0
  28. package/scripts/upgrade-evidence-files.mjs +100 -0
  29. package/scripts/upgrade-evidence.mjs +192 -0
  30. package/scripts/upgrade-host-wire.mjs +162 -0
  31. package/skills/head/SKILL.md +22 -47
  32. package/skills/head/references/routing.md +11 -12
  33. package/skills/head/references/supervision.md +10 -14
  34. package/skills/lane/SKILL.md +14 -16
  35. package/skills/lane/references/workflow.md +14 -27
  36. package/src/cli.ts +59 -79
  37. package/src/config/config.ts +4 -0
  38. package/src/contracts.ts +34 -27
  39. package/src/cron/cron-jobs.ts +4 -3
  40. package/src/cron/cron-pr-intake.ts +1 -2
  41. package/src/extension.ts +57 -14
  42. package/src/gateway/gateway-client.ts +14 -12
  43. package/src/group/group-runner.ts +3 -2
  44. package/src/group-runner-extension.ts +7 -3
  45. package/src/host-extension.ts +109 -2
  46. package/src/host-sdk-helper.ts +12 -3
  47. package/src/lane/decision-tool.ts +2 -3
  48. package/src/lane/lane-report.ts +8 -30
  49. package/src/lane/lane-rows.ts +1 -1
  50. package/src/lane/workflow.ts +44 -3
  51. package/src/lane-extension.ts +5 -46
  52. package/src/messaging/discord-context.ts +8 -6
  53. package/src/omp/host-protocol.ts +4 -3
  54. package/src/omp/host.ts +24 -7
  55. package/src/omp/managed-super.ts +43 -27
  56. package/src/omp/native-sessions.ts +12 -0
  57. package/src/omp/worker-memory-import.ts +410 -0
  58. package/src/omp/worker-memory-sdk.ts +8 -0
  59. package/src/operator/setup.ts +8 -13
  60. package/src/operator/stop-lane.ts +25 -0
  61. package/src/pr/pr-github-schema.ts +9 -0
  62. package/src/pr/pr-github.ts +6 -2
  63. package/src/pr/pr-intake-automation.ts +11 -8
  64. package/src/pr/pr-intake-fix.ts +2 -5
  65. package/src/pr/pr-intake-review.ts +7 -7
  66. package/src/routing/topic-history.ts +2 -2
  67. package/src/runtime/controller.ts +444 -408
  68. package/src/runtime/head-recovery.ts +7 -7
  69. package/src/runtime/worker-memory.ts +156 -0
  70. package/src/storage/deferred-routing.ts +1 -7
  71. package/src/storage/store.ts +441 -375
  72. package/src/worker/worker-host.ts +3 -2
  73. package/src/worker/worker-ledger.ts +20 -11
  74. package/src/worker/worker-memory-page.ts +83 -0
  75. package/src/worker/worker-memory-proofs.ts +260 -0
  76. package/src/worker/worker-memory-source.ts +305 -0
  77. package/src/worker/worker-memory-storage.ts +130 -0
  78. package/src/worker/worker-profile.ts +2 -0
  79. package/src/worker/worker-repository.ts +92 -7
  80. package/src/worker/worker-request.ts +1 -0
  81. package/src/worker/worker-service.ts +25 -8
  82. package/src/worker/worker-wire.ts +20 -6
@@ -37,6 +37,10 @@ still parses as a command.
37
37
  The owner, guild and parent-channel checks still apply. Owner DMs, Discord
38
38
  application commands, approval components and restricted group rooms retain
39
39
  their existing policies.
40
+ An ordinary message from the configured owner in an allowed guild but excluded
41
+ parent channel is not admitted or answered. Once routing identifies the
42
+ exclusion, the Gateway can log only the guild, destination and parent IDs, at
43
+ most once per second per Discord adapter, with no additional metadata lookup.
40
44
 
41
45
  Standalone owner preferences, such as the shared reply voice, cannot be set
42
46
  through a reply, forward, or attachment. Adapters keep that provenance even
@@ -222,6 +226,21 @@ before the foreign completion is still sent to its own conversation. If a
222
226
  native batch cannot be split by origin, only individually identified job
223
227
  receipts are sent.
224
228
 
229
+ Same-conversation Discord HEAD steers still share one final answer. When the
230
+ native session has observed a steer before that answer and completed its
231
+ correlated prompt, the controller records its physical source with the answer.
232
+ The opening request may be a Discord application command with no physical
233
+ message of its own. An unrelated background result or notification cannot
234
+ prove that a joined message was answered, even in the same topic. A clean
235
+ answer observed before that input can still provide proof if selected for
236
+ delivery. An observed job launched in a continuation proved by a completion
237
+ from the same request can contribute to its answer.
238
+ Once Discord confirms the answer's message ID, the outbox queues a short inline
239
+ link for each distinct joined message; a deleted source cannot fall back to a
240
+ standalone link. This does not duplicate the answer or claim that each
241
+ request's work succeeded. An uncertain or failed answer send does not produce
242
+ a link.
243
+
225
244
  ### Uncertain submissions
226
245
 
227
246
  Do not replay an ambiguous native prompt, approval response or external mutation.
@@ -413,6 +432,19 @@ See the [operations guide](../OPERATIONS.en.md#4-commands-and-daily-use) for com
413
432
  and deliver one result for a jointly handled cohort. History lookup verifies
414
433
  a joined reply's topic ownership and its own completed native receipt, not the
415
434
  manager's instructions or completion.
435
+ An authenticated owner's direct, explicit work instruction in the bound topic
436
+ can [revise the lane's scope or acceptance](execution.md#direct-owner-changes-to-bound-topic-work)
437
+ within the selected workspace once consumed, including on a steer. This keeps
438
+ the normal reporting mode and does not grant authority to quoted or forwarded
439
+ material, or to sibling tasks. Before submitting direct work, including a steer
440
+ or queued request after restart, verify the original account and route with
441
+ the connected Gateway. If the account cannot be verified, keep it pending.
442
+ An original physically older than an already admitted message in the same
443
+ logical topic is retained but not submitted as a fresh instruction. Normal
444
+ ordered inputs are not superseded merely because several are queued together.
445
+ For Telegram, use the written selector and the adapter's formatting evidence
446
+ consistently at admission, scheduling and dispatch: quoted selectors cannot
447
+ select a workflow or force a standalone turn. Formatted arguments remain data.
416
448
  Controls, internal reports and workflow selection do not join the run.
417
449
  Pause, approval, compaction and uncertainty gates still apply. Durable intake
418
450
  and RPC admission do not prove consumption: OMP consumes steers at native
@@ -582,8 +614,6 @@ a bound topic. On admission of the valid source, the controller immediately
582
614
  queues one durable HEAD review tied to the same pending native lane dialog.
583
615
  Queueing is not an answer or a guarantee of when HEAD will reply. An unowned
584
616
  native dialog after reconnect is held if its original topic cannot be verified.
585
- Corrective assignments retain owner-only routing: an explicit `to: "head"`
586
- question is refused and cancelled privately, not shown to the owner.
587
617
 
588
618
  The isolated HEAD review permits only `lane_review_decision` for that dialog.
589
619
  For a routine reversible choice shown to be within the assignment, HEAD
@@ -591,14 +621,20 @@ returns an original option to the lane and records the reason internally,
591
621
  without a separate messenger message. When the owner must decide or the
592
622
  supplied evidence cannot establish scope, HEAD escalates that same dialog;
593
623
  the original route gets the card with the unchanged questions and choices
594
- and the reason for escalation. If HEAD stops during an existing regular
624
+ and the reason for escalation. If HEAD stops during an existing
595
625
  review, the controller may escalate that exact pending dialog to the original
596
- owner. This fallback does not apply to refused corrective-assignment questions.
597
- Recommendations are not preselected. This path does not change assignment
598
- scope, grant tool permission or manufacture user consent. Use the
599
- [source-bound scope review](execution.md#bound-topic-assignment-scope-review)
600
- for a conflicting original owner correction. Recommendation, silence, normal
601
- text, quotes and reports are not approval.
626
+ owner. Recommendations are not preselected. This path does not change
627
+ assignment scope, grant tool permission or manufacture user consent. A direct
628
+ bound-topic work instruction can revise the task, but recommendation, silence,
629
+ normal text, quotes and reports are not replies to a native approval card.
630
+
631
+ On upgrade, a card that may belong to an interrupted legacy HEAD scope review
632
+ cannot be displayed or answered as an ordinary approval. Retire an already
633
+ presented card on its exact original route; a lost dismissal receipt is not
634
+ permission to send another dismissal or a native response. A later, verified
635
+ native goal resume can own a new dialog without reviving a previously held one.
636
+ The lane reopens in the same SQLite transaction that records the resume's native
637
+ owner and request ID. A failed ownership read or a duplicate cannot lift a pause.
602
638
 
603
639
  ## Content and delivery
604
640
 
@@ -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)
@@ -0,0 +1,13 @@
1
+ # omp-superagent 0.1.15
2
+
3
+ - In a bound topic, the authenticated owner can change a lane’s assignment directly. The lane keeps its workspace and the conditions the owner did not change; it does not ask HEAD to approve the new scope. Pauses and native approvals still apply.
4
+ - A late original message cannot override a newer instruction in the same topic. On upgrade, retired scope-review cards cannot authorize new work, and uncertain deliveries are not replayed.
5
+ - After `/restart` interrupts an active HEAD goal, the replacement can continue that same goal on its original conversation. It does not replay the interrupted prompt or move its approvals to the conversation that requested the restart.
6
+ - Discord links joined HEAD replies to their original messages. The optional `remoteMemorySync` setting lets HEAD pull eligible project facts from an idle paired SSH lane; it is off by default.
7
+ - The Gateway adapters now share native dialog validation, and Gateway and Host share RPC chunk limits. The test suite reuses its loopback operator across workers, and CI caches Rust dependencies without skipping tests or reusing tagged package builds.
8
+
9
+ **Before upgrading**, follow the [upgrade procedure](https://github.com/dbc-hbin/omp-superagent/blob/v0.1.15/docs/OPERATIONS.en.md#update-an-existing-installation) ([한국어](https://github.com/dbc-hbin/omp-superagent/blob/v0.1.15/docs/OPERATIONS.md#기존-설치-업데이트)). Use the old installation to stop affected resident lanes and Gateway/HEAD and verify their exits. `stop main` alone does not stop independent lanes. Keep the original config and journals, install `omp-superagent@0.1.15`, and restart only previously running Gateways.
10
+
11
+ The `v0.1.14` tag did not publish a package: native restart and bound-topic steering checks failed before publication.
12
+
13
+ [Changes since 0.1.13](https://github.com/dbc-hbin/omp-superagent/compare/v0.1.13...v0.1.15)
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.15",
4
4
  "description": "One messenger-connected OMP head with independent work sessions",
5
5
  "license": "MIT",
6
6
  "author": "dbc-hbin",
@@ -16,7 +16,11 @@
16
16
  "src/",
17
17
  "scripts/build-host-owner.ts",
18
18
  "scripts/prepare-super.ts",
19
+ "scripts/prepare-worker-memory.ts",
19
20
  "scripts/setup.sh",
21
+ "scripts/upgrade-evidence-files.mjs",
22
+ "scripts/upgrade-evidence.mjs",
23
+ "scripts/upgrade-host-wire.mjs",
20
24
  "skills/",
21
25
  "host-owner/bin/",
22
26
  "gateway/bin/",
@@ -35,7 +39,8 @@
35
39
  "build:owner": "bun --no-env-file scripts/build-host-owner.ts --owner",
36
40
  "build:native": "bun --no-env-file scripts/build-host-owner.ts",
37
41
  "check": "tsc --noEmit",
38
- "test": "bun run build:native && cargo build --locked --manifest-path gateway/Cargo.toml --example operator-loopback && bun test --parallel=2 test",
42
+ "test": "bun run build:native && bun run test:suite",
43
+ "test:suite": "operator=$(bun --no-env-file test/fixtures/operator.ts) && OMP_TEST_OPERATOR_LOOPBACK_BIN=\"$operator\" bun --no-env-file test --parallel=2 test",
39
44
  "test:ci": "bun run build:native && bun --no-env-file scripts/ci.ts",
40
45
  "test:baseline": "bash scripts/test-omp.sh",
41
46
  "release": "bun --no-env-file scripts/release.ts",
@@ -43,7 +48,7 @@
43
48
  "setup": "bash scripts/setup.sh",
44
49
  "prepare:ulw": "bun scripts/prepare-super.ts",
45
50
  "prepare": "bun run build:native --install",
46
- "postinstall": "bun scripts/prepare-super.ts"
51
+ "postinstall": "bun --no-env-file scripts/prepare-worker-memory.ts && bun scripts/prepare-super.ts"
47
52
  },
48
53
  "engines": {
49
54
  "bun": ">=1.4.4"
@@ -51,6 +56,7 @@
51
56
  "dependencies": {
52
57
  "@oh-my-pi/pi-catalog": "19.2.1",
53
58
  "@oh-my-pi/pi-coding-agent": "19.2.1",
59
+ "@oh-my-pi/pi-mnemopi": "19.2.1",
54
60
  "@oh-my-pi/pi-natives": "19.2.1",
55
61
  "@oh-my-pi/pi-utils": "19.2.1",
56
62
  "@sinclair/typebox": "^0.34.41",
@@ -0,0 +1,37 @@
1
+ #!/usr/bin/env bun
2
+ import { mkdir, rename, rm, writeFile } from "node:fs/promises";
3
+ import { join, resolve } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ // The standalone OMP extension loader supplies these stock modules directly.
7
+ // Bundle only the unexposed Mnemopi helpers, from the installed locked SDK.
8
+ const root = resolve(import.meta.dir, "..");
9
+ const nativeConfig = fileURLToPath(import.meta.resolve("@oh-my-pi/pi-coding-agent/mnemopi/config"));
10
+ const result = await Bun.build({
11
+ entrypoints: [join(root, "src/omp/worker-memory-sdk.ts")],
12
+ target: "bun",
13
+ format: "esm",
14
+ minify: true,
15
+ external: ["@oh-my-pi/pi-utils", "@oh-my-pi/pi-utils/lru", "@oh-my-pi/pi-natives",
16
+ "@oh-my-pi/pi-ai", "@oh-my-pi/pi-ai/error", "@oh-my-pi/pi-catalog/hosts"],
17
+ plugins: [{
18
+ name: "stock-expand-tilde",
19
+ setup(build) {
20
+ // v19.2.1 imports only expandTilde here; path-utils re-exports it
21
+ // unchanged from pi-utils. Do not pull unrelated editing tools into OMP.
22
+ build.onResolve({ filter: /^\.\.\/tools\/path-utils$/ }, ({ importer }) =>
23
+ importer === nativeConfig ? { path: "@oh-my-pi/pi-utils", external: true } : undefined);
24
+ },
25
+ }],
26
+ });
27
+ const [module] = result.outputs;
28
+ if (!result.success || !module || result.outputs.length !== 1)
29
+ throw new AggregateError(result.logs, "Could not prepare the stock worker memory helpers");
30
+
31
+ const directory = join(root, ".upstream");
32
+ await mkdir(directory, { recursive: true });
33
+ const output = join(directory, "worker-memory-sdk.mjs");
34
+ const staging = `${output}.${crypto.randomUUID()}`;
35
+ await writeFile(staging, new Uint8Array(await module.arrayBuffer()), { flag: "wx" });
36
+ try { await rename(staging, output); }
37
+ finally { await rm(staging, { force: true }); }
@@ -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
+ }