pi-web-ui 0.116.0 → 0.117.0

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 (155) hide show
  1. package/CHANGELOG.md +38 -4
  2. package/bin/device-hub-cli.mjs +26 -3
  3. package/bin/pi-web-ui.mjs +138 -70
  4. package/dist/server/agent-service-daemon.js +52 -6
  5. package/dist/server/agent-service.js +495 -141
  6. package/dist/server/canvas/canvas-workspace.js +18 -86
  7. package/dist/server/client-state.js +35 -6
  8. package/dist/server/compaction-markers.js +43 -24
  9. package/dist/server/dangling-tools.js +172 -16
  10. package/dist/server/device-center/bot-execution.js +48 -1
  11. package/dist/server/device-center/collab-service.js +26 -8
  12. package/dist/server/device-center/collab-tool.js +394 -18
  13. package/dist/server/device-center/connector.js +107 -37
  14. package/dist/server/device-center/delivery-authority.js +98 -0
  15. package/dist/server/device-center/delivery-subject.js +30 -0
  16. package/dist/server/device-center/device-integration.js +453 -183
  17. package/dist/server/device-center/execution-guides.js +15 -5
  18. package/dist/server/device-center/executor.js +47 -5
  19. package/dist/server/device-center/hub-conversations.js +14 -4
  20. package/dist/server/device-center/hub-deliveries.js +120 -15
  21. package/dist/server/device-center/hub-integration.js +655 -334
  22. package/dist/server/device-center/hub-page.js +5 -4
  23. package/dist/server/device-center/hub-setup.js +23 -1
  24. package/dist/server/device-center/hub-transaction-log.js +197 -0
  25. package/dist/server/device-center/hub.js +772 -354
  26. package/dist/server/device-center/integration-verification.js +113 -0
  27. package/dist/server/device-center/local-hub.js +6 -2
  28. package/dist/server/device-center/local-publication.js +423 -0
  29. package/dist/server/device-center/local-verification-job.js +97 -0
  30. package/dist/server/device-center/local-verification.js +274 -0
  31. package/dist/server/device-center/local.js +107 -12
  32. package/dist/server/device-center/main.js +4 -1
  33. package/dist/server/device-center/partition-log.js +62 -25
  34. package/dist/server/device-center/publication-journal.js +312 -0
  35. package/dist/server/device-center/publish-intent.js +379 -0
  36. package/dist/server/device-center/relay.js +134 -24
  37. package/dist/server/device-center/runtime.js +426 -42
  38. package/dist/server/device-center/store.js +225 -47
  39. package/dist/server/device-center/task-outcome.js +81 -0
  40. package/dist/server/device-center/task-recovery.js +603 -178
  41. package/dist/server/device-center/task-settlement.js +353 -0
  42. package/dist/server/device-center/task-workspace.js +443 -0
  43. package/dist/server/device-center/verification-limits.js +10 -0
  44. package/dist/server/device-center/work-contract.js +995 -0
  45. package/dist/server/dispatch-domain-handlers.js +15 -0
  46. package/dist/server/dsh/dsh-agent-service.js +9 -2
  47. package/dist/server/index.js +26 -1
  48. package/dist/server/patch-node-pty.js +3 -2
  49. package/dist/server/patch-remote-catalog.js +3 -2
  50. package/dist/server/preset-fields.js +17 -1
  51. package/dist/server/preset-share.js +1 -0
  52. package/dist/server/protocol-version.js +1 -1
  53. package/dist/server/quick-ask-settings.js +28 -0
  54. package/dist/server/quick-ask.js +164 -0
  55. package/dist/server/resolve-global-sdk.js +61 -11
  56. package/dist/server/scheduler-tasks.js +35 -8
  57. package/dist/server/session-list-scan.js +223 -0
  58. package/dist/server/session-open.js +93 -0
  59. package/dist/server/session-parser.js +4 -0
  60. package/dist/server/session-scan.js +90 -38
  61. package/dist/server/settings-service.js +9 -1
  62. package/dist/server/soft-cap.js +5 -0
  63. package/dist/server/transcript-prepare.js +73 -0
  64. package/dist/server/universal/drivers/claude-code.js +98 -34
  65. package/dist/server/universal/universal-session.js +4 -0
  66. package/dist/server/workspace-handle.js +428 -0
  67. package/docs/architecture-plugins.md +18 -5
  68. package/docs/device-center.md +30 -22
  69. package/package.json +3 -4
  70. package/plugin-sdk/README.md +16 -8
  71. package/plugin-sdk/client.d.ts +27 -0
  72. package/plugin-sdk/client.mjs +82 -0
  73. package/plugin-sdk/index.d.ts +10 -0
  74. package/plugin-sdk/index.mjs +4 -683
  75. package/plugin-sdk/package.json +15 -4
  76. package/plugin-sdk/testing.d.ts +10 -0
  77. package/plugin-sdk/testing.mjs +566 -0
  78. package/themes/flow-cristallo.css +168 -0
  79. package/themes/flow-ink.css +169 -0
  80. package/themes/flow-obsidian.css +169 -0
  81. package/themes/flow-zurich.css +169 -0
  82. package/web/dist/.build-assets.json +1 -1
  83. package/web/dist/assets/{BgTasksModal-BDoOpj-F.js → BgTasksModal-BjNRIUIc.js} +1 -1
  84. package/web/dist/assets/{BgTasksModal-C0i3O1FT.js → BgTasksModal-C0zuU8FE.js} +1 -1
  85. package/web/dist/assets/{CanvasStudio-B8thymBN.js → CanvasStudio-BWvdmJ0M.js} +3 -3
  86. package/web/dist/assets/{CanvasStudio-zSxyIx1R.js → CanvasStudio-VQFjmTGq.js} +3 -3
  87. package/web/dist/assets/DeviceCenter-DI9_0aBB.js +3 -0
  88. package/web/dist/assets/DeviceCenter-DsNtXqzY.js +3 -0
  89. package/web/dist/assets/{DeviceExecutionSettings-q5Ik8oXg.js → DeviceExecutionSettings-BLP1Su5G.js} +1 -1
  90. package/web/dist/assets/DeviceGroups-2Pvk0Cds.js +1 -0
  91. package/web/dist/assets/DeviceGroups-CP7CcyPD.js +1 -0
  92. package/web/dist/assets/{Dropdown-C4LIhshN.js → Dropdown-CQtstPGv.js} +1 -1
  93. package/web/dist/assets/FilePreview-BMB2tNyT.js +2 -0
  94. package/web/dist/assets/FilePreview-RGFQUbJo.js +2 -0
  95. package/web/dist/assets/{GlobalSearchModal-BWgU8yPd.js → GlobalSearchModal-BM5wxiqU.js} +1 -1
  96. package/web/dist/assets/{GlobalSearchModal-F7fNimKk.js → GlobalSearchModal-DGv_WINq.js} +1 -1
  97. package/web/dist/assets/GroupConversation-B7SnuXj1.js +61 -0
  98. package/web/dist/assets/GroupConversation-Dda69q-2.js +61 -0
  99. package/web/dist/assets/{HintTip-c6d0TJoh.js → HintTip-ChTW8o1m.js} +1 -1
  100. package/web/dist/assets/ModelConfigModal-C-0Z4hUZ.js +2 -0
  101. package/web/dist/assets/ModelConfigModal-yqeadyab.js +2 -0
  102. package/web/dist/assets/{PiSetupModal-BmMrrgB9.js → PiSetupModal-BX5rUuoI.js} +1 -1
  103. package/web/dist/assets/{ProviderOAuthControls-BGSBIKD7.js → ProviderOAuthControls-DY4SCfXg.js} +1 -1
  104. package/web/dist/assets/SCMPanel-C4KbQvvK.js +2 -0
  105. package/web/dist/assets/SCMPanel-DPAyY2sW.js +2 -0
  106. package/web/dist/assets/SettingsModal-DxZp6D_g.js +32 -0
  107. package/web/dist/assets/SettingsModal-WhQzaOPt.js +32 -0
  108. package/web/dist/assets/{TerminalPanel-DDavKvFr.js → TerminalPanel-D4By_RVc.js} +2 -2
  109. package/web/dist/assets/{TerminalPanel-0CYvD72B.js → TerminalPanel-lZw8-i3j.js} +2 -2
  110. package/web/dist/assets/{TuiOverlayModal-BsA-QTvN.js → TuiOverlayModal-C3pAVuC8.js} +1 -1
  111. package/web/dist/assets/{TuiOverlayModal-DzoVQBuG.js → TuiOverlayModal-D7_rEXcJ.js} +1 -1
  112. package/web/dist/assets/app-globals-KqOVtmp1.js +123 -0
  113. package/web/dist/assets/{canvas-client-CUnXlQYX.js → canvas-client-BY6ojmle.js} +1 -1
  114. package/web/dist/assets/{desktop-aAKpvKJV.js → desktop-CV6KKp9R.js} +1 -1
  115. package/web/dist/assets/index-BawF7ZP5.js +397 -0
  116. package/web/dist/assets/index-BoGCoq5X.js +397 -0
  117. package/web/dist/assets/index-CVW9FoY2.css +1 -0
  118. package/web/dist/assets/{plugin-host-BRWib9DF.js → plugin-host-Dn8Dd6SC.js} +1 -1
  119. package/web/dist/assets/{remote-ssh-client-CfYSMEZg.js → remote-ssh-client-Dzi-eEyE.js} +1 -1
  120. package/web/dist/assets/{theme-D2l_mLNo.js → theme-D_bihpdN.js} +1 -1
  121. package/web/dist/index.html +11 -11
  122. package/web/dist/sw.js +1 -1
  123. package/dist/gh-comment-781.md +0 -5
  124. package/dist/server/device-center/local-page.js +0 -17
  125. package/dist/server/device-center/smoke-preview.js +0 -3
  126. package/dist/server/durable/durable-capabilities.js +0 -11
  127. package/dist/server/markers/builtins/services.js +0 -123
  128. package/dist/server/markers/builtins/todo.js +0 -189
  129. package/dist/server/markers-list-tool.js +0 -34
  130. package/dist/server/orchestrator.js +0 -109
  131. package/dist/server/patch-turn-end-boundary.js +0 -77
  132. package/dist/server/system-prompt-soul.js +0 -41
  133. package/dist/server/univer-service.js +0 -448
  134. package/dist/server/universal/drivers/dsh-driver.js +0 -379
  135. package/dist/test-artifact.md +0 -9
  136. package/dist/test-preview-modal.md +0 -11
  137. package/dist/test-report.html +0 -20
  138. package/web/dist/assets/DeviceCenter-DfAHKcid.js +0 -3
  139. package/web/dist/assets/DeviceCenter-ydvOTlzE.js +0 -3
  140. package/web/dist/assets/DeviceGroups-CI14_SRb.js +0 -1
  141. package/web/dist/assets/DeviceGroups-DvsB5IEU.js +0 -1
  142. package/web/dist/assets/FilePreview-BgGongmv.js +0 -2
  143. package/web/dist/assets/FilePreview-D4NrhF-U.js +0 -2
  144. package/web/dist/assets/GroupConversation-Dh71Pdb-.js +0 -17
  145. package/web/dist/assets/GroupConversation-ZK3nRmNm.js +0 -17
  146. package/web/dist/assets/ModelConfigModal-YVEgyy34.js +0 -2
  147. package/web/dist/assets/ModelConfigModal-vWtg3srp.js +0 -2
  148. package/web/dist/assets/SCMPanel-B8_EDxNr.js +0 -2
  149. package/web/dist/assets/SCMPanel-BU58qk3T.js +0 -2
  150. package/web/dist/assets/SettingsModal-CMUybq3J.js +0 -32
  151. package/web/dist/assets/SettingsModal-OBmGTh-5.js +0 -32
  152. package/web/dist/assets/app-globals-CZxzGvIo.js +0 -123
  153. package/web/dist/assets/index-C6DwztqE.css +0 -1
  154. package/web/dist/assets/index-CuN802Sj.js +0 -93
  155. package/web/dist/assets/index-EH5Fw9fa.js +0 -93
