@zieglar/pi-chat-exchange 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,17 +1,17 @@
1
- import { constants } from "node:sqlite";
2
1
  export class StorageTransactionError extends Error {
3
- code;
2
+ code = "STORAGE_TRANSACTION_FAILED";
4
3
  stage;
5
- outcome;
6
4
  retryable;
7
5
  constructor(message, stage, options) {
8
6
  super(message, options);
9
7
  this.name = "StorageTransactionError";
8
+ this.stage = stage;
10
9
  this.outcome = options?.outcome ?? "INDETERMINATE";
11
10
  this.retryable = options?.busy === true && this.outcome === "ROLLED_BACK";
12
- this.code = this.retryable ? "STORAGE_TRANSACTION_BUSY" : "STORAGE_TRANSACTION_FAILED";
13
- this.stage = stage;
11
+ if (this.retryable)
12
+ this.code = "STORAGE_TRANSACTION_BUSY";
14
13
  }
14
+ outcome;
15
15
  }
16
16
  export class ConditionalMutationError extends Error {
17
17
  code = "STORAGE_CONDITIONAL_MUTATION_FAILED";
@@ -31,7 +31,7 @@ function invalidate(db) {
31
31
  catch {
32
32
  // If close itself fails, poison authorization as well as helper reuse.
33
33
  try {
34
- db.setAuthorizer(() => constants.SQLITE_DENY);
34
+ db.setAuthorizerPolicy("deny-all");
35
35
  }
36
36
  catch { /* already unusable */ }
37
37
  }
@@ -106,8 +106,6 @@ export function withImmediateTransaction(db, callback) {
106
106
  });
107
107
  }
108
108
  let capabilityActive = true;
109
- let ownerControl = false;
110
- let controlAttempted = false;
111
109
  const assertActive = () => {
112
110
  if (!capabilityActive)
113
111
  throw new StorageTransactionError("transaction handle is revoked", "callback");
@@ -120,11 +118,10 @@ export function withImmediateTransaction(db, callback) {
120
118
  assertActive();
121
119
  const statement = db.prepare(sql);
122
120
  return Object.freeze({
123
- // Parameters extracts the named overload; the cast retains both overloads.
124
121
  // Every supplied argument is forwarded unchanged to SQLite's typed method.
125
- run: ((...args) => { assertActive(); return statement.run(...args); }),
126
- get: ((...args) => { assertActive(); return statement.get(...args); }),
127
- all: ((...args) => { assertActive(); return statement.all(...args); }),
122
+ run: (...args) => { assertActive(); return statement.run(...args); },
123
+ get: (...args) => { assertActive(); return statement.get(...args); },
124
+ all: (...args) => { assertActive(); return statement.all(...args); },
128
125
  });
129
126
  },
130
127
  });
