@gotcos/glasses-server 6.94.4 → 6.98.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 (109) hide show
  1. package/CHANGELOG.md +147 -0
  2. package/README.md +52 -0
  3. package/managed-runtime-contract.json +13 -0
  4. package/package.json +3 -1
  5. package/server/index.ts +19 -1
  6. package/server/lib/attached-provider-adapter.ts +35 -1
  7. package/server/lib/claude-bridge.ts +47 -0
  8. package/server/lib/codex-bridge.ts +11 -1
  9. package/server/lib/codex-rollout-watermark.ts +42 -0
  10. package/server/lib/cursor-bridge.ts +2 -1
  11. package/server/lib/dictation-clean-models.ts +2 -0
  12. package/server/lib/dictation-clean.ts +2 -2
  13. package/server/lib/dictation-polish-pipeline.ts +22 -2
  14. package/server/lib/dictation-prewarm.ts +16 -0
  15. package/server/lib/direct-bridge.ts +14 -2
  16. package/server/lib/direct-sse.ts +6 -1
  17. package/server/lib/display-bus.ts +1 -1
  18. package/server/lib/fork-thread.ts +32 -1
  19. package/server/lib/held-naming-batches.ts +36 -0
  20. package/server/lib/job-audit-caller.ts +20 -0
  21. package/server/lib/lens-gist-engines.ts +17 -5
  22. package/server/lib/live-cos-ask.ts +29 -6
  23. package/server/lib/live-cue-verdicts.ts +43 -8
  24. package/server/lib/live-cues-engine.ts +4 -1
  25. package/server/lib/live-cues-filter.ts +50 -0
  26. package/server/lib/live-cues-general-prompts.ts +137 -0
  27. package/server/lib/live-cues-general-topic.ts +245 -0
  28. package/server/lib/live-cues-general.ts +715 -0
  29. package/server/lib/live-cues-v2-data.ts +453 -0
  30. package/server/lib/live-cues-v2-grounded.ts +262 -0
  31. package/server/lib/live-cues-v2-judge-b.ts +59 -0
  32. package/server/lib/live-cues-v2-names.ts +49 -0
  33. package/server/lib/live-cues-v2-notes.ts +8 -4
  34. package/server/lib/live-cues-v2-open-items.ts +132 -0
  35. package/server/lib/live-cues-v2-pacing.ts +45 -0
  36. package/server/lib/live-cues-v2-prompts-kinds.ts +9 -4
  37. package/server/lib/live-cues-v2-settings.ts +89 -10
  38. package/server/lib/live-cues-v2.ts +570 -47
  39. package/server/lib/mac-recording-asr.ts +6 -3
  40. package/server/lib/mac-speaker-call-human.ts +371 -0
  41. package/server/lib/mac-speaker-call-interval-human.ts +499 -0
  42. package/server/lib/mac-speaker-call-interval-projection.ts +233 -0
  43. package/server/lib/mac-speaker-call-original-view.ts +328 -0
  44. package/server/lib/mac-speaker-call-producer-worker.ts +615 -0
  45. package/server/lib/mac-speaker-call-producer.ts +539 -0
  46. package/server/lib/mac-speaker-call-store.ts +264 -0
  47. package/server/lib/mac-speaker-call-view.ts +373 -0
  48. package/server/lib/mac-speaker-live-compute.ts +72 -0
  49. package/server/lib/mac-speaker-live-memory.ts +414 -0
  50. package/server/lib/mac-speaker-live-projection.ts +126 -0
  51. package/server/lib/mac-speaker-live-save.ts +90 -0
  52. package/server/lib/mac-speaker-live-store.ts +71 -0
  53. package/server/lib/mac-speaker-live-worker.ts +58 -0
  54. package/server/lib/mac-speaker-live.ts +175 -0
  55. package/server/lib/mac-speaker-profile-extractor.ts +15 -10
  56. package/server/lib/mac-speaker-shadow-repair.ts +307 -0
  57. package/server/lib/mac-voice-assignment.ts +44 -26
  58. package/server/lib/mac-voice-display.ts +195 -0
  59. package/server/lib/mac-voice-naming-batch.ts +1067 -0
  60. package/server/lib/mac-voice-suggestions.ts +548 -0
  61. package/server/lib/maintenance-lifecycle.ts +2 -0
  62. package/server/lib/media-store.ts +2 -1
  63. package/server/lib/meeting-ask-pasted.ts +135 -0
  64. package/server/lib/meeting-ask-review.ts +8 -1
  65. package/server/lib/meeting-ask-runner.ts +4 -1
  66. package/server/lib/meeting-ask-runtime.ts +189 -17
  67. package/server/lib/meeting-ask-store.ts +2 -0
  68. package/server/lib/meeting-ask-web.ts +284 -13
  69. package/server/lib/meeting-batch-progress.ts +51 -5
  70. package/server/lib/meeting-batch-transcribe.ts +35 -2
  71. package/server/lib/meeting-fact-check.ts +3 -0
  72. package/server/lib/meeting-finalization-jobs.ts +69 -2
  73. package/server/lib/meeting-public-topic.ts +6 -1
  74. package/server/lib/meeting-speaker-review.ts +182 -17
  75. package/server/lib/meeting-store.ts +6 -1
  76. package/server/lib/parakeet.ts +51 -5
  77. package/server/lib/pending-batch-retention.ts +58 -0
  78. package/server/lib/private-reference.ts +38 -0
  79. package/server/lib/provider-usage.ts +561 -0
  80. package/server/lib/public-https-url.ts +32 -0
  81. package/server/lib/query-job-runtime.ts +3 -0
  82. package/server/lib/rich-media-safety.ts +23 -2
  83. package/server/lib/speaker-shadow-decide.ts +503 -0
  84. package/server/lib/speaker-shadow-models.ts +150 -0
  85. package/server/lib/speaker-shadow-numeric.ts +143 -0
  86. package/server/lib/speaker-shadow-pair-source.ts +91 -0
  87. package/server/lib/speaker-shadow-paired.ts +268 -0
  88. package/server/lib/speaker-shadow-report.ts +113 -0
  89. package/server/lib/speaker-shadow-timeline.ts +210 -0
  90. package/server/lib/speaker-shadow-worker.ts +312 -0
  91. package/server/lib/speaker-shadow.ts +788 -0
  92. package/server/lib/token-audit.ts +36 -6
  93. package/server/lib/transcript-cleanup.ts +3 -2
  94. package/server/lib/voice-directory.ts +8 -4
  95. package/server/lib/web-lookup-ledger.ts +151 -0
  96. package/server/lib/work-review-runtime.ts +2 -0
  97. package/server/lib/work-search.ts +3 -1
  98. package/server/lib/xlsx-text.ts +277 -0
  99. package/server/routes/health.ts +5 -0
  100. package/server/routes/live-cues.ts +36 -14
  101. package/server/routes/meeting.ts +506 -49
  102. package/server/routes/speaker-shadow.ts +79 -0
  103. package/server/routes/transcribe-stream.ts +114 -33
  104. package/server/routes/voice.ts +3 -0
  105. package/server/scripts/live-cues-v3-mutation-gate.mjs +311 -0
  106. package/server/scripts/mac-voice-assignment-6930-mutation-gate.mjs +5 -5
  107. package/shared/live-cues-v2.ts +38 -5
  108. package/shared/media-attachment.ts +2 -0
  109. package/shared/meeting-ask.ts +11 -0
