pi-web-ui 0.115.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 (161) hide show
  1. package/CHANGELOG.md +65 -2
  2. package/bin/device-hub-cli.mjs +26 -3
  3. package/bin/pi-web-ui.mjs +159 -71
  4. package/dist/server/agent-service-daemon.js +136 -8
  5. package/dist/server/agent-service.js +594 -159
  6. package/dist/server/canvas/canvas-workspace.js +18 -86
  7. package/dist/server/client-state.js +52 -8
  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 +77 -2
  11. package/dist/server/device-center/collab-service.js +61 -12
  12. package/dist/server/device-center/collab-tool.js +482 -21
  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 +17 -7
  18. package/dist/server/device-center/execution-instructions.js +2 -1
  19. package/dist/server/device-center/execution-settings.js +138 -25
  20. package/dist/server/device-center/executor.js +51 -6
  21. package/dist/server/device-center/file-sync.js +14 -13
  22. package/dist/server/device-center/group-context-message.js +3 -1
  23. package/dist/server/device-center/group-context.js +73 -3
  24. package/dist/server/device-center/hub-conversations.js +71 -6
  25. package/dist/server/device-center/hub-deliveries.js +120 -15
  26. package/dist/server/device-center/hub-integration.js +655 -334
  27. package/dist/server/device-center/hub-locks.js +320 -0
  28. package/dist/server/device-center/hub-page.js +16 -35
  29. package/dist/server/device-center/hub-setup.js +23 -1
  30. package/dist/server/device-center/hub-transaction-log.js +197 -0
  31. package/dist/server/device-center/hub-webhooks.js +165 -0
  32. package/dist/server/device-center/hub.js +1531 -305
  33. package/dist/server/device-center/integration-verification.js +113 -0
  34. package/dist/server/device-center/local-hub.js +8 -3
  35. package/dist/server/device-center/local-publication.js +423 -0
  36. package/dist/server/device-center/local-verification-job.js +97 -0
  37. package/dist/server/device-center/local-verification.js +274 -0
  38. package/dist/server/device-center/local.js +181 -13
  39. package/dist/server/device-center/main.js +4 -1
  40. package/dist/server/device-center/partition-log.js +330 -0
  41. package/dist/server/device-center/publication-journal.js +312 -0
  42. package/dist/server/device-center/publish-intent.js +379 -0
  43. package/dist/server/device-center/relay.js +134 -24
  44. package/dist/server/device-center/runtime.js +475 -42
  45. package/dist/server/device-center/store.js +366 -89
  46. package/dist/server/device-center/task-outcome.js +81 -0
  47. package/dist/server/device-center/task-recovery.js +603 -178
  48. package/dist/server/device-center/task-scheduler.js +48 -3
  49. package/dist/server/device-center/task-settlement.js +353 -0
  50. package/dist/server/device-center/task-workspace.js +443 -0
  51. package/dist/server/device-center/transfers.js +41 -15
  52. package/dist/server/device-center/verification-limits.js +10 -0
  53. package/dist/server/device-center/work-contract.js +995 -0
  54. package/dist/server/dispatch-domain-handlers.js +29 -3
  55. package/dist/server/dsh/dsh-agent-service.js +9 -2
  56. package/dist/server/engine-probe.js +112 -1
  57. package/dist/server/global-loader.js +119 -19
  58. package/dist/server/index.js +159 -17
  59. package/dist/server/managed.js +2 -0
  60. package/dist/server/model-admin.js +48 -6
  61. package/dist/server/model-enrich.js +10 -1
  62. package/dist/server/patch-node-pty.js +3 -2
  63. package/dist/server/patch-remote-catalog.js +3 -2
  64. package/dist/server/plugins.js +64 -7
  65. package/dist/server/preset-fields.js +17 -1
  66. package/dist/server/preset-share.js +1 -0
  67. package/dist/server/prompt-composer.js +39 -0
  68. package/dist/server/protocol-version.js +1 -1
  69. package/dist/server/quick-ask-settings.js +28 -0
  70. package/dist/server/quick-ask.js +164 -0
  71. package/dist/server/reasoning-registry.js +207 -0
  72. package/dist/server/resolve-global-sdk.js +61 -11
  73. package/dist/server/scheduler-tasks.js +35 -8
  74. package/dist/server/session-list-scan.js +223 -0
  75. package/dist/server/session-open.js +93 -0
  76. package/dist/server/session-parser.js +4 -0
  77. package/dist/server/session-scan.js +90 -38
  78. package/dist/server/settings-service.js +9 -1
  79. package/dist/server/soft-cap.js +5 -0
  80. package/dist/server/startup-banner.js +35 -0
  81. package/dist/server/subagents.js +2 -1
  82. package/dist/server/tool-manager.js +17 -9
  83. package/dist/server/transcript-prepare.js +73 -0
  84. package/dist/server/unauthorized-page.js +319 -0
  85. package/dist/server/universal/drivers/claude-code.js +98 -34
  86. package/dist/server/universal/universal-session.js +4 -0
  87. package/dist/server/workspace-handle.js +428 -0
  88. package/docs/architecture-plugins.md +959 -0
  89. package/docs/device-center.md +34 -20
  90. package/package.json +4 -4
  91. package/plugin-sdk/README.md +16 -8
  92. package/plugin-sdk/client.d.ts +27 -0
  93. package/plugin-sdk/client.mjs +82 -0
  94. package/plugin-sdk/index.d.ts +10 -0
  95. package/plugin-sdk/index.mjs +4 -683
  96. package/plugin-sdk/package.json +15 -4
  97. package/plugin-sdk/testing.d.ts +10 -0
  98. package/plugin-sdk/testing.mjs +566 -0
  99. package/themes/flow-cristallo.css +168 -0
  100. package/themes/flow-ink.css +169 -0
  101. package/themes/flow-obsidian.css +169 -0
  102. package/themes/flow-zurich.css +169 -0
  103. package/web/dist/.build-assets.json +1 -1
  104. package/web/dist/assets/{BgTasksModal-BYzPgmoq.js → BgTasksModal-BjNRIUIc.js} +1 -1
  105. package/web/dist/assets/{BgTasksModal-ni0VTmAQ.js → BgTasksModal-C0zuU8FE.js} +1 -1
  106. package/web/dist/assets/{CanvasStudio-DNmDNBod.js → CanvasStudio-BWvdmJ0M.js} +3 -3
  107. package/web/dist/assets/{CanvasStudio-BCUeEf25.js → CanvasStudio-VQFjmTGq.js} +3 -3
  108. package/web/dist/assets/DeviceCenter-DI9_0aBB.js +3 -0
  109. package/web/dist/assets/DeviceCenter-DsNtXqzY.js +3 -0
  110. package/web/dist/assets/DeviceExecutionSettings-BLP1Su5G.js +1 -0
  111. package/web/dist/assets/DeviceGroups-2Pvk0Cds.js +1 -0
  112. package/web/dist/assets/DeviceGroups-CP7CcyPD.js +1 -0
  113. package/web/dist/assets/{Dropdown-CGXD0DfT.js → Dropdown-CQtstPGv.js} +1 -1
  114. package/web/dist/assets/FilePreview-BMB2tNyT.js +2 -0
  115. package/web/dist/assets/FilePreview-RGFQUbJo.js +2 -0
  116. package/web/dist/assets/{GlobalSearchModal-mevF-ySi.js → GlobalSearchModal-BM5wxiqU.js} +1 -1
  117. package/web/dist/assets/{GlobalSearchModal-qL99FN_F.js → GlobalSearchModal-DGv_WINq.js} +1 -1
  118. package/web/dist/assets/GroupConversation-B7SnuXj1.js +61 -0
  119. package/web/dist/assets/GroupConversation-Dda69q-2.js +61 -0
  120. package/web/dist/assets/{HintTip-LHwkS2jV.js → HintTip-ChTW8o1m.js} +1 -1
  121. package/web/dist/assets/ModelConfigModal-C-0Z4hUZ.js +2 -0
  122. package/web/dist/assets/ModelConfigModal-yqeadyab.js +2 -0
  123. package/web/dist/assets/{PiSetupModal-DE5-gEtI.js → PiSetupModal-BX5rUuoI.js} +1 -1
  124. package/web/dist/assets/{ProviderOAuthControls-6UMARucA.js → ProviderOAuthControls-DY4SCfXg.js} +1 -1
  125. package/web/dist/assets/SCMPanel-C4KbQvvK.js +2 -0
  126. package/web/dist/assets/SCMPanel-DPAyY2sW.js +2 -0
  127. package/web/dist/assets/SettingsModal-DxZp6D_g.js +32 -0
  128. package/web/dist/assets/SettingsModal-WhQzaOPt.js +32 -0
  129. package/web/dist/assets/{TerminalPanel-CTp_BZ4S.js → TerminalPanel-D4By_RVc.js} +2 -2
  130. package/web/dist/assets/{TerminalPanel-CkYxC-Gh.js → TerminalPanel-lZw8-i3j.js} +2 -2
  131. package/web/dist/assets/{TuiOverlayModal-1cRLP8IF.js → TuiOverlayModal-C3pAVuC8.js} +1 -1
  132. package/web/dist/assets/{TuiOverlayModal-2xlptqWX.js → TuiOverlayModal-D7_rEXcJ.js} +1 -1
  133. package/web/dist/assets/app-globals-KqOVtmp1.js +123 -0
  134. package/web/dist/assets/{canvas-client-Bye9nSFO.js → canvas-client-BY6ojmle.js} +1 -1
  135. package/web/dist/assets/{desktop-kjBoE3Nu.js → desktop-CV6KKp9R.js} +1 -1
  136. package/web/dist/assets/index-BawF7ZP5.js +397 -0
  137. package/web/dist/assets/index-BoGCoq5X.js +397 -0
  138. package/web/dist/assets/index-CVW9FoY2.css +1 -0
  139. package/web/dist/assets/{plugin-host-C8mNgghx.js → plugin-host-Dn8Dd6SC.js} +1 -1
  140. package/web/dist/assets/{remote-ssh-client-CeP3CLUW.js → remote-ssh-client-Dzi-eEyE.js} +1 -1
  141. package/web/dist/assets/{theme-BXGpyTMh.js → theme-D_bihpdN.js} +1 -1
  142. package/web/dist/index.html +11 -11
  143. package/web/dist/sw.js +1 -1
  144. package/dist/server/patch-turn-end-boundary.js +0 -77
  145. package/web/dist/assets/DeviceCenter-BcBhRgL6.js +0 -3
  146. package/web/dist/assets/DeviceCenter-CmL5FZmt.js +0 -3
  147. package/web/dist/assets/DeviceGroups-CLdpdnI7.js +0 -1
  148. package/web/dist/assets/DeviceGroups-CgBaDPrD.js +0 -1
  149. package/web/dist/assets/FilePreview-B8iqnBjy.js +0 -2
  150. package/web/dist/assets/FilePreview-BqviZKCN.js +0 -2
  151. package/web/dist/assets/GroupConversation-B88Yy-lt.js +0 -3
  152. package/web/dist/assets/GroupConversation-BwP5NVOE.js +0 -3
  153. package/web/dist/assets/ModelConfigModal-Do3Fe3jH.js +0 -2
  154. package/web/dist/assets/SCMPanel-Hi6QqC1Q.js +0 -2
  155. package/web/dist/assets/SCMPanel-ezY_ZtCu.js +0 -2
  156. package/web/dist/assets/SettingsModal-6HgeEsJ8.js +0 -20
  157. package/web/dist/assets/SettingsModal-CF-7MwqS.js +0 -20
  158. package/web/dist/assets/app-globals-DZNa9v8u.js +0 -325
  159. package/web/dist/assets/index-CsFs_HMb.css +0 -1
  160. package/web/dist/assets/index-DHeeHS_l.js +0 -85
  161. package/web/dist/assets/index-DTZch8uz.js +0 -85
