@harrylabsj/kiwi 0.12.5 → 0.12.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1041 @@
1
+ /**
2
+ * Copyright 2026 harrylabsj
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ /**
17
+ * 可选 owned 运行模式(MANAGER-APPROVAL-SCOPE-v2 §B)。
18
+ *
19
+ * 与 SDK / HTTP / Core 无关的**最小持久生命周期**:
20
+ * - owner 唯一性(journal 代际 + O_EXCL guard)
21
+ * - 持久计数(业务转发 / MCP / Core 预留,失败不退还)
22
+ * - window 期限与持久时间锚(provider/host/boot 绑定,未知即 HOLD)
23
+ * - 终态(到期 / 预算 / 进程内 owner stop)与重启拒绝
24
+ *
25
+ * 本模块不做:外部 stop 通道、跨窗额度迁移、真实业务库与计数跨库原子。
26
+ */
27
+ import { closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, rmdirSync, rmSync, statSync, writeSync } from "node:fs";
28
+ import path from "node:path";
29
+ import { randomBytes, createHash } from "node:crypto";
30
+ import { createRequire } from "node:module";
31
+ import { contentDigest } from "../negotiation/jcs.js";
32
+ import { createOwnedClock, ownedHostBootId } from "./owned-clock.js";
33
+ export { createOwnedClock, ownedHostBootId } from "./owned-clock.js";
34
+ export const requireCjs = createRequire(import.meta.url);
35
+ const OWNED_DIR = "owned";
36
+ export const LEDGER_FILE = "window-ledger.json";
37
+ export const GUARD_FILE = "owner.guard";
38
+ export const JOURNAL_FILE = "journal.sqlite";
39
+ export class OwnedRuntimeError extends Error {
40
+ code;
41
+ constructor(code, message) {
42
+ super(message.startsWith(code) ? message : `${code}: ${message}`);
43
+ this.name = "OwnedRuntimeError";
44
+ this.code = code;
45
+ }
46
+ }
47
+ function fail(code, message) {
48
+ throw new OwnedRuntimeError(code, message);
49
+ }
50
+ function isSqliteBusy(error) {
51
+ const code = String(error?.code ?? "");
52
+ return code === "SQLITE_BUSY" || code === "SQLITE_LOCKED" || /database is locked|database table is locked/i.test(String(error));
53
+ }
54
+ function sha256(input) {
55
+ return createHash("sha256").update(input).digest("hex");
56
+ }
57
+ function canonical(value) {
58
+ return Buffer.from(`${JSON.stringify(value, null, 2)}\n`, "utf8");
59
+ }
60
+ function isPositiveInt(value) {
61
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
62
+ }
63
+ function parseUtc(value, field) {
64
+ if (typeof value !== "string")
65
+ fail("OWNED_POLICY_INVALID", `${field} 必须是 ISO 时间字符串`);
66
+ const ms = Date.parse(value);
67
+ if (!Number.isFinite(ms))
68
+ fail("OWNED_POLICY_INVALID", `${field} 不可解析`);
69
+ return new Date(ms).toISOString();
70
+ }
71
+ /** 严格校验策略:不填补缺省值、不接受多余语义。 */
72
+ export function validateOwnedPolicy(input, nowMs) {
73
+ if (input === null || typeof input !== "object" || Array.isArray(input)) {
74
+ fail("OWNED_POLICY_INVALID", "owned_policy 必须是对象");
75
+ }
76
+ const raw = input;
77
+ const allowed = ["version", "policy_id", "window_id", "window_start_utc", "window_end_utc", "caps"];
78
+ for (const key of Object.keys(raw)) {
79
+ if (!allowed.includes(key))
80
+ fail("OWNED_POLICY_INVALID", `owned_policy 含未知字段:${key}`);
81
+ }
82
+ const version = raw.version;
83
+ if (typeof version !== "string" || version.trim() === "")
84
+ fail("OWNED_POLICY_INVALID", "version 必填");
85
+ const policyId = raw.policy_id;
86
+ if (typeof policyId !== "string" || policyId.trim() === "")
87
+ fail("OWNED_POLICY_INVALID", "policy_id 必填");
88
+ const windowId = raw.window_id;
89
+ if (typeof windowId !== "string" || windowId.trim() === "")
90
+ fail("OWNED_POLICY_INVALID", "window_id 必填");
91
+ const startUtc = parseUtc(raw.window_start_utc, "window_start_utc");
92
+ const endUtc = parseUtc(raw.window_end_utc, "window_end_utc");
93
+ if (Date.parse(endUtc) <= Date.parse(startUtc)) {
94
+ fail("OWNED_POLICY_INVALID", "window_end_utc 必须晚于 window_start_utc");
95
+ }
96
+ const capsRaw = raw.caps;
97
+ if (capsRaw === null || typeof capsRaw !== "object" || Array.isArray(capsRaw)) {
98
+ fail("OWNED_POLICY_INVALID", "caps 必须是对象");
99
+ }
100
+ const caps = capsRaw;
101
+ const capKeys = ["business_requests", "mcp_calls", "core_starts"];
102
+ for (const key of Object.keys(caps)) {
103
+ if (!capKeys.includes(key))
104
+ fail("OWNED_POLICY_INVALID", `caps 含未知字段:${key}`);
105
+ }
106
+ for (const key of capKeys) {
107
+ if (!isPositiveInt(caps[key]))
108
+ fail("OWNED_POLICY_INVALID", `caps.${key} 必须是正整数`);
109
+ }
110
+ // 已过期窗口不允许成为"新"策略,避免用历史夹具开零计数窗口。
111
+ if (Date.parse(endUtc) <= nowMs)
112
+ fail("OWNED_POLICY_EXPIRED", "window_end_utc 已过");
113
+ return {
114
+ version: version.trim(),
115
+ policy_id: policyId.trim(),
116
+ window_id: windowId.trim(),
117
+ window_start_utc: startUtc,
118
+ window_end_utc: endUtc,
119
+ caps: {
120
+ business_requests: caps.business_requests,
121
+ mcp_calls: caps.mcp_calls,
122
+ core_starts: caps.core_starts,
123
+ },
124
+ };
125
+ }
126
+ /** 平台能力探针:只在**自建独占**子目录内操作,绝不递归删除既有目录或未知内容。 */
127
+ export function probeOwnedCapabilities(parentDir) {
128
+ let probeDir;
129
+ let created = false;
130
+ try {
131
+ const parentStat = statSync(parentDir);
132
+ if (!parentStat.isDirectory())
133
+ fail("OWNED_PLATFORM_UNSUPPORTED", `探针父路径不是目录:${parentDir}`);
134
+ }
135
+ catch (error) {
136
+ fail("OWNED_PLATFORM_UNSUPPORTED", `探针父目录不可用:${error.message}`);
137
+ }
138
+ try {
139
+ probeDir = path.join(parentDir, `probe-${randomBytes(8).toString("hex")}`);
140
+ // 独占创建:已存在即说明不是"我们自己新建的",拒绝(不清理他人内容)。
141
+ mkdirSync(probeDir, { mode: 0o700 });
142
+ created = true;
143
+ const file = path.join(probeDir, "cap");
144
+ const fd = openSync(file, "wx", 0o600);
145
+ try {
146
+ writeSync(fd, "ok");
147
+ fsyncSync(fd);
148
+ }
149
+ finally {
150
+ closeSync(fd);
151
+ }
152
+ try {
153
+ openSync(file, "wx", 0o600);
154
+ fail("OWNED_PLATFORM_UNSUPPORTED", "O_EXCL 语义未生效");
155
+ }
156
+ catch (error) {
157
+ if (error instanceof OwnedRuntimeError)
158
+ throw error;
159
+ }
160
+ const moved = path.join(probeDir, "cap.moved");
161
+ renameSync(file, moved);
162
+ const dirFd = openSync(probeDir, "r");
163
+ try {
164
+ fsyncSync(dirFd);
165
+ }
166
+ finally {
167
+ closeSync(dirFd);
168
+ }
169
+ // 只清理本轮自建且身份可证的对象(独占创建 + 单一已知文件)。
170
+ rmSync(moved, { force: true });
171
+ rmSync(file, { force: true });
172
+ }
173
+ catch (error) {
174
+ if (error instanceof OwnedRuntimeError)
175
+ throw error;
176
+ fail("OWNED_PLATFORM_UNSUPPORTED", `持久能力探针失败:${error.message}`);
177
+ }
178
+ finally {
179
+ if (created && probeDir !== undefined) {
180
+ try {
181
+ // 只用 rmdir:非空(出现未知内容)就保持原样,绝不递归删除。
182
+ rmdirSync(probeDir);
183
+ }
184
+ catch {
185
+ // 非空或无法删除:保留原样,不强行递归删除(未知内容一律不动)。
186
+ }
187
+ }
188
+ }
189
+ }
190
+ /**
191
+ * 最小 SQLite journal:owner 所有权(held + token)与操作意图。
192
+ *
193
+ * 所有权 CAS 只在 SQL 里做:`UPDATE ... WHERE held=0 OR token_hash=<观察到的旧 token>`,
194
+ * 单语句原子,且**只处置被观察的对象**(旧 token),不做"先读再按路径删除"。
195
+ */
196
+ export class OwnedJournal {
197
+ db;
198
+ dbPath;
199
+ constructor(db, dbPath) {
200
+ this.db = db;
201
+ this.dbPath = dbPath;
202
+ }
203
+ static open(dbPath) {
204
+ let sqlite;
205
+ try {
206
+ sqlite = requireCjs("node:sqlite");
207
+ }
208
+ catch {
209
+ fail("OWNED_PLATFORM_UNSUPPORTED", "node:sqlite 不可用");
210
+ }
211
+ const db = new sqlite.DatabaseSync(dbPath);
212
+ const journal = new OwnedJournal(db, dbPath);
213
+ journal.migrate();
214
+ return journal;
215
+ }
216
+ migrate() {
217
+ this.db.exec(`
218
+ CREATE TABLE IF NOT EXISTS owner_state (
219
+ id INTEGER PRIMARY KEY CHECK (id = 1),
220
+ generation INTEGER NOT NULL,
221
+ token_hash TEXT NOT NULL,
222
+ held INTEGER NOT NULL DEFAULT 0,
223
+ owner_pid INTEGER,
224
+ owner_boot TEXT,
225
+ owner_at_ms INTEGER,
226
+ pending_json TEXT,
227
+ dispatch_json TEXT,
228
+ last_ledger_sha256 TEXT
229
+ );
230
+ `);
231
+ const cols = this.db.prepare("PRAGMA table_info(owner_state)").all();
232
+ for (const [name, ddl] of [
233
+ ["held", "ALTER TABLE owner_state ADD COLUMN held INTEGER NOT NULL DEFAULT 0"],
234
+ ["owner_pid", "ALTER TABLE owner_state ADD COLUMN owner_pid INTEGER"],
235
+ ["owner_boot", "ALTER TABLE owner_state ADD COLUMN owner_boot TEXT"],
236
+ ["owner_at_ms", "ALTER TABLE owner_state ADD COLUMN owner_at_ms INTEGER"],
237
+ ]) {
238
+ if (!cols.some((c) => c.name === name))
239
+ this.db.exec(ddl);
240
+ }
241
+ }
242
+ state() {
243
+ const row = this.db
244
+ .prepare("SELECT generation, token_hash, held, pending_json, dispatch_json, last_ledger_sha256 FROM owner_state WHERE id = 1")
245
+ .get();
246
+ if (row === undefined)
247
+ return undefined;
248
+ return {
249
+ generation: Number(row.generation),
250
+ token_hash: String(row.token_hash),
251
+ held: Number(row.held ?? 0),
252
+ pending_json: row.pending_json === null ? null : String(row.pending_json),
253
+ dispatch_json: row.dispatch_json === null ? null : String(row.dispatch_json),
254
+ last_ledger_sha256: row.last_ledger_sha256 === null ? null : String(row.last_ledger_sha256),
255
+ };
256
+ }
257
+ /**
258
+ * 取得所有权(原子)。
259
+ * - 全新:INSERT(主键冲突即另一进程已建);
260
+ * - 空闲:held=0 时抢占;
261
+ * - 接管:仅当 held=1 且 token_hash 正好等于**观察到的旧 token**(调用方已证明其 owner 已死)。
262
+ * 任何其它情形 changes=0 → 失败,调用方必须 HOLD/BUSY,不得再改任何文件。
263
+ */
264
+ acquire(identity, observedTokenHash) {
265
+ const current = this.state();
266
+ if (current === undefined) {
267
+ try {
268
+ this.db
269
+ .prepare("INSERT INTO owner_state (id, generation, token_hash, held, owner_pid, owner_boot, owner_at_ms) VALUES (1, 1, ?, 1, ?, ?, ?)")
270
+ .run(identity.tokenHash, identity.pid, identity.hostBootId, identity.atMs);
271
+ }
272
+ catch {
273
+ fail("OWNED_RUNTIME_OWNER_BUSY", "并发首启:owner 行已被创建");
274
+ }
275
+ return 1;
276
+ }
277
+ const next = current.generation + 1;
278
+ const result = observedTokenHash === undefined
279
+ ? this.db
280
+ .prepare("UPDATE owner_state SET generation = ?, token_hash = ?, held = 1, owner_pid = ?, owner_boot = ?, owner_at_ms = ? WHERE id = 1 AND held = 0")
281
+ .run(next, identity.tokenHash, identity.pid, identity.hostBootId, identity.atMs)
282
+ : this.db
283
+ .prepare("UPDATE owner_state SET generation = ?, token_hash = ?, held = 1, owner_pid = ?, owner_boot = ?, owner_at_ms = ? WHERE id = 1 AND held = 1 AND token_hash = ?")
284
+ .run(next, identity.tokenHash, identity.pid, identity.hostBootId, identity.atMs, observedTokenHash);
285
+ if (Number(result.changes ?? 0) !== 1) {
286
+ fail("OWNED_RUNTIME_OWNER_BUSY", observedTokenHash === undefined
287
+ ? "owner 仍被持有(held=1),拒绝第二 owner"
288
+ : "观察到的 owner 已变化,拒绝基于旧观察的接管");
289
+ }
290
+ return next;
291
+ }
292
+ /** 释放:只释放自己的 token(不按路径、不按时间猜测)。 */
293
+ release(tokenHash) {
294
+ this.db.prepare("UPDATE owner_state SET held = 0 WHERE id = 1 AND token_hash = ? AND held = 1").run(tokenHash);
295
+ }
296
+ /** 每次写账本前确认自己仍是 owner(fencing)。 */
297
+ assertOwner(tokenHash) {
298
+ const row = this.db.prepare("SELECT held, token_hash FROM owner_state WHERE id = 1").get();
299
+ if (row === undefined || Number(row.held ?? 0) !== 1 || String(row.token_hash) !== tokenHash) {
300
+ fail("OWNED_RUNTIME_OWNER_FENCED", "已不是当前 owner,拒绝写入");
301
+ }
302
+ }
303
+ setPending(operation) {
304
+ const result = this.db
305
+ .prepare("UPDATE owner_state SET pending_json = ? WHERE id = 1 AND pending_json IS NULL AND held = 1 AND token_hash = ?")
306
+ .run(JSON.stringify(operation), operation.token_hash);
307
+ if (Number(result.changes ?? 0) !== 1)
308
+ fail("OWNED_PENDING_EXISTS", "已有未完成的 journal 操作或已非 owner");
309
+ }
310
+ pending() {
311
+ const state = this.state();
312
+ if (state?.pending_json === null || state?.pending_json === undefined)
313
+ return undefined;
314
+ let parsed;
315
+ try {
316
+ parsed = JSON.parse(state.pending_json);
317
+ }
318
+ catch {
319
+ fail("OWNED_JOURNAL_CORRUPT", "pending 记录不是合法 JSON");
320
+ }
321
+ const value = parsed;
322
+ const keys = Object.keys(value).sort();
323
+ const expected = [
324
+ "base_sha256", "generation", "kind", "operation_id", "schema", "target_json", "target_sha256", "token_hash",
325
+ ];
326
+ if (JSON.stringify(keys) !== JSON.stringify(expected))
327
+ fail("OWNED_JOURNAL_CORRUPT", "pending 字段集不符");
328
+ if (value.schema !== "kiwi.cloud.owned-pending/1")
329
+ fail("OWNED_JOURNAL_CORRUPT", "pending schema 不符");
330
+ for (const key of ["operation_id", "base_sha256", "target_sha256", "target_json", "token_hash"]) {
331
+ if (typeof value[key] !== "string" || value[key].length === 0) {
332
+ fail("OWNED_JOURNAL_CORRUPT", `pending.${key} 非法`);
333
+ }
334
+ }
335
+ if (!isPositiveInt(value.generation))
336
+ fail("OWNED_JOURNAL_CORRUPT", "pending.generation 非法");
337
+ if (value.kind !== "terminal" && value.kind !== "count")
338
+ fail("OWNED_JOURNAL_CORRUPT", "pending.kind 非法");
339
+ return value;
340
+ }
341
+ /** 最终确认:清 pending 并记录账本摘要,只在账本写入+读回之后调用。 */
342
+ finalize(ledgerSha256) {
343
+ const result = this.db
344
+ .prepare("UPDATE owner_state SET pending_json = NULL, last_ledger_sha256 = ? WHERE id = 1")
345
+ .run(ledgerSha256);
346
+ if (Number(result.changes ?? 0) !== 1)
347
+ fail("OWNED_JOURNAL_FINALIZE", "journal 最终确认失败");
348
+ }
349
+ close() {
350
+ this.db.close();
351
+ }
352
+ }
353
+ export function ownedLayout(dataDir) {
354
+ const dir = path.join(dataDir, OWNED_DIR);
355
+ return {
356
+ dir,
357
+ ledger: path.join(dir, LEDGER_FILE),
358
+ guard: path.join(dir, GUARD_FILE),
359
+ journal: path.join(dir, JOURNAL_FILE),
360
+ };
361
+ }
362
+ export function classifyDataDir(dataDir, layout) {
363
+ const ownedExists = existsSync(layout.dir);
364
+ let dataDirEntries = [];
365
+ try {
366
+ dataDirEntries = existsSync(dataDir)
367
+ ? requireCjs("node:fs").readdirSync(dataDir).filter((name) => name !== OWNED_DIR)
368
+ : [];
369
+ }
370
+ catch {
371
+ fail("OWNED_DATA_DIR_UNREADABLE", `无法读取 dataDir:${dataDir}`);
372
+ }
373
+ if (!ownedExists)
374
+ return dataDirEntries.length === 0 ? "FRESH" : "LEGACY";
375
+ const required = [layout.ledger, layout.journal];
376
+ const allThere = required.every((file) => existsSync(file));
377
+ if (!allThere)
378
+ return "PARTIAL";
379
+ return "ACTIVE";
380
+ }
381
+ function readJsonFile(file) {
382
+ return JSON.parse(readFileSync(file, "utf8"));
383
+ }
384
+ function atomicWrite(target, bytes) {
385
+ const tmp = `${target}.tmp-${randomBytes(6).toString("hex")}`;
386
+ const fd = openSync(tmp, "wx", 0o600);
387
+ try {
388
+ writeSync(fd, bytes);
389
+ fsyncSync(fd);
390
+ }
391
+ finally {
392
+ closeSync(fd);
393
+ }
394
+ renameSync(tmp, target);
395
+ const dirFd = openSync(path.dirname(target), "r");
396
+ try {
397
+ fsyncSync(dirFd);
398
+ }
399
+ finally {
400
+ closeSync(dirFd);
401
+ }
402
+ }
403
+ const LEDGER_KEYS = [
404
+ "schema", "policy_id", "policy_sha256", "window_id", "window_start_utc", "window_end_utc",
405
+ "caps", "counts", "process_boots", "revision", "terminal", "terminal_reason", "anchor", "updated_at_utc",
406
+ ];
407
+ const COUNT_KEYS = ["business_requests", "mcp_calls", "core_starts"];
408
+ const TERMINAL_REASONS = [
409
+ "OWNER_STOPPED_PERMANENTLY", "RUNTIME_WINDOW_ENDED", "BUSINESS_REQUESTS_EXHAUSTED",
410
+ "MCP_CALLS_EXHAUSTED", "CORE_STARTS_EXHAUSTED",
411
+ ];
412
+ /** 账本语义门:所有真实入口共用,未知终态/计数/时间锚一律在副作用前 HOLD。 */
413
+ function assertLedgerSemantic(value, policy, nowMs) {
414
+ if (value === null || typeof value !== "object" || Array.isArray(value))
415
+ fail("OWNED_RUNTIME_STATE_UNKNOWN", "账本语义不是对象");
416
+ const raw = value;
417
+ const caps = raw.caps;
418
+ const counts = raw.counts;
419
+ for (const key of COUNT_KEYS) {
420
+ if (!isPositiveInt(caps?.[key]))
421
+ fail("OWNED_LEDGER_BOUNDS", `caps.${key} 非法`);
422
+ if (!Number.isSafeInteger(counts?.[key]) || counts[key] < 0 || counts[key] > caps[key]) {
423
+ fail("OWNED_LEDGER_BOUNDS", `counts.${key} 非法`);
424
+ }
425
+ }
426
+ if (!Number.isSafeInteger(raw.revision) || raw.revision < 0)
427
+ fail("OWNED_LEDGER_BOUNDS", "revision 非法");
428
+ if (!Number.isSafeInteger(raw.process_boots) || raw.process_boots < 1)
429
+ fail("OWNED_LEDGER_BOUNDS", "process_boots 非法");
430
+ if (typeof raw.terminal !== "boolean")
431
+ fail("OWNED_LEDGER_BOUNDS", "terminal 非布尔");
432
+ if (raw.terminal) {
433
+ if (typeof raw.terminal_reason !== "string" || !TERMINAL_REASONS.includes(raw.terminal_reason)) {
434
+ fail("OWNED_RUNTIME_TERMINAL_REASON_UNKNOWN", "终态理由未知");
435
+ }
436
+ }
437
+ else if (raw.terminal_reason !== null) {
438
+ fail("OWNED_LEDGER_BOUNDS", "非终态不得携带 terminal_reason");
439
+ }
440
+ if (raw.terminal) {
441
+ const reason = raw.terminal_reason;
442
+ if (reason === "BUSINESS_REQUESTS_EXHAUSTED" && counts.business_requests < caps.business_requests) {
443
+ fail("OWNED_RUNTIME_TERMINAL_REASON_INCONSISTENT", "业务终态理由与计数不相容");
444
+ }
445
+ if (reason === "MCP_CALLS_EXHAUSTED" && counts.mcp_calls < caps.mcp_calls) {
446
+ fail("OWNED_RUNTIME_TERMINAL_REASON_INCONSISTENT", "MCP终态理由与计数不相容");
447
+ }
448
+ if (reason === "CORE_STARTS_EXHAUSTED" && counts.core_starts < caps.core_starts) {
449
+ fail("OWNED_RUNTIME_TERMINAL_REASON_INCONSISTENT", "Core终态理由与计数不相容");
450
+ }
451
+ if (reason === "RUNTIME_WINDOW_ENDED" && policy !== undefined && nowMs !== undefined && nowMs < Date.parse(policy.window_end_utc)) {
452
+ fail("OWNED_RUNTIME_TERMINAL_REASON_INCONSISTENT", "到期终态理由与当前窗口不相容");
453
+ }
454
+ }
455
+ const anchor = raw.anchor;
456
+ if (anchor === null || typeof anchor !== "object" ||
457
+ !["DARWIN_MACH_CONTINUOUS_NS", "LINUX_PROC_UPTIME_NS"].includes(String(anchor.provider)) ||
458
+ typeof anchor.host_boot_id !== "string" || anchor.host_boot_id.length === 0 ||
459
+ (typeof anchor.clock_namespace !== "string" && anchor.clock_namespace !== null) ||
460
+ !Number.isSafeInteger(anchor.wall_ms) || typeof anchor.monotonic_ns !== "string" || !/^\d+$/.test(anchor.monotonic_ns))
461
+ fail("OWNED_RUNTIME_CLOCK_IDENTITY_UNKNOWN", "持久时间锚语义未知");
462
+ }
463
+ /**
464
+ * 重启前校验:journal 记录的账本摘要、精确键集、数值范围、计数不超上限、
465
+ * 以及**完整不可变策略**(含 caps/起止,经 policy_sha256)与路径身份绑定。
466
+ * 任何漂移都在副作用前 HOLD。
467
+ */
468
+ function assertLedgerIntegrity(ledger, journalState, ledgerPath, policy) {
469
+ if (ledger === null || typeof ledger !== "object" || Array.isArray(ledger)) {
470
+ fail("OWNED_RUNTIME_STATE_UNKNOWN", "ledger 不是对象");
471
+ }
472
+ const value = ledger;
473
+ const keys = Object.keys(value).sort();
474
+ if (JSON.stringify(keys) !== JSON.stringify([...LEDGER_KEYS].sort())) {
475
+ fail("OWNED_LEDGER_SCHEMA_DRIFT", `ledger 键集不符:${keys.join(",")}`);
476
+ }
477
+ if (value.schema !== "kiwi.cloud.owned-ledger/1")
478
+ fail("OWNED_LEDGER_SCHEMA_DRIFT", "ledger schema 不符");
479
+ assertLedgerSemantic(value, policy);
480
+ // 可信摘要:journal 必须记录与磁盘一致的内容摘要。
481
+ const bytes = readFileSync(ledgerPath);
482
+ const actual = sha256(bytes);
483
+ if (journalState?.last_ledger_sha256 !== actual) {
484
+ fail("OWNED_LEDGER_DRIFT", "journal 记录的账本摘要与磁盘不一致");
485
+ }
486
+ // 完整不可变策略绑定(含 caps / 起止),不是只看 id。
487
+ if (value.policy_id !== policy.policy_id || value.window_id !== policy.window_id) {
488
+ fail("OWNED_RUNTIME_POLICY_DRIFT", "策略与既有窗口不一致(不允许换窗/换策略)");
489
+ }
490
+ if (value.policy_sha256 !== contentDigest(policy)) {
491
+ fail("OWNED_RUNTIME_POLICY_DRIFT", "策略内容漂移(caps/期限等被改动)");
492
+ }
493
+ if (value.window_start_utc !== policy.window_start_utc || value.window_end_utc !== policy.window_end_utc) {
494
+ fail("OWNED_RUNTIME_POLICY_DRIFT", "窗口起止与策略不一致");
495
+ }
496
+ // 数值范围与计数不超上限。
497
+ const caps = value.caps;
498
+ const counts = value.counts;
499
+ for (const key of COUNT_KEYS) {
500
+ const cap = caps?.[key];
501
+ const used = counts?.[key];
502
+ if (!isPositiveInt(cap))
503
+ fail("OWNED_LEDGER_BOUNDS", `caps.${key} 非法`);
504
+ if (typeof used !== "number" || !Number.isSafeInteger(used) || used < 0) {
505
+ fail("OWNED_LEDGER_BOUNDS", `counts.${key} 非法`);
506
+ }
507
+ if (used > cap)
508
+ fail("OWNED_LEDGER_BOUNDS", `counts.${key} 超过上限`);
509
+ if (cap !== policy.caps[key]) {
510
+ fail("OWNED_RUNTIME_POLICY_DRIFT", `caps.${key} 与策略不一致`);
511
+ }
512
+ }
513
+ }
514
+ /** pending 恢复:只有完整匹配 base/target 与 delta 时才前向应用,否则保留原文件 HOLD。 */
515
+ function recoverPending(pending, ledgerPath, generation, tokenHash, journal) {
516
+ // pending 必须属于"我们刚刚接管的那个 owner/代际",否则拒绝应用。
517
+ if (pending.generation !== generation || pending.token_hash !== tokenHash) {
518
+ fail("OWNED_RUNTIME_PENDING_FOREIGN", "pending 属于其他 owner/代际,拒绝应用");
519
+ }
520
+ if (!existsSync(ledgerPath))
521
+ fail("OWNED_RUNTIME_PENDING_NO_BASE", "pending 存在但账本缺失");
522
+ const currentBytes = readFileSync(ledgerPath);
523
+ const currentSha = sha256(currentBytes);
524
+ if (currentSha === pending.target_sha256) {
525
+ // 已达目标:只需最终确认。
526
+ if (!canonical(JSON.parse(pending.target_json)).equals(currentBytes)) {
527
+ fail("OWNED_RUNTIME_PENDING_TARGET_MISMATCH", "目标摘要相同但字节不一致");
528
+ }
529
+ finalizePendingAfterCheck(ledgerPath, currentBytes);
530
+ journal.finalize(sha256(currentBytes));
531
+ return;
532
+ }
533
+ if (currentSha !== pending.base_sha256) {
534
+ fail("OWNED_RUNTIME_PENDING_BASE_MISMATCH", "当前账本不处于允许的 base/target 状态");
535
+ }
536
+ const base = JSON.parse(currentBytes.toString("utf8"));
537
+ assertLedgerSemantic(base);
538
+ const targetBytes = Buffer.from(pending.target_json, "utf8");
539
+ if (sha256(targetBytes) !== pending.target_sha256) {
540
+ fail("OWNED_RUNTIME_PENDING_TARGET_MISMATCH", "target_json 与 target_sha256 不符");
541
+ }
542
+ const target = JSON.parse(targetBytes.toString("utf8"));
543
+ assertLedgerSemantic(target);
544
+ assertDeltaAllowed(base, target, pending.kind);
545
+ if (!canonical(JSON.parse(targetBytes.toString("utf8"))).equals(targetBytes)) {
546
+ fail("OWNED_RUNTIME_PENDING_TARGET_MISMATCH", "target_json 非规范序列化");
547
+ }
548
+ finalizePendingAfterCheck(ledgerPath, targetBytes);
549
+ journal.finalize(sha256(targetBytes));
550
+ }
551
+ function finalizePendingAfterCheck(ledgerPath, bytes) {
552
+ atomicWrite(ledgerPath, bytes);
553
+ const readBack = readFileSync(ledgerPath);
554
+ if (!readBack.equals(bytes))
555
+ fail("OWNED_RUNTIME_PENDING_READBACK", "恢复写回不一致");
556
+ }
557
+ /** 允许的 delta:计数只增不退、策略/anchor/window 不变、revision 恰好 +1、终态理由合法。 */
558
+ function assertDeltaAllowed(base, target, kind) {
559
+ if (target.schema !== "kiwi.cloud.owned-ledger/1")
560
+ fail("OWNED_RUNTIME_PENDING_DELTA", "target schema 不符");
561
+ if (target.policy_sha256 !== base.policy_sha256 || target.policy_id !== base.policy_id || target.window_id !== base.window_id) {
562
+ fail("OWNED_RUNTIME_PENDING_DELTA", "pending 试图改变策略绑定");
563
+ }
564
+ if (JSON.stringify(target.anchor) !== JSON.stringify(base.anchor)) {
565
+ fail("OWNED_RUNTIME_PENDING_DELTA", "pending 试图改变时间锚");
566
+ }
567
+ if (target.window_start_utc !== base.window_start_utc || target.window_end_utc !== base.window_end_utc) {
568
+ fail("OWNED_RUNTIME_PENDING_DELTA", "pending 试图改变窗口");
569
+ }
570
+ if (JSON.stringify(target.caps) !== JSON.stringify(base.caps)) {
571
+ fail("OWNED_RUNTIME_PENDING_DELTA", "pending 试图改变上限");
572
+ }
573
+ if (target.revision !== base.revision + 1)
574
+ fail("OWNED_RUNTIME_PENDING_DELTA", "pending revision 非法");
575
+ if (Date.parse(target.updated_at_utc) < Date.parse(base.updated_at_utc)) {
576
+ fail("OWNED_RUNTIME_PENDING_DELTA", "pending 时间倒退");
577
+ }
578
+ for (const key of ["business_requests", "mcp_calls", "core_starts"]) {
579
+ const before = base.counts[key];
580
+ const after = target.counts[key];
581
+ if (!Number.isSafeInteger(after) || after < before) {
582
+ fail("OWNED_RUNTIME_PENDING_DELTA", `pending 使 ${key} 倒退`);
583
+ }
584
+ if (after > base.caps[key])
585
+ fail("OWNED_RUNTIME_PENDING_DELTA", `pending 使 ${key} 超上限`);
586
+ }
587
+ if (base.terminal && !target.terminal)
588
+ fail("OWNED_RUNTIME_PENDING_DELTA", "pending 试图撤销终态");
589
+ if (!base.terminal && target.terminal) {
590
+ if (kind !== "terminal")
591
+ fail("OWNED_RUNTIME_PENDING_DELTA", "非 terminal 操作不得写终态");
592
+ if (typeof target.terminal_reason !== "string" || !TERMINAL_REASONS.includes(target.terminal_reason)) {
593
+ fail("OWNED_RUNTIME_PENDING_DELTA", "终态理由不在白名单");
594
+ }
595
+ }
596
+ if (target.process_boots !== base.process_boots) {
597
+ fail("OWNED_RUNTIME_PENDING_DELTA", "pending 试图改变 process_boots");
598
+ }
599
+ }
600
+ export async function startOwnedRuntime(options) {
601
+ const { dataDir, policy } = options;
602
+ const now = options.now ?? Date.now;
603
+ const clock = options.clock ?? createOwnedClock();
604
+ const clockIdentity = clock.identity;
605
+ const layout = ownedLayout(dataDir);
606
+ const crashHook = options.crashHook ?? (() => { });
607
+ const dataClass = classifyDataDir(dataDir, layout);
608
+ if (dataClass === "LEGACY") {
609
+ fail("OWNED_RUNTIME_LEGACY_STATE", `dataDir 非空且无 owned 状态,拒绝初始化:${dataDir}`);
610
+ }
611
+ if (dataClass === "FRESH") {
612
+ // 全新:先确保 dataDir 自身存在(0700);owned/ 随后独占创建。
613
+ try {
614
+ mkdirSync(dataDir, { recursive: true, mode: 0o700 });
615
+ }
616
+ catch (error) {
617
+ fail("OWNED_DATA_DIR_UNWRITABLE", `无法创建 dataDir:${error.message}`);
618
+ }
619
+ }
620
+ // 能力探针:只在 dataDir 下自建**独占随机子目录**,只清理该子目录(非递归、且仅自有对象)。
621
+ probeOwnedCapabilities(options.probeDir ?? dataDir);
622
+ if (dataClass === "FRESH") {
623
+ try {
624
+ mkdirSync(layout.dir, { mode: 0o700 });
625
+ }
626
+ catch (error) {
627
+ if (error.code === "EEXIST") {
628
+ fail("OWNED_RUNTIME_CONCURRENT_INIT", "并发首启:owned 目录已被创建");
629
+ }
630
+ throw error;
631
+ }
632
+ }
633
+ // guard:同一时刻只允许一个 owner 进入;身份(host boot + pid + 代际)随 guard 落盘,
634
+ // 只有"同一 host boot 且该 pid 已不存在"才视为可证明的 dead owner,可接管;
635
+ // 未知身份(跨 boot / 解析失败 / guard 损坏)一律 HOLD,不按 mtime 或超时清锁。
636
+ const token = randomBytes(16).toString("hex");
637
+ const tokenHash = sha256(token);
638
+ const hostBootId = ownedHostBootId(clockIdentity);
639
+ const guardBody = (generation) => `${JSON.stringify({ schema: "kiwi.cloud.owned-owner-guard/1", token_hash: tokenHash, host_boot_id: hostBootId, pid: process.pid, generation, at_ms: now() })}\n`;
640
+ /** 读取既有 guard 并判定其 owner 是否可证明已死;结构未知一律 HOLD。 */
641
+ const readGuard = () => {
642
+ if (!existsSync(layout.guard))
643
+ return undefined;
644
+ let existing;
645
+ try {
646
+ existing = JSON.parse(readFileSync(layout.guard, "utf8"));
647
+ }
648
+ catch {
649
+ fail("OWNED_RUNTIME_UNKNOWN_OWNER", "owner guard 损坏,无法判定存活");
650
+ }
651
+ if (existing === undefined ||
652
+ existing.schema !== "kiwi.cloud.owned-owner-guard/1" ||
653
+ typeof existing.host_boot_id !== "string" ||
654
+ typeof existing.pid !== "number" ||
655
+ typeof existing.generation !== "number" ||
656
+ typeof existing.token_hash !== "string") {
657
+ fail("OWNED_RUNTIME_UNKNOWN_OWNER", "owner guard 结构未知,拒绝接管");
658
+ }
659
+ if (existing.host_boot_id !== hostBootId) {
660
+ fail("OWNED_RUNTIME_UNKNOWN_OWNER", "owner 来自不同 host boot,无法证明已死");
661
+ }
662
+ let alive = true;
663
+ try {
664
+ process.kill(existing.pid, 0);
665
+ }
666
+ catch (error) {
667
+ alive = error.code === "EPERM";
668
+ }
669
+ return { token_hash: existing.token_hash, generation: existing.generation, dead: !alive };
670
+ };
671
+ let guardFd;
672
+ /** guard 仅作诊断标记(所有权在 SQL);写入失败不授予/撤销所有权。 */
673
+ const writeGuard = (generation) => {
674
+ try {
675
+ if (guardFd !== undefined)
676
+ closeSync(guardFd);
677
+ if (existsSync(layout.guard)) {
678
+ renameSync(layout.guard, `${layout.guard}.stale-${Date.now()}`);
679
+ }
680
+ guardFd = openSync(layout.guard, "w", 0o600);
681
+ writeSync(guardFd, guardBody(generation));
682
+ fsyncSync(guardFd);
683
+ }
684
+ catch (error) {
685
+ fail("OWNED_RUNTIME_GUARD_WRITE", `guard 写入失败:${error.message}`);
686
+ }
687
+ };
688
+ if (dataClass === "PARTIAL") {
689
+ fail("OWNED_RUNTIME_STATE_UNKNOWN", `owned 状态不完整:${layout.dir}`);
690
+ }
691
+ let journal;
692
+ try {
693
+ journal = OwnedJournal.open(layout.journal);
694
+ }
695
+ catch (error) {
696
+ if (isSqliteBusy(error))
697
+ fail("OWNED_RUNTIME_OWNER_BUSY", "SQLite owner journal 正在被其他 owner 写入");
698
+ throw error;
699
+ }
700
+ let ownerReleased = false;
701
+ let acquiredOwner = false;
702
+ const releaseOwner = () => {
703
+ if (ownerReleased)
704
+ return;
705
+ ownerReleased = true;
706
+ // 只有真正取得过所有权才释放/清理 guard;失败路径保留现场(不清他人的锁)。
707
+ if (acquiredOwner) {
708
+ try {
709
+ if (guardFd !== undefined)
710
+ closeSync(guardFd);
711
+ }
712
+ catch {
713
+ /* ignore */
714
+ }
715
+ try {
716
+ rmSync(layout.guard, { force: true });
717
+ }
718
+ catch {
719
+ /* ignore */
720
+ }
721
+ journal.release(tokenHash);
722
+ }
723
+ journal.close();
724
+ };
725
+ try {
726
+ // 所有权:SQL CAS。held=0 → 抢占;held=1 但观察到的是可证明已死的旧 token → 接管。
727
+ const observed = readGuard();
728
+ if (observed !== undefined && !observed.dead) {
729
+ fail("OWNED_RUNTIME_OWNER_BUSY", "guard 显示 owner 仍存活,拒绝启动");
730
+ }
731
+ const prior = journal.state();
732
+ // 只有 journal 标记 held=1 时才走"基于观察旧 token 的接管 CAS";
733
+ // 否则是空闲状态,用 held=0 抢占。
734
+ const observedToken = prior !== undefined && prior.held === 1 && observed !== undefined ? observed.token_hash : undefined;
735
+ if (prior !== undefined && prior.held === 1 && observedToken !== prior.token_hash) {
736
+ fail("OWNED_RUNTIME_UNKNOWN_OWNER", "guard 与 journal 的 owner 不一致,拒绝接管");
737
+ }
738
+ let generation;
739
+ try {
740
+ generation = journal.acquire({ tokenHash, pid: process.pid, hostBootId, atMs: now() }, observedToken);
741
+ }
742
+ catch (error) {
743
+ if (isSqliteBusy(error))
744
+ fail("OWNED_RUNTIME_OWNER_BUSY", "SQLite owner journal 正在被其他 owner 写入");
745
+ throw error;
746
+ }
747
+ acquiredOwner = true;
748
+ const clockSample = clock.read();
749
+ const pending = journal.pending();
750
+ if (pending !== undefined) {
751
+ recoverPending(pending, layout.ledger, prior.generation, prior.token_hash, journal);
752
+ crashHook("recovered-pending");
753
+ }
754
+ const startMs = now();
755
+ if (startMs >= Date.parse(policy.window_end_utc)) {
756
+ fail("OWNED_RUNTIME_WINDOW_EXPIRED", "策略窗口已结束");
757
+ }
758
+ if (startMs < Date.parse(policy.window_start_utc)) {
759
+ fail("OWNED_RUNTIME_WINDOW_NOT_STARTED", "策略窗口尚未开始");
760
+ }
761
+ const ledgerPath = layout.ledger;
762
+ let ledger;
763
+ if (!existsSync(ledgerPath)) {
764
+ ledger = {
765
+ schema: "kiwi.cloud.owned-ledger/1",
766
+ policy_id: policy.policy_id,
767
+ policy_sha256: contentDigest(policy),
768
+ window_id: policy.window_id,
769
+ window_start_utc: policy.window_start_utc,
770
+ window_end_utc: policy.window_end_utc,
771
+ caps: { ...policy.caps },
772
+ counts: { business_requests: 0, mcp_calls: 0, core_starts: 0 },
773
+ process_boots: generation,
774
+ revision: 0,
775
+ terminal: false,
776
+ terminal_reason: null,
777
+ anchor: {
778
+ provider: clockIdentity.provider,
779
+ host_boot_id: hostBootId,
780
+ clock_namespace: clockIdentity.namespace,
781
+ wall_ms: startMs,
782
+ monotonic_ns: clockSample.monotonicNs,
783
+ },
784
+ updated_at_utc: new Date(startMs).toISOString(),
785
+ };
786
+ atomicWrite(ledgerPath, canonical(ledger));
787
+ journal.finalize(sha256(canonical(ledger)));
788
+ writeGuard(generation);
789
+ }
790
+ else {
791
+ ledger = readJsonFile(ledgerPath);
792
+ assertLedgerIntegrity(ledger, journal.state(), ledgerPath, policy);
793
+ const anchor = ledger.anchor;
794
+ if (anchor.provider !== clockIdentity.provider || anchor.host_boot_id !== hostBootId || anchor.clock_namespace !== clockIdentity.namespace) {
795
+ fail("OWNED_RUNTIME_CLOCK_IDENTITY_DRIFT", "持久时间锚与当前 host/boot/provider/namespace 不一致");
796
+ }
797
+ assertLedgerSemantic(ledger, policy, startMs);
798
+ if (ledger.terminal) {
799
+ fail("OWNED_RUNTIME_STOPPED_PERMANENTLY", `窗口已终态:${ledger.terminal_reason ?? "UNKNOWN"}`);
800
+ }
801
+ ledger = {
802
+ ...ledger,
803
+ process_boots: generation,
804
+ revision: ledger.revision + 1,
805
+ updated_at_utc: new Date(startMs).toISOString(),
806
+ };
807
+ atomicWrite(ledgerPath, canonical(ledger));
808
+ journal.finalize(sha256(canonical(ledger)));
809
+ writeGuard(generation);
810
+ }
811
+ let closing = false;
812
+ let forwarding = true;
813
+ const persist = (mutate) => {
814
+ clock.read();
815
+ const current = readJsonFile(ledgerPath);
816
+ assertLedgerSemantic(current, policy, now());
817
+ if (current.terminal)
818
+ fail("OWNED_RUNTIME_TERMINAL", "窗口已终态,拒绝写入");
819
+ journal.assertOwner(tokenHash);
820
+ const next = mutate({ ...current, revision: current.revision + 1, updated_at_utc: new Date(now()).toISOString() });
821
+ atomicWrite(ledgerPath, canonical(next));
822
+ journal.finalize(sha256(canonical(next)));
823
+ return next;
824
+ };
825
+ const terminal = (reason) => {
826
+ clock.read();
827
+ const current = readJsonFile(ledgerPath);
828
+ assertLedgerSemantic(current, policy, now());
829
+ if (current.terminal) {
830
+ if (current.terminal_reason === reason)
831
+ return current;
832
+ fail("OWNED_RUNTIME_TERMINAL_REASON_DRIFT", `已存在终态 ${current.terminal_reason}`);
833
+ }
834
+ const next = {
835
+ ...current,
836
+ terminal: true,
837
+ terminal_reason: reason,
838
+ revision: current.revision + 1,
839
+ updated_at_utc: new Date(now()).toISOString(),
840
+ };
841
+ journal.assertOwner(tokenHash);
842
+ const baseBytes = readFileSync(ledgerPath);
843
+ const intentBytes = canonical(next);
844
+ // 注册完整操作:base/target 摘要 + owner 身份;恢复时必须逐项核验。
845
+ journal.setPending({
846
+ schema: "kiwi.cloud.owned-pending/1",
847
+ operation_id: `terminal-${reason}-${next.revision}`,
848
+ kind: "terminal",
849
+ generation,
850
+ token_hash: tokenHash,
851
+ base_sha256: sha256(baseBytes),
852
+ target_sha256: sha256(intentBytes),
853
+ target_json: intentBytes.toString("utf8"),
854
+ });
855
+ crashHook("after-intent-commit");
856
+ atomicWrite(ledgerPath, intentBytes);
857
+ crashHook("after-ledger-replace");
858
+ // 读回确认后才做最终 SQL 确认(清 pending + 记录摘要)。
859
+ const readBack = readFileSync(ledgerPath);
860
+ if (!readBack.equals(intentBytes))
861
+ fail("OWNED_LEDGER_READBACK_MISMATCH", "终态账本读回不一致");
862
+ journal.finalize(sha256(readBack));
863
+ crashHook("after-finalize");
864
+ return next;
865
+ };
866
+ const reserve = (kind) => {
867
+ if (closing || !forwarding)
868
+ fail("OWNED_RUNTIME_STOPPING", "运行期正在关闭");
869
+ if (now() >= Date.parse(policy.window_end_utc)) {
870
+ terminal("RUNTIME_WINDOW_ENDED");
871
+ fail("OWNED_RUNTIME_WINDOW_EXPIRED", "窗口已到期");
872
+ }
873
+ const current = readJsonFile(ledgerPath);
874
+ assertLedgerSemantic(current, policy, now());
875
+ if (current.counts[kind] >= current.caps[kind]) {
876
+ const reason = kind === "business_requests"
877
+ ? "BUSINESS_REQUESTS_EXHAUSTED"
878
+ : kind === "mcp_calls"
879
+ ? "MCP_CALLS_EXHAUSTED"
880
+ : "CORE_STARTS_EXHAUSTED";
881
+ try {
882
+ terminal(reason);
883
+ }
884
+ catch {
885
+ /* 已终态:保留既有理由,不覆盖 */
886
+ }
887
+ fail(`OWNED_${reason}`, `${kind} 已达上限 ${current.caps[kind]}`);
888
+ }
889
+ persist((ledgerNow) => ({ ...ledgerNow, counts: { ...ledgerNow.counts, [kind]: ledgerNow.counts[kind] + 1 } }));
890
+ };
891
+ // Core 预留必须发生在 bootstrap(Core/listener)之前。
892
+ reserve("core_starts");
893
+ const value = await options.bootstrap();
894
+ const readLedger = () => readJsonFile(ledgerPath);
895
+ const status = () => {
896
+ const current = readLedger();
897
+ return {
898
+ policy_id: current.policy_id,
899
+ window_id: current.window_id,
900
+ window_start_utc: current.window_start_utc,
901
+ window_end_utc: current.window_end_utc,
902
+ counts: { ...current.counts },
903
+ caps: { ...current.caps },
904
+ process_boots: current.process_boots,
905
+ terminal: current.terminal,
906
+ terminal_reason: current.terminal_reason,
907
+ };
908
+ };
909
+ const closeInternal = async (reason) => {
910
+ if (confirmedStop !== undefined)
911
+ return { result: { status: "CLOSED", terminal: true } };
912
+ if (stopping)
913
+ return { result: { status: "HOLD", code: "OWNED_RUNTIME_STOPPING" } };
914
+ if (closing)
915
+ return { result: { status: "CLOSED", terminal: readLedger().terminal } };
916
+ closing = true;
917
+ forwarding = false;
918
+ try {
919
+ let ledgerAfter;
920
+ if (reason !== undefined)
921
+ ledgerAfter = terminal(reason);
922
+ if (options.closeInstance)
923
+ await options.closeInstance(value);
924
+ releaseOwner();
925
+ return { result: { status: "CLOSED", terminal: ledgerAfter?.terminal ?? readLedger().terminal }, ledger: ledgerAfter };
926
+ }
927
+ catch (error) {
928
+ // 关闭失败:保持非转发,暴露 UNKNOWN/HOLD,不宣称成功。
929
+ return { result: { status: "HOLD", code: error.code ?? "OWNED_CLOSE_UNKNOWN" } };
930
+ }
931
+ };
932
+ let stopping = false;
933
+ let stopInFlight;
934
+ let confirmedStop;
935
+ const handle = {
936
+ value,
937
+ status,
938
+ isClosing: () => closing,
939
+ forwardingEnabled: () => forwarding,
940
+ reserveBusiness: () => reserve("business_requests"),
941
+ reserveMcp: () => reserve("mcp_calls"),
942
+ reserveCore: () => reserve("core_starts"),
943
+ async close() {
944
+ const { result } = await closeInternal();
945
+ return result;
946
+ },
947
+ stopPermanently() {
948
+ if (confirmedStop !== undefined)
949
+ return Promise.resolve(confirmedStop);
950
+ if (stopInFlight !== undefined)
951
+ return stopInFlight;
952
+ if (closing || stopping)
953
+ return Promise.resolve({ status: "HOLD", code: "OWNED_RUNTIME_STOPPING" });
954
+ stopping = true;
955
+ stopInFlight = (async () => {
956
+ // 1) 停新请求 2) 校验未决状态 3) 单次时钟样本(到期优先)
957
+ forwarding = false;
958
+ try {
959
+ clock.read();
960
+ }
961
+ catch (error) {
962
+ return { status: "HOLD", code: error.code ?? "OWNED_CLOCK_IDENTITY_UNKNOWN" };
963
+ }
964
+ const state = journal.state();
965
+ if (state?.pending_json !== null && state?.pending_json !== undefined) {
966
+ return { status: "HOLD", code: "OWNED_RUNTIME_STATE_UNKNOWN" };
967
+ }
968
+ if (state?.dispatch_json !== null && state?.dispatch_json !== undefined) {
969
+ return { status: "HOLD", code: "OWNED_RUNTIME_STATE_UNKNOWN" };
970
+ }
971
+ const atMs = now();
972
+ const expired = atMs >= Date.parse(policy.window_end_utc);
973
+ const requestedReason = expired ? "RUNTIME_WINDOW_ENDED" : "OWNER_STOPPED_PERMANENTLY";
974
+ let ledgerAfter;
975
+ const existing = readJsonFile(layout.ledger);
976
+ let reason = requestedReason;
977
+ if (existing.terminal) {
978
+ try {
979
+ assertLedgerSemantic(existing, policy, atMs);
980
+ }
981
+ catch (error) {
982
+ return { status: "HOLD", code: error.code ?? "OWNED_RUNTIME_STATE_UNKNOWN" };
983
+ }
984
+ // 自然终态已经是权威结果:stop 只读回并复用实际 reason,不重写账本。
985
+ reason = existing.terminal_reason;
986
+ ledgerAfter = existing;
987
+ }
988
+ else {
989
+ try {
990
+ ledgerAfter = terminal(requestedReason);
991
+ }
992
+ catch (error) {
993
+ return { status: "HOLD", code: error.code ?? "OWNED_STOP_UNKNOWN" };
994
+ }
995
+ }
996
+ // 读回校验:账本字节、理由、revision、计数、journal ledger sha 必须一致。
997
+ const bytes = readFileSync(layout.ledger);
998
+ const readBack = readJsonFile(layout.ledger);
999
+ const journalState = journal.state();
1000
+ const consistent = canonical(readBack).equals(bytes) &&
1001
+ readBack.terminal === true &&
1002
+ readBack.terminal_reason === reason &&
1003
+ readBack.revision === ledgerAfter.revision &&
1004
+ journalState?.pending_json === null &&
1005
+ journalState?.last_ledger_sha256 === sha256(bytes);
1006
+ if (!consistent)
1007
+ return { status: "HOLD", code: "OWNED_TERMINAL_READBACK_MISMATCH" };
1008
+ // 终态已持久且读回一致;资源释放失败也不能 reject 或谎称仍转发。
1009
+ if (options.closeInstance) {
1010
+ try {
1011
+ await options.closeInstance(value);
1012
+ }
1013
+ catch (error) {
1014
+ releaseOwner();
1015
+ return {
1016
+ status: "HOLD",
1017
+ code: error.code ?? "OWNED_CLOSE_FAILED",
1018
+ reason,
1019
+ revision: readBack.revision,
1020
+ ledger_sha256: sha256(bytes),
1021
+ };
1022
+ }
1023
+ }
1024
+ releaseOwner();
1025
+ return { status: "TERMINAL_CONFIRMED", reason, revision: readBack.revision, ledger_sha256: sha256(bytes) };
1026
+ })().then((result) => {
1027
+ if (result.status === "TERMINAL_CONFIRMED")
1028
+ confirmedStop = result;
1029
+ return result;
1030
+ }, (error) => ({ status: "HOLD", code: error.code ?? "OWNED_STOP_UNKNOWN" }));
1031
+ return stopInFlight;
1032
+ },
1033
+ };
1034
+ return handle;
1035
+ }
1036
+ catch (error) {
1037
+ releaseOwner();
1038
+ throw error;
1039
+ }
1040
+ }
1041
+ //# sourceMappingURL=owned-runtime.js.map