@@ -1,12 +1,18 @@
1
1
  import { execFile } from "node:child_process";
2
+ import { randomUUID } from "node:crypto";
2
3
  import { existsSync } from "node:fs";
3
4
  import { lstat, mkdir, readdir, readFile, realpath, rm, unlink, writeFile } from "node:fs/promises";
4
5
  import { join, resolve } from "node:path";
5
6
  import { promisify } from "node:util";
7
+ import { canonicalPath, computeCanonicalRepositoryId, git, safeId, verifyPatchProducesTree, verifyRepoRoot, verifyWorktreeIdentity, snapshotTree, } from "../workspace-handle.js";
8
+ import { canonicalizeJson, validateDeviceArtifact } from "./work-contract.js";
9
+ import { runVerificationCommand, validateLocalVerificationPlan, VERIFICATION_COMMAND_TIMEOUT_MS, VERIFICATION_TOTAL_TIMEOUT_MS, VerificationStopUnconfirmedError, } from "./local-verification.js";
6
10
  import { integrationError } from "./integration-errors.js";
11
+ import { readPublicationJournal } from "./publication-journal.js";
12
+ import { assertPublishIntentScope, validatePublishIntent } from "./publish-intent.js";
13
+ import { cancelLocalPublication, localPublicationStatus, publishLocalIntent, PublicationStopUnconfirmedError, runPublicationGit, } from "./local-publication.js";
7
14
  const exec = promisify(execFile);
8
15
  const GIT_TIMEOUT_MS = 30_000;
9
- const COMMAND_TIMEOUT_MS = 60_000;
10
16
  const MAX_DIFF_BYTES = 64 * 1024;
11
17
  /** 持久化会话映射表文件路径 */