@@ -1,16 +1,14 @@
1
- import { createHash } from "node:crypto";
2
- import { readFileSync } from "node:fs";
1
+ import { readFileSync, unlinkSync } from "node:fs";
3
2
  import { join } from "node:path";
4
3
  import { writeAtomicSync } from "../atomic-file.js";
5
- import { deviceTaskFailure } from "./task-error.js";
6
- import { boundTaskReport } from "./task-report.js";
7
4
  import { parseReportMetadata } from "./report-metadata.js";
8
- export function computeOutcomeFingerprint(taskId, attemptId, status, report, error, reportMetadata) {
9
- return createHash("sha256")
10
- .update(`${taskId}:${attemptId}:${status}:${report ?? ""}:${error ?? ""}${reportMetadata ? JSON.stringify(reportMetadata) : ""}`)
11
- .digest("hex")
12
- .slice(0, 16);
13
- }
5
+ import { TASK_REPORT_BYTES } from "./task-report.js";
6
+ import { computeOutcomeFingerprint, computeLegacyOutcomeFingerprint, normalizeTaskOutcome, TASK_OUTCOME_ERROR_BYTES, } from "./task-outcome.js";
7
+ import { validateDeviceArtifact } from "./work-contract.js";
8
+ export { computeOutcomeFingerprint, normalizeTaskOutcome };
9
+ export const TASK_QUARANTINE_LIMITS = { maxEntries: 128, maxTotalBytes: 2 * 1024 * 1024 };
10
+ /** Includes both outcome budgets, active leases and serialization overhead. */
11
+ export const TASK_RECOVERY_STATE_MAX_BYTES = 8 * 1024 * 1024;
14
12
  export const TASK_RECOVERY_DEFAULTS = {
15
13
  maxInactivityMs: 20 * 60 * 1000, // 20 minutes without activity (human waits pause this)
16
14
  maxDurationMs: 0, // 0 = unbounded overall duration by default (honors long-running jobs)
@@ -21,152 +19,361 @@ export const TASK_OUTBOX_LIMITS = {
21
19
  maxEntries: 128,
22
20
  maxTotalBytes: 2 * 1024 * 1024, // 2 MiB bounded durable storage budget
23
21
  };
22
+ // Reserve worst-case JSON escaping, artifact patchBase64, plus bounded identity and metadata overhead before execution.
23
+ export const TASK_ARTIFACT_WORST_CASE_BYTES = 256 * 1024;
24
+ export const TASK_OUTBOX_RESERVATION_BYTES = 6 * (TASK_REPORT_BYTES + TASK_OUTCOME_ERROR_BYTES) + 16 * 1024 + TASK_ARTIFACT_WORST_CASE_BYTES;
25
+ function validateOutboxItem(item, deviceId) {
26
+ if (!item ||
27
+ typeof item !== "object" ||
28
+ typeof item.id !== "string" ||
29
+ !item.id ||
30
+ item.id.length > 257 ||
31
+ typeof item.taskId !== "string" ||
32
+ !item.taskId ||
33
+ item.taskId.length > 128 ||
34
+ typeof item.attemptId !== "string" ||
35
+ !item.attemptId ||
36
+ item.attemptId.length > 128 ||
37
+ typeof item.botId !== "string" ||
38
+ !item.botId ||
39
+ item.botId.length > 128 ||
40
+ item.deviceId !== deviceId ||
41
+ !["completed", "failed", "interrupted"].includes(item.status) ||
42
+ !Number.isSafeInteger(item.createdAt) ||
43
+ item.createdAt <= 0 ||
44
+ !Number.isSafeInteger(item.updatedAt) ||
45
+ !Number.isSafeInteger(item.attempts)) {
46
+ throw new Error("Invalid outbox item schema");
47
+ }
48
+ const entry = item;
49
+ if (entry.id !== `${entry.taskId}:${entry.attemptId}` ||
50
+ (entry.report !== undefined && typeof entry.report !== "string") ||
51
+ (entry.error !== undefined && typeof entry.error !== "string"))
52
+ throw new Error("Invalid outbox identity or content");
53
+ if (entry.reportMetadata !== undefined) {
54
+ entry.reportMetadata = parseReportMetadata(entry.reportMetadata);
55
+ }
56
+ if (entry.artifact !== undefined) {
57
+ const res = validateDeviceArtifact(entry.artifact);
58
+ if (!res.valid)
59
+ throw new Error(`Invalid outbox artifact: ${res.reason}`);
60
+ }
61
+ if (entry.leaseToken !== undefined && (typeof entry.leaseToken !== "string" || entry.leaseToken.length > 128)) {
62
+ throw new Error("Invalid outbox leaseToken");
63
+ }
64
+ if (entry.leaseGeneration !== undefined &&
65
+ (!Number.isSafeInteger(entry.leaseGeneration) || entry.leaseGeneration < 1)) {
66
+ throw new Error("Invalid outbox leaseGeneration");
67
+ }
68
+ if (entry.hubUrl !== undefined && (typeof entry.hubUrl !== "string" || entry.hubUrl.length > 512)) {
69
+ throw new Error("Invalid outbox hubUrl");
70
+ }
71
+ const hasProofOrArtifact = entry.artifact !== undefined || entry.executionCompleted !== undefined || entry.artifactProduced !== undefined;
72
+ const fingerprint = computeOutcomeFingerprint(entry.taskId, entry.attemptId, entry.status, entry.report, entry.error, entry.reportMetadata, entry.artifact?.digest, entry.executionCompleted, entry.artifactProduced);
73
+ if (hasProofOrArtifact) {
74
+ // 当有新字段时必须且只能匹配 canonical 指纹,禁止降级到旧指纹
75
+ if (entry.fingerprint !== undefined && entry.fingerprint !== fingerprint) {
76
+ throw new Error("Invalid outbox outcome fingerprint (proof bound artifact requires canonical fingerprint)");
77
+ }
78
+ }
79
+ else {
80
+ // 仅在无 artifact / proof 的旧项中允许 legacy 指纹
81
+ const legacyFingerprint = computeLegacyOutcomeFingerprint(entry.taskId, entry.attemptId, entry.status, entry.report, entry.error, entry.reportMetadata);
82
+ if (entry.fingerprint !== undefined &&
83
+ entry.fingerprint !== fingerprint &&
84
+ entry.fingerprint !== legacyFingerprint) {
85
+ throw new Error("Invalid outbox outcome fingerprint");
86
+ }
87
+ }
88
+ entry.fingerprint ??= fingerprint;
89
+ return entry;
90
+ }
91
+ function validateLeaseItem(item, deviceId) {
92
+ if (!item ||
93
+ typeof item !== "object" ||
94
+ typeof item.taskId !== "string" ||
95
+ !item.taskId ||
96
+ item.taskId.length > 128 ||
97
+ typeof item.attemptId !== "string" ||
98
+ !item.attemptId ||
99
+ item.attemptId.length > 128 ||
100
+ typeof item.botId !== "string" ||
101
+ !item.botId ||
102
+ item.botId.length > 128 ||
103
+ typeof item.roomId !== "string" ||
104
+ !item.roomId ||
105
+ item.roomId.length > 128 ||
106
+ typeof item.leaseToken !== "string" ||
107
+ !item.leaseToken ||
108
+ item.leaseToken.length > 128 ||
109
+ !Number.isSafeInteger(item.leaseGeneration) ||
110
+ item.deviceId !== deviceId ||
111
+ !Number.isSafeInteger(item.startedAt) ||
112
+ item.startedAt <= 0 ||
113
+ !Number.isSafeInteger(item.lastActivityAt) ||
114
+ !Number.isSafeInteger(item.lastRenewedActivityAt)) {
115
+ throw new Error("Invalid lease item schema");
116
+ }
117
+ const lease = item;
118
+ if (lease.hubUrl !== undefined && (typeof lease.hubUrl !== "string" || lease.hubUrl.length > 512)) {
119
+ throw new Error("Invalid lease hubUrl");
120
+ }
121
+ return lease;
122
+ }
24
123
  /**
25
124
  * Durable Task Recovery Manager:
26
- * 1. Transactional Outbox for completed/failed/interrupted results.
27
- * 2. Active lease registration with activity tracking and bounded life.
28
- * 3. Safe crash/restart detection: never blindly re-runs side effects; safely interrupts orphans.
125
+ * 1. Single unified versioned recovery state file for active leases & terminal outbox.
126
+ * 2. Atomic disk commit guarantees lease removal and terminal outcome entry happen in a single transaction.
127
+ * 3. Double-crash safe recovery: never blindly re-runs side effects; safely interrupts orphans and preserves outcomes.
128
+ * 4. Outcome immutability: identical retry is idempotent; conflicting outcome is strictly rejected.
129
+ * 5. ACK binding: strictly requires matching outcome fingerprint to clear outbox.
130
+ * 6. Hub fencing & isolation: leases carry leaseToken & generation into TaskOutboxEntry; entries are isolated per hubUrl.
29
131
  */
30
132
  export class TaskRecoveryManager {
31
- outboxPath;
32
- leasesPath;
133
+ statePath;
134
+ legacyOutboxPath;
135
+ legacyLeasesPath;
33
136
  deviceId;
34
137
  hubUrl;
35
138
  maxInactivityMs;
36
139
  maxDurationMs;
37
140
  outbox = new Map();
38
141
  activeLeases = new Map();
142
+ otherHubOutbox = [];
143
+ otherHubLeases = [];
39
144
  haltedOrphans = [];
40
- outboxLoadError = false;
41
- leasesLoadError = false;
145
+ loadError = false;
146
+ quarantine = [];
42
147
  constructor(options) {
43
148
  this.deviceId = options.deviceId;
44
149
  this.hubUrl = options.hubUrl;
45
150
  this.maxInactivityMs = options.maxInactivityMs ?? TASK_RECOVERY_DEFAULTS.maxInactivityMs;
46
151
  this.maxDurationMs = options.maxDurationMs ?? TASK_RECOVERY_DEFAULTS.maxDurationMs;
47
152
  if (options.dataDir) {
48
- this.outboxPath = join(options.dataDir, "task-recovery-outbox.json");
49
- this.leasesPath = join(options.dataDir, "task-active-leases.json");
153
+ this.statePath = join(options.dataDir, "task-recovery-state.json");
154
+ this.legacyOutboxPath = join(options.dataDir, "task-recovery-outbox.json");
155
+ this.legacyLeasesPath = join(options.dataDir, "task-active-leases.json");
50
156
  }
51
- this.loadOutbox();
52
- this.loadAndDetectOrphanLeases(options.onHaltOrphaned);
157
+ this.loadStateAndMigrate(options.onHaltOrphaned);
158
+ }
159
+ get outboxLoadError() {
160
+ return this.loadError;
161
+ }
162
+ get leasesLoadError() {
163
+ return this.loadError;
53
164
  }
54
165
  leaseKey(taskId, attemptId) {
55
166
  return `${taskId}:${attemptId}`;
56
167
  }
57
- loadOutbox() {
58
- if (!this.outboxPath)
59
- return;
60
- try {
61
- const raw = readFileSync(this.outboxPath, "utf8");
62
- const data = JSON.parse(raw);
63
- if (!Array.isArray(data))
64
- throw new Error("Invalid outbox data root");
65
- const seenKeys = new Set();
66
- for (const item of data) {
67
- if (!item ||
68
- typeof item !== "object" ||
69
- typeof item.id !== "string" ||
70
- item.id.length > 128 ||
71
- typeof item.taskId !== "string" ||
72
- item.taskId.length > 128 ||
73
- typeof item.attemptId !== "string" ||
74
- item.attemptId.length > 128 ||
75
- typeof item.botId !== "string" ||
76
- item.botId.length > 128 ||
77
- item.deviceId !== this.deviceId ||
78
- !["completed", "failed", "interrupted"].includes(item.status) ||
79
- !Number.isSafeInteger(item.createdAt) ||
80
- item.createdAt <= 0 ||
81
- !Number.isSafeInteger(item.updatedAt) ||
82
- !Number.isSafeInteger(item.attempts)) {
83
- throw new Error("Invalid outbox item schema");
84
- }
85
- if (item.reportMetadata !== undefined)
86
- item.reportMetadata = parseReportMetadata(item.reportMetadata);
87
- const key = item.id;
88
- if (seenKeys.has(key))
89
- throw new Error("Duplicate outbox key");
90
- seenKeys.add(key);
91
- this.outbox.set(key, item);
168
+ matchesHub(entryHubUrl) {
169
+ return this.hubUrl === entryHubUrl;
170
+ }
171
+ cleanupLegacyFiles() {
172
+ if (this.legacyOutboxPath) {
173
+ try {
174
+ unlinkSync(this.legacyOutboxPath);
92
175
  }
176
+ catch { }
93
177
  }
94
- catch (error) {
95
- if (error.code === "ENOENT") {
96
- return; // Truly non-existent file is clean startup
178
+ if (this.legacyLeasesPath) {
179
+ try {
180
+ unlinkSync(this.legacyLeasesPath);
97
181
  }
98
- // Fail-closed on ANY error (syntax, schema, permission): disallow overwriting
99
- this.outboxLoadError = true;
182
+ catch { }
100
183
  }
101
184
  }
102
- persistOutboxSync(entries) {
103
- if (!this.outboxPath)
185
+ writeStateToDiskSync(state) {
186
+ if (!this.statePath)
104
187
  return;
105
- if (this.outboxLoadError)
188
+ if (this.loadError) {
106
189
  throw new Error("Outbox persistence blocked: corrupted storage was preserved");
107
- const text = JSON.stringify(entries, null, 2) + "\n";
108
- writeAtomicSync(this.outboxPath, text, { mode: 0o600 });
109
- }
110
- persistLeasesSync(entries) {
111
- if (!this.leasesPath)
112
- return;
113
- if (this.leasesLoadError)
114
- throw new Error("Active leases persistence blocked: corrupted storage was preserved");
115
- const text = JSON.stringify(entries, null, 2) + "\n";
116
- writeAtomicSync(this.leasesPath, text, { mode: 0o600 });
190
+ }
191
+ // v2 prevents older readers from silently discarding archived terminal evidence.
192
+ const text = JSON.stringify({ ...state, version: 2, quarantine: state.quarantine ?? this.quarantine }, null, 2) + "\n";
193
+ if (Buffer.byteLength(text) > TASK_RECOVERY_STATE_MAX_BYTES)
194
+ throw new Error("Recovery state capacity exceeded; evidence retained");
195
+ writeAtomicSync(this.statePath, text, { mode: 0o600, fsync: true });
117
196
  }
118
- /**
119
- * Detect uncompleted leases from a previous process crash/restart.
120
- * Explicit safety requirement: NEVER blindly rerun side-effects!
121
- * Mark orphaned tasks as safely interrupted and stage them into Outbox,
122
- * EXCEPT if an existing completed/terminal outcome is already in Outbox.
123
- */
124
- loadAndDetectOrphanLeases(onHaltOrphaned) {
125
- if (!this.leasesPath)
197
+ loadStateAndMigrate(onHaltOrphaned) {
198
+ if (!this.statePath)
126
199
  return;
127
- let stored = [];
200
+ let loadedState = null;
201
+ // 1. Try reading the unified state file
128
202
  try {
129
- const raw = readFileSync(this.leasesPath, "utf8");
203
+ const raw = readFileSync(this.statePath, "utf8");
204
+ if (Buffer.byteLength(raw) > TASK_RECOVERY_STATE_MAX_BYTES)
205
+ throw new Error("Recovery state capacity exceeded");
130
206
  const parsed = JSON.parse(raw);
131
- if (!Array.isArray(parsed))
132
- throw new Error("Invalid leases data root");
133
- const seenKeys = new Set();
134
- for (const x of parsed) {
135
- if (!x ||
136
- typeof x !== "object" ||
137
- typeof x.taskId !== "string" ||
138
- x.taskId.length > 128 ||
139
- typeof x.attemptId !== "string" ||
140
- x.attemptId.length > 128 ||
141
- typeof x.botId !== "string" ||
142
- x.botId.length > 128 ||
143
- typeof x.roomId !== "string" ||
144
- x.roomId.length > 128 ||
145
- typeof x.leaseToken !== "string" ||
146
- x.leaseToken.length > 128 ||
147
- !Number.isSafeInteger(x.leaseGeneration) ||
148
- x.deviceId !== this.deviceId ||
149
- !Number.isSafeInteger(x.startedAt) ||
150
- x.startedAt <= 0 ||
151
- !Number.isSafeInteger(x.lastActivityAt) ||
152
- !Number.isSafeInteger(x.lastRenewedActivityAt)) {
153
- throw new Error("Invalid lease item schema");
154
- }
155
- const key = this.leaseKey(x.taskId, x.attemptId);
156
- if (seenKeys.has(key))
157
- throw new Error("Duplicate active lease key");
158
- seenKeys.add(key);
159
- stored.push(x);
207
+ if (!parsed || typeof parsed !== "object" || ![1, 2].includes(parsed.version)) {
208
+ throw new Error("Invalid recovery state file version or root");
209
+ }
210
+ if (typeof parsed.deviceId !== "string" || parsed.deviceId !== this.deviceId) {
211
+ throw new Error("Invalid recovery state file deviceId binding");
212
+ }
213
+ if (!Array.isArray(parsed.outbox) || !Array.isArray(parsed.activeLeases)) {
214
+ throw new Error("Invalid recovery state file collections");
160
215
  }
216
+ if (parsed.version === 2) {
217
+ if (!Array.isArray(parsed.quarantine))
218
+ throw new Error("Invalid quarantine collection");
219
+ const seen = new Set();
220
+ const archive = parsed.quarantine.map((item) => {
221
+ if (!item ||
222
+ !["terminal_conflict", "attempt_expired", "legacy_lease_missing"].includes(item.reasonCode) ||
223
+ !Number.isSafeInteger(item.quarantinedAt) ||
224
+ item.quarantinedAt < 0)
225
+ throw new Error("Invalid quarantined outcome");
226
+ const outcome = validateOutboxItem(item.outcome, this.deviceId);
227
+ const key = JSON.stringify([outcome.hubUrl, outcome.id]);
228
+ if (seen.has(key))
229
+ throw new Error("Duplicate quarantined outcome");
230
+ seen.add(key);
231
+ return { outcome, reasonCode: item.reasonCode, quarantinedAt: item.quarantinedAt };
232
+ });
233
+ if (archive.length > TASK_QUARANTINE_LIMITS.maxEntries ||
234
+ Buffer.byteLength(JSON.stringify(archive)) > TASK_QUARANTINE_LIMITS.maxTotalBytes)
235
+ throw new Error("Quarantine capacity exceeded");
236
+ this.quarantine = archive;
237
+ }
238
+ else if (parsed.quarantine !== undefined)
239
+ throw new Error("Unexpected v1 quarantine");
240
+ const seenOutboxKeys = new Set();
241
+ const validOutbox = [];
242
+ for (const item of parsed.outbox) {
243
+ const entry = validateOutboxItem(item, this.deviceId);
244
+ entry.hubUrl ??= typeof parsed.hubUrl === "string" ? parsed.hubUrl : this.hubUrl;
245
+ const scopedKey = JSON.stringify([entry.hubUrl, entry.id]);
246
+ if (seenOutboxKeys.has(scopedKey) ||
247
+ this.quarantine.some((item) => JSON.stringify([item.outcome.hubUrl, item.outcome.id]) === scopedKey))
248
+ throw new Error("Duplicate outbox or quarantined key in state file");
249
+ seenOutboxKeys.add(scopedKey);
250
+ validOutbox.push(entry);
251
+ }
252
+ const seenLeaseKeys = new Set();
253
+ const validLeases = [];
254
+ for (const item of parsed.activeLeases) {
255
+ const lease = validateLeaseItem(item, this.deviceId);
256
+ lease.hubUrl ??= typeof parsed.hubUrl === "string" ? parsed.hubUrl : this.hubUrl;
257
+ const key = JSON.stringify([lease.hubUrl, this.leaseKey(lease.taskId, lease.attemptId)]);
258
+ if (seenLeaseKeys.has(key))
259
+ throw new Error("Duplicate active lease key in state file");
260
+ seenLeaseKeys.add(key);
261
+ validLeases.push(lease);
262
+ }
263
+ loadedState = {
264
+ version: 1,
265
+ deviceId: this.deviceId,
266
+ hubUrl: typeof parsed.hubUrl === "string" ? parsed.hubUrl : this.hubUrl,
267
+ outbox: validOutbox,
268
+ activeLeases: validLeases,
269
+ };
270
+ // Best-effort cleanup of any remaining legacy files
271
+ this.cleanupLegacyFiles();
161
272
  }
162
273
  catch (error) {
163
274
  if (error.code === "ENOENT") {
275
+ loadedState = null;
276
+ }
277
+ else {
278
+ // State file exists but is corrupted: FAIL CLOSED and forbid overwrites
279
+ this.loadError = true;
164
280
  return;
165
281
  }
166
- this.leasesLoadError = true;
167
- return;
168
282
  }
169
- if (stored.length > 0) {
283
+ // 2. If unified state does not exist, migrate from legacy 2 files if present
284
+ if (loadedState === null) {
285
+ let legacyOutbox = [];
286
+ let legacyLeases = [];
287
+ let hasLegacy = false;
288
+ if (this.legacyOutboxPath) {
289
+ try {
290
+ const raw = readFileSync(this.legacyOutboxPath, "utf8");
291
+ hasLegacy = true;
292
+ const parsed = JSON.parse(raw);
293
+ if (!Array.isArray(parsed))
294
+ throw new Error("Invalid legacy outbox root");
295
+ const seenKeys = new Set();
296
+ for (const item of parsed) {
297
+ const entry = validateOutboxItem(item, this.deviceId);
298
+ if (seenKeys.has(entry.id))
299
+ throw new Error("Duplicate outbox key in legacy file");
300
+ seenKeys.add(entry.id);
301
+ entry.hubUrl ??= this.hubUrl;
302
+ legacyOutbox.push(entry);
303
+ }
304
+ }
305
+ catch (error) {
306
+ if (error.code !== "ENOENT") {
307
+ this.loadError = true;
308
+ return;
309
+ }
310
+ }
311
+ }
312
+ if (this.legacyLeasesPath) {
313
+ try {
314
+ const raw = readFileSync(this.legacyLeasesPath, "utf8");
315
+ hasLegacy = true;
316
+ const parsed = JSON.parse(raw);
317
+ if (!Array.isArray(parsed))
318
+ throw new Error("Invalid legacy leases root");
319
+ const seenKeys = new Set();
320
+ for (const item of parsed) {
321
+ const lease = validateLeaseItem(item, this.deviceId);
322
+ const key = this.leaseKey(lease.taskId, lease.attemptId);
323
+ if (seenKeys.has(key))
324
+ throw new Error("Duplicate active lease key in legacy file");
325
+ seenKeys.add(key);
326
+ lease.hubUrl ??= this.hubUrl;
327
+ legacyLeases.push(lease);
328
+ }
329
+ }
330
+ catch (error) {
331
+ if (error.code !== "ENOENT") {
332
+ this.loadError = true;
333
+ return;
334
+ }
335
+ }
336
+ }
337
+ if (this.loadError)
338
+ return;
339
+ loadedState = {
340
+ version: 1,
341
+ deviceId: this.deviceId,
342
+ hubUrl: this.hubUrl,
343
+ outbox: legacyOutbox,
344
+ activeLeases: legacyLeases,
345
+ };
346
+ if (hasLegacy) {
347
+ try {
348
+ this.writeStateToDiskSync(loadedState);
349
+ this.cleanupLegacyFiles();
350
+ }
351
+ catch {
352
+ this.loadError = true;
353
+ return;
354
+ }
355
+ }
356
+ }
357
+ // Partition entries by hubUrl isolation
358
+ for (const entry of loadedState.outbox) {
359
+ if (this.matchesHub(entry.hubUrl)) {
360
+ this.outbox.set(entry.id, entry);
361
+ }
362
+ else {
363
+ this.otherHubOutbox.push(entry);
364
+ }
365
+ }
366
+ for (const lease of loadedState.activeLeases) {
367
+ if (this.matchesHub(lease.hubUrl)) {
368
+ this.activeLeases.set(this.leaseKey(lease.taskId, lease.attemptId), lease);
369
+ }
370
+ else {
371
+ this.otherHubLeases.push(lease);
372
+ }
373
+ }
374
+ // 3. Crash detection: detect orphaned active leases for current hub from prior crash/restart
375
+ if (this.activeLeases.size > 0) {
376
+ const stored = Array.from(this.activeLeases.values());
170
377
  const now = Date.now();
171
378
  const newOutboxEntries = [];
172
379
  for (const lease of stored) {
@@ -177,30 +384,43 @@ export class TaskRecoveryManager {
177
384
  catch { }
178
385
  const outboxKey = this.leaseKey(lease.taskId, lease.attemptId);
179
386
  const existingOutbox = this.outbox.get(outboxKey);
180
- // If outbox already has a terminal outcome (e.g. completed before crash), NEVER overwrite it!
387
+ // If outbox already has a terminal outcome, NEVER overwrite it!
181
388
  if (!existingOutbox) {
389
+ const report = "Execution safely halted on device process restart to prevent duplicate side effects.";
390
+ const error = "Device process restarted during execution";
391
+ const fingerprint = computeOutcomeFingerprint(lease.taskId, lease.attemptId, "interrupted", report, error);
182
392
  const outboxEntry = {
183
393
  id: outboxKey,
184
394
  taskId: lease.taskId,
185
395
  attemptId: lease.attemptId,
186
396
  botId: lease.botId,
187
397
  deviceId: this.deviceId,
398
+ hubUrl: lease.hubUrl ?? this.hubUrl,
188
399
  roomId: lease.roomId,
189
400
  status: "interrupted",
190
- report: "Execution safely halted on device process restart to prevent duplicate side effects.",
191
- error: "Device process restarted during execution",
401
+ report,
402
+ error,
403
+ fingerprint,
192
404
  createdAt: now,
193
405
  updatedAt: now,
194
406
  attempts: 0,
407
+ leaseToken: lease.leaseToken,
408
+ leaseGeneration: lease.leaseGeneration,
195
409
  };
196
410
  newOutboxEntries.push(outboxEntry);
197
411
  }
198
412
  }
199
- // Atomic disk commit first: write empty leases, then write augmented outbox
200
- this.persistLeasesSync([]);
201
- const combinedOutbox = [...Array.from(this.outbox.values()), ...newOutboxEntries];
202
- this.persistOutboxSync(combinedOutbox);
203
- // After successful disk commit, update in-memory maps
413
+ // Atomic disk commit: empty activeLeases, augmented outbox in one shot, preserving other Hubs
414
+ const allOutbox = [...this.otherHubOutbox, ...Array.from(this.outbox.values()), ...newOutboxEntries];
415
+ const allLeases = [...this.otherHubLeases];
416
+ const nextState = {
417
+ version: 1,
418
+ deviceId: this.deviceId,
419
+ hubUrl: this.hubUrl,
420
+ outbox: allOutbox,
421
+ activeLeases: allLeases,
422
+ };
423
+ this.writeStateToDiskSync(nextState);
204
424
  for (const entry of newOutboxEntries) {
205
425
  this.outbox.set(entry.id, entry);
206
426
  }
@@ -213,19 +433,74 @@ export class TaskRecoveryManager {
213
433
  }
214
434
  /**
215
435
  * Record a newly running task lease.
436
+ * Rejects if (taskId, attemptId) has already been finalized in Outbox.
437
+ * Rejects if an active lease is already registered for this task attempt.
438
+ * Validates inputs before persisting to disk to prevent state corruption.
216
439
  */
217
440
  recordTaskStart(lease) {
441
+ // Strict pre-validation: reject invalid inputs BEFORE touching disk state
442
+ if (!lease ||
443
+ typeof lease !== "object" ||
444
+ typeof lease.taskId !== "string" ||
445
+ !lease.taskId ||
446
+ lease.taskId.length > 128 ||
447
+ typeof lease.attemptId !== "string" ||
448
+ !lease.attemptId ||
449
+ lease.attemptId.length > 128 ||
450
+ typeof lease.botId !== "string" ||
451
+ !lease.botId ||
452
+ lease.botId.length > 128 ||
453
+ typeof lease.roomId !== "string" ||
454
+ !lease.roomId ||
455
+ lease.roomId.length > 128 ||
456
+ typeof lease.leaseToken !== "string" ||
457
+ !lease.leaseToken ||
458
+ lease.leaseToken.length > 128 ||
459
+ (lease.leaseGeneration !== undefined && !Number.isSafeInteger(lease.leaseGeneration)) ||
460
+ (lease.deviceId && lease.deviceId !== this.deviceId)) {
461
+ throw new Error("Invalid task lease parameters for recordTaskStart");
462
+ }
463
+ const key = this.leaseKey(lease.taskId, lease.attemptId);
464
+ if (this.outbox.has(key) ||
465
+ this.quarantine.some((item) => this.matchesHub(item.outcome.hubUrl) && item.outcome.id === key)) {
466
+ throw new Error(`Cannot start task: outcome for task ${lease.taskId} attempt ${lease.attemptId} already finalized in outbox`);
467
+ }
468
+ // Reject conflicting concurrent or prior attempts for the same taskId in active leases
469
+ for (const [existingKey, existingLease] of this.activeLeases) {
470
+ if (existingLease.taskId === lease.taskId) {
471
+ if (existingKey === key) {
472
+ throw new Error(`Task lease already active for task ${lease.taskId} attempt ${lease.attemptId}`);
473
+ }
474
+ throw new Error(`Conflicting attempt active for task ${lease.taskId}: existing=${existingLease.attemptId}, new=${lease.attemptId}`);
475
+ }
476
+ }
477
+ if (lease.hubUrl !== undefined && lease.hubUrl !== this.hubUrl)
478
+ throw new Error("Task lease Hub identity mismatch");
479
+ const capacity = this.hasOutboxCapacity();
480
+ if (!capacity.available)
481
+ throw new Error(capacity.reason);
218
482
  const now = Date.now();
219
483
  const record = {
220
484
  ...lease,
485
+ deviceId: this.deviceId,
486
+ hubUrl: lease.hubUrl ?? this.hubUrl,
221
487
  activitySequence: lease.activitySequence ?? 0,
222
488
  startedAt: lease.startedAt ?? now,
223
489
  lastActivityAt: now,
224
490
  lastRenewedActivityAt: now,
225
491
  };
226
- const nextEntries = [...Array.from(this.activeLeases.values()), record];
227
- this.persistLeasesSync(nextEntries);
228
- this.activeLeases.set(this.leaseKey(record.taskId, record.attemptId), record);
492
+ const nextLeases = [...Array.from(this.activeLeases.values()), record];
493
+ const allOutbox = [...this.otherHubOutbox, ...Array.from(this.outbox.values())];
494
+ const allLeases = [...this.otherHubLeases, ...nextLeases];
495
+ const state = {
496
+ version: 1,
497
+ deviceId: this.deviceId,
498
+ hubUrl: this.hubUrl,
499
+ outbox: allOutbox,
500
+ activeLeases: allLeases,
501
+ };
502
+ this.writeStateToDiskSync(state);
503
+ this.activeLeases.set(key, record);
229
504
  return structuredClone(record);
230
505
  }
231
506
  /**
@@ -244,8 +519,17 @@ export class TaskRecoveryManager {
244
519
  removeActiveLease(taskId, attemptId) {
245
520
  const key = this.leaseKey(taskId, attemptId);
246
521
  if (this.activeLeases.has(key)) {
247
- const next = Array.from(this.activeLeases.values()).filter((l) => this.leaseKey(l.taskId, l.attemptId) !== key);
248
- this.persistLeasesSync(next);
522
+ const nextLeases = Array.from(this.activeLeases.values()).filter((l) => this.leaseKey(l.taskId, l.attemptId) !== key);
523
+ const allOutbox = [...this.otherHubOutbox, ...Array.from(this.outbox.values())];
524
+ const allLeases = [...this.otherHubLeases, ...nextLeases];
525
+ const state = {
526
+ version: 1,
527
+ deviceId: this.deviceId,
528
+ hubUrl: this.hubUrl,
529
+ outbox: allOutbox,
530
+ activeLeases: allLeases,
531
+ };
532
+ this.writeStateToDiskSync(state);
249
533
  this.activeLeases.delete(key);
250
534
  }
251
535
  }
@@ -257,13 +541,14 @@ export class TaskRecoveryManager {
257
541
  return lease ? structuredClone(lease) : undefined;
258
542
  }
259
543
  /**
260
- * Get all active leases (used for reconnection claim).
544
+ * Get all active leases for current Hub (used for reconnection claim).
261
545
  */
262
546
  getActiveLeases() {
263
547
  return structuredClone(Array.from(this.activeLeases.values()));
264
548
  }
265
549
  /**
266
550
  * Prepare claim payload for all running tasks upon reconnection.
551
+ * Strictly isolated to current Hub.
267
552
  */
268
553
  prepareClaims() {
269
554
  const claims = [];
@@ -287,7 +572,6 @@ export class TaskRecoveryManager {
287
572
  const renews = [];
288
573
  for (const lease of this.activeLeases.values()) {
289
574
  const isWaitingHuman = options?.waitingForHumanTaskIds?.has(lease.taskId) ?? false;
290
- // Human wait pauses inactivity expiration
291
575
  const inactive = !isWaitingHuman && now - lease.lastActivityAt > this.maxInactivityMs;
292
576
  const totalExceeded = this.maxDurationMs > 0 && now - lease.startedAt > this.maxDurationMs;
293
577
  if (!inactive && !totalExceeded) {
@@ -336,7 +620,9 @@ export class TaskRecoveryManager {
336
620
  * if the recovery outbox has reached its budget ceiling, preserving existing results.
337
621
  */
338
622
  hasOutboxCapacity() {
339
- if (this.outbox.size >= TASK_OUTBOX_LIMITS.maxEntries) {
623
+ const reservations = this.activeLeases.size + this.otherHubLeases.length;
624
+ const totalEntries = this.outbox.size + this.otherHubOutbox.length + reservations;
625
+ if (totalEntries >= TASK_OUTBOX_LIMITS.maxEntries) {
340
626
  return {
341
627
  available: false,
342
628
  reason: `Recovery outbox reached maximum capacity (${TASK_OUTBOX_LIMITS.maxEntries} entries). Reconnect to Hub to flush pending outcomes before starting new tasks.`,
@@ -346,7 +632,10 @@ export class TaskRecoveryManager {
346
632
  for (const entry of this.outbox.values()) {
347
633
  totalBytes += Buffer.byteLength(JSON.stringify(entry));
348
634
  }
349
- if (totalBytes >= TASK_OUTBOX_LIMITS.maxTotalBytes) {
635
+ for (const entry of this.otherHubOutbox) {
636
+ totalBytes += Buffer.byteLength(JSON.stringify(entry));
637
+ }
638
+ if (totalBytes + (reservations + 1) * TASK_OUTBOX_RESERVATION_BYTES > TASK_OUTBOX_LIMITS.maxTotalBytes) {
350
639
  return {
351
640
  available: false,
352
641
  reason: `Recovery outbox reached byte budget (${Math.round(TASK_OUTBOX_LIMITS.maxTotalBytes / 1024)} KiB). Reconnect to Hub to flush pending outcomes before starting new tasks.`,
@@ -356,36 +645,63 @@ export class TaskRecoveryManager {
356
645
  }
357
646
  /**
358
647
  * Enqueue task terminal outcome into durable outbox.
359
- * First write disk synchronously; throw on error so execution doesn't falsely succeed.
360
- * Idempotent: identical (taskId, attemptId, status) returns existing; conflicting rejects.
648
+ * Atomically writes to unified state file and removes active lease in a single transaction.
649
+ * Enforces outcome immutability: identical outcome is idempotent; conflicting outcome is rejected.
650
+ * Carries leaseToken & leaseGeneration for Hub fencing.
361
651
  */
362
652
  recordTaskFinish(task, outcome) {
653
+ if (!task ||
654
+ typeof task !== "object" ||
655
+ typeof task.id !== "string" ||
656
+ !task.id ||
657
+ task.id.length > 128 ||
658
+ typeof task.attemptId !== "string" ||
659
+ !task.attemptId ||
660
+ task.attemptId.length > 128 ||
661
+ typeof task.botId !== "string" ||
662
+ !task.botId ||
663
+ task.botId.length > 128) {
664
+ throw new Error("Invalid task parameters for recordTaskFinish");
665
+ }
666
+ if (task.hubUrl !== undefined && task.hubUrl !== this.hubUrl)
667
+ throw new Error("Task outcome Hub identity mismatch");
363
668
  const now = Date.now();
364
- const safeReport = outcome.report ? boundTaskReport(outcome.report) : undefined;
365
- const safeError = outcome.error ? deviceTaskFailure(outcome.error) : undefined;
366
- const reportMetadata = outcome.reportMetadata === undefined ? undefined : parseReportMetadata(outcome.reportMetadata);
367
- const fingerprint = computeOutcomeFingerprint(task.id, task.attemptId, outcome.status, safeReport, safeError, reportMetadata);
669
+ const normalized = normalizeTaskOutcome(task.id, task.attemptId, outcome);
368
670
  const key = this.leaseKey(task.id, task.attemptId);
369
- const existing = this.outbox.get(key);
671
+ const activeLease = this.activeLeases.get(key);
672
+ const leaseToken = task.leaseToken ?? activeLease?.leaseToken;
673
+ const leaseGeneration = task.leaseGeneration ?? activeLease?.leaseGeneration;
674
+ const hubUrl = task.hubUrl ?? activeLease?.hubUrl ?? this.hubUrl;
675
+ const contractDigest = task.contractDigest ?? activeLease?.contractDigest;
676
+ const manifestDigest = task.manifestDigest ?? activeLease?.manifestDigest;
677
+ const existing = this.outbox.get(key) ??
678
+ this.quarantine.find((item) => this.matchesHub(item.outcome.hubUrl) && item.outcome.id === key)?.outcome;
370
679
  if (existing) {
371
680
  const targetDeviceId = task.deviceId || this.deviceId;
372
- if (existing.fingerprint === fingerprint &&
681
+ // Strict immutability: identical retry is idempotent; conflicting outcome is rejected.
682
+ // Lease fields must also be identical to prevent cross-generation outcome aliasing.
683
+ const leaseTokenMatches = leaseToken === undefined || existing.leaseToken === leaseToken;
684
+ const leaseGenMatches = leaseGeneration === undefined || existing.leaseGeneration === leaseGeneration;
685
+ const artifactMatches = existing.artifact?.digest === normalized.artifact?.digest;
686
+ const proofMatches = existing.executionCompleted === normalized.executionCompleted &&
687
+ existing.artifactProduced === normalized.artifactProduced;
688
+ if (existing.report === normalized.report &&
689
+ existing.error === normalized.error &&
690
+ existing.status === normalized.status &&
373
691
  existing.botId === task.botId &&
374
692
  existing.deviceId === targetDeviceId &&
375
- existing.roomId === task.roomId &&
376
- JSON.stringify(existing.reportMetadata) === JSON.stringify(reportMetadata)) {
693
+ (task.roomId === undefined || existing.roomId === task.roomId) &&
694
+ JSON.stringify(existing.reportMetadata) === JSON.stringify(normalized.reportMetadata) &&
695
+ leaseTokenMatches &&
696
+ leaseGenMatches &&
697
+ artifactMatches &&
698
+ proofMatches) {
699
+ if (this.activeLeases.has(key)) {
700
+ this.removeActiveLease(task.id, task.attemptId);
701
+ }
377
702
  return structuredClone(existing);
378
703
  }
379
- existing.status = outcome.status;
380
- existing.report = safeReport;
381
- existing.error = safeError;
382
- existing.reportMetadata = reportMetadata;
383
- existing.fingerprint = fingerprint;
384
- existing.updatedAt = now;
385
- const nextOutbox = Array.from(this.outbox.values());
386
- this.persistOutboxSync(nextOutbox);
387
- this.removeActiveLease(task.id, task.attemptId);
388
- return structuredClone(existing);
704
+ throw new Error(`Task outcome conflict: outcome for task ${task.id} attempt ${task.attemptId} already finalized with status=${existing.status}, fingerprint=${existing.fingerprint} (attempted status=${normalized.status}, fingerprint=${normalized.fingerprint})`);
389
705
  }
390
706
  const entry = {
391
707
  id: key,
@@ -393,31 +709,67 @@ export class TaskRecoveryManager {
393
709
  attemptId: task.attemptId,
394
710
  botId: task.botId,
395
711
  deviceId: task.deviceId || this.deviceId,
712
+ hubUrl,
396
713
  roomId: task.roomId,
397
- status: outcome.status,
398
- reportMetadata,
399
- report: safeReport,
400
- error: safeError,
401
- fingerprint,
714
+ status: normalized.status,
715
+ reportMetadata: normalized.reportMetadata,
716
+ report: normalized.report,
717
+ error: normalized.error,
718
+ fingerprint: normalized.fingerprint,
719
+ artifact: normalized.artifact,
720
+ executionCompleted: normalized.executionCompleted,
721
+ artifactProduced: normalized.artifactProduced,
722
+ contractDigest,
723
+ manifestDigest,
402
724
  createdAt: now,
403
725
  updatedAt: now,
404
726
  attempts: 0,
727
+ leaseToken,
728
+ leaseGeneration,
405
729
  };
406
- // Transactional write: first stage next entries and commit to disk
730
+ validateOutboxItem(entry, this.deviceId);
731
+ if (activeLease &&
732
+ (activeLease.botId !== entry.botId ||
733
+ (task.roomId !== undefined && activeLease.roomId !== task.roomId) ||
734
+ activeLease.leaseToken !== leaseToken ||
735
+ activeLease.leaseGeneration !== leaseGeneration))
736
+ throw new Error("Task outcome lease identity mismatch");
737
+ // Transactional commit: add outbox and remove active lease atomically in unified state
407
738
  const nextOutbox = [...Array.from(this.outbox.values()), entry];
408
- this.persistOutboxSync(nextOutbox);
739
+ const allPending = [...this.otherHubOutbox, ...nextOutbox];
740
+ if (allPending.length > TASK_OUTBOX_LIMITS.maxEntries ||
741
+ allPending.reduce((bytes, pending) => bytes + Buffer.byteLength(JSON.stringify(pending)), 0) >
742
+ TASK_OUTBOX_LIMITS.maxTotalBytes)
743
+ throw new Error("Recovery outbox capacity exceeded; outcome lease retained");
744
+ const nextLeases = Array.from(this.activeLeases.values()).filter((l) => this.leaseKey(l.taskId, l.attemptId) !== key);
745
+ const allOutbox = [...this.otherHubOutbox, ...nextOutbox];
746
+ const allLeases = [...this.otherHubLeases, ...nextLeases];
747
+ const state = {
748
+ version: 1,
749
+ deviceId: this.deviceId,
750
+ hubUrl: this.hubUrl,
751
+ outbox: allOutbox,
752
+ activeLeases: allLeases,
753
+ };
754
+ this.writeStateToDiskSync(state);
409
755
  // Disk succeeded; update memory
410
756
  this.outbox.set(entry.id, entry);
411
- // Clean active lease
412
- this.removeActiveLease(task.id, task.attemptId);
757
+ this.activeLeases.delete(key);
413
758
  return structuredClone(entry);
414
759
  }
415
760
  /**
416
- * List all pending outbox entries waiting for Hub ACK.
761
+ * List all pending outbox entries waiting for Hub ACK for the current Hub.
417
762
  */
418
763
  getPendingOutbox() {
419
764
  return structuredClone(Array.from(this.outbox.values()));
420
765
  }
766
+ /**
767
+ * Find a pending outbox entry by taskId and attemptId.
768
+ */
769
+ getPendingOutboxEntry(taskId, attemptId) {
770
+ const entry = this.outbox.get(this.leaseKey(taskId, attemptId));
771
+ return entry ? structuredClone(entry) : undefined;
772
+ }
421
773
  /**
422
774
  * Mark attempt sent to Hub for backoff/tracking.
423
775
  */
@@ -425,28 +777,101 @@ export class TaskRecoveryManager {
425
777
  const entry = this.outbox.get(id);
426
778
  if (entry) {
427
779
  const updated = { ...entry, attempts: entry.attempts + 1, updatedAt: Date.now() };
428
- const next = Array.from(this.outbox.values()).map((e) => (e.id === id ? updated : e));
429
- this.persistOutboxSync(next);
780
+ const nextOutbox = Array.from(this.outbox.values()).map((e) => (e.id === id ? updated : e));
781
+ const allOutbox = [...this.otherHubOutbox, ...nextOutbox];
782
+ const allLeases = [...this.otherHubLeases, ...Array.from(this.activeLeases.values())];
783
+ const state = {
784
+ version: 1,
785
+ deviceId: this.deviceId,
786
+ hubUrl: this.hubUrl,
787
+ outbox: allOutbox,
788
+ activeLeases: allLeases,
789
+ };
790
+ this.writeStateToDiskSync(state);
430
791
  this.outbox.set(id, updated);
431
792
  }
432
793
  }
794
+ /** Durable rejected evidence remains inspectable and never participates in automatic replay. */
795
+ getQuarantinedOutcomes() {
796
+ return structuredClone(this.quarantine.filter((item) => this.matchesHub(item.outcome.hubUrl)));
797
+ }
798
+ quarantineOutbox(taskId, attemptId, fingerprint, reasonCode, status, artifactDigest) {
799
+ if (this.loadError ||
800
+ typeof reasonCode !== "string" ||
801
+ !["terminal_conflict", "attempt_expired", "legacy_lease_missing"].includes(reasonCode))
802
+ return false;
803
+ const key = this.leaseKey(taskId, attemptId);
804
+ const outcome = this.outbox.get(key);
805
+ if (!outcome ||
806
+ typeof fingerprint !== "string" ||
807
+ fingerprint !== outcome.fingerprint ||
808
+ status !== outcome.status ||
809
+ artifactDigest !== outcome.artifact?.digest)
810
+ return false;
811
+ const next = [
812
+ ...this.quarantine,
813
+ {
814
+ outcome: structuredClone(outcome),
815
+ reasonCode: reasonCode,
816
+ quarantinedAt: Date.now(),
817
+ },
818
+ ];
819
+ if (next.length > TASK_QUARANTINE_LIMITS.maxEntries ||
820
+ Buffer.byteLength(JSON.stringify(next)) > TASK_QUARANTINE_LIMITS.maxTotalBytes)
821
+ return false;
822
+ // Commit archive + removal together. Keep all active leases and other hubs intact.
823
+ this.writeStateToDiskSync({
824
+ version: 2,
825
+ deviceId: this.deviceId,
826
+ hubUrl: this.hubUrl,
827
+ outbox: [...this.otherHubOutbox, ...Array.from(this.outbox.values()).filter((e) => e.id !== key)],
828
+ activeLeases: [...this.otherHubLeases, ...Array.from(this.activeLeases.values())],
829
+ quarantine: next,
830
+ });
831
+ this.quarantine = next;
832
+ this.outbox.delete(key);
833
+ return true;
834
+ }
433
835
  /**
434
836
  * Acknowledge outbox entry upon receiving task_result_ack from Hub.
435
- * Binds fingerprint to prevent mismatched outcome clearing wrong entry.
837
+ * Strictly requires matching outcome fingerprint; rejects clearing without or with mismatched fingerprint.
436
838
  */
437
- ackOutbox(taskId, attemptId, fingerprint) {
438
- const next = Array.from(this.outbox.values()).filter((e) => !(e.taskId === taskId && e.attemptId === attemptId && (!fingerprint || e.fingerprint === fingerprint)));
439
- if (next.length !== this.outbox.size) {
440
- this.persistOutboxSync(next);
441
- for (const [id, entry] of this.outbox) {
442
- if (entry.taskId === taskId &&
443
- entry.attemptId === attemptId &&
444
- (!fingerprint || entry.fingerprint === fingerprint)) {
445
- this.outbox.delete(id);
446
- }
839
+ ackOutbox(taskId, attemptId, fingerprint, extra) {
840
+ const key = this.leaseKey(taskId, attemptId);
841
+ const entry = this.outbox.get(key);
842
+ if (!entry)
843
+ return false;
844
+ if (entry.fingerprint) {
845
+ if (!fingerprint || entry.fingerprint !== fingerprint) {
846
+ return false;
447
847
  }
448
- return true;
449
848
  }
450
- return false;
849
+ else if (fingerprint) {
850
+ return false;
851
+ }
852
+ if (extra?.status !== undefined && entry.status !== extra.status)
853
+ return false;
854
+ if (extra?.artifactDigest !== undefined && entry.artifact?.digest !== extra.artifactDigest) {
855
+ return false;
856
+ }
857
+ if (extra?.contractDigest !== undefined && entry.contractDigest !== extra.contractDigest) {
858
+ return false;
859
+ }
860
+ if (extra?.manifestDigest !== undefined && entry.manifestDigest !== extra.manifestDigest) {
861
+ return false;
862
+ }
863
+ const nextOutbox = Array.from(this.outbox.values()).filter((e) => e.id !== key);
864
+ const allOutbox = [...this.otherHubOutbox, ...nextOutbox];
865
+ const allLeases = [...this.otherHubLeases, ...Array.from(this.activeLeases.values())];
866
+ const state = {
867
+ version: 1,
868
+ deviceId: this.deviceId,
869
+ hubUrl: this.hubUrl,
870
+ outbox: allOutbox,
871
+ activeLeases: allLeases,
872
+ };
873
+ this.writeStateToDiskSync(state);
874
+ this.outbox.delete(key);
875
+ return true;
451
876
  }
452
877
  }