@@ -132,22 +129,19 @@ export function withImmediateTransaction(db, callback) {
132
129
  try {
133
130
  // SQLite authorizes parsed actions, including previously prepared statements
134
131
  // invalidated by setAuthorizer. Not a SQL-prefix/regex filter.
135
- db.setAuthorizer((action) => {
136
- if (!ownerControl && (action === constants.SQLITE_TRANSACTION || action === constants.SQLITE_SAVEPOINT)) {
137
- controlAttempted = true;
138
- return constants.SQLITE_DENY;
139
- }
140
- return constants.SQLITE_OK;
141
- });
132
+ db.setAuthorizerPolicy("deny-transaction-control");
142
133
  assertVoidResult(callback(tx));
143
- if (controlAttempted)
134
+ if (db.authorizerDenials() > 0)
144
135
  throw new Error("callback attempted owned transaction control");
145
136
  if (!db.isTransaction)
146
137
  throw new Error("owned transaction ended unexpectedly");
147
138
  }
148
139
  catch (error) {
149
140
  capabilityActive = false;
150
- ownerControl = true;
141
+ try {
142
+ db.setAuthorizerPolicy("off");
143
+ }
144
+ catch { /* rollback classification owns closed state */ }
151
145
  rollbackOwnedTransaction(db, error);
152
146
  if (error instanceof ConditionalMutationError)
153
147
  throw error;
@@ -157,7 +151,10 @@ export function withImmediateTransaction(db, callback) {
157
151
  }
158
152
  finally {
159
153
  capabilityActive = false;
160
- ownerControl = true;
154
+ try {
155
+ db.setAuthorizerPolicy("off");
156
+ }
157
+ catch { /* do not mask the original outcome */ }
161
158
  }
162
159
  try {
163
160
  db.exec("COMMIT");
@@ -183,7 +180,7 @@ export function withImmediateTransaction(db, callback) {
183
180
  capabilityActive = false;
184
181
  if (!invalidated.has(db)) {
185
182
  try {
186
- db.setAuthorizer(null);
183
+ db.setAuthorizerPolicy("off");
187
184
  }
188
185
  catch {
189
186
  invalidate(db);
@@ -42,7 +42,7 @@ export const TUNNEL_REFUSAL_CODES = [
42
42
  "CE_TUNNEL_STATE_CORRUPT",
43
43
  ];
44
44
  const MESSAGES = Object.freeze({
45
- CE_TUNNEL_PROFILE_INVALID: "tunnel profile shape rejected; for the MCP Node command, verify trusted absolute CE_NODE_PATH (approved Node 24.21.0 or 24.22.1)",
45
+ CE_TUNNEL_PROFILE_INVALID: "tunnel profile shape rejected; for the MCP Node command, verify trusted absolute CE_NODE_PATH (candidate Node >=24.12.0 within majors 24/25/26 with SQLite >=3.51.3 and proven capabilities)",
46
46
  CE_TUNNEL_DOCTOR_FAILED: "tunnel client preflight did not pass",
47
47
  CE_TUNNEL_SPAWN_FAILED: "tunnel client could not be started; verify trusted absolute CE_TUNNEL_CLIENT_PATH or a trusted system installation (no project PATH fallback)",
48
48
  CE_TUNNEL_READY_TIMEOUT: "tunnel client did not present health evidence in time",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zieglar/pi-chat-exchange",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "license": "MIT",
5
5
  "publishConfig": {
6
6
  "access": "public",
@@ -14,15 +14,17 @@
14
14
  },
15
15
  "type": "module",
16
16
  "engines": {
17
- "node": "24.21.0 || 24.22.1"
17
+ "node": ">=22.19.0"
18
18
  },
19
19
  "scripts": {
20
- "test": "CE_DEFAULT_CLIENT_GUARD=1 vitest run --exclude test/tunnel/real-client-compat.test.ts --exclude test/tunnel/offline.integration.test.ts --exclude test/host-regression/real-host-recovery.test.ts --exclude test/package/installed-host.test.ts",
20
+ "test": "CE_DEFAULT_CLIENT_GUARD=1 vitest run --exclude test/tunnel/real-client-compat.test.ts --exclude test/tunnel/offline.integration.test.ts --exclude test/host-regression/real-host-recovery.test.ts --exclude test/package/installed-host.test.ts --exclude '**/native-{artifact,value-regression,cli}.test.ts' --exclude '**/sqlite-driver-cross.test.ts'",
21
21
  "test:distribution-host": "CE_DISTRIBUTION_HOST_TEST=1 vitest run test/package/installed-host.test.ts",
22
22
  "test:distribution-npm": "CE_DISTRIBUTION_HOST_TEST=1 CE_DISTRIBUTION_MODE=managed-npm vitest run test/package/installed-host.test.ts",
23
23
  "test:installed-client": "vitest run test/tunnel/real-client-compat.test.ts test/tunnel/offline.integration.test.ts",
24
24
  "test:host-regression": "CE_HOST_REGRESSION_TEST=1 vitest run test/host-regression/real-host-recovery.test.ts",
25
- "test:storage": "vitest run test/storage",
25
+ "test:storage": "vitest run test/storage --exclude '**/native-{artifact,value-regression,cli}.test.ts' --exclude '**/sqlite-driver-cross.test.ts'",
26
+ "native": "node dist/bin/ce-native.js",
27
+ "test:rust-native": "vitest run --config test/rust-native.vitest.config.ts --dir test/storage --testTimeout 120000 --hookTimeout 120000 --exclude '**/runtime-cross-version.test.ts' --exclude '**/runtime-wal-safety.test.ts' --exclude '**/inbox-ack-volume.test.ts'",
26
28
  "test:plugin-package": "CE_PLUGIN_PACKAGE_TEST=1 vitest run test/plugin/local-plugin-package.test.ts",
27
29
  "test:watch": "vitest",
28
30
  "typecheck": "tsc --noEmit -p tsconfig.json",
@@ -31,7 +33,7 @@
31
33
  "package:desktop-plugin": "node scripts/package-local-plugin.mjs",
32
34
  "recover:ownership": "node scripts/recover-stale-ownership.mjs",
33
35
  "reconcile:session-mutex": "node scripts/reconcile-session-process-mutex.mjs",
34
- "check": "node scripts/check-contract.mjs",
36
+ "check": "node scripts/check-contract.mjs && node scripts/check-native.mjs",
35
37
  "verify": "pnpm run check && pnpm run typecheck && pnpm run build && pnpm test && pnpm run test:plugin-package"
36
38
  },
37
39
  "dependencies": {
@@ -48,25 +50,11 @@
48
50
  },
49
51
  "files": [
50
52
  "pi-extension/*.ts",
51
- "pi-extension/README.md",
52
53
  "pi-extension/allowlist.example.json",
53
54
  "dist/**/*.js",
54
55
  "native/tunnel-keychain.swift",
55
56
  "scripts/recover-stale-ownership.mjs",
56
- "scripts/reconcile-session-process-mutex.mjs",
57
- "docs/independent-install.md",
58
- "docs/tunnel-setup.md",
59
- "docs/multi-session-usage.md",
60
- "docs/chatgpt-installation.md",
61
- "docs/architecture.md",
62
- "docs/tunnel-manager-background.md",
63
- "docs/protocol-v2.md",
64
- "docs/ownership-contract.md",
65
- "docs/storage-contract.md",
66
- "docs/delivery-ack-contract.md",
67
- "docs/storage-security.md",
68
- "CHANGELOG.md",
69
- "docs/releases/0.2.0.md"
57
+ "scripts/reconcile-session-process-mutex.mjs"
70
58
  ],
71
59
  "peerDependencies": {
72
60
  "@earendil-works/pi-coding-agent": "1.3.0"
@@ -49,6 +49,7 @@ import { PI_ADAPTER_KIND } from "../dist/endpoints/pi/contract.js";
49
49
  import { initializeStore, openStore } from "../dist/storage/store.js";
50
50
  import { RuntimeEligibilityError } from "../dist/storage/runtime.js";
51
51
  import { diagnoseInstallation, hostRuntimeRepairMessage, installationDiagnosticMessage } from "../dist/runtime/diagnostics.js";
52
+ import { assertNativeReadyForTunnel, inspectNativeReadiness, runNativeCommand, NATIVE_STARTUP_WARNING } from "../dist/runtime/native-readiness.js";
52
53
  import { TunnelRefusal } from "../dist/tunnel/codes.js";
53
54
  import {
54
55
  captureTunnelSecret,
@@ -389,6 +390,14 @@ function openHostStore(allowlist: AllowlistFile) {
389
390
  const TUNNEL_STATUS_KEYS = ["ce", "ce-tunnel", "ce-client"] as const;
390
391
 
391
392
  export default function ceChatExchange(pi: ExtensionApiView): void {
393
+ // Management is registered independently of subsequent Store/session activation.
394
+ let nativeStartupWarned = false;
395
+ pi.registerCommand("ce-native", {
396
+ description: "Inspect, install or verify the trusted Native driver; check release discovery",
397
+ async handler(args, ctx) {
398
+ notify(ctx, await runNativeCommand(args), "info");
399
+ },
400
+ });
392
401
  // Transport UI, the offline manager, and any in-flight credential capture
393
402
  // belong to THIS factory instance, independently of CE generation.
394
403
  let lastUiPort: ExtensionContextView | undefined;
@@ -986,6 +995,17 @@ export default function ceChatExchange(pi: ExtensionApiView): void {
986
995
  };
987
996
 
988
997
  pi.on("session_start", async (event, ctx) => {
998
+ // The warning is about the Native default path only. An explicit node-sqlite
999
+ // compatibility selection keeps messaging available, so it must not be told
1000
+ // that messaging is disabled.
1001
+ if (!nativeStartupWarned) {
1002
+ const readiness = inspectNativeReadiness();
1003
+ if (readiness.driver === "rust-native" && readiness.state !== "READY") {
1004
+ nativeStartupWarned = true;
1005
+ notify(ctx, NATIVE_STARTUP_WARNING, "warning");
1006
+ }
1007
+ }
1008
+
989
1009
  const transport = clearTunnelStatus();
990
1010
  if (generation !== undefined || shutdownInFlight !== undefined) await shutdownCe(event.reason === "reload" ? "reload" : "new");
991
1011
  // A new session must never begin while the previous owned child is still
@@ -2004,6 +2024,9 @@ export default function ceChatExchange(pi: ExtensionApiView): void {
2004
2024
  binding: view.binding, credential: view.credentialConfigured ? "configured" : "not configured",
2005
2025
  configurationState: view.state, ...(view.errorCode === undefined ? {} : { errorCode: view.errorCode }), runtimeState, evidence,
2006
2026
  }, { signal: controller.signal });
2027
+ // Native readiness is independent evidence from the Tunnel lifecycle; never infer STOPPED.
2028
+ const native = inspectNativeReadiness();
2029
+ notify(ctx, `ce-tunnel: native=${native.state} (${native.code}) | transport lifecycle is reported separately; /ce-native for driver details`);
2007
2030
  if (!presentInteractive && !controller.signal.aborted) notify(ctx, `ce-tunnel: ce=${ceStatusText()} | tunnel(real background): ${presented.lines.join(" | ")}`);
2008
2031
  })();
2009
2032
  if (presentInteractive) managerUiTask = task;
@@ -2048,6 +2071,17 @@ export default function ceChatExchange(pi: ExtensionApiView): void {
2048
2071
  /** Direct shortcuts and the Manager invoke this same operation path. */
2049
2072
  const runTunnelCommand = async (args: string, ctx: ExtensionContextView): Promise<void> => {
2050
2073
  const sub = args.trim().split(/\s+/)[0] ?? "";
2074
+ // The start gate precedes every manager, profile and process side effect.
2075
+ if (sub === "start") {
2076
+ try { assertNativeReadyForTunnel(); }
2077
+ catch (error) {
2078
+ if (error instanceof RuntimeEligibilityError) {
2079
+ notify(ctx, `ce-tunnel: start refused ${error.code}; ${hostRuntimeRepairMessage()}`, "warning"); return;
2080
+ }
2081
+ const code = error instanceof Error && "code" in error && typeof error.code === "string" && /^CE_NATIVE_/.test(error.code) ? error.code : "CE_NATIVE_INITIALIZATION_FAILED";
2082
+ notify(ctx, `ce-tunnel: start refused ${code}; run /ce-native to inspect or install the trusted driver`, "warning"); return;
2083
+ }
2084
+ }
2051
2085
  if (sub === "doctor") {
2052
2086
  notify(ctx, installationDiagnosticMessage(diagnoseInstallation({ env: process.env }))); return;
2053
2087
  }
package/CHANGELOG.md DELETED
@@ -1,70 +0,0 @@
1
- # Changelog
2
-
3
- ## 0.2.0
4
-
5
- First packaged release line of this extension. Version 0.1.1 was an internal
6
- private version only; it was never published to npm, so nothing below is an
7
- upgrade from a public release.
8
- CE's own code is owner-authorized MIT, Copyright (c) 2026 zieglar.
9
- Third-party license evidence is complete and `private: true` is removed from the manifest.
10
-
11
- ### Messaging
12
-
13
- - Add the default-disabled, opt-in `ce_ack` MCP tool, advertised only when the
14
- binding declares the Session-authorized ACK capability. The host supplies all
15
- authority fields and equivalent calls replay the original receipt. An ACK
16
- records a recipient reception statement — not proof of delivery, reading,
17
- processing or task completion. BUSY rollback and uncertain outcomes never grant
18
- retry permission.
19
-
20
- ### Tunnel lifecycle commands
21
-
22
- - Add `/ce-tunnel doctor`: read-only qualification diagnostics. With no trusted
23
- client installed it reports a safe refusal such as `CE_EXECUTABLE_UNTRUSTED`.
24
- That refusal is the expected diagnosis, not an install failure, and `doctor` is
25
- never an exit proof.
26
- - Add `/ce-tunnel deactivate`: bounded, normal release of this Session's own
27
- binding, retaining registration and history. It is not revoke and not Recovery.
28
-
29
- ### Multi-session and runtime
30
-
31
- - Support independent Pi Sessions on a shared Tunnel: `/ce-tunnel convert` keeps
32
- the current native Session's original endpoint and `/ce-tunnel register` gives a
33
- new Session its own stable endpoint without starting transport.
34
- - Support trusted portable runtime installations for the pinned Node launch path.
35
-
36
- ### Runtime qualification
37
-
38
- - The 0.2.0 certification target is exactly **Node 24.21.0 + Pi 1.3.0 +
39
- macOS arm64**.
40
- - Node **24.22.1** was admitted earlier as a second permitted runtime and remains
41
- declared in `engines`. That historical admission is **not** part of 0.2.0's
42
- certification. Linux is experimental and unverified.
43
-
44
- ### Packaging and documentation
45
-
46
- - Prepare the prebuilt Pi extension npm distribution and consumer documentation
47
- closure. The consumer tarball ships the operating guides plus the protocol,
48
- ownership, storage, ACK and Store-security contracts, so no repository access
49
- is required to operate the package safely. `private: true` was removed once the third-party audit closed with three-layer evidence. The
50
- owner-authorized MIT LICENSE ships in the prebuilt tarball; dependency licenses
51
- remain separate and must be preserved at installation/redistribution.
52
- - Document owned transport Stop, independently confirmed STOPPED, normal binding
53
- release and then native Pi removal; Store, profile, credentials and history are
54
- retained.
55
- - Keep managed npm, physical tarball fallback and monorepo source development
56
- routes distinct.
57
- - Cloud transport is NOT_VERIFIED; offline synthetic fixtures only.
58
-
59
- ### Release-process note
60
-
61
- The queued `.changeset/ce-e2b-ack-mcp.md` patch entry describes the same `ce_ack`
62
- behavior change, and its content is already reflected in this 0.2.0 entry. It is
63
- deliberately **not** consumed by this entry: Changesets remains the repository's
64
- version authority, and a future Changesets version PR must reconcile and consume
65
- it together with this hand-written 0.2.0 entry and the 0.2.0 version pins. Root
66
- Changesets configuration and queued entries are untouched by this delta. With
67
- `private` now removed, `privatePackages.version: false` no longer keeps the queued
68
- changeset inert — the next Changesets version PR owns that reconciliation explicitly.
69
-
70
- **Third-party evidence complete; `private: true` removed.** The 101-item dependency closure is fully audited: the two former evidence gaps (pi-tui and the Host peer) closed with three-layer exact-version evidence — registry tarball MIT declarations plus the upstream `v1.3.0` tag root LICENSE (MIT, (c) 2025 Mario Zechner); their artifacts omit license text (upstream packaging omission, not incompatibility). The per-version audit record is `docs/license-audit.md`, which is repo-only and not distributed in the tarball. Owner authorization covers CE's own code only — not a grant to relicense dependencies.
@@ -1,170 +0,0 @@
1
- # pi-chat-exchange 开发者架构指南
2
-
3
- 本文说明消息、Endpoint/Session authority、transport 与 Pi 适配器的边界。用户入口见[快速开始](tunnel-setup.md),多项目操作见[多 Session 使用](multi-session-usage.md)。精确约束仍以协议、Storage 与 Ownership 契约及源码 gate 为准。
4
-
5
- ## 分层与依赖方向
6
-
7
- ```text
8
- ChatGPT (Tunnel MCP / Desktop stdio) Pi runtime
9
- | |
10
- src/bin + src/control/mcp pi-extension/index.ts
11
- | |
12
- | src/endpoints/pi
13
- +---------- src/host ---------------+
14
- |
15
- src/storage
16
- |
17
- src/core
18
- |
19
- src/protocol
20
-
21
- src/tunnel: transport/profile/setup/Manager;不替代 CE Host authority
22
- ```
23
-
24
- | 层 | 职责 | 不应做什么 |
25
- |---|---|---|
26
- | `src/protocol/` | 中立实体、lifecycle、action grants、support declarations | 不依赖 Pi、MCP、网络或数据库 |
27
- | `src/core/` | 纯证据/授权规则,reference in-memory 行为 | 不读 env、文件或真实调用 endpoint |
28
- | `src/storage/` | 私有 SQLite、事务、schema/migrations、Ownership/fencing、最终数据授权 | 不把 private SQL/migration/evidence 类型暴露到 public barrel |
29
- | `src/host/` | adapter-neutral durable Endpoint Host,可信 binding、Session、幂等消息与 receipt 操作 | 不从 tool 参数接受 sender/capability,不替代外层工作流完成权威 |
30
- | `src/control/mcp/` | MCP schema/输出;默认 ping,注入 bound port 后提供 messaging | 不读任意 env、不直接 import Pi integration,不凭工具调用识别 ChatGPT 对话身份 |
31
- | `src/endpoints/pi/` | Pi Session host 的薄适配 | 不 import MCP SDK 或其他 endpoint integration |
32
- | `src/bin/` | stdio 组合根、可信绝对路径 `--config`、进程生命周期 | 不另造消息 broker 或平行 authority |
33
- | `pi-extension/` | 运行时 Session lookup、工具/命令、生命周期、UI、mapping identifiers | 不持久化 capability,不代替 Storage 决定可见性 |
34
- | `src/tunnel/` | client 生命周期、健康测量、私有配置事务、masked 输入与显式激活 UI | 不把 CONNECTED 当消息 Gate,不隐式读取/ACK/重试消息 |
35
-
36
- 核心依赖向内:`bin → control/endpoints/host → storage → core → protocol`,具体许可由 `scripts/check-contract.mjs` 的 TypeScript AST gates 决定。protocol/core 不可 reach 外层;control 与 endpoints 不互相 import;禁止借 barrel、dynamic import 或 require 绕开。tunnel 属外层组合,不提升协议权威。共享行为优先下沉已有 Host/Storage seam,不让 ChatGPT/Pi 各实现第二套 Message 系统。
37
-
38
- ## 身份模型与注册权威
39
-
40
- - **Exchange**:关联聚合,不是一个对话或 transport 连接;namespace/idempotencyKey 只负责确定性 bootstrap。
41
- - **EndpointRef**:`{adapter, endpointId}` 是非秘密身份。初始配对为 `chatgpt/main` 与 `pi/main`;多 Session 时每个 Pi Session 显式注册独立稳定 Endpoint(如 `pi/project-B`)。各 Endpoint 是独立 Authority,不共享 Owner;共享 ChatGPT inbox 不是对话隔离。
42
- - **Participant**:Store/Exchange 中注册的参与者;与当前具体 Session/incarnation 分开。
43
- - **CE Session / Ownership / fencing**:活跃执行权威与 incarnation,需 membership、lease、current owner、fencing 和精确作用域 capability 一起校验。
44
- - **Pi runtime Session ID**:从可信 Pi API 取得,作为 operator allowlist lookup。不是 CE Session ID,也不是凭自身能发消息的凭据。
45
- - **Recipient label**:工具 `to` 使用精确 endpointId,不是认证。labels、support declarations、工具存在和 UI 选择都不直接发 authority。
46
- - **Capability**:Host 内存中的 scoped authority;不写 mapping/日志/配置,不让模型自选。
47
-
48
- MCP 身份固定于 operator-owned `--config`,不是由一次 MCP invocation 或 ChatGPT 当前文字声明认证。Pi 身份固定于可信 allowlist 与当前 context。两边共享 Store directory/file 与 Exchange namespace/key;任一不同都没有自动路由补偿。`managed`/`managedBy` 是 provenance,不是替代 recipients 或 Storage 检查的许可。
49
-
50
- ### 多 Session:配置准入不取代 durable authority
51
-
52
- `src/tunnel/{multi-session-policy,multi-session-admission}.ts` 管理 profile 选中的不可变 registration 策略;`pi-extension/multi-session-runtime.ts` 管理当前进程 guard。注册绑定可信 native Pi Session、稳定 Endpoint、active/revoked 状态与 epoch,payload/ACK 独立 opt-in;不从项目路径或模型参数推导身份。
53
-
54
- - convert/register/revoke 需人工确认、配置 revision 校验与 verified STOPPED transport lock;不自动启停,也不能约束仍在运行的旧二进制。
55
- - Pi factory grants 在 reload 前不变;MCP child 在显式 Stop/Start 前不能宣称已加载新 generation。selected configured、loaded、bound、connected 分开报告。
56
- - deny-only gates 约束后续准入,包括 read/renew;已经准入的操作可能完成。正常 end/release 不被撤销门禁阻挡;撤销不删除 Owner、Participant、历史消息或 Receipt。
57
- - process mutex 是本地 exclusion,不是 CE authority/recovery。runtime/epoch/Store/Exchange 与 guard 均须一致,最终权限仍由原 Host/Storage 校验;不增加 takeover 或跨 Exchange router。
58
- - `/ce-tunnel sessions` 仅在当前 runtime 经 admission 后投影所选 active Endpoint IDs;不读取 Inbox,不证明运行中的 MCP 已加载。
59
-
60
- ## Message、DeliveryAttempt、Receipt、Result 的分离
61
-
62
- 1. `ce_send` 将一次逻辑发送持久化为独立 Message;Message、幂等记录与创建 Audit 在本地 Store 同一事务提交,不证明云端传输或对端接收。key 在 Exchange 内作用域化,相同 key/请求重放原记录,改变正文或 Endpoint 则冲突;这不授予未知结果重试许可,也不承诺 exactly-once delivery/execution。反向回复/后续追问也是新 Message,不是 Result 的变形。
63
- 2. Inbox 按 creation Audit 有界扫描并应用 recipient/membership/join boundary,不 ACK、不消费、不推进 delivery cursor。
64
- 3. metadata read 与 payload read 是不同权限;后者在 materialize bytes 前完成 Storage 授权。
65
- 4. ACK 追加 immutable reception receipt,第一次 CREATED、已有则 REPLAYED。Message 创建 Audit sequence 与 receipt Audit sequence 是不同证据。
66
- 5. Result 是 immutable processing evidence,发布不自动回复、关闭 Exchange 或赋予 Wayforge completion authority。
67
-
68
- 纯 core 的完整 delivery lifecycle 仍约束 claim、dispatch intent、attempt、runtime evidence、settlement、quarantine。不能因为当前工具提供持久消息/ACK,就宣称所有远端 delivery/execution/result 流程均已落地。
69
-
70
- **冻结安全语义:** intent 先于 effect;需相关 Message/Attempt/Endpoint/incarnation/lease/fencing 证据。模糊 delivery 进入 `DELIVERY_UNKNOWN`,不 retry/requeue,不将它改成 `CANCELLED`。已知送达但执行未知也不能合成 acceptance/settlement/Result。普通 close 需所有 Message 完结;独立授权的 `ABANDONED_UNRESOLVED` 保留未知事实,不代表 cancellation/normal close/success。
71
-
72
- CE Receipt、Pi UI 通知、Tunnel health、runtime 执行事实和 Wayforge 工作流裁决是不同平面。任何外部完成动作仍须其本身的显式授权和证据,不能从 ACK 或模型断言推导。
73
-
74
- ## 生命周期、并发与恢复边界
75
-
76
- - MCP startup bind 使用 `requireUnowned`;独立 heartbeat 续租。SIGINT/SIGTERM/stdio-close 走一次 release/end,不自动接管 crashed Owner。
77
- - Pi `session_start` 按可信 runtime lookup 选择 Endpoint;有 mapping 的 startup/reload/resume 校验恢复。reload 缺 mapping 拒绝,新/fork 不继承旧 authority。
78
- - Pi reload 结束旧内存 generation/timer,不结束有效 durable Ownership;正常退出/Session replacement 尝试 end/release/detach。renew/end 未知或 diagnostic persistence 失败锁住后续路径。
79
- - `ce-mapping`、`ce-messaging-released`、`ce-lifecycle-blocked` 仅存 identifiers/拒绝证据,不携带 capability。释放标记不能独立授予新权威,需验证旧 mapping 的 exact released+detached proof。
80
- - 显式 activation 在 profile lock 下核实当前配置/环境/runtime,只有 requireUnowned 可绑定。匹配已有有效 binding 为 no-op;未知释放、映射写入失败或旧 Exchange 证据不符拒绝,不自动 takeover。
81
- - `/ce-tunnel deactivate` 在确认与当前 generation/Session fence 后复用 `shutdownCe()` 正常结束路径;仅释放本地 CE binding,保留 registration/history/transport。未知 end 或证据持久化失败仍关闭操作;已释放 mapping 不在 reload 时自动重绑,只有显式 activate 可重新申请。
82
- - Tunnel 管理的是 detached client 的进程所有权,不是 CE Owner。跨进程 directory lock、PID+exact command+start key、write-ahead termination ledger 共同避免误杀/双启动;UNKNOWN 不等于进程消失。
83
- - 每个 record-backed run 最多一次 SIGTERM,不 SIGKILL、不 name-based bulk kill。intent 持久后信号丢失允许零次实际 signal;不能删除 ledger 以便重发。client MCP child 属 client,不由 Manager 擅自终止。
84
-
85
- 恢复 CLI 是另行授权的 operator-only 路径,既不注册为 MCP tool 也不由模型自动调用。进程恢复、CE Owner 恢复、消息未知结果调查是三个不同问题。
86
-
87
- `/ce-tunnel doctor` 是独立只读安装诊断:host qualification、child executable qualification 与 client metadata trust 分开;复用现有 executable admission,不启动 Manager/client、不读取 credential 或 Store、不发布配置。它不证明 profile 当前 child 命令、client schema 兼容、云端权限或网络健康;对应证据仍由配置/真实兼容测试和 Manager 提供。
88
-
89
- ## 配置 generation 与原子迁移
90
-
91
- 源码定位:`src/tunnel/{profile,managed-binding,messaging-config,setup}.ts`,UI 在 `setup-ui.ts` / `secure-input.ts`,加载/激活在 `pi-extension/index.ts`。
92
-
93
- - Profile 是唯一 activation pointer。普通 binding 由完整 Tunnel/Organization/adapter 身份生成,文件名短尾只显示,不承担完整 identity 比较。
94
- - Advanced Messaging 发布完整 binding 与 Pi allowlist sidecar,名称 `messaging-<full SHA-256>.yaml` 及其 `.pi-allowlist.json`。digest 同时覆盖两份 bytes;generation 使用 no-overwrite link,loader 拒绝不完整/不符 pair。
95
- - 两个文件发布不是跨文件 crash-atomic;最终 profile temp+rename 才是逻辑提交点。失败可能保留未选中的私有 staging/generation,不回滚或删除不确定属于谁的文件。
96
- - Credential 替换先创建 0700 目录与 0600 exclusive generation,同步目录/内容,再提交引用;macOS 先清 inherited ACL。Keep 不读取内容,旧代保留,无自动 GC。
97
- - postcommit sync 失败只能报 durability uncertain,不能说 rollback。ACTIVE/UNKNOWN 不能被 UI 文字绕过为可编辑。
98
- - `/ce-tunnel migrate` 仅修 canonical generated YAML:移除 client 0.0.16 拒绝的 admin_ui 项并修批准 Node command,保留 identity/credential reference/binding/Store/recipient bytes;不是任意 YAML formatter。
99
-
100
- ## Storage 运行契约
101
-
102
- 精确批准 Node **24.21.0 或 24.22.1**,不接受其他 patch、25.x 或范围匹配。每个 registry tuple 绑定 SQLite **3.53.4**、source identity `2026-07-24 19:02:57 bf7c7f30031888f4e796e429ab3978879485813aaca6f641c7b33e4e09459bcc`、必要编译选项(`THREADSAFE=1`、`MUTEX_PTHREADS`;禁止 `OMIT_WAL`、`OMIT_FOREIGN_KEY`、`OMIT_TRIGGER`、`OMIT_CHECK`、`OMIT_COMPILEOPTION_DIAGS`)及实际 defensive/statement/transaction-state API 检查。Store 路径准备前即拒绝不合格 runtime;环境版本标签不是资格证据;实测矩阵与原始证据记录为 `docs/runtime-qualification.md`(作者侧证据记录,仅仓库保留、不随 tarball 分发)。平台 allowlist 仍为 macOS arm64 / Linux x64;此次双版本实测仅 macOS arm64,不等于 Linux 新增验收。还需 approved detectable local filesystem、当前用户 ownership、目录 0700、DB/WAL/SHM 0600、非 symlink final artifacts。writers 使用 defensive mode、WAL、synchronous FULL、foreign keys、trusted-schema OFF、有界 busy wait;macOS 另有 fullfsync/checkpoint_fullfsync。
103
-
104
- migration ledger/checksum、application/store identity、integrity 与 restore hold 会拒绝 foreign/newer/corrupt Store,不自动 reset。Node 25 即使能执行 Pi UI,也不代表可以打开 CE Store。精确 gate 以 `src/storage/runtime.ts` 与 [Storage contract](storage-contract.md) 为准;受限文件权限并不能消除所有 TOCTOU、mount substitution、OS crash/power loss 风险。
105
-
106
- ## 验证层次
107
-
108
- 从包目录、批准 Node 运行:
109
-
110
- ```bash
111
- pnpm run check
112
- pnpm run typecheck
113
- pnpm run build
114
- pnpm test
115
- pnpm run test:plugin-package
116
- # 可选(需本机已安装 tunnel-client;不属于默认门禁)
117
- pnpm run test:installed-client
118
- # 可选(真实 Pi CLI + PTY 的 crash/resume 回归;数分钟,不属于默认门禁)
119
- CE_HOST_REGRESSION_KEEP=1 pnpm run test:host-regression
120
- # 完整串行门禁(build 在 test 前)
121
- pnpm run verify
122
- ```
123
-
124
- | 层次 | 证据范围 | 不能替代 |
125
- |---|---|---|
126
- | AST/type/compile-negative | 依赖方向、封闭 schema、类型拒绝 | 真实 runtime/客户端行为 |
127
- | core/protocol unit | 纯状态转移、scope、quarantine/authority | 文件事务/远端结果 |
128
- | Storage 事务/故障/多进程 | identity、lease/fencing、crash、并发、read/ACK privacy | ChatGPT UI 或云端连接 |
129
- | Host/MCP/Pi isolated harness | 参数、工具发现、mapping、activation、payload/ACK、生命周期 | 实体终端和端到端用户 Gate |
130
- | Tunnel offline / TUI harness | 合成 health、取消/在途/通知/屏幕契约 | 真实 client schema、认证、计费连接、终端物理表现 |
131
- | `test/tunnel/real-client-compat.test.ts` | 真实 client doctor 与本地 schema 兼容;可选 lane(`pnpm run test:installed-client`),需本机已安装 tunnel-client,未安装时按可用性跳过;已排除出 `pnpm test` 与 `pnpm run verify` | 真实网络 readiness 或双向消息 |
132
- | `test/tunnel/offline.integration.test.ts` | 真实 client 的离线集成;同一可选 lane,需本机已安装 tunnel-client,未安装时大声失败而非静默跳过;已排除出 `pnpm test` 与 `pnpm run verify` | 真实网络 readiness 或双向消息 |
133
- | `test/host-regression/real-host-recovery.test.ts` | 真实 Pi 1.3.0 CLI + 真实 PTY 的 crash→mutex 拒绝→离线 reconcile→resume→租约续期→授权路由完成→策略收窄拒绝→expired Owner 拒绝(含 reason/hint、fencing、slot 计数)回归;可选 lane(`CE_HOST_REGRESSION_TEST=1 pnpm run test:host-regression`),先以 `git archive HEAD` 出树编译并比对 blob 身份,全合成 Store/loopback provider,零 tunnel-client 执行;前置缺失或未设 opt-in 时大声失败而非跳过;已排除出 `pnpm test` 与 `pnpm run verify` | 真实 Tunnel/Exchange、真实凭据/网络、ChatGPT UI、installed client、Operator Recovery 执行 |
134
- | packaged plugin tests | 可移植包内容、stdio 启动、tool discovery | Desktop 安装菜单/资格/对话更新 |
135
- | 人工 real Gate | 当前 ChatGPT 对话与 Pi 的实际 send/list/read/ACK、Tunnel 启停 | 冷启动、所有平台、所有客户端或正式发布资格 |
136
-
137
- 真实 Host lane 的证据留在原始临时根目录,不复制到另一处。`CE_HOST_REGRESSION_KEEP=1` 保留成功运行的证据;测试、进程/provider 清理(含本地超时)或清理记录写入失败时不启动删除,并尽力打印原始路径。仅在所有测试成功、驱动已等待并回收其自有子进程、合成 provider 已关闭、清理记录写入成功且未设 KEEP 时删除根目录。递归删除本身失败可能已部分移除证据;此时聚合错误以 `possibly-partially-removed` 标明状态并尽力打印原始路径,不承诺完整保留。两次离线 reconcile 均由驱动确认并记录**当前启动实例**的退出/回收身份,且在串行离线窗口前后再确认无存活自有 Store-capable 进程;未确认退出即拒绝执行,不以 `/quit` 加固定等待代替。默认收集的 `test/host-regression/*-cleanup.test.ts`、`failure-path.test.ts` 与 `refusal-comparator.test.ts` 只验证合成进程清理、离线屏障、故障证据状态和拒绝前后完整 message/audit 数组比较,不启动真实 Pi/client 或业务恢复。
138
-
139
- 本地测试只对其实际执行的固定版本与环境提供证据,跳过项和平台限制必须明示。人工消息验收与隔离回归互不替代;不要将历史报告的测试数当作当前变更的新鲜执行证据。公共验收边界见[README](../README.md)。
140
-
141
- ### 高价值回归入口
142
-
143
- - `test/tunnel/{setup-messaging,messaging-config,messaging-config-security,messaging-binding}.test.ts`:配对、immutable publication、权限/文件与失败路径。
144
- - `test/endpoints/pi/extension-messaging-activation.test.ts`:旧映射释放、reload、显式 activation、deny paths。
145
- - `test/endpoints/pi/extension-ack.test.ts` 与 `test/control/mcp/messaging-ack-tool.test.ts`:独立 opt-in、四字段与模型可见 metadata。
146
- - `test/tunnel/{background-manager,extension-deferred-start,real-client-compat}.test.ts`:进程证据、异步启动和真实 schema。
147
- - `test/storage/delivery-ack*.test.ts`、`inbox-*.test.ts`:receipt、privacy、事务/进程边界与分页。
148
-
149
- ## 扩展点与已知债务
150
-
151
- - 新 ControlSurface 必须使用既有 Host port、封闭请求 schema 与 adapter-neutral 规则;不能从不可信 label 自授权。
152
- - 新 endpoint integration 声明独立 support,不假设 peer capabilities 对称;unsupported/unknown 保持明确,需真实 evidence 才能声称实现。
153
- - 新 client 版本要真实 schema/doctor 回归,不能仅用 offline fixture;新 Node/SQLite/平台先独立资格验证,不能放松 runtime guard。
154
- - UI/异步任务要保留 draft/commit 边界、Session generation、在途合并、取消/teardown 的权限分离;不以通知成功当显示/送达成功。
155
- - 仍待后续:credential/generation 的显式安全 GC、机器冷启动与部分实体终端交互、受控 client 安装/升级流程。Desktop 已支持对私有副本显式配置本机批准 Node;这不是自动跨机安装或 Desktop UI 验收。
156
- - 不在当前范围:自动 Inbox draining/idle wake、自动业务重试/Owner takeover、自动远端执行、任意 Store 合并或跨 Exchange router、以 ACK 代替任务完成。
157
-
158
- ## 文档事实溯源与维护
159
-
160
- | 事实 | 首要源码/证据 |
161
- |---|---|
162
- | 版本与 scripts | `../package.json`、仓库根 `package.json`、`src/storage/runtime.ts` |
163
- | Pi 加载与 session_start/reload | Pi 1.3.0 CLI help / extensions 文档与运行时 `AgentSession.reload`;本包 `pi-extension/index.ts` |
164
- | Tunnel 字段/格式/child env | `src/tunnel/profile.ts`、`setup-ui.ts`、`background-manager.ts` |
165
- | binding closed schema / opt-in | `src/host/mcp-binding-config.ts`、`src/control/mcp/` |
166
- | generation/Store/Exchange 一致性 | `src/tunnel/{managed-binding,messaging-config,setup}.ts` |
167
- | 工具参数/ACK metadata/状态 | `pi-extension/index.ts`、Host port、对应 extension-ack / messaging-ack tests |
168
- | 当前支持与验收边界 | [README](../README.md)、对应隔离测试与独立人工验收;公共文档不复制原始消息/Session/日志 |
169
-
170
- 历史 plans/audits/validation 报告保留其时间截面,不应机械改写为“今日已全部完成”。发现代码/配置与文档目标冲突时记录限制、另开实现任务;文档提交不偷偷改 runtime 或冻结契约。