@@ -0,0 +1,615 @@
1
+ /** Guarded child-only closed-call consumer. Hashes establish integrity, never
2
+ * native authentication. Automatic admission requires a separately provisioned
3
+ * reviewed policy; this module cannot issue one or infer a human name. */
4
+ import { createHash, randomUUID } from 'node:crypto';
5
+ import { closeSync, constants, existsSync, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, unlinkSync, writeFileSync } from 'node:fs';
6
+ import { dirname, join, resolve } from 'node:path';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { durableAtomicWriteFileSync } from './atomic-fs.js';
9
+ import { isMacSpeakerHumanProtected } from './mac-speaker-protection.js';
10
+ import { bindMacSpeakerShadowRepair } from './mac-speaker-shadow-repair.js';
11
+ import { reconcileMacSpeaker256Snapshot, validateMacSpeaker256State, type MacSpeaker256SnapshotInput, type MacSpeaker256State } from './mac-speaker-live-memory.js';
12
+ import { prepareMacSpeakerCallPacket } from './mac-speaker-call-view.js';
13
+ import { executeMacSpeakerCallPublication, prepareMacSpeakerCallPublication, hashMacSpeakerCallFileInventory, type MacSpeakerCallFrozenFile, type MacSpeakerCallQualification } from './mac-speaker-call-store.js';
14
+ import { readPcm16Wav, shadowEntries, type ShadowTimelineRow } from './speaker-shadow-timeline.js';
15
+ import { SHADOW_MODEL_FILES, SHADOW_MODEL_REPO, SHADOW_MODEL_REVISION, SHADOW_REVISION_MARKER } from './speaker-shadow-models.js';
16
+ const SHA = /^[a-f0-9]{64}$/;
17
+ const hash = (v: string | Buffer) => createHash('sha256').update(v).digest('hex');
18
+ const seal = (v: unknown) => hash(JSON.stringify(v));
19
+ const fail = (message: string): never => { throw Error(`mac_call_producer_${message}`); };
20
+ let operationFence: (() => void) | null = null;
21
+ /** Also checked synchronously at IO/publication boundaries: a busy child event
22
+ * loop cannot defer parent-death or absolute-deadline checks until after writes. */
23
+ export function createMacSpeakerCallWorkerFence(input: {
24
+ parentPid: number;
25
+ deadline: number;
26
+ now?: () => number;
27
+ parentPidNow?: () => number;
28
+ alive?: (pid: number) => boolean;
29
+ }): () => void {
30
+ return () => {
31
+ if ((input.now ?? Date.now)() > input.deadline)
32
+ fail('worker_deadline');
33
+ let alive = false;
34
+ try {
35
+ alive = input.alive ? input.alive(input.parentPid) : (process.kill(input.parentPid, 0), true);
36
+ }
37
+ catch { }
38
+ if (input.parentPid < 2 || (input.parentPidNow ?? (() => process.ppid))() !== input.parentPid || !alive)
39
+ fail('parent_exited');
40
+ };
41
+ }
42
+ export const MAC_CALL_PRODUCER_RUNTIME_FILES = [
43
+ 'mac-speaker-call-producer.ts', 'mac-speaker-call-producer-worker.ts', 'mac-speaker-call-store.ts', 'mac-speaker-call-view.ts',
44
+ 'mac-speaker-live-memory.ts', 'mac-speaker-shadow-repair.ts', 'mac-speaker-protection.ts', 'speaker-shadow.ts', 'speaker-shadow-worker.ts',
45
+ 'speaker-shadow-models.ts', 'speaker-shadow-decide.ts', 'speaker-shadow-timeline.ts', 'speaker-shadow-numeric.ts',
46
+ ] as const;
47
+ export interface MacSpeakerCallPolicyAdmission {
48
+ version: 1;
49
+ kind: 'mac-speaker-call-policy-admission';
50
+ admission: 'qualified';
51
+ scope: 'AUTOMATIC_CLOSED_CALL_ANONYMOUS_ESTIMATE';
52
+ policy: 'fluid256-call-view-v1';
53
+ projectionPolicy: 'anonymous-estimate';
54
+ review: {
55
+ path: string;
56
+ sha256: string;
57
+ reviewer: string;
58
+ };
59
+ runtimeFiles: Record<string, string>;
60
+ cliSHA256: string;
61
+ modelSHA256: string;
62
+ modelManifestPath: string;
63
+ }
64
+ export interface MacSpeakerCallProducerRequest {
65
+ captureId: string;
66
+ sidecarPath: string;
67
+ ledgerPath: string;
68
+ root: string;
69
+ policyPath: string;
70
+ policySHA256: string;
71
+ humanJournalPath: string;
72
+ }
73
+ export interface MacSpeakerCallNativeRef {
74
+ path: string;
75
+ sha256: string;
76
+ captureId: string;
77
+ }
78
+ type Pin = {
79
+ path: string;
80
+ sha256: string | null;
81
+ stamp: string | null;
82
+ };
83
+ interface NativeContext {
84
+ request: MacSpeakerCallProducerRequest;
85
+ policy: MacSpeakerCallPolicyAdmission;
86
+ generation: string;
87
+ originalPath: string;
88
+ pins: Pin[];
89
+ rawAudio: MacSpeaker256SnapshotInput['rawAudio'];
90
+ timeline: MacSpeaker256SnapshotInput['timeline'];
91
+ cliPath: string;
92
+ rawManifest: any;
93
+ modelManifest: any;
94
+ sourceJSON: string;
95
+ ledgerJSONL: string;
96
+ }
97
+ interface NativeArtifact extends Omit<NativeContext, 'policy' | 'sourceJSON' | 'ledgerJSONL'> {
98
+ version: 1;
99
+ kind: 'mac-speaker-call-native-export';
100
+ nativePath: string;
101
+ embeddingPath: string;
102
+ nativeSHA256: string;
103
+ embeddingSHA256: string;
104
+ execution: {
105
+ exitCode: 0;
106
+ closed: true;
107
+ networkDenied: true;
108
+ nativeAuthenticated: false;
109
+ };
110
+ artifactSHA256: string;
111
+ }
112
+ function canonical(path: string) {
113
+ operationFence?.();
114
+ if (resolve(path) !== path)
115
+ fail('canonical_path');
116
+ let parent = dirname(path);
117
+ while (!existsSync(parent)) {
118
+ const next = dirname(parent);
119
+ if (next === parent)
120
+ fail('canonical_path');
121
+ parent = next;
122
+ }
123
+ if (realpathSync(parent) !== parent)
124
+ fail('canonical_path');
125
+ return path;
126
+ }
127
+ function stamp(path: string) {
128
+ const s = lstatSync(path);
129
+ if (!s.isFile() || s.isSymbolicLink())
130
+ fail('regular_file');
131
+ return JSON.stringify([s.dev, s.ino, s.size, s.mtimeMs, s.ctimeMs]);
132
+ }
133
+ function bounded(path: string, max: number, absent = false): Buffer | null {
134
+ canonical(path);
135
+ let fd: number;
136
+ try {
137
+ fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
138
+ }
139
+ catch (e) {
140
+ if (absent && (e as NodeJS.ErrnoException).code === 'ENOENT')
141
+ return null;
142
+ throw e;
143
+ }
144
+ try {
145
+ const s = fstatSync(fd), atStart = lstatSync(path), identity = (v: typeof s) => JSON.stringify([v.dev, v.ino, v.size, v.mtimeMs, v.ctimeMs]);
146
+ if (!s.isFile() || s.size > max || !atStart.isFile() || atStart.isSymbolicLink() || identity(s) !== identity(atStart) || realpathSync(path) !== path)
147
+ fail('fd_path_drift');
148
+ const bytes = readFileSync(fd), after = fstatSync(fd), atEnd = lstatSync(path);
149
+ if (bytes.length !== s.size || !atEnd.isFile() || atEnd.isSymbolicLink() || identity(after) !== identity(s) || identity(atEnd) !== identity(after) || realpathSync(path) !== path)
150
+ fail('read_drift');
151
+ return bytes;
152
+ }
153
+ finally {
154
+ closeSync(fd);
155
+ }
156
+ }
157
+ /** Bounded integrity read exposed for deterministic fd/path race regressions. */
158
+ export const readMacSpeakerCallProducerFile = bounded;
159
+ /** Pending work is scoped to one exact representation, never just a capture. */
160
+ export function validateMacSpeakerCallPending(p: any, r: MacSpeakerCallProducerRequest, ref: MacSpeakerCallNativeRef, cursorSHA256: string) {
161
+ const stem = r.sidecarPath.replace(/\.g2-chunks\.json$/, ''), root = join(r.root, r.captureId, 'transactions');
162
+ if (stem === r.sidecarPath || p.captureId !== r.captureId || p.sidecarPath !== r.sidecarPath || p.nativeRefSHA256 !== ref.sha256 || p.policySHA256 !== r.policySHA256 || p.cursorSHA256 !== cursorSHA256 || p.packetPath !== `${stem}.speaker-call.json` || p.statePath !== `${stem}.speaker-call-state.json` || typeof p.directory !== 'string' || dirname(p.directory) !== root || !SHA.test(p.intentSHA256) || !SHA.test(p.publication?.packetSHA256) || !SHA.test(p.publication?.stateFileSHA256))
163
+ fail('pending_publication_target_or_source_drift');
164
+ }
165
+ function pin(path: string, max: number, absent = false): Pin {
166
+ const before = existsSync(path) ? stamp(path) : null, b = bounded(path, max, absent), after = existsSync(path) ? stamp(path) : null;
167
+ if (before !== after || (b === null) !== (after === null))
168
+ fail('pin_drift');
169
+ return { path, sha256: b === null ? null : hash(b), stamp: after };
170
+ }
171
+ function checkPins(pins: Pin[]) {
172
+ for (const p of pins) {
173
+ const q = pin(p.path, 1024 * 1024 * 1024, p.sha256 === null);
174
+ if (q.sha256 !== p.sha256 || q.stamp !== p.stamp)
175
+ fail('source_drift');
176
+ }
177
+ }
178
+ function put(path: string, bytes: string | Buffer) {
179
+ canonical(path);
180
+ const fd = openSync(path, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW | constants.O_NONBLOCK, 0o400);
181
+ try {
182
+ writeFileSync(fd, bytes);
183
+ fsyncSync(fd);
184
+ }
185
+ finally {
186
+ closeSync(fd);
187
+ }
188
+ const d = openSync(dirname(path), constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
189
+ try {
190
+ fsyncSync(d);
191
+ }
192
+ finally {
193
+ closeSync(d);
194
+ }
195
+ }
196
+ function captureDir(r: MacSpeakerCallProducerRequest) {
197
+ if (!/^mac_[A-Za-z0-9_-]{1,100}$/.test(r.captureId) || realpathSync(r.root) !== r.root)
198
+ fail('capture_path');
199
+ const dir = join(r.root, r.captureId);
200
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
201
+ if (realpathSync(dir) !== dir)
202
+ fail('capture_symlink');
203
+ return dir;
204
+ }
205
+ function producerLock(r: MacSpeakerCallProducerRequest) {
206
+ const path = join(captureDir(r), 'producer.lock'), old = bounded(path, 4096, true);
207
+ if (old) {
208
+ const value = JSON.parse(old.toString());
209
+ if (value.kind !== 'mac-speaker-call-producer' || value.captureId !== r.captureId || !Number.isSafeInteger(value.pid) || value.pid <= 0 || typeof value.token !== 'string')
210
+ fail('producer_lock_foreign');
211
+ try {
212
+ process.kill(value.pid, 0);
213
+ fail('producer_lock_alive');
214
+ }
215
+ catch (e) {
216
+ if ((e as NodeJS.ErrnoException).code !== 'ESRCH')
217
+ throw e;
218
+ }
219
+ if (hash(bounded(path, 4096)!) !== hash(old))
220
+ fail('producer_lock_drift');
221
+ unlinkSync(path);
222
+ }
223
+ const bytes = JSON.stringify({ kind: 'mac-speaker-call-producer', captureId: r.captureId, pid: process.pid, token: randomUUID() });
224
+ put(path, bytes);
225
+ return () => {
226
+ if (hash(bounded(path, 4096)!) !== hash(bytes))
227
+ fail('producer_lock_owner_drift');
228
+ unlinkSync(path);
229
+ };
230
+ }
231
+ function guardHuman(r: MacSpeakerCallProducerRequest, ownTransaction?: string) {
232
+ const lock = join(dirname(r.sidecarPath), `.${r.captureId}.speaker-call.lock`);
233
+ if (existsSync(lock) && (!ownTransaction || JSON.parse(bounded(lock, 4096)!.toString()).directory !== ownTransaction))
234
+ fail('capture_locked');
235
+ const j = bounded(r.humanJournalPath, 1024 * 1024, true);
236
+ if (j && JSON.parse(j.toString()).phase !== 'complete')
237
+ fail('human_transaction_pending');
238
+ }
239
+ function recoverDeadSeedLock(r:MacSpeakerCallProducerRequest,seedPath:string):void{
240
+ const path=join(dirname(r.sidecarPath),`.${r.captureId}.speaker-call.lock`),bytes=bounded(path,4096,true);
241
+ if(!bytes)return;
242
+ let value:any;try{value=JSON.parse(bytes.toString())}catch{fail('capture_locked')}
243
+ if(value.kind!=='producer_seed')fail('capture_locked');
244
+ if(value.version!==1||value.captureId!==r.captureId||value.policySHA256!==r.policySHA256||value.seedPath!==seedPath||!SHA.test(value.sourceSHA256)||value.seedSHA256!==value.sourceSHA256||value.ledgerSHA256!==null&&!SHA.test(value.ledgerSHA256)||!Number.isSafeInteger(value.pid)||value.pid<=0||typeof value.token!=='string'||!/^[a-f0-9-]{36}$/.test(value.token))fail('producer_seed_lock_foreign');
245
+ try{process.kill(value.pid,0);fail('producer_seed_lock_alive')}catch(error){if((error as NodeJS.ErrnoException).code!=='ESRCH')throw error}
246
+ const current=pin(r.sidecarPath,32*1024*1024),ledger=pin(r.ledgerPath,8*1024*1024,true),seed=pin(seedPath,32*1024*1024,true);
247
+ if(current.sha256!==value.sourceSHA256||ledger.sha256!==value.ledgerSHA256||seed.sha256!==null&&seed.sha256!==value.seedSHA256)fail('producer_seed_lock_source_drift');
248
+ // Never remove a human transaction/annotation or a foreign/live lock.
249
+ // The normal seed gate below rechecks human history before resuming.
250
+ readMacSpeakerCallPolicy(r);checkPins([current,ledger,seed]);
251
+ if(hash(bounded(path,4096)!)!==hash(bytes))fail('producer_seed_lock_drift');
252
+ unlinkSync(path);
253
+ const fd=openSync(dirname(path),constants.O_RDONLY|constants.O_DIRECTORY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{fsyncSync(fd)}finally{closeSync(fd)}
254
+ }
255
+ function human(value: unknown): boolean { return !!value && typeof value === 'object' && (isMacSpeakerHumanProtected(value) || Object.values(value).some(v => human(v))); }
256
+ /** This is an independently supplied admission decision, NOT a self-hash grant. */
257
+ export function readMacSpeakerCallPolicy(r: MacSpeakerCallProducerRequest): MacSpeakerCallPolicyAdmission {
258
+ const b = bounded(r.policyPath, 256 * 1024)!, p = JSON.parse(b.toString()) as MacSpeakerCallPolicyAdmission;
259
+ if (hash(b) !== r.policySHA256 || p.version !== 1 || p.kind !== 'mac-speaker-call-policy-admission' || p.admission !== 'qualified' || p.scope !== 'AUTOMATIC_CLOSED_CALL_ANONYMOUS_ESTIMATE' || p.policy !== 'fluid256-call-view-v1' || p.projectionPolicy !== 'anonymous-estimate' || !SHA.test(p.cliSHA256) || !SHA.test(p.modelSHA256) || typeof p.review?.reviewer !== 'string' || !p.review.reviewer.trim() || p.review.reviewer.length > 200 || !SHA.test(p.review.sha256) || hash(bounded(p.review.path, 16 * 1024 * 1024)!) !== p.review.sha256)
260
+ fail('independent_policy_required');
261
+ if (Object.keys(p.runtimeFiles ?? {}).sort().join() !== [...MAC_CALL_PRODUCER_RUNTIME_FILES].sort().join())
262
+ fail('policy_code_inventory');
263
+ for (const name of MAC_CALL_PRODUCER_RUNTIME_FILES)
264
+ if (hash(bounded(fileURLToPath(new URL(name, import.meta.url)), 2 * 1024 * 1024)!) !== p.runtimeFiles[name])
265
+ fail('policy_code_drift');
266
+ const modelBytes = bounded(p.modelManifestPath, 256 * 1024)!, model = JSON.parse(modelBytes.toString()), expected = Object.fromEntries([{ path: SHADOW_REVISION_MARKER.path, sha256: SHADOW_REVISION_MARKER.sha256 }, ...SHADOW_MODEL_FILES].map(m => [`speaker-diarization/${m.path}`, m.sha256]));
267
+ if (hash(modelBytes) !== p.modelSHA256 || model.repository !== SHADOW_MODEL_REPO || model.revision !== SHADOW_MODEL_REVISION || seal(Object.entries(model.files ?? {}).sort()) !== seal(Object.entries(expected).sort()))
268
+ fail('model_policy_identity');
269
+ return p;
270
+ }
271
+ /** Read-only route admission check. This proves retained receipt integrity and
272
+ * reviewed policy conformance, never independent authentication of native IO. */
273
+ export function checkMacSpeakerCallCachedNative(r: MacSpeakerCallProducerRequest, ref: MacSpeakerCallNativeRef): void {
274
+ readMacSpeakerCallPolicy(r);
275
+ const dir = join(r.root, r.captureId), exportDir = dirname(ref.path);
276
+ if (ref.captureId !== r.captureId || dirname(exportDir) !== dir || !/^native-[a-f0-9-]{36}$/.test(exportDir.split('/').at(-1) ?? '') || ref.path !== join(exportDir, 'receipt.json') || !SHA.test(ref.sha256))
277
+ fail('cached_native_path');
278
+ const bytes = bounded(ref.path, 16 * 1024 * 1024)!, a = JSON.parse(bytes.toString()), { artifactSHA256, ...body } = a;
279
+ if (hash(bytes) !== ref.sha256 || a.version !== 1 || a.kind !== 'mac-speaker-call-native-export' || artifactSHA256 !== seal(body) || a.request?.captureId !== r.captureId || a.request?.root !== r.root || a.request?.policyPath !== r.policyPath || a.request?.policySHA256 !== r.policySHA256 || a.execution?.closed !== true || a.execution?.exitCode !== 0 || a.execution?.networkDenied !== true || a.execution?.nativeAuthenticated !== false || a.nativePath !== join(exportDir, 'native.json') || a.embeddingPath !== join(exportDir, 'embeddings.json') || hash(bounded(a.nativePath, 64 * 1024 * 1024)!) !== a.nativeSHA256 || hash(bounded(a.embeddingPath, 96 * 1024 * 1024)!) !== a.embeddingSHA256)
280
+ fail('cached_native_integrity');
281
+ }
282
+ /** Called in a short child before the finalization job is released. Never seeds
283
+ * from corrected history, and never edits BASE/ledger or reclaims a human lock. */
284
+ export function freezeMacSpeakerCallSeed(r: MacSpeakerCallProducerRequest): {
285
+ seedPath: string;
286
+ generation: string;
287
+ } {
288
+ readMacSpeakerCallPolicy(r);
289
+ const dir = captureDir(r), seedPath = join(dir, 'original.json'), metaPath = join(dir, 'seed.json');
290
+ recoverDeadSeedLock(r,seedPath);guardHuman(r);
291
+ if (existsSync(metaPath)) {
292
+ const meta = JSON.parse(bounded(metaPath, 4096)!.toString());
293
+ if (meta.captureId !== r.captureId || hash(bounded(seedPath, 32 * 1024 * 1024)!) !== meta.originalSHA256 || typeof meta.generation !== 'string')
294
+ fail('seed_integrity');
295
+ return { seedPath, generation: meta.generation };
296
+ }
297
+ const source = bounded(r.sidecarPath, 32 * 1024 * 1024)!, ledger = bounded(r.ledgerPath, 8 * 1024 * 1024, true), doc = JSON.parse(source.toString());
298
+ if (doc.sessionId !== r.captureId || doc.finalizationState !== 'complete' || doc.sourceType !== 'mac_system_audio' || doc.active || doc.isActive || doc.claimPending)
299
+ fail('closed_source_required');
300
+ if (ledger?.toString().trim() || human(doc) || existsSync(r.humanJournalPath) || existsSync(r.sidecarPath.replace(/\.g2-chunks\.json$/, '.speaker-call-human.json')))
301
+ fail('human_history_without_seed');
302
+ const orphanSeed = bounded(seedPath, 32 * 1024 * 1024, true);
303
+ if (orphanSeed && (hash(orphanSeed) !== hash(source) || existsSync(join(dir, 'cursor.json')) || existsSync(r.sidecarPath.replace(/\.g2-chunks\.json$/, '.speaker-call-state.json'))))
304
+ fail('orphan_seed_requires_recovery');
305
+ const sourcePin = pin(r.sidecarPath, 32 * 1024 * 1024), ledgerPin = pin(r.ledgerPath, 8 * 1024 * 1024, true);
306
+ const lock = join(dirname(r.sidecarPath), `.${r.captureId}.speaker-call.lock`), token = JSON.stringify({version:1,pid:process.pid,token:randomUUID(),kind:'producer_seed',captureId:r.captureId,policySHA256:r.policySHA256,sourceSHA256:hash(source),ledgerSHA256:ledgerPin.sha256,seedPath,seedSHA256:hash(source)});
307
+ put(lock, token);
308
+ try {
309
+ checkPins([sourcePin, ledgerPin]);
310
+ if (sourcePin.sha256 !== hash(source))
311
+ fail('seed_source_drift');
312
+ const generation = randomUUID();
313
+ if (!orphanSeed)
314
+ put(seedPath, source);
315
+ put(metaPath, JSON.stringify({ version: 1, captureId: r.captureId, generation, originalSHA256: hash(source) }) + '\n');
316
+ return { seedPath, generation };
317
+ }
318
+ finally {
319
+ if (hash(bounded(lock, 4096)!) !== hash(token))
320
+ fail('seed_lock_drift');
321
+ unlinkSync(lock);
322
+ }
323
+ }
324
+ /** Hash the exact native input geometry without allocating a second whole-call
325
+ * buffer. Gap zeros and trimmed source tails follow buildShadowTimeline. The
326
+ * caller must supply only bytes joined to the immutable raw/PCM pins. */
327
+ export function verifyMacSpeakerCallTimelinePCM(timeline: NativeContext['timeline'], readRaw: (index: number) => Buffer): void {
328
+ if (!Array.isArray(timeline.rows) || !timeline.rows.length || timeline.rows.length > 6000 || !Number.isSafeInteger(timeline.total) || timeline.total <= 0 || timeline.total > 4 * 3600 * 16000 || !SHA.test(timeline.pcmSHA256))
329
+ fail('timeline_schema');
330
+ const digest = createHash('sha256'), zeros = Buffer.alloc(65536), seen = new Set<number>();
331
+ let offset = 0;
332
+ const gap = (samples: number) => { let bytes = samples * 2; while (bytes > 0) {
333
+ const n = Math.min(bytes, zeros.length);
334
+ digest.update(zeros.subarray(0, n));
335
+ bytes -= n;
336
+ } };
337
+ for (const row of timeline.rows) {
338
+ if (!Number.isSafeInteger(row.rawChunkIndex) || row.rawChunkIndex < 0 || seen.has(row.rawChunkIndex) || !Number.isSafeInteger(row.startSample) || row.startSample < offset || !Number.isSafeInteger(row.sampleCount) || row.sampleCount <= 0 || row.sampleCount > 480000 || !Number.isSafeInteger(row.usedSampleCount) || row.usedSampleCount <= 0 || row.usedSampleCount > row.sampleCount || row.startSample + row.usedSampleCount > timeline.total)
339
+ fail('timeline_geometry');
340
+ seen.add(row.rawChunkIndex);
341
+ gap(row.startSample - offset);
342
+ const pcm = readRaw(row.rawChunkIndex);
343
+ if (pcm.length !== row.sampleCount * 2)
344
+ fail('timeline_raw_samples');
345
+ digest.update(pcm.subarray(0, row.usedSampleCount * 2));
346
+ offset = row.startSample + row.usedSampleCount;
347
+ }
348
+ gap(timeline.total - offset);
349
+ if (digest.digest('hex') !== timeline.pcmSHA256)
350
+ fail('timeline_pcm_drift');
351
+ }
352
+ /** Before the shared shadow native run. Raw/model/tool stamps remain immutable
353
+ * through child close; ABA replacement also invalidates this attempt. */
354
+ export function beginMacSpeakerCallNative(r: MacSpeakerCallProducerRequest, input: {
355
+ sourceJSON: string;
356
+ audioDir: string;
357
+ cliPath: string;
358
+ modelsDir: string;
359
+ timeline: {
360
+ rows: ShadowTimelineRow[];
361
+ total: number;
362
+ pcmSHA256: string;
363
+ };
364
+ }): NativeContext {
365
+ const policy = readMacSpeakerCallPolicy(r), seed = freezeMacSpeakerCallSeed(r);
366
+ guardHuman(r);
367
+ if (hash(bounded(r.sidecarPath, 32 * 1024 * 1024)!) !== hash(input.sourceJSON))
368
+ fail('native_base_drift');
369
+ const pins = [pin(r.sidecarPath, 32 * 1024 * 1024), pin(r.ledgerPath, 8 * 1024 * 1024, true), pin(input.cliPath, 256 * 1024 * 1024)];
370
+ if (pins[2].sha256 !== policy.cliSHA256)
371
+ fail('cli_drift');
372
+ const rawAudio = shadowEntries(JSON.parse(input.sourceJSON)).map(e => { const path = realpathSync(join(input.audioDir, `chunk_${String(e.chunkIndex).padStart(4, '0')}.wav`)), b = bounded(path, 1024 * 1024)!, pcm = readPcm16Wav(b); pins.push(pin(path, 1024 * 1024)); return { rawChunkIndex: e.chunkIndex, wavSHA256: hash(b), pcmSHA256: hash(pcm.pcm), sampleCount: pcm.sampleCount }; });
373
+ const rawManifest = { version: 1, captureId: r.captureId, rows: rawAudio.map((a, i) => ({ ...a, path: pins[i + 3].path, wavSHA256: a.wavSHA256 })) };
374
+ if (input.timeline.rows.length !== rawAudio.length)
375
+ fail('timeline_raw_inventory');
376
+ const rawByIndex = new Map(rawManifest.rows.map(row => [row.rawChunkIndex, row]));
377
+ verifyMacSpeakerCallTimelinePCM(input.timeline, index => {
378
+ const row = rawByIndex.get(index);
379
+ if (!row)
380
+ fail('timeline_raw_inventory');
381
+ const bytes = bounded(row!.path, 1024 * 1024)!, pcm = readPcm16Wav(bytes);
382
+ if (hash(bytes) !== row!.wavSHA256 || hash(pcm.pcm) !== row!.pcmSHA256 || pcm.sampleCount !== row!.sampleCount)
383
+ fail('timeline_raw_drift');
384
+ return pcm.pcm;
385
+ });
386
+ const modelRows = [{ path: SHADOW_REVISION_MARKER.path, sha256: SHADOW_REVISION_MARKER.sha256 }, ...SHADOW_MODEL_FILES];
387
+ const modelManifest = { version: 1, modelSHA256: policy.modelSHA256, files: modelRows.map(m => {
388
+ const p = pin(realpathSync(join(input.modelsDir, m.path)), 1024 * 1024 * 1024);
389
+ if (p.sha256 !== m.sha256)
390
+ fail('model_drift');
391
+ pins.push(p);
392
+ return { path: p.path, sha256: p.sha256 };
393
+ }) };
394
+ pins.push(pin(seed.seedPath, 32 * 1024 * 1024), pin(join(dirname(seed.seedPath), 'seed.json'), 4096));
395
+ const ledgerJSONL = bounded(r.ledgerPath, 8 * 1024 * 1024, true)?.toString() ?? '';
396
+ if (hash(ledgerJSONL) !== (pins[1].sha256 ?? hash('')))
397
+ fail('native_ledger_drift');
398
+ return { request: r, policy, generation: seed.generation, originalPath: seed.seedPath, pins, rawAudio, timeline: input.timeline, cliPath: input.cliPath, rawManifest, modelManifest, sourceJSON: input.sourceJSON, ledgerJSONL };
399
+ }
400
+ /** Only called after the actual shared CLI emits close(exit0). Retains exports
401
+ * once for a separate consumer; no second inference and no meeting mutation. */
402
+ export function retainMacSpeakerCallNative(ctx: NativeContext, outputs: {
403
+ nativePath: string;
404
+ embeddingPath: string;
405
+ exitCode: number | null;
406
+ closed: boolean;
407
+ networkDenied: boolean;
408
+ }): MacSpeakerCallNativeRef {
409
+ if (outputs.exitCode !== 0 || !outputs.closed || !outputs.networkDenied)
410
+ fail('native_not_closed_offline');
411
+ readMacSpeakerCallPolicy(ctx.request);
412
+ guardHuman(ctx.request);
413
+ checkPins(ctx.pins);
414
+ const native = bounded(outputs.nativePath, 64 * 1024 * 1024)!, emb = bounded(outputs.embeddingPath, 96 * 1024 * 1024)!, dir = join(captureDir(ctx.request), `native-${randomUUID()}`);
415
+ mkdirSync(dir, { mode: 0o700 });
416
+ put(join(dir, 'native.json'), native);
417
+ put(join(dir, 'embeddings.json'), emb);
418
+ put(join(dir, 'raw-manifest.json'), JSON.stringify(ctx.rawManifest) + '\n');
419
+ put(join(dir, 'model-manifest.json'), JSON.stringify(ctx.modelManifest) + '\n');
420
+ put(join(dir, 'native-source.json'), ctx.sourceJSON);
421
+ put(join(dir, 'native-ledger.jsonl'), ctx.ledgerJSONL);
422
+ const { policy: _, sourceJSON: __, ledgerJSONL: ___, ...base } = ctx;
423
+ const body = { ...base, version: 1 as const, kind: 'mac-speaker-call-native-export' as const, nativePath: join(dir, 'native.json'), embeddingPath: join(dir, 'embeddings.json'), nativeSHA256: hash(native), embeddingSHA256: hash(emb), execution: { exitCode: 0 as const, closed: true as const, networkDenied: true as const, nativeAuthenticated: false as const } };
424
+ const artifact = { ...body, artifactSHA256: seal(body) }, path = join(dir, 'receipt.json');
425
+ checkPins(ctx.pins);
426
+ put(path, JSON.stringify(artifact) + '\n');
427
+ return { path, sha256: hash(bounded(path, 16 * 1024 * 1024)!), captureId: ctx.request.captureId };
428
+ }
429
+ /** Worker-only publication. Requires reviewed policy + retained execution receipt
430
+ * and freshly verifies every native/raw/model/current/ledger source again. */
431
+ export function publishMacSpeakerCallNative(ref: MacSpeakerCallNativeRef, target?: MacSpeakerCallProducerRequest): {
432
+ status: 'applied';
433
+ directory: string;
434
+ packetPath: string;
435
+ statePath: string;
436
+ } {
437
+ const artifact = JSON.parse(bounded(ref.path, 16 * 1024 * 1024)!.toString()) as NativeArtifact, r = target ?? artifact.request;
438
+ readMacSpeakerCallPolicy(r);
439
+ const release = producerLock(r);
440
+ try {
441
+ return publishUnlocked(ref, target);
442
+ }
443
+ finally {
444
+ release();
445
+ }
446
+ }
447
+ function publishUnlocked(ref: MacSpeakerCallNativeRef, target?: MacSpeakerCallProducerRequest): {
448
+ status: 'applied';
449
+ directory: string;
450
+ packetPath: string;
451
+ statePath: string;
452
+ } {
453
+ const bytes = bounded(ref.path, 16 * 1024 * 1024)!, a = JSON.parse(bytes.toString()) as NativeArtifact, { artifactSHA256, ...body } = a;
454
+ if (hash(bytes) !== ref.sha256 || a.kind !== 'mac-speaker-call-native-export' || a.request.captureId !== ref.captureId || artifactSHA256 !== seal(body) || a.execution.exitCode !== 0 || a.execution.closed !== true || a.execution.networkDenied !== true || a.execution.nativeAuthenticated !== false)
455
+ fail('native_receipt_integrity');
456
+ const r = target ?? a.request;
457
+ if (r.captureId !== a.request.captureId || r.root !== a.request.root || r.policyPath !== a.request.policyPath || r.policySHA256 !== a.request.policySHA256)
458
+ fail('target_capture_or_policy');
459
+ const p = readMacSpeakerCallPolicy(r), dir = captureDir(r), cursorPath = join(dir, 'cursor.json'), pendingPath = join(dir, 'pending-publication.json');
460
+ const exportDir = dirname(ref.path), modelRows = [{ path: SHADOW_REVISION_MARKER.path, sha256: SHADOW_REVISION_MARKER.sha256 }, ...SHADOW_MODEL_FILES];
461
+ if (dirname(exportDir) !== dir || !/^native-[a-f0-9-]{36}$/.test(exportDir.split('/').at(-1) ?? '') || a.originalPath !== join(dir, 'original.json') || a.nativePath !== join(exportDir, 'native.json') || a.embeddingPath !== join(exportDir, 'embeddings.json') || !Array.isArray(a.pins) || a.pins.length > 6500 || !Array.isArray(a.rawAudio) || !Array.isArray(a.rawManifest?.rows) || a.rawManifest.rows.length !== a.rawAudio.length || !Array.isArray(a.modelManifest?.files) || a.modelManifest.files.length !== modelRows.length)
462
+ fail('native_inventory');
463
+ for (const row of modelRows)
464
+ if (a.modelManifest.files.filter((f: any) => f.path.endsWith(`/${row.path}`) && f.sha256 === row.sha256).length !== 1)
465
+ fail('model_native_membership');
466
+ const expectedPaths = [a.request.sidecarPath, a.request.ledgerPath, a.cliPath, a.originalPath, join(dir, 'seed.json'), ...a.rawManifest.rows.map((x: any) => x.path), ...a.modelManifest.files.map((x: any) => x.path)];
467
+ if (new Set(expectedPaths).size !== expectedPaths.length || seal([...expectedPaths].sort()) !== seal(a.pins.map(x => x.path).sort()))
468
+ fail('native_source_inventory');
469
+ for (const [i, row] of a.rawManifest.rows.entries())
470
+ if (row.rawChunkIndex !== i || seal(a.rawAudio[i]) !== seal({ rawChunkIndex: i, wavSHA256: row.wavSHA256, pcmSHA256: row.pcmSHA256, sampleCount: row.sampleCount }))
471
+ fail('native_raw_join');
472
+ const pendingBytes = bounded(pendingPath, 16384, true);
473
+ if (pendingBytes) {
474
+ const pending = JSON.parse(pendingBytes.toString());
475
+ validateMacSpeakerCallPending(pending, r, ref, hash(bounded(cursorPath, 32768)!));
476
+ guardHuman(r, pending.directory);
477
+ const intentBytes = bounded(join(pending.directory, 'intent.json'), 4 * 1024 * 1024)!, intent = JSON.parse(intentBytes.toString());
478
+ if (hash(intentBytes) !== pending.intentSHA256 || intent.captureId !== r.captureId || intent.directory !== pending.directory || intent.root !== join(dir, 'transactions') || intent.images?.length !== 2 || intent.images[0].path !== pending.packetPath || intent.images[1].path !== pending.statePath || intent.images[0].afterSHA256 !== pending.publication.packetSHA256 || intent.images[1].afterSHA256 !== pending.publication.stateFileSHA256)
479
+ fail('pending_intent_drift');
480
+ const fence = () => {
481
+ readMacSpeakerCallPolicy(r);
482
+ guardHuman(r, pending.directory);
483
+ if (hash(bounded(pendingPath, 16384)!) !== hash(pendingBytes) || hash(bounded(cursorPath, 32768)!) !== pending.cursorSHA256 || hash(bounded(join(pending.directory, 'intent.json'), 4 * 1024 * 1024)!) !== pending.intentSHA256)
484
+ fail('pending_publication_drift');
485
+ };
486
+ executeMacSpeakerCallPublication(pending.directory, 'apply', { resume: true, beforeWrite: fence });
487
+ fence();
488
+ if (hash(bounded(pending.packetPath, 16 * 1024 * 1024)!) !== pending.publication.packetSHA256 || hash(bounded(pending.statePath, 16 * 1024 * 1024)!) !== pending.publication.stateFileSHA256)
489
+ fail('pending_postimage_drift');
490
+ const cursor = JSON.parse(bounded(cursorPath, 32768)!.toString());
491
+ cursor.publications[pending.sidecarPath] = pending.publication;
492
+ durableAtomicWriteFileSync(cursorPath, JSON.stringify(cursor) + '\n');
493
+ unlinkSync(pendingPath);
494
+ return { status: 'applied', directory: pending.directory, packetPath: pending.packetPath, statePath: pending.statePath };
495
+ }
496
+ guardHuman(r);
497
+ // Current BASE/ledger may acquire protected human annotations after inference.
498
+ // Raw/model/tool pins must never change; inspector validates all geometry.
499
+ checkPins(a.pins.filter(x => x.path !== a.request.sidecarPath && x.path !== a.request.ledgerPath));
500
+ if (hash(bounded(join(exportDir, 'native-source.json'), 32 * 1024 * 1024)!) !== a.pins.find(x => x.path === a.request.sidecarPath)?.sha256 || hash(bounded(join(exportDir, 'native-ledger.jsonl'), 8 * 1024 * 1024)!) !== (a.pins.find(x => x.path === a.request.ledgerPath)?.sha256 ?? hash('')))
501
+ fail('native_snapshot_drift');
502
+ const originalJSON = bounded(a.originalPath, 32 * 1024 * 1024)!.toString(), currentJSON = bounded(r.sidecarPath, 32 * 1024 * 1024)!.toString(), ledgerJSONL = bounded(r.ledgerPath, 8 * 1024 * 1024, true)?.toString() ?? '', nativeJSON = bounded(a.nativePath, 64 * 1024 * 1024)!.toString(), embeddingsJSON = bounded(a.embeddingPath, 96 * 1024 * 1024)!.toString();
503
+ if (hash(nativeJSON) !== a.nativeSHA256 || hash(embeddingsJSON) !== a.embeddingSHA256)
504
+ fail('native_export_drift');
505
+ const source = { originalJSON, currentJSON, ledgerJSONL, rawAudio: a.rawAudio, timeline: a.timeline, cohort: { nativeJSON, embeddingsJSON, modelSHA256: p.modelSHA256, cliSHA256: p.cliSHA256 } }, input: MacSpeaker256SnapshotInput = { ...source, sourceBindingSHA256: bindMacSpeakerShadowRepair(source), generation: a.generation };
506
+ const cursor = bounded(cursorPath, 32768, true), prior = cursor ? JSON.parse(cursor.toString()) : null;
507
+ let previous: MacSpeaker256State | null = null;
508
+ if (prior) {
509
+ if (typeof prior.inputPath !== 'string' || !prior.inputPath.startsWith(`${dir}/candidate-`) || dirname(prior.inputPath) !== dirname(prior.statePath) || !prior.inputPath.endsWith('/input.json') || !prior.statePath.endsWith('/state.json') || !prior.publications || typeof prior.publications !== 'object')
510
+ fail('cursor_path');
511
+ const b = bounded(prior.inputPath, 256 * 1024 * 1024)!, s = bounded(prior.statePath, 16 * 1024 * 1024)!;
512
+ if (hash(b) !== prior.inputSHA256 || hash(s) !== prior.stateFileSHA256)
513
+ fail('cursor_drift');
514
+ const recovered = JSON.parse(s.toString()) as MacSpeaker256State;
515
+ validateMacSpeaker256State(recovered, JSON.parse(b.toString()));
516
+ previous = recovered;
517
+ input.expectedStateSHA256 = recovered.stateSHA256;
518
+ }
519
+ const state = reconcileMacSpeaker256Snapshot(previous, input), packet = prepareMacSpeakerCallPacket(input, state, { admission: 'qualified', projectionPolicy: 'anonymous-estimate' }), packetJSON = JSON.stringify(packet) + '\n', stateJSON = JSON.stringify(state) + '\n';
520
+ const candidate = join(dir, `candidate-${randomUUID()}`);
521
+ mkdirSync(candidate, { mode: 0o700 });
522
+ put(join(candidate, 'input.json'), JSON.stringify(input) + '\n');
523
+ put(join(candidate, 'state.json'), stateJSON);
524
+ const nextCursor = { inputPath: join(candidate, 'input.json'), inputSHA256: hash(JSON.stringify(input) + '\n'), statePath: join(candidate, 'state.json'), stateFileSHA256: hash(stateJSON), publications: prior?.publications ?? {} };
525
+ if ((bounded(cursorPath, 32768, true)?.toString() ?? null) !== (cursor?.toString() ?? null))
526
+ fail('cursor_cas');
527
+ // Reserve the opaque namespace before publication. Failure may leave unused
528
+ // reservations, which are retained rather than recycling IDs on retry.
529
+ durableAtomicWriteFileSync(cursorPath, JSON.stringify(nextCursor) + '\n');
530
+ const artifactDir = dirname(ref.path), sources: MacSpeakerCallFrozenFile[] = [];
531
+ const add = (role: MacSpeakerCallFrozenFile['role'], path: string, absent = false) => { const b = bounded(path, 1024 * 1024 * 1024, absent); sources.push({ role, path, sha256: b === null ? null : hash(b) }); };
532
+ add('original', a.originalPath);
533
+ add('current', r.sidecarPath);
534
+ add('ledger', r.ledgerPath, true);
535
+ add('raw-pcm-manifest', join(artifactDir, 'raw-manifest.json'));
536
+ add('model-manifest', join(artifactDir, 'model-manifest.json'));
537
+ add('cli', a.cliPath);
538
+ add('native-export', a.nativePath);
539
+ add('embedding-export', a.embeddingPath);
540
+ for (const row of a.rawManifest.rows)
541
+ add('raw-audio', row.path);
542
+ for (const row of a.modelManifest.files)
543
+ add('model-file', row.path);
544
+ const q: MacSpeakerCallQualification = { version: 1, kind: 'mac-speaker-call-qualified', captureId: r.captureId, policy: p.policy, admissionPolicy: p.projectionPolicy, qualification: { status: 'qualified', reviewer: p.review.reviewer, reviewReceiptSHA256: p.review.sha256 }, sourceFilesSHA256: hashMacSpeakerCallFileInventory(sources), bindings: { originalSHA256: hash(originalJSON), currentSHA256: hash(currentJSON), ledgerSHA256: hash(ledgerJSONL), rawPCMManifestSHA256: sources.find(s => s.role === 'raw-pcm-manifest')!.sha256!, cliSHA256: p.cliSHA256, modelSHA256: p.modelSHA256, nativeExportSHA256: a.nativeSHA256, embeddingExportSHA256: a.embeddingSHA256, sourceBindingSHA256: input.sourceBindingSHA256, stateSHA256: state.stateSHA256, packetSHA256: packet.packetSHA256, stateFileSHA256: hash(stateJSON), packetFileSHA256: hash(packetJSON) } };
545
+ const qualifiedPath = join(candidate, 'policy-conformance.json');
546
+ put(qualifiedPath, JSON.stringify({ ...q, basis: 'independently-admitted-policy-conformance', policyAdmissionSHA256: r.policySHA256, nativeReceiptSHA256: ref.sha256, nativeAuthenticated: false }) + '\n');
547
+ const stem = r.sidecarPath.replace(/\.g2-chunks\.json$/, '');
548
+ if (stem === r.sidecarPath)
549
+ fail('sidecar_suffix');
550
+ const packetPath = `${stem}.speaker-call.json`, statePath = `${stem}.speaker-call-state.json`, root = join(dir, 'transactions');
551
+ mkdirSync(root, { recursive: true, mode: 0o700 });
552
+ const beforePacket = bounded(packetPath, 16 * 1024 * 1024, true), beforeState = bounded(statePath, 16 * 1024 * 1024, true);
553
+ const known = nextCursor.publications[r.sidecarPath];
554
+ if ((beforePacket ? hash(beforePacket) : null) !== (known?.packetSHA256 ?? null) || (beforeState ? hash(beforeState) : null) !== (known?.stateFileSHA256 ?? null))
555
+ fail('published_artifact_drift');
556
+ readMacSpeakerCallPolicy(r);
557
+ guardHuman(r);
558
+ const transaction = prepareMacSpeakerCallPublication({ captureId: r.captureId, transactionRoot: root, packetPath, statePath, packetJSON, stateJSON, expectedPacketSHA256: beforePacket ? hash(beforePacket) : null, expectedStateFileSHA256: beforeState ? hash(beforeState) : null, sources, qualificationReceipt: { path: qualifiedPath, expectedSHA256: hash(bounded(qualifiedPath, 1024 * 1024)!) } });
559
+ put(join(candidate, 'transaction.json'), JSON.stringify({ directory: transaction }) + '\n');
560
+ put(pendingPath, JSON.stringify({ captureId: r.captureId, policySHA256: r.policySHA256, nativeRefSHA256: ref.sha256, directory: transaction, intentSHA256: hash(bounded(join(transaction, 'intent.json'), 4 * 1024 * 1024)!), cursorSHA256: hash(bounded(cursorPath, 32768)!), sidecarPath: r.sidecarPath, packetPath, statePath, publication: { packetSHA256: hash(packetJSON), stateFileSHA256: hash(stateJSON) } }) + '\n');
561
+ const pending = bounded(pendingPath, 16384)!, cursorHash = hash(bounded(cursorPath, 32768)!);
562
+ const fence = () => {
563
+ readMacSpeakerCallPolicy(r);
564
+ guardHuman(r, transaction);
565
+ if (hash(bounded(pendingPath, 16384)!) !== hash(pending) || hash(bounded(cursorPath, 32768)!) !== cursorHash)
566
+ fail('publication_cursor_drift');
567
+ };
568
+ executeMacSpeakerCallPublication(transaction, 'apply', { beforeWrite: fence });
569
+ fence();
570
+ nextCursor.publications[r.sidecarPath] = { packetSHA256: hash(packetJSON), stateFileSHA256: hash(stateJSON) };
571
+ durableAtomicWriteFileSync(cursorPath, JSON.stringify(nextCursor) + '\n');
572
+ unlinkSync(pendingPath);
573
+ return { status: 'applied', directory: transaction, packetPath, statePath };
574
+ }
575
+ async function main() {
576
+ const parentPid = process.ppid, started = Date.now();
577
+ let deadline = started + 10000;
578
+ operationFence = () => createMacSpeakerCallWorkerFence({ parentPid, deadline })();
579
+ const watch = setInterval(() => { try {
580
+ operationFence?.();
581
+ }
582
+ catch {
583
+ process.kill(process.pid, 'SIGKILL');
584
+ } }, 200);
585
+ watch.unref();
586
+ let text = '';
587
+ try {
588
+ for await (const b of process.stdin) {
589
+ operationFence();
590
+ text += b.toString();
591
+ if (Buffer.byteLength(text) > 65536)
592
+ fail('job_bound');
593
+ }
594
+ try {
595
+ const job = JSON.parse(text);
596
+ if (job.action === 'publish')
597
+ deadline = started + 75000;
598
+ operationFence();
599
+ const { macSpeakerCallProducerRequestValid } = await import('./mac-speaker-call-producer.js');
600
+ if (!macSpeakerCallProducerRequestValid(job.request))
601
+ fail('job_request_invalid');
602
+ const result = job.action === 'freeze' ? freezeMacSpeakerCallSeed(job.request) : job.action === 'publish' ? publishMacSpeakerCallNative(job.ref, job.request) : fail('unknown_job');
603
+ process.stdout.write(JSON.stringify({ status: job.action === 'freeze' ? 'frozen' : 'applied', result }) + '\n');
604
+ }
605
+ catch (e) {
606
+ process.stdout.write(JSON.stringify({ status: 'withheld', reason: e instanceof Error ? e.message.slice(0, 200) : 'worker_failure' }) + '\n');
607
+ }
608
+ }
609
+ finally {
610
+ clearInterval(watch);
611
+ operationFence = null;
612
+ }
613
+ }
614
+ if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url))
615
+ void main().catch(() => { process.exitCode = 1; });