12
18
  function sessionsFilePath(dataDir) {
@@ -37,20 +43,74 @@ export async function loadPersistentSessions(dataDir) {
37
43
  /** 原子保存持久化的集成会话记录 */
38
44
  export async function savePersistentSessions(dataDir, sessionsMap) {
39
45
  const filePath = sessionsFilePath(dataDir);
40
- const tempPath = `${filePath}.tmp.${Date.now()}`;
46
+ const tempPath = `${filePath}.tmp.${randomUUID()}`;
41
47
  const data = Array.from(sessionsMap.values());
42
48
  await writeFile(tempPath, JSON.stringify(data, null, 2), "utf8");
43
- if (existsSync(filePath))
44
- await unlink(filePath).catch(() => { });
45
49
  const { rename } = await import("node:fs/promises");
46
- await rename(tempPath, filePath).catch(async () => {
47
- await writeFile(filePath, JSON.stringify(data, null, 2), "utf8");
48
- await unlink(tempPath).catch(() => { });
50
+ await rename(tempPath, filePath);
51
+ }
52
+ const sessionWrites = new Map();
53
+ function persistSession(dataDir, integrationId, session) {
54
+ const key = resolve(dataDir);
55
+ const snapshot = session && structuredClone(session);
56
+ const operation = (sessionWrites.get(key) ?? Promise.resolve())
57
+ .catch(() => { })
58
+ .then(async () => {
59
+ const sessions = await loadPersistentSessions(dataDir);
60
+ if (snapshot)
61
+ sessions.set(integrationId, snapshot);
62
+ else
63
+ sessions.delete(integrationId);
64
+ await savePersistentSessions(dataDir, sessions);
49
65
  });
66
+ sessionWrites.set(key, operation);
67
+ void operation
68
+ .finally(() => {
69
+ if (sessionWrites.get(key) === operation)
70
+ sessionWrites.delete(key);
71
+ })
72
+ .catch(() => { });
73
+ return operation;
50
74
  }
51
75
  /** 内存活跃会话映射及操作中断控制器 */
52
76
  const memorySessions = new Map();
53
77
  const activeOperations = new Map();
78
+ const sessionKey = (params) => JSON.stringify([resolve(params.dataDir), params.integrationId]);
79
+ function sameIdentity(a, b) {
80
+ return (a.targetBotId === b.targetBotId &&
81
+ a.targetBotRevision === b.targetBotRevision &&
82
+ resolve(a.repoRoot) === resolve(b.repoRoot));
83
+ }
84
+ function localOperation(params, signal, run) {
85
+ safeId(params.integrationId, "integration");
86
+ const key = sessionKey(params);
87
+ if (activeOperations.has(key))
88
+ return Promise.reject(new Error("Integration operation already active or stop unconfirmed"));
89
+ const operation = {
90
+ controller: new AbortController(),
91
+ identity: { ...params },
92
+ done: Promise.resolve(),
93
+ };
94
+ activeOperations.set(key, operation);
95
+ operation.done = Promise.resolve()
96
+ .then(() => run(AbortSignal.any([operation.controller.signal, ...(signal ? [signal] : [])])))
97
+ .catch(async (error) => {
98
+ if (error instanceof VerificationStopUnconfirmedError || error instanceof PublicationStopUnconfirmedError) {
99
+ operation.blocked = error;
100
+ const session = memorySessions.get(key);
101
+ if (session) {
102
+ session.stopUnconfirmed = true;
103
+ await persistSession(params.dataDir, params.integrationId, session).catch(() => { });
104
+ }
105
+ }
106
+ throw error;
107
+ })
108
+ .finally(() => {
109
+ if (!operation.blocked && activeOperations.get(key) === operation)
110
+ activeOperations.delete(key);
111
+ });
112
+ return operation.done;
113
+ }
54
114
  function sanitizeError(error) {
55
115
  if (!error)
56
116
  return "Unknown error";
@@ -192,6 +252,10 @@ export async function runIsolatedGit(cwd, dataDir, args, timeoutMs = GIT_TIMEOUT
192
252
  "-c",
193
253
  "core.autocrlf=false",
194
254
  "-c",
255
+ "core.fsmonitor=false",
256
+ "-c",
257
+ "core.eol=lf",
258
+ "-c",
195
259
  "core.quotepath=false",
196
260
  ...args,
197
261
  ];
@@ -265,8 +329,15 @@ export async function safeRemoveWorktree(repoRoot, dataDir, worktreePath) {
265
329
  if (!existsSync(worktreePath))
266
330
  return;
267
331
  const normalizedPath = worktreePath.replace(/\\/g, "/");
268
- // 若处于未提交的预合并暂存态,先尝试安全 abort merge,还原工作树到干净状态
269
- await runIsolatedGit(worktreePath, dataDir, ["merge", "--abort"]).catch(() => { });
332
+ const sessions = await loadPersistentSessions(dataDir);
333
+ const session = [...sessions.values()].find((item) => resolve(item.worktreePath) === resolve(worktreePath));
334
+ // Only discard the exact staged merge we prepared; preserve modified or unpinned workspaces.
335
+ if (session) {
336
+ if (session.stopUnconfirmed || session.verificationInFlight)
337
+ throw new VerificationStopUnconfirmedError();
338
+ await assertPreparedTree(session, dataDir);
339
+ await runIsolatedGit(worktreePath, dataDir, ["merge", "--abort"]).catch(() => { });
340
+ }
270
341
  try {
271
342
  await runIsolatedGit(repoRoot, dataDir, ["worktree", "remove", normalizedPath]);
272
343
  }
@@ -291,10 +362,18 @@ export async function recoverOrphanWorktrees(dataDir, repoRootFinder) {
291
362
  const fullPath = join(worktreesRoot, entry);
292
363
  const session = persisted.get(id);
293
364
  const repoRoot = session?.repoRoot ?? repoRootFinder?.(id);
365
+ if (!session ||
366
+ session.verificationStopConfirmed !== true ||
367
+ session.stopUnconfirmed ||
368
+ session?.verificationInFlight ||
369
+ activeOperations.has(sessionKey({ dataDir, integrationId: id }))) {
370
+ pendingCount++;
371
+ continue;
372
+ }
294
373
  if (repoRoot && existsSync(repoRoot)) {
295
374
  try {
296
375
  await safeRemoveWorktree(repoRoot, dataDir, fullPath);
297
- persisted.delete(id);
376
+ await persistSession(dataDir, id);
298
377
  recoveredCount++;
299
378
  }
300
379
  catch {
@@ -305,37 +384,92 @@ export async function recoverOrphanWorktrees(dataDir, repoRootFinder) {
305
384
  pendingCount++;
306
385
  }
307
386
  }
308
- await savePersistentSessions(dataDir, persisted);
309
387
  return { recoveredCount, pendingCount };
310
388
  }
311
389
  /** 获取会话对象并严格核验多租户 Bot 身份、Revision 与工作区归属 */
312
- async function getVerifiedSession(dataDir, params) {
313
- let session = memorySessions.get(params.integrationId);
390
+ async function getVerifiedSession(dataDir, params, allowUnpinned = false) {
391
+ const key = sessionKey({ dataDir, integrationId: params.integrationId });
392
+ let session = memorySessions.get(key);
314
393
  if (!session) {
315
394
  const persisted = await loadPersistentSessions(dataDir);
316
395
  session = persisted.get(params.integrationId);
317
396
  if (session)
318
- memorySessions.set(params.integrationId, session);
397
+ memorySessions.set(key, session);
319
398
  }
320
399
  if (!session || !existsSync(session.worktreePath)) {
321
400
  throw new Error("Active integration worktree session not found on this device");
322
401
  }
402
+ if (session.stopUnconfirmed || session.verificationInFlight)
403
+ throw new VerificationStopUnconfirmedError();
323
404
  // 严格跨 Bot 隔离校验:防止 opaque ID 借由另一 Bot 的 lease 跨权操作
324
405
  if (session.targetBotId !== params.targetBotId ||
325
406
  session.targetBotRevision !== params.targetBotRevision ||
326
407
  resolve(session.repoRoot) !== resolve(params.repoRoot)) {
327
408
  throw new Error("Integration session Bot identity, revision or workspace mismatch");
328
409
  }
410
+ if ((await verifyRepoRoot(params.repoRoot)).repoRoot !== (await canonicalPath(params.repoRoot)))
411
+ throw new Error("Integration Bot workspace must be the canonical repository root");
412
+ const identity = await verifyWorktreeIdentity(session.worktreePath, session.repoRoot, undefined, session.gitDir, session.commonDir);
413
+ if ((!allowUnpinned && (!session.gitDir || !session.commonDir)) ||
414
+ (identity.headCommit !== session.expectedTargetSha && identity.headCommit !== session.newCommitSha))
415
+ throw new Error("Integration workspace identity changed or unpinned session");
329
416
  return session;
330
417
  }
331
418
  /** 设备本地:准备集成(创建隔离 worktree,尝试预合并并提取 diff 或冲突) */
332
- export async function devicePrepareIntegration(params, options) {
333
- const { integrationId, targetBotId, targetBotRevision, repoRoot, dataDir, targetBranch, commit } = params;
419
+ async function prepareIntegration(params, options) {
420
+ const { integrationId, targetBotId, targetBotRevision, dataDir, targetBranch } = params;
421
+ const repoRoot = await canonicalPath(params.repoRoot);
422
+ const repository = await verifyRepoRoot(repoRoot, options?.signal);
423
+ if (repository.repoRoot !== repoRoot)
424
+ throw new Error("Integration Bot workspace must be the canonical repository root");
425
+ const repositoryId = await computeCanonicalRepositoryId(repoRoot, options?.signal);
426
+ const objectFormat = (await runPublicationGit(repoRoot, ["rev-parse", "--show-object-format"], { signal: options?.signal })).stdout.trim();
427
+ let commit = params.commit;
428
+ let retainedRef;
334
429
  const { headSha: expectedTargetSha, isDirty } = await inspectLocalTarget(repoRoot, dataDir, targetBranch, options);
335
430
  if (isDirty) {
336
431
  const statusRes = await runIsolatedGit(repoRoot, dataDir, ["status", "--porcelain"], GIT_TIMEOUT_MS, options).catch(() => ({ stdout: "" }));
337
432
  throw new Error(`Target repository has uncommitted changes (dirty state: ${statusRes.stdout.trim()}); cannot integrate`);
338
433
  }
434
+ if (params.artifactRef) {
435
+ const ref = params.artifactRef;
436
+ const checked = validateDeviceArtifact(params.artifact);
437
+ if (!checked.valid || !checked.artifact)
438
+ throw new Error("Invalid artifact payload");
439
+ const artifact = checked.artifact;
440
+ if (artifact.digest !== ref.artifactDigest ||
441
+ artifact.id !== ref.artifactId ||
442
+ artifact.producer.taskId !== ref.artifactTaskId ||
443
+ artifact.producer.attemptId !== ref.attemptId ||
444
+ artifact.producer.contractDigest !== ref.contractDigest ||
445
+ artifact.producer.manifestDigest !== ref.manifestDigest ||
446
+ artifact.baseline?.commit !== ref.baselineCommit ||
447
+ artifact.baseline.repositoryId !== ref.repositoryId ||
448
+ artifact.inputTree !== ref.inputTree ||
449
+ artifact.outputTree !== ref.outputTree)
450
+ throw new Error("Artifact subject mismatch");
451
+ if ((await computeCanonicalRepositoryId(repoRoot, options?.signal)) !== ref.repositoryId)
452
+ throw new Error("Canonical repository identity mismatch");
453
+ if (expectedTargetSha !== ref.baselineCommit)
454
+ throw new Error("Artifact target HEAD must equal baseline commit");
455
+ await verifyPatchProducesTree(repoRoot, ref.baselineCommit, Buffer.from(artifact.patchBase64 ?? "", "base64"), ref.outputTree, dataDir, options?.signal);
456
+ commit = (await git(repoRoot, [
457
+ "-c",
458
+ "user.name=Device Hub Integration",
459
+ "-c",
460
+ "user.email=integration@local",
461
+ "commit-tree",
462
+ ref.outputTree,
463
+ "-p",
464
+ ref.baselineCommit,
465
+ "-m",
466
+ `Materialize artifact ${ref.artifactDigest}`,
467
+ ], options?.signal)).trim();
468
+ retainedRef = `refs/pi/integrations/${safeId(integrationId)}/${randomUUID()}`;
469
+ await git(repoRoot, ["update-ref", retainedRef, commit], options?.signal);
470
+ }
471
+ if (!commit || !/^[a-f0-9]{40,64}$/i.test(commit))
472
+ throw new Error("Delivery commit required");
339
473
  const commitValid = await runIsolatedGit(repoRoot, dataDir, ["cat-file", "-e", `${commit}^{commit}`], GIT_TIMEOUT_MS, options)
340
474
  .then(() => true)
341
475
  .catch(() => false);
@@ -347,12 +481,12 @@ export async function devicePrepareIntegration(params, options) {
347
481
  if (!worktreePath.startsWith(worktreesRoot)) {
348
482
  throw new Error("Worktree path traversal attempt rejected");
349
483
  }
350
- if (existsSync(worktreePath)) {
351
- await safeRemoveWorktree(repoRoot, dataDir, worktreePath).catch(() => { });
352
- }
484
+ if (existsSync(worktreePath))
485
+ throw new Error("Integration worktree already exists; explicit cancellation required");
353
486
  // 检出 expectedTargetSha 的 detached 隔离工作树
354
487
  await runIsolatedGit(repoRoot, dataDir, ["worktree", "add", "--detach", worktreePath, expectedTargetSha], GIT_TIMEOUT_MS, options);
355
488
  await verifyGitAttributesSafe(worktreePath, dataDir);
489
+ const identity = await verifyWorktreeIdentity(worktreePath, repoRoot, options?.signal, undefined, repository.commonDir);
356
490
  const session = {
357
491
  integrationId,
358
492
  targetBotId,
@@ -364,6 +498,15 @@ export async function devicePrepareIntegration(params, options) {
364
498
  deliveryCommit: commit,
365
499
  preparedTreeSha: "",
366
500
  createdAt: Date.now(),
501
+ gitDir: identity.gitDir,
502
+ commonDir: identity.commonDir,
503
+ artifactRef: params.artifactRef,
504
+ retainedRef,
505
+ verificationStopConfirmed: true,
506
+ accountId: params.accountId,
507
+ roomId: params.roomId,
508
+ conversationId: params.conversationId,
509
+ targetDeviceId: params.targetDeviceId,
367
510
  };
368
511
  try {
369
512
  await runIsolatedGit(worktreePath, dataDir, ["merge", "--no-commit", "--no-ff", commit], GIT_TIMEOUT_MS, options);
@@ -371,16 +514,20 @@ export async function devicePrepareIntegration(params, options) {
371
514
  const statRes = await runIsolatedGit(worktreePath, dataDir, ["diff", "--stat", "HEAD"], GIT_TIMEOUT_MS, options);
372
515
  const treeRes = await runIsolatedGit(worktreePath, dataDir, ["write-tree"], GIT_TIMEOUT_MS, options);
373
516
  session.preparedTreeSha = treeRes.stdout.trim();
517
+ if (params.artifactRef && session.preparedTreeSha !== params.artifactRef.outputTree)
518
+ throw new Error("Prepared tree does not match artifact outputTree");
374
519
  // 保存到内存和持久化磁盘
375
- memorySessions.set(integrationId, session);
376
- const persisted = await loadPersistentSessions(dataDir);
377
- persisted.set(integrationId, session);
378
- await savePersistentSessions(dataDir, persisted);
520
+ memorySessions.set(sessionKey(params), session);
521
+ await persistSession(dataDir, integrationId, session);
379
522
  const fullDiff = `${statRes.stdout}\n\n${diffRes.stdout}`.trim();
380
523
  const diff = fullDiff.length > MAX_DIFF_BYTES ? `${fullDiff.slice(0, MAX_DIFF_BYTES)}\n... [diff truncated]` : fullDiff;
381
524
  return {
382
525
  status: "prepared",
383
526
  expectedTargetSha,
527
+ materializedCommit: commit,
528
+ preparedTree: session.preparedTreeSha,
529
+ repositoryId,
530
+ objectFormat,
384
531
  diff,
385
532
  };
386
533
  }
@@ -405,191 +552,314 @@ export async function devicePrepareIntegration(params, options) {
405
552
  await runIsolatedGit(worktreePath, dataDir, ["merge", "--abort"], GIT_TIMEOUT_MS, options).catch(() => { });
406
553
  return {
407
554
  status: "conflict",
555
+ repositoryId,
556
+ objectFormat,
408
557
  expectedTargetSha,
409
558
  conflicts: conflictFiles,
410
559
  diff,
411
560
  };
412
561
  }
413
562
  await safeRemoveWorktree(repoRoot, dataDir, worktreePath).catch(() => { });
414
- memorySessions.delete(integrationId);
563
+ memorySessions.delete(sessionKey(params));
415
564
  throw mergeError;
416
565
  }
417
566
  }
418
567
  /** 设备本地:在隔离 worktree 中执行显式选择的验证命令(全量透传 signal 并支持 cancel 中断) */
419
- export async function deviceVerifyIntegration(params, options) {
568
+ async function assertPreparedTree(session, dataDir, signal) {
569
+ const identity = await verifyWorktreeIdentity(session.worktreePath, session.repoRoot, signal, session.gitDir, session.commonDir);
570
+ if (identity.headCommit !== session.expectedTargetSha && identity.headCommit !== session.newCommitSha)
571
+ throw new Error("Integration worktree HEAD changed");
572
+ if (session.artifactRef) {
573
+ const tree = (await runIsolatedGit(session.repoRoot, dataDir, ["rev-parse", `${session.deliveryCommit}^{tree}`], GIT_TIMEOUT_MS, { signal })).stdout.trim();
574
+ const parent = (await runIsolatedGit(session.repoRoot, dataDir, ["rev-parse", `${session.deliveryCommit}^`], GIT_TIMEOUT_MS, {
575
+ signal,
576
+ })).stdout.trim();
577
+ const retained = session.retainedRef &&
578
+ (await runIsolatedGit(session.repoRoot, dataDir, ["rev-parse", session.retainedRef], GIT_TIMEOUT_MS, { signal })).stdout.trim();
579
+ if (tree !== session.artifactRef.outputTree ||
580
+ parent !== session.artifactRef.baselineCommit ||
581
+ retained !== session.deliveryCommit)
582
+ throw new Error("Materialized artifact commit or retained ref changed");
583
+ }
584
+ const flags = (await runIsolatedGit(session.worktreePath, dataDir, ["ls-files", "-v", "-z"], GIT_TIMEOUT_MS, { signal })).stdout;
585
+ if (flags.split("\0").some((entry) => /^[a-zS] /.test(entry)))
586
+ throw new Error("Integration index has hidden assume-unchanged or skip-worktree flags");
587
+ const rawTree = await snapshotTree(session.worktreePath, dataDir, signal, "integration-indexes", session.preparedTreeSha);
588
+ if (rawTree !== session.preparedTreeSha)
589
+ throw new Error("Integration prepared tree is dirty or changed (raw working tree byte mismatch)");
590
+ const unstaged = await runIsolatedGit(session.worktreePath, dataDir, ["diff", "--name-only"], GIT_TIMEOUT_MS, {
591
+ signal,
592
+ });
593
+ const untracked = await runIsolatedGit(session.worktreePath, dataDir, ["ls-files", "--others", "--exclude-standard"], GIT_TIMEOUT_MS, { signal });
594
+ const tree = (await runIsolatedGit(session.worktreePath, dataDir, ["write-tree"], GIT_TIMEOUT_MS, { signal })).stdout.trim();
595
+ if (unstaged.stdout.trim() || untracked.stdout.trim() || !session.preparedTreeSha || tree !== session.preparedTreeSha)
596
+ throw new Error("Integration prepared tree is dirty or changed");
597
+ await verifyWorktreeIdentity(session.worktreePath, session.repoRoot, signal, session.gitDir, session.commonDir);
598
+ return tree;
599
+ }
600
+ async function assertTarget(session, dataDir, signal) {
601
+ const repo = await verifyRepoRoot(session.repoRoot, signal);
602
+ if (repo.commonDir !== session.commonDir || repo.repoRoot !== session.repoRoot)
603
+ throw new Error("Integration target repository identity changed");
604
+ const target = await inspectLocalTarget(session.repoRoot, dataDir, session.branch, { signal });
605
+ if (target.headSha !== session.expectedTargetSha)
606
+ throw integrationError("INTEGRATION_TARGET_MOVED");
607
+ if (target.isDirty)
608
+ throw new Error("Integration target dirty or moved");
609
+ }
610
+ async function verifyIntegration(params, options) {
611
+ const plan = validateLocalVerificationPlan(params.verificationPlan);
420
612
  const session = await getVerifiedSession(params.dataDir, params);
421
- const opController = new AbortController();
422
- activeOperations.set(params.integrationId, opController);
423
- const effectiveSignal = options?.signal
424
- ? AbortSignal.any([options.signal, opController.signal])
425
- : opController.signal;
426
- const results = [];
427
- let hasFailure = false;
613
+ if (session.localVerification)
614
+ throw new Error("Successful verification is immutable; create another integration");
615
+ if (params.materializedCommit !== session.deliveryCommit ||
616
+ params.preparedTree !== session.preparedTreeSha ||
617
+ params.expectedTargetSha !== session.expectedTargetSha ||
618
+ canonicalizeJson(params.artifactRef ?? null) !== canonicalizeJson(session.artifactRef ?? null))
619
+ throw new Error("Verification subject mismatch");
620
+ await assertTarget(session, params.dataDir, options?.signal);
621
+ const treeBefore = await assertPreparedTree(session, params.dataDir, options?.signal);
428
622
  const env = await buildIsolatedEnv(params.dataDir);
623
+ const deadline = Date.now() + (options?.totalTimeoutMs ?? VERIFICATION_TOTAL_TIMEOUT_MS);
624
+ const results = [];
625
+ session.verificationInFlight = true;
626
+ session.verificationStopConfirmed = false;
627
+ await persistSession(params.dataDir, params.integrationId, session);
628
+ let stopConfirmed = true;
429
629
  try {
430
- for (const cmd of params.commands) {
431
- effectiveSignal.throwIfAborted();
432
- const item = {
433
- command: cmd,
434
- status: "running",
435
- };
436
- try {
437
- const { stdout, stderr } = await exec(cmd, {
438
- cwd: session.worktreePath,
439
- timeout: COMMAND_TIMEOUT_MS,
440
- shell: true,
441
- windowsHide: true,
442
- maxBuffer: 4 * 1024 * 1024,
443
- env,
444
- signal: effectiveSignal,
445
- });
446
- item.status = "passed";
447
- item.exitCode = 0;
448
- item.output = `${stdout ?? ""}\n${stderr ?? ""}`.trim().slice(0, 16 * 1024);
449
- }
450
- catch (error) {
451
- const err = error;
452
- if (err.name === "AbortError" || effectiveSignal.aborted) {
453
- throw new Error("Validation command execution was cancelled");
454
- }
455
- item.status = "failed";
456
- item.exitCode = typeof err.code === "number" ? err.code : 1;
457
- item.output = sanitizeError(`${err.stdout ?? ""}\n${err.stderr ?? ""}\n${err.message ?? ""}`).slice(0, 16 * 1024);
458
- hasFailure = true;
459
- }
460
- results.push(item);
461
- if (hasFailure)
462
- break;
630
+ for (const command of plan.commands) {
631
+ options?.signal?.throwIfAborted();
632
+ const remaining = deadline - Date.now();
633
+ if (remaining <= 0)
634
+ throw new Error("Verification aggregate deadline exceeded");
635
+ results.push(await runVerificationCommand(command, {
636
+ cwd: session.worktreePath,
637
+ env,
638
+ signal: options?.signal,
639
+ timeoutMs: Math.min(options?.commandTimeoutMs ?? VERIFICATION_COMMAND_TIMEOUT_MS, remaining),
640
+ }));
463
641
  }
464
- return {
465
- status: hasFailure ? "failed" : "verified",
466
- validationCommands: results,
642
+ const treeAfter = await assertPreparedTree(session, params.dataDir, options?.signal);
643
+ await assertTarget(session, params.dataDir, options?.signal);
644
+ const facts = {
645
+ planDigest: plan.digest,
646
+ artifactDigest: session.artifactRef?.artifactDigest,
647
+ materializedCommit: session.deliveryCommit,
648
+ treeBefore,
649
+ treeAfter,
650
+ results,
467
651
  };
652
+ const status = results.every((result) => result.status === "passed" && result.exitCode === 0)
653
+ ? "verified"
654
+ : "failed";
655
+ if (status === "verified") {
656
+ session.localVerification = structuredClone(facts);
657
+ session.verifiedPlan = plan;
658
+ }
659
+ return { status, ...facts };
660
+ }
661
+ catch (error) {
662
+ if (error instanceof VerificationStopUnconfirmedError) {
663
+ stopConfirmed = false;
664
+ session.stopUnconfirmed = true;
665
+ }
666
+ throw error;
468
667
  }
469
668
  finally {
470
- activeOperations.delete(params.integrationId);
471
- }
472
- }
473
- /**
474
- * 设备本地:用户确认写入目标分支
475
- * 1. 严格排他锁:不能在当前有在途验证命令执行时并发 apply
476
- * 2. 多租户会话与 Bot 身份、Revision 强校验
477
- * 3. 检查未被验证命令污染或篡改(diff / untracked / write-tree 三重验证)
478
- * 4. 验证生成的 merge commit 父链(HEAD^1 === expectedTargetSha 且 HEAD^2 === deliveryCommit)
479
- * 5. 前置紧邻二次检查目标仓库 dirty 状态与目标分支 HEAD SHA
480
- * 6. 执行原子 CAS update-ref 写入目标分支
481
- * 7. 若目标分支为 checked-out 分支,使用安全无覆盖 read-tree -u -m 同步当前工作区(绝不 hard reset!)
482
- */
483
- export async function deviceConfirmIntegration(params, options) {
484
- if (activeOperations.has(params.integrationId)) {
485
- throw new Error("Integration is currently executing validation commands; cannot apply");
669
+ if (stopConfirmed) {
670
+ delete session.verificationInFlight;
671
+ session.verificationStopConfirmed = true;
672
+ }
673
+ await persistSession(params.dataDir, params.integrationId, session).catch((error) => {
674
+ if (stopConfirmed)
675
+ throw error;
676
+ });
486
677
  }
678
+ }
679
+ async function confirmIntegration(params, options) {
487
680
  const session = await getVerifiedSession(params.dataDir, params);
488
- // 1. 幂等性防护:若本地已记录 CAS applied 成功(如重试或重启确认),直接幂等返回已生效的新提交 SHA
489
- if (session.applied && session.newCommitSha) {
490
- return {
491
- status: "applied",
492
- newCommitSha: session.newCommitSha,
493
- };
494
- }
495
- // 2. 前置安全校验:在任何 commit 操作前完成所有检查,确保 409 拒绝后重试保持干净幂等
496
- // 2.1 检查目标分支在任何工作树中未被检出(前置拦截,防止 commit 后才报错导致切离重试无改动)
497
- const wtList = await runIsolatedGit(session.repoRoot, params.dataDir, ["worktree", "list", "--porcelain"], GIT_TIMEOUT_MS, options);
498
- const targetBranchRef = `refs/heads/${session.branch}`;
499
- for (const line of wtList.stdout.split("\n")) {
500
- if (line.trim() === `branch ${targetBranchRef}`) {
681
+ if (session.stopUnconfirmed)
682
+ throw new VerificationStopUnconfirmedError();
683
+ const facts = session.localVerification;
684
+ const plan = validateLocalVerificationPlan(session.verifiedPlan);
685
+ if (!facts ||
686
+ facts.planDigest !== plan.digest ||
687
+ facts.materializedCommit !== session.deliveryCommit ||
688
+ facts.artifactDigest !== session.artifactRef?.artifactDigest ||
689
+ facts.treeBefore !== session.preparedTreeSha ||
690
+ facts.treeAfter !== session.preparedTreeSha ||
691
+ facts.results.length !== plan.commands.length ||
692
+ !facts.results.every((result, index) => result.command === plan.commands[index] &&
693
+ result.status === "passed" &&
694
+ result.exitCode === 0 &&
695
+ /^[a-f0-9]{64}$/.test(result.outputDigest) &&
696
+ typeof result.outputPreview === "string"))
697
+ throw new Error("Successful local verification receipt required");
698
+ const intent = validatePublishIntent(params.publishIntent);
699
+ if (session.accountId &&
700
+ (session.accountId !== intent.accountId ||
701
+ session.roomId !== intent.roomId ||
702
+ session.conversationId !== intent.conversationId ||
703
+ session.targetDeviceId !== intent.targetDeviceId))
704
+ throw new Error("Publication original session scope mismatch");
705
+ assertPublishIntentScope(intent, {
706
+ accountId: intent.accountId,
707
+ integrationId: params.integrationId,
708
+ targetBotId: params.targetBotId,
709
+ targetBotRevision: params.targetBotRevision,
710
+ });
711
+ const deliveryCommit = params.materializedCommit ?? params.commit;
712
+ if (deliveryCommit !== session.deliveryCommit || intent.materializedCommit !== session.deliveryCommit)
713
+ throw new Error("Confirmation materialized commit mismatch");
714
+ if (intent.delivery.id !== params.deliveryId ||
715
+ intent.expectedOld !== params.expectedTargetSha ||
716
+ intent.expectedOld !== session.expectedTargetSha ||
717
+ intent.preparedTree !== session.preparedTreeSha ||
718
+ intent.targetRef !== "refs/heads/" + session.branch)
719
+ throw new Error("Publication intent does not match prepared integration");
720
+ const { digest: _digest, verifiedAt: _verifiedAt, ...intentFacts } = intent.verification;
721
+ if (canonicalizeJson(intentFacts) !== canonicalizeJson(facts) ||
722
+ canonicalizeJson(intent.verificationPlan) !== canonicalizeJson(plan) ||
723
+ canonicalizeJson(intent.delivery.artifactRef ?? null) !== canonicalizeJson(session.artifactRef ?? null))
724
+ throw new Error("Publication intent local verification mismatch");
725
+ const verifiedRepo = await verifyRepoRoot(session.repoRoot, options?.signal);
726
+ const repositoryId = await computeCanonicalRepositoryId(session.repoRoot, options?.signal);
727
+ const format = (await runPublicationGit(session.repoRoot, ["rev-parse", "--show-object-format"], { signal: options?.signal })).stdout.trim();
728
+ if (repositoryId !== intent.repositoryId || format !== intent.objectFormat)
729
+ throw new Error("Publication intent repository identity mismatch");
730
+ const verify = async (signal) => {
731
+ await assertPreparedTree(session, params.dataDir, signal);
732
+ const worktrees = await runIsolatedGit(session.repoRoot, params.dataDir, ["worktree", "list", "--porcelain"], GIT_TIMEOUT_MS, { signal });
733
+ const checkedOut = worktrees.stdout
734
+ .split("\n")
735
+ .some((line) => line.startsWith("branch ") && line.slice(7).trim() === intent.targetRef);
736
+ if (checkedOut)
501
737
  throw integrationError("INTEGRATION_TARGET_CHECKED_OUT");
738
+ await assertTarget(session, params.dataDir, signal);
739
+ };
740
+ const result = await publishLocalIntent({
741
+ dataDir: params.dataDir,
742
+ publishIntent: intent,
743
+ mode: params.mode ?? "first",
744
+ repository: { ...verifiedRepo, repositoryId, objectFormat: intent.objectFormat },
745
+ verify,
746
+ }, options);
747
+ if (result.publishReceipt) {
748
+ session.newCommitSha = intent.candidateSha;
749
+ session.applied = true;
750
+ try {
751
+ await persistSession(params.dataDir, params.integrationId, session);
752
+ await cancelIntegration(params, { stopConfirmed: true });
502
753
  }
754
+ catch {
755
+ return { ...result, newCommitSha: intent.candidateSha, cleanupPending: true };
756
+ }
757
+ return { ...result, newCommitSha: intent.candidateSha };
503
758
  }
504
- // 2.2 紧邻当下二次检查目标仓库 dirty 状态与目标分支 HEAD SHA
505
- const { headSha: currentHeadSha, isDirty } = await inspectLocalTarget(session.repoRoot, params.dataDir, session.branch, options);
506
- if (isDirty) {
507
- throw new Error("Target repository has uncommitted changes (dirty state); cannot apply integration");
508
- }
509
- if (currentHeadSha !== params.expectedTargetSha || currentHeadSha !== session.expectedTargetSha) {
510
- throw integrationError("INTEGRATION_TARGET_MOVED");
511
- }
512
- // 2.3 验证命令完整性校验:验证命令绝不能篡改代码或修改工作树内容
513
- const unstaged = await runIsolatedGit(session.worktreePath, params.dataDir, ["diff", "--name-only"], GIT_TIMEOUT_MS, options);
514
- if (unstaged.stdout.trim().length > 0) {
515
- throw new Error("Worktree content modified by validation commands; integration rejected for security");
516
- }
517
- const untracked = await runIsolatedGit(session.worktreePath, params.dataDir, ["ls-files", "--others", "--exclude-standard"], GIT_TIMEOUT_MS, options);
518
- if (untracked.stdout.trim().length > 0) {
519
- throw new Error("Untracked files created by validation commands; integration rejected for security");
520
- }
521
- const treeRes = await runIsolatedGit(session.worktreePath, params.dataDir, ["write-tree"], GIT_TIMEOUT_MS, options);
522
- const currentTreeSha = treeRes.stdout.trim();
523
- if (session.preparedTreeSha && currentTreeSha !== session.preparedTreeSha) {
524
- throw new Error("Worktree content tree SHA mismatch; validation commands altered repository contents, integration rejected for security");
759
+ return result;
760
+ }
761
+ async function cancelIntegration(params, options) {
762
+ const stored = (await loadPersistentSessions(params.dataDir)).get(params.integrationId);
763
+ if (stored &&
764
+ (stored.targetBotId !== params.targetBotId ||
765
+ stored.targetBotRevision !== params.targetBotRevision ||
766
+ resolve(stored.repoRoot) !== resolve(params.repoRoot)))
767
+ throw new Error("Integration cancellation identity mismatch");
768
+ if ((stored ||
769
+ params.verificationMayBeRunning ||
770
+ ["verifying", "verified", "failed"].includes(params.priorStatus ?? "")) &&
771
+ (params.verificationMayBeRunning || params.priorStatus !== "prepared") &&
772
+ !options?.stopConfirmed &&
773
+ stored?.verificationStopConfirmed !== true &&
774
+ !stored?.localVerification) {
775
+ if (stored) {
776
+ stored.stopUnconfirmed = true;
777
+ await persistSession(params.dataDir, params.integrationId, stored).catch(() => { });
778
+ }
779
+ throw new VerificationStopUnconfirmedError();
525
780
  }
526
- // 3. 幂等生成或复用 merge commit
527
- let newCommitSha = session.newCommitSha;
528
- if (!newCommitSha) {
529
- await runIsolatedGit(session.worktreePath, params.dataDir, [
530
- "-c",
531
- "user.name=Device Hub Integration",
532
- "-c",
533
- "user.email=integration@local",
534
- "commit",
535
- "-m",
536
- `Merge delivery ${params.deliveryId.slice(0, 8)} (${params.commit.slice(0, 8)}) into ${session.branch}`,
537
- ], GIT_TIMEOUT_MS, options);
538
- const rev = await runIsolatedGit(session.worktreePath, params.dataDir, ["rev-parse", "HEAD"], GIT_TIMEOUT_MS, options);
539
- newCommitSha = rev.stdout.trim();
540
- if (!/^[a-f0-9]{40,64}$/i.test(newCommitSha)) {
541
- throw new Error("Failed to resolve integrated commit SHA");
781
+ const session = await getVerifiedSession(params.dataDir, params, params.priorStatus === "prepared" || stored?.verificationStopConfirmed === true || !!stored?.localVerification).catch((error) => {
782
+ if (String(error).includes("not found"))
783
+ return undefined;
784
+ throw error;
785
+ });
786
+ if (!session) {
787
+ const path = resolve(await getVerifiedWorktreesRoot(params.dataDir), `int-${safeId(params.integrationId)}`);
788
+ if (existsSync(path))
789
+ throw new VerificationStopUnconfirmedError();
790
+ if (stored) {
791
+ if (stored.retainedRef) {
792
+ const repo = await verifyRepoRoot(stored.repoRoot);
793
+ if (repo.commonDir !== stored.commonDir)
794
+ throw new Error("Original integration repository identity changed");
795
+ await git(stored.repoRoot, ["update-ref", "-d", stored.retainedRef, stored.deliveryCommit]);
796
+ }
797
+ await persistSession(params.dataDir, params.integrationId);
798
+ memorySessions.delete(sessionKey(params));
542
799
  }
543
- // 严格核验父提交链拓扑:HEAD^1 必须等于 expectedTargetSha,HEAD^2 必须等于 deliveryCommit
544
- const p1 = (await runIsolatedGit(session.worktreePath, params.dataDir, ["rev-parse", "HEAD^1"], GIT_TIMEOUT_MS, options)).stdout.trim();
545
- const p2 = (await runIsolatedGit(session.worktreePath, params.dataDir, ["rev-parse", "HEAD^2"], GIT_TIMEOUT_MS, options)).stdout.trim();
546
- if (p1 !== session.expectedTargetSha || p2 !== params.commit) {
547
- throw new Error("Integrated commit parent chain mismatch; foreign commits or altered ancestry detected");
800
+ return { status: "cancelled" };
801
+ }
802
+ await assertPreparedTree(session, params.dataDir);
803
+ await safeRemoveWorktree(session.repoRoot, params.dataDir, session.worktreePath);
804
+ if (session.retainedRef)
805
+ await git(session.repoRoot, ["update-ref", "-d", session.retainedRef, session.deliveryCommit]);
806
+ memorySessions.delete(sessionKey(params));
807
+ await persistSession(params.dataDir, params.integrationId);
808
+ return { status: "cancelled" };
809
+ }
810
+ export function devicePrepareIntegration(params, options) {
811
+ params = structuredClone(params);
812
+ return localOperation(params, options?.signal, (signal) => prepareIntegration(params, { signal }));
813
+ }
814
+ export function deviceVerifyIntegration(params, options) {
815
+ params = structuredClone(params);
816
+ return localOperation(params, options?.signal, (signal) => verifyIntegration(params, { ...options, signal }));
817
+ }
818
+ export function deviceConfirmIntegration(params, options) {
819
+ params = structuredClone(params);
820
+ return (async () => {
821
+ if (params.publishIntent) {
822
+ const journal = await readPublicationJournal(params.dataDir, params.publishIntent);
823
+ if (journal?.receipt || journal?.stop || journal?.phase === "cas_started") {
824
+ const result = await localPublicationStatus({ dataDir: params.dataDir, publishIntent: params.publishIntent });
825
+ return { ...result, ...(result.publishReceipt ? { newCommitSha: result.publishReceipt.candidateSha } : {}) };
826
+ }
548
827
  }
549
- session.newCommitSha = newCommitSha;
550
- const persisted = await loadPersistentSessions(params.dataDir);
551
- persisted.set(params.integrationId, session);
552
- await savePersistentSessions(params.dataDir, persisted);
553
- }
554
- // 4. 执行原子 CAS update-ref 写入目标分支
555
- await runIsolatedGit(session.repoRoot, params.dataDir, ["update-ref", `refs/heads/${session.branch}`, newCommitSha, params.expectedTargetSha], GIT_TIMEOUT_MS, options);
556
- // 5. CAS 成功:立即落盘 applied receipt,保证掉电或崩溃不可重做
557
- session.applied = true;
558
- const persisted = await loadPersistentSessions(params.dataDir);
559
- persisted.set(params.integrationId, session);
560
- await savePersistentSessions(params.dataDir, persisted);
561
- // 6. 工作树安全清理
562
- let cleanupPending = false;
563
- try {
564
- await safeRemoveWorktree(session.repoRoot, params.dataDir, session.worktreePath);
565
- memorySessions.delete(params.integrationId);
566
- persisted.delete(params.integrationId);
567
- await savePersistentSessions(params.dataDir, persisted);
568
- }
569
- catch (cleanupErr) {
570
- cleanupPending = true;
571
- console.warn(`[IntegrationCleanup] Worktree cleanup deferred: ${sanitizeError(cleanupErr)}`);
572
- }
573
- return {
574
- status: "applied",
575
- newCommitSha,
576
- ...(cleanupPending ? { cleanupPending: true } : {}),
577
- };
828
+ return localOperation(params, options?.signal, (signal) => confirmIntegration(params, { signal }));
829
+ })();
578
830
  }
579
- /** 设备本地:取消集成并清理隔离工作树(中断在途命令并核验租约归属) */
580
- export async function deviceCancelIntegration(params, _options) {
581
- const activeOp = activeOperations.get(params.integrationId);
582
- if (activeOp) {
583
- activeOp.abort();
584
- activeOperations.delete(params.integrationId);
585
- }
586
- const session = await getVerifiedSession(params.dataDir, params).catch(() => undefined);
587
- if (session) {
588
- await safeRemoveWorktree(session.repoRoot, params.dataDir, session.worktreePath);
589
- memorySessions.delete(params.integrationId);
590
- const persisted = await loadPersistentSessions(params.dataDir);
591
- persisted.delete(params.integrationId);
592
- await savePersistentSessions(params.dataDir, persisted);
831
+ export function devicePublicationStatus(params) {
832
+ return localPublicationStatus(params);
833
+ }
834
+ export function deviceCancelPublication(params) {
835
+ const intent = validatePublishIntent(params.publishIntent);
836
+ const operation = activeOperations.get(sessionKey({ dataDir: params.dataDir, integrationId: intent.integrationId }));
837
+ // Install the publication fence synchronously even if confirmation has not reached its gate yet.
838
+ const cancellation = cancelLocalPublication(params);
839
+ operation?.controller.abort(new Error("Publication cancelled"));
840
+ return (async () => {
841
+ await operation?.done.catch(() => { });
842
+ const result = await cancellation;
843
+ if (operation?.blocked)
844
+ return { ...result, cleanupPending: true };
845
+ const session = memorySessions.get(sessionKey({ dataDir: params.dataDir, integrationId: intent.integrationId })) ??
846
+ (await loadPersistentSessions(params.dataDir)).get(intent.integrationId);
847
+ return { ...result, ...(session ? { cleanupPending: true } : {}) };
848
+ })();
849
+ }
850
+ export async function deviceCancelIntegration(params, options) {
851
+ params = structuredClone(params);
852
+ const operation = activeOperations.get(sessionKey(params));
853
+ if (operation) {
854
+ if (!sameIdentity(operation.identity, params))
855
+ throw new Error("Integration cancellation identity mismatch");
856
+ operation.controller.abort(new Error("Integration cancelled"));
857
+ await operation.done.catch((error) => {
858
+ if (operation.blocked)
859
+ throw error;
860
+ });
861
+ if (operation.blocked)
862
+ throw operation.blocked;
593
863
  }
594
- return { status: "cancelled" };
864
+ return localOperation(params, options?.signal, () => cancelIntegration(params, { ...options, stopConfirmed: !!operation }));
595
865
  }