@dsh-ray/assistant-delivery 0.0.1-seed.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (185) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +610 -1
  3. package/bin/dsh-restart-supervisor.js +102 -0
  4. package/cordis.patch.yml +29 -0
  5. package/lib/acceptance.d.ts +54 -0
  6. package/lib/acceptance.d.ts.map +1 -0
  7. package/lib/acceptance.js +2 -0
  8. package/lib/acceptance.js.map +1 -0
  9. package/lib/agent-runtime.d.ts +247 -0
  10. package/lib/agent-runtime.d.ts.map +1 -0
  11. package/lib/agent-runtime.js +4458 -0
  12. package/lib/agent-runtime.js.map +1 -0
  13. package/lib/approval-status-context.d.ts +8 -0
  14. package/lib/approval-status-context.d.ts.map +1 -0
  15. package/lib/approval-status-context.js +55 -0
  16. package/lib/approval-status-context.js.map +1 -0
  17. package/lib/attention-audit-store.d.ts +54 -0
  18. package/lib/attention-audit-store.d.ts.map +1 -0
  19. package/lib/attention-audit-store.js +213 -0
  20. package/lib/attention-audit-store.js.map +1 -0
  21. package/lib/attention-enforcement.d.ts +75 -0
  22. package/lib/attention-enforcement.d.ts.map +1 -0
  23. package/lib/attention-enforcement.js +84 -0
  24. package/lib/attention-enforcement.js.map +1 -0
  25. package/lib/attention.d.ts +208 -0
  26. package/lib/attention.d.ts.map +1 -0
  27. package/lib/attention.js +288 -0
  28. package/lib/attention.js.map +1 -0
  29. package/lib/canonical.d.ts +28 -0
  30. package/lib/canonical.d.ts.map +1 -0
  31. package/lib/canonical.js +190 -0
  32. package/lib/canonical.js.map +1 -0
  33. package/lib/coordinator.d.ts +134 -0
  34. package/lib/coordinator.d.ts.map +1 -0
  35. package/lib/coordinator.js +746 -0
  36. package/lib/coordinator.js.map +1 -0
  37. package/lib/feedback-command.d.ts +105 -0
  38. package/lib/feedback-command.d.ts.map +1 -0
  39. package/lib/feedback-command.js +547 -0
  40. package/lib/feedback-command.js.map +1 -0
  41. package/lib/foreground-observation.d.ts +66 -0
  42. package/lib/foreground-observation.d.ts.map +1 -0
  43. package/lib/foreground-observation.js +13 -0
  44. package/lib/foreground-observation.js.map +1 -0
  45. package/lib/foreground-termination.d.ts +31 -0
  46. package/lib/foreground-termination.d.ts.map +1 -0
  47. package/lib/foreground-termination.js +42 -0
  48. package/lib/foreground-termination.js.map +1 -0
  49. package/lib/goal-wake-types.d.ts +93 -0
  50. package/lib/goal-wake-types.d.ts.map +1 -0
  51. package/lib/goal-wake-types.js +70 -0
  52. package/lib/goal-wake-types.js.map +1 -0
  53. package/lib/in-process-reload-runtime.d.ts +120 -0
  54. package/lib/in-process-reload-runtime.d.ts.map +1 -0
  55. package/lib/in-process-reload-runtime.js +1280 -0
  56. package/lib/in-process-reload-runtime.js.map +1 -0
  57. package/lib/inbound-images.d.ts +38 -0
  58. package/lib/inbound-images.d.ts.map +1 -0
  59. package/lib/inbound-images.js +269 -0
  60. package/lib/inbound-images.js.map +1 -0
  61. package/lib/index.d.ts +41 -0
  62. package/lib/index.d.ts.map +1 -0
  63. package/lib/index.js +25 -0
  64. package/lib/index.js.map +1 -0
  65. package/lib/learning-command.d.ts +40 -0
  66. package/lib/learning-command.d.ts.map +1 -0
  67. package/lib/learning-command.js +57 -0
  68. package/lib/learning-command.js.map +1 -0
  69. package/lib/native-termination.d.ts +12 -0
  70. package/lib/native-termination.d.ts.map +1 -0
  71. package/lib/native-termination.js +57 -0
  72. package/lib/native-termination.js.map +1 -0
  73. package/lib/native-web-owner.d.ts +97 -0
  74. package/lib/native-web-owner.d.ts.map +1 -0
  75. package/lib/native-web-owner.js +338 -0
  76. package/lib/native-web-owner.js.map +1 -0
  77. package/lib/operator-snapshot.d.ts +107 -0
  78. package/lib/operator-snapshot.d.ts.map +1 -0
  79. package/lib/operator-snapshot.js +1013 -0
  80. package/lib/operator-snapshot.js.map +1 -0
  81. package/lib/operator.d.ts +25 -0
  82. package/lib/operator.d.ts.map +1 -0
  83. package/lib/operator.js +48 -0
  84. package/lib/operator.js.map +1 -0
  85. package/lib/progress-attention.d.ts +55 -0
  86. package/lib/progress-attention.d.ts.map +1 -0
  87. package/lib/progress-attention.js +128 -0
  88. package/lib/progress-attention.js.map +1 -0
  89. package/lib/reply-replay.d.ts +52 -0
  90. package/lib/reply-replay.d.ts.map +1 -0
  91. package/lib/reply-replay.js +122 -0
  92. package/lib/reply-replay.js.map +1 -0
  93. package/lib/restart-native.d.ts +47 -0
  94. package/lib/restart-native.d.ts.map +1 -0
  95. package/lib/restart-native.js +170 -0
  96. package/lib/restart-native.js.map +1 -0
  97. package/lib/restart-runtime.d.ts +38 -0
  98. package/lib/restart-runtime.d.ts.map +1 -0
  99. package/lib/restart-runtime.js +335 -0
  100. package/lib/restart-runtime.js.map +1 -0
  101. package/lib/restart-store.d.ts +132 -0
  102. package/lib/restart-store.d.ts.map +1 -0
  103. package/lib/restart-store.js +757 -0
  104. package/lib/restart-store.js.map +1 -0
  105. package/lib/restart-supervisor.d.ts +129 -0
  106. package/lib/restart-supervisor.d.ts.map +1 -0
  107. package/lib/restart-supervisor.js +615 -0
  108. package/lib/restart-supervisor.js.map +1 -0
  109. package/lib/service.d.ts +1279 -0
  110. package/lib/service.d.ts.map +1 -0
  111. package/lib/service.js +8694 -0
  112. package/lib/service.js.map +1 -0
  113. package/lib/session-commands.d.ts +52 -0
  114. package/lib/session-commands.d.ts.map +1 -0
  115. package/lib/session-commands.js +180 -0
  116. package/lib/session-commands.js.map +1 -0
  117. package/lib/session-lease-runtime.d.ts +70 -0
  118. package/lib/session-lease-runtime.d.ts.map +1 -0
  119. package/lib/session-lease-runtime.js +395 -0
  120. package/lib/session-lease-runtime.js.map +1 -0
  121. package/lib/session-lease-types.d.ts +27 -0
  122. package/lib/session-lease-types.d.ts.map +1 -0
  123. package/lib/session-lease-types.js +2 -0
  124. package/lib/session-lease-types.js.map +1 -0
  125. package/lib/sqlite.d.ts +8 -0
  126. package/lib/sqlite.d.ts.map +1 -0
  127. package/lib/sqlite.js +1665 -0
  128. package/lib/sqlite.js.map +1 -0
  129. package/lib/store.d.ts +1267 -0
  130. package/lib/store.d.ts.map +1 -0
  131. package/lib/store.js +8039 -0
  132. package/lib/store.js.map +1 -0
  133. package/lib/tools.d.ts +4 -0
  134. package/lib/tools.d.ts.map +1 -0
  135. package/lib/tools.js +73 -0
  136. package/lib/tools.js.map +1 -0
  137. package/lib/types.d.ts +1091 -0
  138. package/lib/types.d.ts.map +1 -0
  139. package/lib/types.js +10 -0
  140. package/lib/types.js.map +1 -0
  141. package/lib/version-query.d.ts +77 -0
  142. package/lib/version-query.d.ts.map +1 -0
  143. package/lib/version-query.js +2208 -0
  144. package/lib/version-query.js.map +1 -0
  145. package/lib/version.d.ts +2 -0
  146. package/lib/version.d.ts.map +1 -0
  147. package/lib/version.js +2 -0
  148. package/lib/version.js.map +1 -0
  149. package/lib/work-item-engineering-context.d.ts +127 -0
  150. package/lib/work-item-engineering-context.d.ts.map +1 -0
  151. package/lib/work-item-engineering-context.js +151 -0
  152. package/lib/work-item-engineering-context.js.map +1 -0
  153. package/lib/work-item-feedback-schema.d.ts +2 -0
  154. package/lib/work-item-feedback-schema.d.ts.map +1 -0
  155. package/lib/work-item-feedback-schema.js +29 -0
  156. package/lib/work-item-feedback-schema.js.map +1 -0
  157. package/lib/work-item-feedback-store.d.ts +29 -0
  158. package/lib/work-item-feedback-store.d.ts.map +1 -0
  159. package/lib/work-item-feedback-store.js +111 -0
  160. package/lib/work-item-feedback-store.js.map +1 -0
  161. package/lib/work-item-feedback.d.ts +157 -0
  162. package/lib/work-item-feedback.d.ts.map +1 -0
  163. package/lib/work-item-feedback.js +2 -0
  164. package/lib/work-item-feedback.js.map +1 -0
  165. package/lib/work-item-replies-schema.d.ts +3 -0
  166. package/lib/work-item-replies-schema.d.ts.map +1 -0
  167. package/lib/work-item-replies-schema.js +45 -0
  168. package/lib/work-item-replies-schema.js.map +1 -0
  169. package/lib/work-item-replies-store.d.ts +43 -0
  170. package/lib/work-item-replies-store.d.ts.map +1 -0
  171. package/lib/work-item-replies-store.js +203 -0
  172. package/lib/work-item-replies-store.js.map +1 -0
  173. package/lib/work-item-replies.d.ts +93 -0
  174. package/lib/work-item-replies.d.ts.map +1 -0
  175. package/lib/work-item-replies.js +15 -0
  176. package/lib/work-item-replies.js.map +1 -0
  177. package/lib/workflow-auto-producer.d.ts +37 -0
  178. package/lib/workflow-auto-producer.d.ts.map +1 -0
  179. package/lib/workflow-auto-producer.js +58 -0
  180. package/lib/workflow-auto-producer.js.map +1 -0
  181. package/lib/workflow-command.d.ts +16 -0
  182. package/lib/workflow-command.d.ts.map +1 -0
  183. package/lib/workflow-command.js +52 -0
  184. package/lib/workflow-command.js.map +1 -0
  185. package/package.json +174 -4
@@ -0,0 +1,1013 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { closeSync, constants, fstatSync, lstatSync, mkdtempSync, openSync, readdirSync, readSync, realpathSync, rmSync, rmdirSync, statSync, unlinkSync, writeSync, } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import { dirname, isAbsolute, join, basename, resolve } from 'node:path';
5
+ import { pathToFileURL } from 'node:url';
6
+ import { DatabaseSync } from 'node:sqlite';
7
+ import { canonicalConversation, canonicalOwnerRouteAuthority, canonicalPrincipal, externalPrincipalId, ownerRouteAuthorityHash } from './canonical.js';
8
+ import { deliverySchemaVersion } from './sqlite.js';
9
+ function unavailable() { return Object.freeze({ status: 'unavailable' }); }
10
+ function mismatch() { return Object.freeze({ status: 'mismatch' }); }
11
+ function policyRef(value) {
12
+ return typeof value === 'string' && value === value.normalize('NFC').trim() && value.length > 0
13
+ && Buffer.byteLength(value, 'utf8') <= 256 && ![...value].some(character => (character.codePointAt(0) ?? 0) <= 0x1f || character.codePointAt(0) === 0x7f);
14
+ }
15
+ function privateDatabase(path) {
16
+ try {
17
+ if (!isAbsolute(path))
18
+ return undefined;
19
+ const entry = lstatSync(path);
20
+ if (!entry.isFile() || entry.isSymbolicLink() || entry.uid !== process.getuid?.() || (entry.mode & 0o077) !== 0)
21
+ return undefined;
22
+ const parent = realpathSync(dirname(path));
23
+ const resolved = realpathSync(path);
24
+ if (resolved !== join(parent, basename(path)))
25
+ return undefined;
26
+ const directory = statSync(parent);
27
+ if (!directory.isDirectory() || directory.uid !== process.getuid?.() || (directory.mode & 0o077) !== 0)
28
+ return undefined;
29
+ return resolved;
30
+ }
31
+ catch {
32
+ return undefined;
33
+ }
34
+ }
35
+ function number(value, min = 0) { return typeof value === 'number' && Number.isSafeInteger(value) && value >= min; }
36
+ function equal(left, right) { return JSON.stringify(left) === JSON.stringify(right); }
37
+ function identifier(value, prefix) { return typeof value === 'string' && new RegExp(`^${prefix}[0-9a-f-]{8,}$`, 'u').test(value); }
38
+ function inspectRow(input, expected, row) {
39
+ if (row.lease_state !== null && row.lease_state !== 'released')
40
+ return Object.freeze({ status: 'busy' });
41
+ const conversation = canonicalConversation(JSON.parse(row.conversation_json));
42
+ const bindingPrincipal = canonicalPrincipal(JSON.parse(row.binding_principal_json));
43
+ const ownerPrincipal = canonicalPrincipal(JSON.parse(row.owner_principal_json));
44
+ const expectedConversation = { channel: 'web', account: expected.account, tenant: expected.tenant, kind: 'dm', chat: input.sessionId };
45
+ if (row.conversation_json !== JSON.stringify(conversation) || row.binding_principal_json !== JSON.stringify(bindingPrincipal) || row.owner_principal_json !== JSON.stringify(ownerPrincipal)
46
+ || !equal(conversation, expectedConversation) || row.session_id !== input.sessionId || !identifier(row.binding_id, 'binding_') || !identifier(row.owner_id, 'principal_')
47
+ || bindingPrincipal.channel !== 'web' || !equal(bindingPrincipal, expected) || !equal(ownerPrincipal, expected)
48
+ || row.binding_status !== 'active' || row.owner_role !== 'owner' || row.owner_status !== 'active' || row.linked_to_id !== null
49
+ || row.workspace !== input.workspace || row.agent_preset !== input.agentPreset || !policyRef(row.policy_ref)
50
+ || ![row.generation, row.binding_version, row.owner_version].every(value => number(value, 1))
51
+ || ![row.binding_created_at, row.binding_updated_at, row.owner_created_at, row.owner_updated_at].every(value => number(value)))
52
+ return mismatch();
53
+ const binding = Object.freeze({ id: row.binding_id, conversation: Object.freeze(conversation), principal: Object.freeze(bindingPrincipal), workspace: row.workspace,
54
+ agentPreset: row.agent_preset, sessionId: row.session_id, generation: row.generation, policyRef: row.policy_ref, status: 'active', createdAt: row.binding_created_at, updatedAt: row.binding_updated_at, version: row.binding_version });
55
+ const owner = Object.freeze({ id: row.owner_id, principal: Object.freeze(ownerPrincipal), role: 'owner', status: 'active', createdAt: row.owner_created_at, updatedAt: row.owner_updated_at, version: row.owner_version });
56
+ return Object.freeze({ status: 'matched', snapshot: Object.freeze({ binding, owner }) });
57
+ }
58
+ /**
59
+ * Opens an already-existing Delivery database read-only. It never invokes the Delivery migrator,
60
+ * creates a database, pairs an owner, reads message content, or acquires a Session lease.
61
+ */
62
+ export function inspectActiveWebOwnerBindingLocally(input) {
63
+ let expected;
64
+ try {
65
+ expected = canonicalPrincipal(input.expectedPrincipal);
66
+ if (expected.channel !== 'web' || !isAbsolute(input.workspace) || typeof input.agentPreset !== 'string' || input.agentPreset.length === 0 || typeof input.sessionId !== 'string' || input.sessionId.length === 0)
67
+ return mismatch();
68
+ }
69
+ catch {
70
+ return mismatch();
71
+ }
72
+ const path = privateDatabase(input.databasePath);
73
+ if (path === undefined)
74
+ return unavailable();
75
+ let database;
76
+ try {
77
+ database = new DatabaseSync(path, { readOnly: true });
78
+ database.exec('PRAGMA query_only = ON; PRAGMA busy_timeout = 100');
79
+ database.exec('BEGIN');
80
+ const version = database.prepare('PRAGMA user_version').get();
81
+ if (version.user_version !== deliverySchemaVersion)
82
+ return unavailable();
83
+ const rows = database.prepare(`
84
+ SELECT binding.id AS binding_id, binding.conversation_json, binding.principal_json AS binding_principal_json,
85
+ binding.workspace, binding.agent_preset, binding.session_id, binding.generation, binding.policy_ref,
86
+ binding.status AS binding_status, binding.created_at AS binding_created_at, binding.updated_at AS binding_updated_at, binding.version AS binding_version,
87
+ owner.id AS owner_id, owner.principal_json AS owner_principal_json, owner.role AS owner_role, owner.status AS owner_status,
88
+ owner.linked_to_id, owner.created_at AS owner_created_at, owner.updated_at AS owner_updated_at, owner.version AS owner_version,
89
+ lease.state AS lease_state
90
+ FROM conversation_bindings AS binding
91
+ JOIN delivery_principals AS owner ON owner.id = binding.principal_id
92
+ LEFT JOIN delivery_session_leases AS lease ON lease.session_id = binding.session_id
93
+ WHERE binding.session_id = ?
94
+ LIMIT 2
95
+ `).all(input.sessionId);
96
+ if (rows.length !== 1)
97
+ return mismatch();
98
+ const row = rows[0];
99
+ return inspectRow(input, expected, row);
100
+ }
101
+ catch (error) {
102
+ if (error instanceof Error && /(?:busy|locked)/iu.test(error.message))
103
+ return Object.freeze({ status: 'busy' });
104
+ return unavailable();
105
+ }
106
+ finally {
107
+ try {
108
+ database?.exec('ROLLBACK');
109
+ }
110
+ catch { }
111
+ try {
112
+ database?.close();
113
+ }
114
+ catch { }
115
+ }
116
+ }
117
+ /** Bounded operator discovery in one read-only snapshot; it creates no sessions or bindings. */
118
+ export function listActiveIdleWebOwnerBindingsLocally(input) {
119
+ let expected;
120
+ try {
121
+ expected = canonicalPrincipal(input.expectedPrincipal);
122
+ if (expected.channel !== 'web' || !isAbsolute(input.workspace) || typeof input.agentPreset !== 'string' || !input.agentPreset)
123
+ return { status: 'unavailable', reason: 'invalid-scope' };
124
+ }
125
+ catch {
126
+ return { status: 'unavailable', reason: 'invalid-scope' };
127
+ }
128
+ const path = privateDatabase(input.databasePath);
129
+ if (!path)
130
+ return { status: 'unavailable', reason: 'snapshot-unavailable' };
131
+ let database;
132
+ try {
133
+ database = new DatabaseSync(path, { readOnly: true });
134
+ database.exec('PRAGMA query_only = ON; PRAGMA busy_timeout = 100; BEGIN');
135
+ if (database.prepare('PRAGMA user_version').get().user_version !== deliverySchemaVersion)
136
+ return { status: 'unavailable', reason: 'snapshot-unavailable' };
137
+ const rows = database.prepare(`
138
+ SELECT binding.id AS binding_id, binding.conversation_json, binding.principal_json AS binding_principal_json,
139
+ binding.workspace, binding.agent_preset, binding.session_id, binding.generation, binding.policy_ref,
140
+ binding.status AS binding_status, binding.created_at AS binding_created_at, binding.updated_at AS binding_updated_at, binding.version AS binding_version,
141
+ owner.id AS owner_id, owner.principal_json AS owner_principal_json, owner.role AS owner_role, owner.status AS owner_status,
142
+ owner.linked_to_id, owner.created_at AS owner_created_at, owner.updated_at AS owner_updated_at, owner.version AS owner_version,
143
+ lease.state AS lease_state
144
+ FROM conversation_bindings AS binding
145
+ JOIN delivery_principals AS owner ON owner.id = binding.principal_id
146
+ LEFT JOIN delivery_session_leases AS lease ON lease.session_id = binding.session_id
147
+ WHERE owner.principal_json = ? AND binding.workspace = ? AND binding.agent_preset = ?
148
+ AND owner.role = 'owner' AND owner.status = 'active' AND binding.status = 'active'
149
+ AND (lease.state IS NULL OR lease.state = 'released')
150
+ ORDER BY binding.session_id LIMIT 101
151
+ `).all(JSON.stringify(expected), input.workspace, input.agentPreset);
152
+ if (rows.length > 100)
153
+ return { status: 'unavailable', reason: 'too-many-sessions' };
154
+ const snapshots = [];
155
+ const seen = new Set();
156
+ for (const row of rows) {
157
+ if (seen.has(row.session_id))
158
+ return { status: 'unavailable', reason: 'snapshot-unavailable' };
159
+ const checked = inspectRow({ ...input, sessionId: row.session_id }, expected, row);
160
+ if (checked.status !== 'matched')
161
+ return { status: 'unavailable', reason: 'snapshot-unavailable' };
162
+ seen.add(row.session_id);
163
+ snapshots.push(checked.snapshot);
164
+ }
165
+ return Object.freeze({ status: 'matched', snapshots: Object.freeze(snapshots) });
166
+ }
167
+ catch {
168
+ return { status: 'unavailable', reason: 'snapshot-unavailable' };
169
+ }
170
+ finally {
171
+ try {
172
+ database?.exec('ROLLBACK');
173
+ }
174
+ catch { }
175
+ try {
176
+ database?.close();
177
+ }
178
+ catch { }
179
+ }
180
+ }
181
+ export const activeLarkOwnerBindingsSnapshotProtocol = 'assistant-delivery/active-lark-owner-bindings-snapshot/v1';
182
+ export const revokedOwnerRouteSnapshotProtocol = 'assistant-delivery/revoked-owner-route-snapshot/v1';
183
+ export class ActiveLarkOwnerBindingsSnapshotError extends Error {
184
+ code;
185
+ constructor(code, message) {
186
+ super(message);
187
+ this.code = code;
188
+ this.name = 'ActiveLarkOwnerBindingsSnapshotError';
189
+ }
190
+ }
191
+ const operatorDigestPattern = /^[a-f0-9]{64}$/u;
192
+ const operatorKeyPattern = /^[A-Za-z0-9][A-Za-z0-9._@/-]{0,255}$/u;
193
+ const operatorMaximumBindings = 100;
194
+ const operatorBufferBytes = 64 * 1024;
195
+ function operatorFail(code, message) {
196
+ throw new ActiveLarkOwnerBindingsSnapshotError(code, `delivery Lark owner snapshot: ${message}`);
197
+ }
198
+ function operatorFreeze(value) {
199
+ if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) {
200
+ for (const child of Object.values(value))
201
+ operatorFreeze(child);
202
+ Object.freeze(value);
203
+ }
204
+ return value;
205
+ }
206
+ function operatorCanonicalJson(value) {
207
+ if (value === null || typeof value !== 'object')
208
+ return JSON.stringify(value);
209
+ if (Array.isArray(value))
210
+ return `[${value.map(operatorCanonicalJson).join(',')}]`;
211
+ const record = value;
212
+ return `{${Object.keys(record).sort().map(key => `${JSON.stringify(key)}:${operatorCanonicalJson(record[key])}`).join(',')}}`;
213
+ }
214
+ function operatorSha256(value) {
215
+ return createHash('sha256').update(value).digest('hex');
216
+ }
217
+ function operatorSameFile(left, right) {
218
+ return left.dev === right.dev && left.ino === right.ino && left.size === right.size
219
+ && left.mtimeNs === right.mtimeNs && left.ctimeNs === right.ctimeNs
220
+ && left.mode === right.mode && left.uid === right.uid && left.nlink === right.nlink;
221
+ }
222
+ function operatorDigestDescriptor(descriptor, size) {
223
+ const hash = createHash('sha256');
224
+ const buffer = Buffer.allocUnsafe(operatorBufferBytes);
225
+ let position = 0n;
226
+ while (position < size) {
227
+ const remaining = size - position;
228
+ const length = Number(remaining > BigInt(buffer.length) ? BigInt(buffer.length) : remaining);
229
+ const count = readSync(descriptor, buffer, 0, length, Number(position));
230
+ if (count <= 0)
231
+ operatorFail('database-drift', 'a storage file changed while it was hashed');
232
+ hash.update(buffer.subarray(0, count));
233
+ position += BigInt(count);
234
+ }
235
+ return hash.digest('hex');
236
+ }
237
+ function operatorFileIdentity(file) {
238
+ return operatorFreeze({
239
+ device: file.stat.dev.toString(), inode: file.stat.ino.toString(), size: file.stat.size.toString(),
240
+ mtimeNs: file.stat.mtimeNs.toString(), digest: file.digest,
241
+ });
242
+ }
243
+ function operatorPinPrivateParent(path) {
244
+ let descriptor;
245
+ try {
246
+ descriptor = openSync(path, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
247
+ }
248
+ catch (error) {
249
+ if (error.code === 'ENOENT') {
250
+ operatorFail('database-missing', 'database parent disappeared before the snapshot');
251
+ }
252
+ operatorFail('unsafe-parent', 'database parent is unavailable');
253
+ }
254
+ try {
255
+ const pathname = lstatSync(path, { bigint: true });
256
+ const metadata = fstatSync(descriptor, { bigint: true });
257
+ const uid = process.getuid?.();
258
+ const physical = realpathSync(path);
259
+ if (!pathname.isDirectory() || pathname.isSymbolicLink() || !metadata.isDirectory()
260
+ || pathname.dev !== metadata.dev || pathname.ino !== metadata.ino || physical !== path
261
+ || uid === undefined || metadata.uid !== BigInt(uid)
262
+ || (metadata.mode & 3647n) !== 0n || (metadata.mode & 320n) !== 320n) {
263
+ operatorFail('unsafe-parent', 'database parent must be a private owner directory without symlinks');
264
+ }
265
+ const pinned = { path, descriptor, device: metadata.dev, inode: metadata.ino, mode: metadata.mode };
266
+ descriptor = undefined;
267
+ return pinned;
268
+ }
269
+ catch (error) {
270
+ if (error instanceof ActiveLarkOwnerBindingsSnapshotError)
271
+ throw error;
272
+ operatorFail('unsafe-parent', 'database parent cannot be resolved');
273
+ }
274
+ finally {
275
+ if (descriptor !== undefined)
276
+ closeSync(descriptor);
277
+ }
278
+ throw new Error('unreachable');
279
+ }
280
+ function operatorPinnedParentMatches(parent) {
281
+ try {
282
+ const pathname = lstatSync(parent.path, { bigint: true });
283
+ const descriptor = fstatSync(parent.descriptor, { bigint: true });
284
+ return pathname.isDirectory() && !pathname.isSymbolicLink() && descriptor.isDirectory()
285
+ && pathname.dev === parent.device && pathname.ino === parent.inode
286
+ && descriptor.dev === parent.device && descriptor.ino === parent.inode
287
+ && descriptor.mode === parent.mode;
288
+ }
289
+ catch {
290
+ return false;
291
+ }
292
+ }
293
+ // Inode binding is enforced through Linux /proc/self/fd. On other platforms the
294
+ // snapshot keeps its historical path-based pinning; CI still exercises that code.
295
+ const operatorInodeBindSupported = process.platform === 'linux';
296
+ const operatorProcSelfFd = '/proc/self/fd';
297
+ /**
298
+ * Enumerate the regular-file inodes held by THIS process, excluding the
299
+ * descriptors the snapshot pinned itself. After the exclusion the only
300
+ * remaining database fds are SQLite's, so a (dev,ino) match proves the
301
+ * connection genuinely opened the pinned inode rather than an attacker's
302
+ * same-name replacement. An attacker in another process cannot plant an fd
303
+ * here because /proc/self/fd never lists another process's descriptors.
304
+ */
305
+ function operatorConnectionInodes(exclude) {
306
+ let entries;
307
+ try {
308
+ entries = readdirSync(operatorProcSelfFd);
309
+ }
310
+ catch {
311
+ operatorFail('database-corrupt', 'cannot inspect the database connection file descriptors');
312
+ }
313
+ const inodes = [];
314
+ for (const entry of entries) {
315
+ const descriptor = Number(entry);
316
+ if (!Number.isInteger(descriptor) || descriptor <= 2 || exclude.has(descriptor))
317
+ continue;
318
+ let stat;
319
+ try {
320
+ stat = fstatSync(descriptor, { bigint: true });
321
+ }
322
+ catch {
323
+ continue;
324
+ } // transient/closed fd
325
+ if (stat.isFile())
326
+ inodes.push({ device: stat.dev, inode: stat.ino });
327
+ }
328
+ return inodes;
329
+ }
330
+ function operatorAssertConnectionBound(files, exclude) {
331
+ const held = operatorConnectionInodes(exclude);
332
+ for (const file of files) {
333
+ if (!held.some(inode => inode.device === file.stat.dev && inode.inode === file.stat.ino)) {
334
+ operatorFail('database-drift', 'database connection is not bound to the pinned inode');
335
+ }
336
+ }
337
+ }
338
+ /** Pin the private mkdtemp copy directory itself so a same-name swap cannot retarget the copies. */
339
+ function operatorPinTempDirectory(path) {
340
+ let descriptor;
341
+ try {
342
+ descriptor = openSync(path, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
343
+ const linked = lstatSync(path, { bigint: true });
344
+ const opened = fstatSync(descriptor, { bigint: true });
345
+ const uid = process.getuid?.();
346
+ if (!linked.isDirectory() || linked.isSymbolicLink() || !opened.isDirectory()
347
+ || linked.dev !== opened.dev || linked.ino !== opened.ino
348
+ || (opened.mode & 4095n) !== 448n
349
+ || uid === undefined || opened.uid !== BigInt(uid)) {
350
+ operatorFail('unsafe-path', 'temporary snapshot directory cannot be pinned');
351
+ }
352
+ const pinned = { path, descriptor, device: opened.dev, inode: opened.ino };
353
+ descriptor = undefined;
354
+ return pinned;
355
+ }
356
+ catch (error) {
357
+ if (error instanceof ActiveLarkOwnerBindingsSnapshotError)
358
+ throw error;
359
+ operatorFail('unsafe-path', 'temporary snapshot directory cannot be pinned');
360
+ }
361
+ finally {
362
+ if (descriptor !== undefined)
363
+ try {
364
+ closeSync(descriptor);
365
+ }
366
+ catch { }
367
+ }
368
+ throw new Error('unreachable');
369
+ }
370
+ /**
371
+ * Materialise one private byte-for-byte copy THROUGH the pinned directory fd
372
+ * (`/proc/self/fd/<dirfd>/<name>`), then reopen it O_NOFOLLOW through the same
373
+ * anchor and keep that descriptor open. Neither the create, the verify, the
374
+ * SQLite open, or the cleanup ever resolve a swappable path component, so a
375
+ * same-name directory swap cannot retarget the replica. The returned file is
376
+ * left open and must be closed by the caller.
377
+ */
378
+ function operatorCopyAndPin(source, targetRef) {
379
+ const buffer = Buffer.allocUnsafe(operatorBufferBytes);
380
+ let destination;
381
+ try {
382
+ destination = openSync(targetRef, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, 0o600);
383
+ let position = 0n;
384
+ while (position < source.stat.size) {
385
+ const remaining = source.stat.size - position;
386
+ const length = Number(remaining > BigInt(buffer.length) ? BigInt(buffer.length) : remaining);
387
+ const count = readSync(source.descriptor, buffer, 0, length, Number(position));
388
+ if (count <= 0)
389
+ operatorFail('database-drift', `${basename(source.path)} changed while it was copied`);
390
+ let written = 0;
391
+ while (written < count)
392
+ written += writeSync(destination, buffer, written, count - written);
393
+ position += BigInt(count);
394
+ }
395
+ }
396
+ catch (error) {
397
+ if (destination !== undefined)
398
+ try {
399
+ closeSync(destination);
400
+ }
401
+ catch { }
402
+ if (error instanceof ActiveLarkOwnerBindingsSnapshotError)
403
+ throw error;
404
+ throw error;
405
+ }
406
+ if (destination !== undefined)
407
+ closeSync(destination);
408
+ const copied = operatorOpenPrivateFile(targetRef, false);
409
+ if (copied.stat.size !== source.stat.size || copied.digest !== source.digest) {
410
+ try {
411
+ closeSync(copied.descriptor);
412
+ }
413
+ catch { }
414
+ operatorFail('database-drift', `${basename(source.path)} copy does not match its pinned source`);
415
+ }
416
+ return copied;
417
+ }
418
+ /**
419
+ * Remove the replica THROUGH the pinned directory fd, unlinking only the fixed
420
+ * names SQLite could create. The directory itself is rmdir'd by path only after
421
+ * the pinned fd proves the path still names the same empty inode; a swapped or
422
+ * non-empty directory is left untouched and the snapshot fails closed rather
423
+ * than recursively deleting an attacker-controlled replacement.
424
+ */
425
+ function operatorRemovePinnedTemp(pinned, names) {
426
+ const anchor = `${operatorProcSelfFd}/${pinned.descriptor}`;
427
+ for (const name of names) {
428
+ try {
429
+ unlinkSync(`${anchor}/${name}`);
430
+ }
431
+ catch (error) {
432
+ if (error.code !== 'ENOENT') {
433
+ operatorFail('database-drift', 'temporary snapshot copy cannot be removed through its pinned directory');
434
+ }
435
+ }
436
+ }
437
+ let entries;
438
+ try {
439
+ entries = readdirSync(anchor);
440
+ }
441
+ catch {
442
+ operatorFail('database-drift', 'temporary snapshot directory became unavailable');
443
+ }
444
+ if (entries.length !== 0)
445
+ operatorFail('database-drift', 'temporary snapshot directory contains unexpected entries');
446
+ const linked = lstatSync(pinned.path, { bigint: true });
447
+ const opened = fstatSync(pinned.descriptor, { bigint: true });
448
+ if (linked.dev !== pinned.device || linked.ino !== pinned.inode
449
+ || opened.dev !== pinned.device || opened.ino !== pinned.inode) {
450
+ operatorFail('database-drift', 'temporary snapshot directory was retargeted before cleanup');
451
+ }
452
+ closeSync(pinned.descriptor);
453
+ try {
454
+ rmdirSync(pinned.path);
455
+ }
456
+ catch (error) {
457
+ if (error.code !== 'ENOENT') {
458
+ operatorFail('database-drift', 'temporary snapshot directory could not be removed');
459
+ }
460
+ }
461
+ }
462
+ function operatorOpenPrivateFile(path, missing) {
463
+ let linked;
464
+ try {
465
+ linked = lstatSync(path, { bigint: true });
466
+ }
467
+ catch (error) {
468
+ if (missing && error.code === 'ENOENT')
469
+ operatorFail('database-missing', 'database does not exist');
470
+ operatorFail('unsafe-path', `${basename(path)} cannot be inspected`);
471
+ }
472
+ const uid = process.getuid?.();
473
+ if (!linked.isFile() || linked.isSymbolicLink() || linked.nlink !== 1n
474
+ || (linked.mode & 4095n) !== 384n
475
+ || (uid !== undefined && linked.uid !== BigInt(uid))
476
+ || linked.size > BigInt(Number.MAX_SAFE_INTEGER)) {
477
+ operatorFail('unsafe-path', `${basename(path)} must be one private owned regular file`);
478
+ }
479
+ let descriptor;
480
+ try {
481
+ descriptor = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
482
+ }
483
+ catch {
484
+ operatorFail('unsafe-path', `${basename(path)} cannot be opened safely`);
485
+ }
486
+ try {
487
+ const opened = fstatSync(descriptor, { bigint: true });
488
+ const after = lstatSync(path, { bigint: true });
489
+ if (!operatorSameFile(linked, opened) || !operatorSameFile(opened, after)) {
490
+ operatorFail('database-drift', `${basename(path)} changed while it was opened`);
491
+ }
492
+ const digest = operatorDigestDescriptor(descriptor, opened.size);
493
+ if (!operatorSameFile(opened, fstatSync(descriptor, { bigint: true }))) {
494
+ operatorFail('database-drift', `${basename(path)} changed while it was hashed`);
495
+ }
496
+ return { path, descriptor, stat: opened, digest };
497
+ }
498
+ catch (error) {
499
+ closeSync(descriptor);
500
+ throw error;
501
+ }
502
+ }
503
+ function operatorOptionalFile(path) {
504
+ try {
505
+ lstatSync(path);
506
+ }
507
+ catch (error) {
508
+ if (error.code === 'ENOENT')
509
+ return null;
510
+ operatorFail('unsafe-path', `${basename(path)} cannot be inspected`);
511
+ }
512
+ return operatorOpenPrivateFile(path, false);
513
+ }
514
+ function operatorPinnedFileIdentityMatches(file) {
515
+ try {
516
+ const pathname = lstatSync(file.path, { bigint: true });
517
+ const opened = fstatSync(file.descriptor, { bigint: true });
518
+ return pathname.isFile() && !pathname.isSymbolicLink()
519
+ && pathname.dev === file.stat.dev && pathname.ino === file.stat.ino
520
+ && opened.dev === file.stat.dev && opened.ino === file.stat.ino;
521
+ }
522
+ catch {
523
+ return false;
524
+ }
525
+ }
526
+ function operatorAssertUnchanged(file) {
527
+ try {
528
+ const linked = lstatSync(file.path, { bigint: true });
529
+ const opened = fstatSync(file.descriptor, { bigint: true });
530
+ if (!operatorSameFile(file.stat, linked) || !operatorSameFile(file.stat, opened)
531
+ || operatorDigestDescriptor(file.descriptor, opened.size) !== file.digest) {
532
+ operatorFail('database-drift', `${basename(file.path)} changed during the snapshot`);
533
+ }
534
+ }
535
+ catch (error) {
536
+ if (error instanceof ActiveLarkOwnerBindingsSnapshotError)
537
+ throw error;
538
+ operatorFail('database-drift', `${basename(file.path)} changed during the snapshot`);
539
+ }
540
+ }
541
+ function operatorAssertSidecar(path, file) {
542
+ if (file !== null)
543
+ return operatorAssertUnchanged(file);
544
+ try {
545
+ lstatSync(path);
546
+ operatorFail('database-drift', `${basename(path)} appeared during the snapshot`);
547
+ }
548
+ catch (error) {
549
+ if (error instanceof ActiveLarkOwnerBindingsSnapshotError)
550
+ throw error;
551
+ if (error.code !== 'ENOENT') {
552
+ operatorFail('database-drift', `${basename(path)} changed during the snapshot`);
553
+ }
554
+ }
555
+ }
556
+ function operatorDatabasePath(path) {
557
+ if (typeof path !== 'string' || !isAbsolute(path) || resolve(path) !== path || path === '/'
558
+ || path !== path.normalize('NFC') || /[\p{Cc}]/u.test(path)) {
559
+ operatorFail('invalid-path', 'database path must be canonical and absolute');
560
+ }
561
+ let physical;
562
+ try {
563
+ physical = realpathSync(path);
564
+ }
565
+ catch (error) {
566
+ if (error.code === 'ENOENT')
567
+ operatorFail('database-missing', 'database does not exist');
568
+ operatorFail('unsafe-path', 'database path cannot be resolved');
569
+ }
570
+ let parentPhysical;
571
+ try {
572
+ parentPhysical = realpathSync(dirname(path));
573
+ }
574
+ catch (error) {
575
+ if (error.code === 'ENOENT')
576
+ operatorFail('database-missing', 'database parent disappeared');
577
+ operatorFail('unsafe-path', 'database parent cannot be resolved');
578
+ }
579
+ if (physical !== path || parentPhysical !== dirname(path)) {
580
+ operatorFail('unsafe-path', 'database path must not traverse a symbolic link');
581
+ }
582
+ return physical;
583
+ }
584
+ function operatorScope(input) {
585
+ const validKey = (value) => typeof value === 'string' && value === value.normalize('NFC').trim()
586
+ && operatorKeyPattern.test(value);
587
+ const validText = (value, maximum) => typeof value === 'string' && value.length > 0
588
+ && value === value.normalize('NFC').trim() && Buffer.byteLength(value, 'utf8') <= maximum
589
+ && !/[\p{Cc}]/u.test(value);
590
+ if (!validKey(input.account) || !validKey(input.tenant)
591
+ || !validText(input.workspace, 4_096) || !isAbsolute(input.workspace) || resolve(input.workspace) !== input.workspace
592
+ || !validText(input.agentPreset, 128))
593
+ operatorFail('invalid-scope', 'query scope is invalid');
594
+ return operatorFreeze({ account: input.account, tenant: input.tenant, workspace: input.workspace, agentPreset: input.agentPreset });
595
+ }
596
+ function operatorCopyFile(source, target) {
597
+ const buffer = Buffer.allocUnsafe(operatorBufferBytes);
598
+ let destination;
599
+ try {
600
+ destination = openSync(target, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, 0o600);
601
+ let position = 0n;
602
+ while (position < source.stat.size) {
603
+ const remaining = source.stat.size - position;
604
+ const length = Number(remaining > BigInt(buffer.length) ? BigInt(buffer.length) : remaining);
605
+ const count = readSync(source.descriptor, buffer, 0, length, Number(position));
606
+ if (count <= 0)
607
+ operatorFail('database-drift', `${basename(source.path)} changed while it was copied`);
608
+ let written = 0;
609
+ while (written < count)
610
+ written += writeSync(destination, buffer, written, count - written);
611
+ position += BigInt(count);
612
+ }
613
+ }
614
+ finally {
615
+ if (destination !== undefined)
616
+ closeSync(destination);
617
+ }
618
+ // Close the write window, then re-open the private copy as an independent
619
+ // file and prove its bytes equal the pinned source before it is ever read.
620
+ const copied = operatorOpenPrivateFile(target, false);
621
+ try {
622
+ if (copied.stat.size !== source.stat.size || copied.digest !== source.digest) {
623
+ operatorFail('database-drift', `${basename(source.path)} copy does not match its pinned source`);
624
+ }
625
+ }
626
+ finally {
627
+ closeSync(copied.descriptor);
628
+ }
629
+ }
630
+ function operatorText(value, maximum) {
631
+ return typeof value === 'string' && value.length > 0 && value === value.normalize('NFC').trim()
632
+ && Buffer.byteLength(value, 'utf8') <= maximum && !/[\p{Cc}]/u.test(value);
633
+ }
634
+ function operatorInteger(value, minimum = 0) {
635
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= minimum;
636
+ }
637
+ function operatorBinding(row, scope) {
638
+ let conversation;
639
+ let principal;
640
+ try {
641
+ if (typeof row.conversation_json !== 'string' || typeof row.binding_principal_json !== 'string'
642
+ || typeof row.owner_principal_json !== 'string')
643
+ throw new Error('invalid JSON metadata');
644
+ conversation = canonicalConversation(JSON.parse(row.conversation_json));
645
+ principal = canonicalPrincipal(JSON.parse(row.binding_principal_json));
646
+ const ownerPrincipal = canonicalPrincipal(JSON.parse(row.owner_principal_json));
647
+ if (row.conversation_json !== JSON.stringify(conversation)
648
+ || row.binding_principal_json !== JSON.stringify(principal)
649
+ || row.owner_principal_json !== JSON.stringify(ownerPrincipal)
650
+ || !equal(principal, ownerPrincipal))
651
+ throw new Error('non-canonical identity metadata');
652
+ }
653
+ catch {
654
+ return operatorFail('database-corrupt', 'a matching binding has invalid canonical identity metadata');
655
+ }
656
+ if (conversation.channel !== 'lark' || conversation.account !== scope.account
657
+ || conversation.tenant !== scope.tenant || conversation.kind !== 'dm' || conversation.thread !== undefined
658
+ || principal.channel !== 'lark' || principal.account !== scope.account || principal.tenant !== scope.tenant
659
+ || row.workspace !== scope.workspace || row.agent_preset !== scope.agentPreset
660
+ || row.binding_status !== 'active' || row.owner_role !== 'owner' || row.owner_status !== 'active'
661
+ || row.linked_to_id !== null || !identifier(row.binding_id, 'binding_') || !identifier(row.owner_id, 'principal_')
662
+ || row.principal_id !== row.owner_id || !operatorDigestPattern.test(String(row.conversation_hash))
663
+ || !operatorDigestPattern.test(String(row.owner_key_hash))
664
+ || row.conversation_hash !== operatorSha256(row.conversation_json)
665
+ || row.owner_key_hash !== operatorSha256(row.owner_principal_json)
666
+ || !operatorText(row.session_id, 512) || !operatorText(row.policy_ref, 256)
667
+ || !operatorInteger(row.generation, 1) || !operatorInteger(row.binding_version, 1)
668
+ || !operatorInteger(row.owner_version, 1) || !operatorInteger(row.binding_created_at)
669
+ || !operatorInteger(row.binding_updated_at) || row.binding_updated_at < row.binding_created_at
670
+ || !operatorInteger(row.owner_created_at) || !operatorInteger(row.owner_updated_at)
671
+ || row.owner_updated_at < row.owner_created_at) {
672
+ operatorFail('database-corrupt', 'a matching binding row is inconsistent');
673
+ }
674
+ const owner = { id: row.owner_id, principal, role: 'owner', status: 'active',
675
+ createdAt: row.owner_created_at, updatedAt: row.owner_updated_at, version: row.owner_version };
676
+ return operatorFreeze({
677
+ id: row.binding_id, conversation, principal, workspace: row.workspace, agentPreset: row.agent_preset,
678
+ sessionId: row.session_id, generation: row.generation, policyRef: row.policy_ref, status: 'active',
679
+ createdAt: row.binding_created_at, updatedAt: row.binding_updated_at, version: row.binding_version, owner,
680
+ });
681
+ }
682
+ function operatorClassifySqlite(error) {
683
+ const message = error instanceof Error ? error.message.toLowerCase() : '';
684
+ const code = error.errcode;
685
+ if (code === 5 || code === 6 || /(?:busy|locked)/u.test(message))
686
+ operatorFail('database-busy', 'database is busy');
687
+ operatorFail('database-corrupt', 'database cannot produce a valid snapshot');
688
+ }
689
+ /** Shared source-preserving reader: every operator proof uses the same storage fences. */
690
+ function operatorInspectDatabase(databasePath, inspect) {
691
+ const path = operatorDatabasePath(databasePath);
692
+ // Pin the private parent directory for the whole snapshot so an ancestor
693
+ // rename or a same-name directory swap cannot retarget the database path
694
+ // between the path checks and the read.
695
+ const pinnedParent = operatorPinPrivateParent(dirname(path));
696
+ const walPath = `${path}-wal`;
697
+ const shmPath = `${path}-shm`;
698
+ let source;
699
+ let wal = null;
700
+ let shm = null;
701
+ let temporaryPath;
702
+ let temporaryPinned;
703
+ let copyFiles = [];
704
+ let database;
705
+ let transaction = false;
706
+ let deferred;
707
+ let result;
708
+ // Descriptors the snapshot itself holds; these are excluded when proving that
709
+ // SQLite opened the pinned inode, so the connection can never vouch for itself.
710
+ const selfDescriptors = () => new Set([
711
+ pinnedParent.descriptor, source?.descriptor, wal?.descriptor, shm?.descriptor,
712
+ temporaryPinned?.descriptor, ...copyFiles.map(file => file.descriptor),
713
+ ].filter((descriptor) => descriptor !== undefined));
714
+ try {
715
+ try {
716
+ lstatSync(`${path}-journal`);
717
+ operatorFail('database-busy', 'database has a rollback journal');
718
+ }
719
+ catch (error) {
720
+ if (error instanceof ActiveLarkOwnerBindingsSnapshotError)
721
+ throw error;
722
+ if (error.code !== 'ENOENT')
723
+ operatorFail('unsafe-path', 'rollback journal cannot be inspected');
724
+ }
725
+ source = operatorOpenPrivateFile(path, true);
726
+ wal = operatorOptionalFile(walPath);
727
+ shm = operatorOptionalFile(shmPath);
728
+ if ((wal === null) !== (shm === null))
729
+ operatorFail('database-drift', 'WAL sidecar set is incomplete');
730
+ operatorAssertUnchanged(source);
731
+ operatorAssertSidecar(walPath, wal);
732
+ operatorAssertSidecar(shmPath, shm);
733
+ // Files SQLite must prove it is reading. Without WAL that is the pinned
734
+ // source inode; with WAL it is the pinned private replica inodes.
735
+ let bound = [];
736
+ let target;
737
+ if (wal === null) {
738
+ // Open the pinned descriptor itself by inode (Linux) so a same-name swap
739
+ // cannot retarget the connection; immutable=1 forbids WAL/journal access.
740
+ target = operatorInodeBindSupported
741
+ ? `file://${operatorProcSelfFd}/${source.descriptor}?mode=ro&immutable=1`
742
+ : `${pathToFileURL(path).href}?immutable=1`;
743
+ bound = [source];
744
+ }
745
+ else {
746
+ temporaryPath = mkdtempSync(join(tmpdir(), 'delivery-operator-snapshot-'));
747
+ const temporaryMetadata = lstatSync(temporaryPath, { bigint: true });
748
+ const temporaryUid = process.getuid?.();
749
+ if (!temporaryMetadata.isDirectory() || temporaryMetadata.isSymbolicLink()
750
+ || (temporaryMetadata.mode & 4095n) !== 448n
751
+ || (temporaryUid !== undefined && temporaryMetadata.uid !== BigInt(temporaryUid))) {
752
+ operatorFail('unsafe-path', 'temporary snapshot directory is not private');
753
+ }
754
+ if (operatorInodeBindSupported) {
755
+ temporaryPinned = operatorPinTempDirectory(temporaryPath);
756
+ const anchor = `${operatorProcSelfFd}/${temporaryPinned.descriptor}`;
757
+ const mainRef = `${anchor}/delivery.sqlite`;
758
+ const copiedMain = operatorCopyAndPin(source, mainRef);
759
+ let copiedWal;
760
+ try {
761
+ copiedWal = operatorCopyAndPin(wal, `${mainRef}-wal`);
762
+ }
763
+ catch (error) {
764
+ try {
765
+ closeSync(copiedMain.descriptor);
766
+ }
767
+ catch { }
768
+ ;
769
+ throw error;
770
+ }
771
+ copyFiles = Object.freeze([copiedMain, copiedWal]);
772
+ target = mainRef;
773
+ bound = copyFiles;
774
+ }
775
+ else {
776
+ const copy = join(temporaryPath, 'delivery.sqlite');
777
+ operatorCopyFile(source, copy);
778
+ operatorCopyFile(wal, `${copy}-wal`);
779
+ target = copy;
780
+ }
781
+ operatorAssertUnchanged(source);
782
+ operatorAssertSidecar(walPath, wal);
783
+ operatorAssertSidecar(shmPath, shm);
784
+ }
785
+ if (!operatorPinnedFileIdentityMatches(source)) {
786
+ operatorFail('database-drift', 'database path changed before open');
787
+ }
788
+ database = new DatabaseSync(target, { readOnly: true });
789
+ // The WAL/SHM fds are opened lazily on first query, so right after the
790
+ // constructor only the main database inode can be claimed.
791
+ if (operatorInodeBindSupported)
792
+ operatorAssertConnectionBound([bound[0]], selfDescriptors());
793
+ if (!operatorPinnedFileIdentityMatches(source)) {
794
+ operatorFail('database-drift', 'database path changed during open');
795
+ }
796
+ database.exec('PRAGMA query_only = ON; PRAGMA busy_timeout = 0; BEGIN');
797
+ transaction = true;
798
+ const queryOnly = database.prepare('PRAGMA query_only').get();
799
+ if (queryOnly.query_only !== 1)
800
+ operatorFail('database-corrupt', 'read-only guard was not enabled');
801
+ const version = database.prepare('PRAGMA user_version').get().user_version;
802
+ // A staged upgrade reads owner identity before starting the new Host.
803
+ // v24 adds natural feedback, v25 foreground completion ordering, v26
804
+ // restart fences, v27 progress handles, v28 foreground termination, v29 WorkItems reply sidecars, v30 owner feedback and v31 attention audit.
805
+ // The owner tables read here are unchanged in these six reviewed schemas. Do not accept future versions.
806
+ if (version !== 23 && version !== 24 && version !== 25 && version !== 26 && version !== 27 && version !== 28 && version !== 29 && version !== 30 && version !== 31) {
807
+ operatorFail('schema-unsupported', 'expected schema 23, 24, 25, 26, 27, 28, 29, 30 or 31');
808
+ }
809
+ const quick = database.prepare('PRAGMA quick_check').all();
810
+ if (quick.length !== 1 || quick[0]?.quick_check !== 'ok')
811
+ operatorFail('database-corrupt', 'SQLite quick_check failed');
812
+ if (database.prepare('PRAGMA foreign_key_check').all().length !== 0)
813
+ operatorFail('database-corrupt', 'foreign-key integrity check failed');
814
+ const value = inspect(database);
815
+ // The caller query has opened the WAL/SHM fds; prove all represented inodes.
816
+ if (operatorInodeBindSupported)
817
+ operatorAssertConnectionBound(bound, selfDescriptors());
818
+ database.exec('ROLLBACK');
819
+ transaction = false;
820
+ database.close();
821
+ database = undefined;
822
+ operatorAssertUnchanged(source);
823
+ operatorAssertSidecar(walPath, wal);
824
+ operatorAssertSidecar(shmPath, shm);
825
+ const databaseIdentity = operatorFileIdentity(source);
826
+ const sidecars = operatorFreeze({ wal: wal === null ? null : operatorFileIdentity(wal), shm: shm === null ? null : operatorFileIdentity(shm) });
827
+ const storageDigest = operatorSha256(operatorCanonicalJson({
828
+ protocol: 'assistant-delivery/operator-storage/v1', database: source.digest, wal: wal?.digest ?? null,
829
+ }));
830
+ result = operatorFreeze({ schemaVersion: version, database: databaseIdentity, sidecars, storageDigest, value });
831
+ }
832
+ catch (error) {
833
+ deferred = error;
834
+ }
835
+ finally {
836
+ if (transaction)
837
+ try {
838
+ database?.exec('ROLLBACK');
839
+ }
840
+ catch (error) {
841
+ deferred ??= error;
842
+ }
843
+ try {
844
+ database?.close();
845
+ }
846
+ catch (error) {
847
+ deferred ??= error;
848
+ }
849
+ if (source !== undefined) {
850
+ try {
851
+ operatorAssertUnchanged(source);
852
+ operatorAssertSidecar(walPath, wal);
853
+ operatorAssertSidecar(shmPath, shm);
854
+ }
855
+ catch (error) {
856
+ deferred ??= error;
857
+ }
858
+ }
859
+ if (!operatorPinnedParentMatches(pinnedParent)) {
860
+ deferred = new ActiveLarkOwnerBindingsSnapshotError('unsafe-parent', 'delivery Lark owner snapshot: database parent changed while it was inspected');
861
+ }
862
+ for (const file of [shm, wal, source])
863
+ if (file !== null && file !== undefined) {
864
+ try {
865
+ closeSync(file.descriptor);
866
+ }
867
+ catch { }
868
+ }
869
+ for (const file of copyFiles) {
870
+ try {
871
+ closeSync(file.descriptor);
872
+ }
873
+ catch { }
874
+ }
875
+ if (temporaryPinned !== undefined) {
876
+ try {
877
+ operatorRemovePinnedTemp(temporaryPinned, ['delivery.sqlite', 'delivery.sqlite-wal', 'delivery.sqlite-shm']);
878
+ }
879
+ catch (error) {
880
+ deferred ??= error;
881
+ }
882
+ }
883
+ else if (temporaryPath !== undefined) {
884
+ try {
885
+ rmSync(temporaryPath, { recursive: true, force: true });
886
+ }
887
+ catch (error) {
888
+ deferred ??= error;
889
+ }
890
+ }
891
+ try {
892
+ closeSync(pinnedParent.descriptor);
893
+ }
894
+ catch (error) {
895
+ deferred ??= error;
896
+ }
897
+ }
898
+ if (deferred !== undefined) {
899
+ if (deferred instanceof ActiveLarkOwnerBindingsSnapshotError)
900
+ throw deferred;
901
+ operatorClassifySqlite(deferred);
902
+ }
903
+ return result;
904
+ }
905
+ /**
906
+ * Produces one exact, content-free Lark owner-DM inventory without opening a
907
+ * writable connection to the source. A temporary private byte-for-byte view
908
+ * is used when WAL state exists so SQLite cannot update the source WAL index.
909
+ */
910
+ export function inspectActiveLarkOwnerBindingsLocally(input) {
911
+ const scope = operatorScope(input);
912
+ const snapshot = operatorInspectDatabase(input.databasePath, database => {
913
+ const rows = database.prepare(`
914
+ SELECT binding.id AS binding_id, binding.conversation_hash, binding.conversation_json,
915
+ binding.principal_id, binding.principal_json AS binding_principal_json, binding.workspace,
916
+ binding.agent_preset, binding.session_id, binding.generation, binding.policy_ref,
917
+ binding.status AS binding_status, binding.created_at AS binding_created_at,
918
+ binding.updated_at AS binding_updated_at, binding.version AS binding_version,
919
+ owner.id AS owner_id, owner.key_hash AS owner_key_hash, owner.principal_json AS owner_principal_json,
920
+ owner.role AS owner_role, owner.status AS owner_status, owner.linked_to_id,
921
+ owner.created_at AS owner_created_at, owner.updated_at AS owner_updated_at, owner.version AS owner_version,
922
+ NULL AS lease_state
923
+ FROM conversation_bindings AS binding
924
+ JOIN delivery_principals AS owner ON owner.id = binding.principal_id
925
+ WHERE binding.status = 'active' AND owner.role = 'owner' AND owner.status = 'active'
926
+ AND binding.workspace = ? AND binding.agent_preset = ?
927
+ AND json_extract(owner.principal_json, '$.channel') = 'lark'
928
+ AND json_extract(owner.principal_json, '$.account') = ?
929
+ AND json_extract(owner.principal_json, '$.tenant') = ?
930
+ AND json_extract(binding.conversation_json, '$.channel') = 'lark'
931
+ AND json_extract(binding.conversation_json, '$.account') = ?
932
+ AND json_extract(binding.conversation_json, '$.tenant') = ?
933
+ AND json_extract(binding.conversation_json, '$.kind') = 'dm'
934
+ ORDER BY binding.id COLLATE BINARY
935
+ LIMIT ?
936
+ `).all(scope.workspace, scope.agentPreset, scope.account, scope.tenant, scope.account, scope.tenant, operatorMaximumBindings + 1);
937
+ if (rows.length > operatorMaximumBindings)
938
+ operatorFail('too-many-bindings', `more than ${operatorMaximumBindings} bindings match`);
939
+ return operatorFreeze(rows.map(row => operatorBinding(row, scope)));
940
+ });
941
+ const unsigned = operatorFreeze({
942
+ protocol: activeLarkOwnerBindingsSnapshotProtocol, schemaVersion: snapshot.schemaVersion, scope,
943
+ database: snapshot.database, sidecars: snapshot.sidecars, storageDigest: snapshot.storageDigest, bindings: snapshot.value,
944
+ });
945
+ return operatorFreeze({ ...unsigned, snapshotDigest: operatorSha256(operatorCanonicalJson(unsigned)) });
946
+ }
947
+ /**
948
+ * Observe the exact revoked durable owner using trusted frozen installer
949
+ * authority. No active binding is required, and no permission is granted.
950
+ * Uses the same pinned, source-preserving SQLite reader as the active inventory.
951
+ */
952
+ export function inspectRevokedOwnerRouteLocally(input) {
953
+ try {
954
+ let authority;
955
+ try {
956
+ authority = canonicalOwnerRouteAuthority(input.authority);
957
+ }
958
+ catch {
959
+ return operatorFail('invalid-scope', 'frozen owner authority is invalid');
960
+ }
961
+ if (!operatorText(input.principalRecordId, 128) || !identifier(input.principalRecordId, 'principal_')
962
+ || !operatorInteger(input.frozenPrincipalVersion, 1)) {
963
+ operatorFail('invalid-scope', 'frozen owner lineage is invalid');
964
+ }
965
+ const principalId = externalPrincipalId(authority.principal);
966
+ const authorityHash = ownerRouteAuthorityHash(authority);
967
+ const snapshot = operatorInspectDatabase(input.databasePath, database => {
968
+ const row = database.prepare(`
969
+ SELECT id, key_hash, principal_json, role, status, linked_to_id, created_at, updated_at, version
970
+ FROM delivery_principals WHERE id = ?
971
+ `).get(input.principalRecordId);
972
+ if (row === undefined)
973
+ operatorFail('owner-not-revoked', 'exact revoked owner was not observed');
974
+ let principal;
975
+ try {
976
+ if (typeof row.principal_json !== 'string')
977
+ throw new Error('invalid identity');
978
+ principal = canonicalPrincipal(JSON.parse(row.principal_json));
979
+ if (row.principal_json !== JSON.stringify(principal)
980
+ || row.key_hash !== operatorSha256(row.principal_json))
981
+ throw new Error('invalid identity');
982
+ }
983
+ catch {
984
+ return operatorFail('database-corrupt', 'owner identity metadata is inconsistent');
985
+ }
986
+ if (!operatorInteger(row.version, 1) || !operatorInteger(row.created_at)
987
+ || !operatorInteger(row.updated_at) || row.updated_at < row.created_at) {
988
+ operatorFail('database-corrupt', 'owner lineage metadata is inconsistent');
989
+ }
990
+ if (row.id !== input.principalRecordId || externalPrincipalId(principal) !== principalId
991
+ || row.role !== 'owner' || row.status !== 'revoked' || row.linked_to_id !== null
992
+ || row.version < input.frozenPrincipalVersion) {
993
+ operatorFail('owner-not-revoked', 'exact revoked owner was not observed');
994
+ }
995
+ const state = operatorFreeze({
996
+ status: 'revoked', authorityId: authority.id, authorityHash, principalId,
997
+ principalRecordId: input.principalRecordId, principalVersion: row.version,
998
+ });
999
+ return state;
1000
+ });
1001
+ const unsigned = operatorFreeze({
1002
+ protocol: revokedOwnerRouteSnapshotProtocol, schemaVersion: snapshot.schemaVersion,
1003
+ authority, frozenPrincipalVersion: input.frozenPrincipalVersion, state: snapshot.value,
1004
+ database: snapshot.database, sidecars: snapshot.sidecars, storageDigest: snapshot.storageDigest,
1005
+ });
1006
+ return operatorFreeze({ ...unsigned, snapshotDigest: operatorSha256(operatorCanonicalJson(unsigned)) });
1007
+ }
1008
+ catch (error) {
1009
+ // Keep database rows, caller configuration and source paths out of failures.
1010
+ throw new ActiveLarkOwnerBindingsSnapshotError(error instanceof ActiveLarkOwnerBindingsSnapshotError ? error.code : 'database-corrupt', 'delivery revoked owner snapshot: inspection failed');
1011
+ }
1012
+ }
1013
+ //# sourceMappingURL=operator-snapshot.js.map