@tomflow/chatloop-tools 0.9.63 → 0.9.70

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 (83) hide show
  1. package/README.md +13 -1
  2. package/index.mjs +7 -7
  3. package/lib/context-control-run.mjs +23 -5
  4. package/lib/extension-proxy.mjs +16 -7
  5. package/lib/native-owner-v2.mjs +128 -0
  6. package/lib/release-health-checks.mjs +29 -5
  7. package/lib/trace-gateway.mjs +3 -1
  8. package/node_modules/@tomflow/chatloop-context/README.md +56 -0
  9. package/node_modules/@tomflow/chatloop-context/capabilities/document.mjs +24 -0
  10. package/node_modules/@tomflow/chatloop-context/capabilities/start.mjs +1 -1
  11. package/node_modules/@tomflow/chatloop-context/capabilities/task.mjs +2 -2
  12. package/node_modules/@tomflow/chatloop-context/docs/interfaces.md +69 -0
  13. package/node_modules/@tomflow/chatloop-context/index.mjs +3 -1
  14. package/node_modules/@tomflow/chatloop-context/lib/capability-catalog.generated.json +50 -3
  15. package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +54 -1
  16. package/node_modules/@tomflow/chatloop-context/lib/core/context.mjs +2 -0
  17. package/node_modules/@tomflow/chatloop-context/lib/core/health.mjs +61 -2
  18. package/node_modules/@tomflow/chatloop-context/lib/core/review.mjs +33 -0
  19. package/node_modules/@tomflow/chatloop-context/lib/core/run-cancel.mjs +14 -0
  20. package/node_modules/@tomflow/chatloop-context/lib/core/run-recovery.mjs +112 -0
  21. package/node_modules/@tomflow/chatloop-context/lib/core/run.mjs +31 -39
  22. package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +6 -5
  23. package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +84 -3
  24. package/node_modules/@tomflow/chatloop-context/lib/trusted-run.mjs +52 -7
  25. package/node_modules/@tomflow/chatloop-context/package.json +2 -4
  26. package/node_modules/@tomflow/chatloop-extension/README.md +66 -0
  27. package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +19 -4
  28. package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +40 -1
  29. package/node_modules/@tomflow/chatloop-extension/capabilities/session.mjs +1 -1
  30. package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +54 -4
  31. package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff-scoped.js +143 -0
  32. package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +9 -3
  33. package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +9 -5
  34. package/node_modules/@tomflow/chatloop-extension/extension/actions/session.js +53 -10
  35. package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +34 -0
  36. package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +16 -2
  37. package/node_modules/@tomflow/chatloop-extension/extension/background.js +16 -0
  38. package/node_modules/@tomflow/chatloop-extension/extension/loop/index.js +1 -1
  39. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-poll.js +7 -6
  40. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer.js +64 -7
  41. package/node_modules/@tomflow/chatloop-extension/extension/loop/resource-maintenance.js +159 -0
  42. package/node_modules/@tomflow/chatloop-extension/extension/loop/resources.js +235 -95
  43. package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +1 -0
  44. package/node_modules/@tomflow/chatloop-extension/extension/session.html +1 -0
  45. package/node_modules/@tomflow/chatloop-extension/extension/worker/admission.js +3 -0
  46. package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +73 -16
  47. package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +23 -6
  48. package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +237 -13
  49. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-action-v2.js +278 -0
  50. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-cancel-recovery-v2.js +52 -0
  51. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-cancel-v2.js +93 -0
  52. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-continue-recovery-v2.js +78 -0
  53. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-handoff-recovery-v2.js +148 -0
  54. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-handoff-v2.js +325 -0
  55. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-hold-recovery-v2.js +109 -0
  56. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-intent-dispatch-v2.js +220 -0
  57. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-intent-v2.js +106 -0
  58. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-owner-resolver.js +110 -0
  59. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-recover-v2.js +209 -0
  60. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-routes-v2.js +357 -0
  61. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-run-store.js +400 -0
  62. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-scheduler.js +78 -0
  63. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-start-v2.js +361 -0
  64. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-terminal-v2.js +235 -0
  65. package/node_modules/@tomflow/chatloop-extension/index.mjs +7 -0
  66. package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +94 -19
  67. package/node_modules/@tomflow/chatloop-extension/lib/browser-launch.mjs +3 -3
  68. package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +9 -2
  69. package/node_modules/@tomflow/chatloop-extension/lib/owner-kernel-lock.mjs +106 -0
  70. package/node_modules/@tomflow/chatloop-extension/lib/owner-ledger.mjs +316 -0
  71. package/node_modules/@tomflow/chatloop-extension/lib/owner-locked-write.mjs +30 -0
  72. package/node_modules/@tomflow/chatloop-extension/lib/scoped-cancel-v2.mjs +190 -0
  73. package/node_modules/@tomflow/chatloop-extension/lib/scoped-continue-v2.mjs +214 -0
  74. package/node_modules/@tomflow/chatloop-extension/lib/scoped-handoff-v2.mjs +338 -0
  75. package/node_modules/@tomflow/chatloop-extension/lib/scoped-native-control.mjs +398 -0
  76. package/node_modules/@tomflow/chatloop-extension/lib/scoped-recovery-v2.mjs +234 -0
  77. package/node_modules/@tomflow/chatloop-extension/lib/scoped-retire-v2.mjs +70 -0
  78. package/node_modules/@tomflow/chatloop-extension/lib/scoped-terminal-v2.mjs +143 -0
  79. package/node_modules/@tomflow/chatloop-extension/lib/session-file.mjs +50 -7
  80. package/node_modules/@tomflow/chatloop-extension/package.json +1 -3
  81. package/node_modules/@tomflow/chatloop-trace/package.json +1 -3
  82. package/package.json +9 -11
  83. package/providers/extension.mjs +59 -16
@@ -0,0 +1,398 @@
1
+ // Task-scoped Native protocol. A single Owner authority remains in Native.
2
+ import {createHash} from 'node:crypto';
3
+ const startSessionForRequest=requestId=>{
4
+ if(typeof requestId!=='string'||!/^[a-f0-9]{32}$/.test(requestId))
5
+ throw Object.assign(Error('Invalid Start request'),{
6
+ code:'SCOPED_START_REQUEST_ID_INVALID'});
7
+ const bytes=createHash('sha256')
8
+ .update('chatloop-start-v2:'+requestId).digest();
9
+ bytes[6]=(bytes[6]&0x0f)|0x50;
10
+ bytes[8]=(bytes[8]&0x3f)|0x80;
11
+ const hex=bytes.subarray(0,16).toString('hex');
12
+ return [hex.slice(0,8),hex.slice(8,12),hex.slice(12,16),
13
+ hex.slice(16,20),hex.slice(20)].join('-');
14
+ };
15
+ import {createScopedContinueControl} from './scoped-continue-v2.mjs';
16
+ import {createScopedHandoffControl} from './scoped-handoff-v2.mjs';
17
+ import {createScopedTerminalControl} from './scoped-terminal-v2.mjs';
18
+ import {createScopedCancelControl} from './scoped-cancel-v2.mjs';
19
+ import {createScopedRetireControl} from './scoped-retire-v2.mjs';
20
+ import {createScopedRecoveryControl} from './scoped-recovery-v2.mjs';
21
+ // Mutating Start operations require a private request and exact Ledger CAS.
22
+ // Exact-identity snapshot and writer checks are read-only, never sender permits.
23
+ export function createScopedNativeControl(ports){
24
+ const {readRequest,readScopedOwner,writeScopedOwner,
25
+ retireScopedOwner,nativeContextControl}=ports||{};
26
+ const continueControl=createScopedContinueControl(ports);
27
+ const handoffControl=createScopedHandoffControl(ports);
28
+ const recoveryControl=createScopedRecoveryControl({
29
+ ...ports,verifyOriginalAbort:m=>handoffControl.handle(m)});
30
+ const terminalControl=createScopedTerminalControl(ports);
31
+ const cancelControl=createScopedCancelControl(ports);
32
+ const retireControl=createScopedRetireControl(ports);
33
+ if([readRequest,readScopedOwner,writeScopedOwner,nativeContextControl]
34
+ .some(port=>typeof port!=='function'))throw Error('SCOPED_NATIVE_PORTS_MISSING');
35
+ return async function handleScopedNativeMessage(m){
36
+ let result=null;
37
+ const write=value=>{result=value};
38
+ if(['continue-permit-v2','continue-reconcile-v2',
39
+ 'continue-send-check-v2','continue-result-v2',
40
+ 'continue-result-read-v2'].includes(m?.op))
41
+ return continueControl.handle(m);
42
+ if(['handoff-permit-v2','handoff-send-check-v2',
43
+ 'handoff-abort-fence-v2',
44
+ 'handoff-abort-fence-read-v2','handoff-result-v2',
45
+ 'handoff-result-read-v2'].includes(m?.op))
46
+ return handoffControl.handle(m);
47
+ if(m?.op==='task-recover-handoff-v2')
48
+ return recoveryControl.handle(m);
49
+ if(m?.op==='task-recover-finalize-v2')
50
+ return recoveryControl.finalize(m);
51
+ if(m?.op==='task-recover-read-v2')
52
+ return recoveryControl.readCommitted(m);
53
+ if(m?.op==='task-terminal-v2')
54
+ return terminalControl.handle(m);
55
+ if(m?.op==='task-terminal-read-v2')
56
+ return terminalControl.readCommitted(m);
57
+ if(m?.op==='task-cancel-v2')
58
+ return cancelControl.handle(m);
59
+ if(m?.op==='task-cancel-read-v2')
60
+ return cancelControl.readCommitted(m);
61
+ if(m?.op==='task-retire-v2')
62
+ return retireControl.handle(m);
63
+ if(m?.op==='context-status-v2'){
64
+ // Existing Status Action, exact authorized Task only. No sender
65
+ // or permission grant. The trusted Context read independently checks
66
+ // Project access through its scoped principal and Native proof.
67
+ if(!m||Object.keys(m).length!==2
68
+ ||typeof m.sourceRequestId!=='string'
69
+ ||!/^[a-f0-9]{32}$/.test(m.sourceRequestId))
70
+ throw Object.assign(Error('Invalid Task status request'),
71
+ {code:'SCOPED_STATUS_SOURCE_INVALID'});
72
+ const request=readRequest(m.sourceRequestId),intent=request?.intent;
73
+ const id=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
74
+ if(request?.action!=='status'||!intent
75
+ ||Object.keys(intent).length!==2
76
+ ||!id.test(intent.projectId||'')||!id.test(intent.taskId||''))
77
+ throw Object.assign(Error('Exact status intent required'),
78
+ {code:'SCOPED_STATUS_SOURCE_INVALID'});
79
+ const current=readScopedOwner(intent.projectId,intent.taskId).session;
80
+ if(!current)throw Object.assign(Error('Task Owner not found'),
81
+ {code:'SCOPED_TASK_OWNER_NOT_FOUND'});
82
+ const proof=Object.fromEntries(['projectId','taskId','sessionId',
83
+ 'generation','revision','phase','activeChatId']
84
+ .map(k=>[k,current[k]]));
85
+ const state=await nativeContextControl('run.terminalStatus',{
86
+ projectId:current.projectId,taskId:current.taskId,
87
+ sessionId:current.sessionId,generation:current.generation,
88
+ activeChatId:current.activeChatId},{ownerProofV2:proof});
89
+ if(state?.projectId!==current.projectId
90
+ ||state.taskId!==current.taskId
91
+ ||!Number.isSafeInteger(state.taskRevision)
92
+ ||!Number.isSafeInteger(state.bindingRevision))
93
+ throw Object.assign(Error('Context Task Status unavailable'),
94
+ {code:'SCOPED_STATUS_CONTEXT_UNVERIFIED'});
95
+ const after=readScopedOwner(current.projectId,current.taskId).session;
96
+ if(!after||after.sessionId!==current.sessionId
97
+ ||after.generation!==current.generation
98
+ ||after.revision!==current.revision
99
+ ||after.phase!==current.phase
100
+ ||after.activeChatId!==current.activeChatId)
101
+ throw Object.assign(Error('Task owner changed'),
102
+ {code:'SCOPED_STATUS_OWNER_CHANGED'});
103
+ return {status:'OK',scope:'TASK_SCOPED_STATUS_READ_ONLY',
104
+ projectId:current.projectId,taskId:current.taskId,
105
+ sessionId:current.sessionId,generation:current.generation,
106
+ phase:current.phase,nativeOwnerRevision:current.revision,
107
+ context:{storeEpoch:state.storeEpoch,
108
+ taskRevision:state.taskRevision,
109
+ approvalRevision:state.approvalRevision,
110
+ bindingRevision:state.bindingRevision,
111
+ runBound:state.runRef!==null,
112
+ writerMatchesOwner:state.runRef===current.sessionId+':'+current.taskId+':'+current.generation,
113
+ pendingHandoff:state.pendingHandoff,
114
+ pendingCheckpoint:state.pendingCheckpointId!==null,
115
+ unknownEffectCount:state.unknownEffectCount,
116
+ executionOutcome:state.executionOutcome,
117
+ deliveryCommitted:state.executionOutcome==='DONE'
118
+ &&typeof state.deliveryRef==='string'&&state.deliveryRef.length>0,
119
+ writerApprovalCurrent:state.writerApprovalCurrent,
120
+ projectRulesDrift:state.projectRulesDrift,
121
+ sessionCancelled:state.sessionCancellation?.status==='CANCELLED_NOT_DELIVERED'
122
+ &&state.sessionCancellation.sessionId===current.sessionId
123
+ &&state.sessionCancellation.generation===current.generation}};
124
+ }
125
+ if(m?.op==='context-writer-check-v2'){
126
+ // A read-only, version-pinned send precondition. No approval or action
127
+ // token is manufactured here, and no browser message is sent.
128
+ const id=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
129
+ const uuid=/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
130
+ if(Object.keys(m).length!==6||!id.test(m.projectId||'')
131
+ ||!id.test(m.taskId||'')||!uuid.test(m.sessionId||'')
132
+ ||!Number.isSafeInteger(m.generation)||m.generation<0
133
+ ||!Number.isSafeInteger(m.expectedSessionRevision)
134
+ ||m.expectedSessionRevision<1)
135
+ throw Object.assign(Error('Invalid Task writer lookup'),
136
+ {code:'SCOPED_WRITER_SCOPE_INVALID'});
137
+ const observed=readScopedOwner(m.projectId,m.taskId).session;
138
+ if(!observed||observed.sessionId!==m.sessionId
139
+ ||observed.generation!==m.generation
140
+ ||observed.revision!==m.expectedSessionRevision
141
+ ||observed.phase!=='WAITING_REPLY'||!observed.activeChatId)
142
+ throw Object.assign(Error('Native writer owner drift'),
143
+ {code:'SCOPED_WRITER_OWNER_CHANGED'});
144
+ const proof=Object.fromEntries(['projectId','taskId','sessionId',
145
+ 'generation','revision','phase','activeChatId']
146
+ .map(k=>[k,observed[k]]));
147
+ const state=await nativeContextControl('run.terminalStatus',{
148
+ projectId:observed.projectId,taskId:observed.taskId,
149
+ sessionId:observed.sessionId,generation:observed.generation,
150
+ activeChatId:observed.activeChatId},{ownerProofV2:proof});
151
+ const wanted=observed.sessionId+':'+observed.taskId+':'+
152
+ observed.generation;
153
+ if(state?.projectId!==observed.projectId
154
+ ||state.taskId!==observed.taskId
155
+ ||state.runRef!==wanted
156
+ ||!Number.isSafeInteger(state.bindingRevision)
157
+ ||state.bindingRevision<1
158
+ ||typeof state.storeEpoch!=='string'
159
+ ||state.storeEpoch.length<10
160
+ ||!Number.isSafeInteger(state.taskRevision)
161
+ ||state.taskRevision<1
162
+ ||!Number.isSafeInteger(state.approvalRevision)
163
+ ||state.approvalRevision<1
164
+ ||state.unknownEffectCount!==0
165
+ ||state.pendingHandoff!==false
166
+ ||state.pendingCheckpointId!==null
167
+ ||state.writerApprovalCurrent!==true
168
+ ||state.projectRulesDrift!==false
169
+ ||state.sessionCancellation!==null
170
+ ||state.executionOutcome!==null)
171
+ throw Object.assign(Error('Context writer not ready'),
172
+ {code:'SCOPED_WRITER_UNVERIFIED'});
173
+ // Another Task's Ledger CAS must not invalidate this lookup, but this
174
+ // Task's Owner may have changed during the signed Context roundtrip.
175
+ const fresh=readScopedOwner(observed.projectId,observed.taskId).session;
176
+ if(!fresh||fresh.sessionId!==observed.sessionId
177
+ ||fresh.generation!==observed.generation
178
+ ||fresh.revision!==observed.revision
179
+ ||fresh.phase!=='WAITING_REPLY'
180
+ ||fresh.activeChatId!==observed.activeChatId)
181
+ throw Object.assign(Error('Native writer changed during lookup'),
182
+ {code:'SCOPED_WRITER_OWNER_CHANGED'});
183
+ return {status:'OK',scope:'TASK_SCOPED_WRITER_VERIFIED',
184
+ projectId:observed.projectId,taskId:observed.taskId,
185
+ sessionId:observed.sessionId,generation:observed.generation,
186
+ nativeOwnerRevision:observed.revision,
187
+ contextBindingRevision:state.bindingRevision,
188
+ contextStoreEpoch:state.storeEpoch,
189
+ taskRevision:state.taskRevision,
190
+ approvalRevision:state.approvalRevision};
191
+ }
192
+ if(m?.op==='session-snapshot-v2'){
193
+ // Internal exact-identity read for a Task-addressed Worker observer.
194
+ // This has no authority to claim a Chat, consume a permit or send.
195
+ const id=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
196
+ const uuid=/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
197
+ if(Object.keys(m).length!==5||!id.test(m.projectId||'')
198
+ ||!id.test(m.taskId||'')||!uuid.test(m.sessionId||'')
199
+ ||!Number.isSafeInteger(m.generation)||m.generation<0)
200
+ throw Object.assign(Error('Scoped read identity invalid'),
201
+ {code:'SCOPED_SNAPSHOT_SOURCE_INVALID'});
202
+ const current=readScopedOwner(m.projectId,m.taskId).session;
203
+ if(!current||current.sessionId!==m.sessionId
204
+ ||current.generation!==m.generation)
205
+ throw Object.assign(Error('Scoped session no longer owns Task'),
206
+ {code:'SCOPED_SNAPSHOT_IDENTITY_CHANGED'});
207
+ // Chat IDs alone do not distinguish the exact canonical group path.
208
+ // The Worker compares this URL to the real sender tab before routing.
209
+ const keys=['projectId','taskId','sessionId','generation','revision',
210
+ 'phase','activeChatId','activeChatUrl'];
211
+ return {status:'OK',scope:'TASK_SCOPED_SNAPSHOT',
212
+ session:Object.fromEntries(keys.map(k=>[k,current[k]]))};
213
+ }
214
+ if(m.op==='session-read-v2'||m.op==='session-sync-v2'){
215
+ // Start-scoped Native lifecycle. The private Start request proves the
216
+ // requested Task and lease, not that a web user Turn was actually sent.
217
+ // WAITING_REPLY claims are only safe when the Worker has independently
218
+ // verified the real browser/Observer source and Context permit.
219
+ const req=readRequest(m.sourceRequestId),intent=req?.intent;
220
+ if(req?.action!=='start'||intent?.taskFirst!==true
221
+ ||intent.mode!=='adopt'
222
+ ||intent.confirmed!==true||!intent.contextLeaseRef
223
+ ||!intent.taskId||!intent.projectId)
224
+ throw Object.assign(Error('V2 source not authorized'),
225
+ {code:'SCOPED_START_SOURCE_INVALID'});
226
+ if(m.op==='session-read-v2'){
227
+ const current=readScopedOwner(intent.projectId,intent.taskId);
228
+ write({status:'OK',scope:'TASK_SCOPED_READ_ONLY',
229
+ projectId:intent.projectId,taskId:intent.taskId,
230
+ ledgerRevision:current.ledgerRevision,session:current.session});
231
+ }else{
232
+ const s=m.session;
233
+ const prepermit=!!s&&['STARTING','RESERVED'].includes(s.phase)
234
+ &&s.activeChatId===null&&s.activeChatUrl===null;
235
+ const chatId=intent.chatUrl?.split('/').at(-1)||null;
236
+ const path=intent.chatUrl?new URL(intent.chatUrl).pathname:null;
237
+ const evidence=m.ownerEvidence;
238
+ const committing=!!s&&s.phase==='WAITING_REPLY'
239
+ &&typeof intent.chatUrl==='string'
240
+ &&s.activeChatUrl===intent.chatUrl&&s.activeChatId===chatId
241
+ &&evidence&&Object.keys(evidence).length===3
242
+ &&evidence.page===path
243
+ &&Number.isSafeInteger(evidence.tabId)&&evidence.tabId>0
244
+ &&typeof evidence.userKey==='string'
245
+ &&/^user:[^\s]{8,}$/.test(evidence.userKey);
246
+ // A pre-Permit Native reservation is claimable after an ACK loss
247
+ // ONLY by the same private Start request. No guessed Session ID,
248
+ // task-only fallback, or replay of a Context START Permit.
249
+ if(!s||s.projectId!==intent.projectId||s.taskId!==intent.taskId
250
+ ||s.sessionId!==startSessionForRequest(m.sourceRequestId)
251
+ ||s.generation!==0||!(prepermit||committing)
252
+ ||!Number.isSafeInteger(m.expectedLedgerRevision)
253
+ ||m.expectedLedgerRevision<0)
254
+ throw Object.assign(Error('V2 native projection denied'),
255
+ {code:'SCOPED_START_PREPERMIT_ONLY'});
256
+ if(committing){
257
+ const observed=readScopedOwner(intent.projectId,intent.taskId);
258
+ if(observed.session?.phase!=='PENDING'
259
+ ||observed.session?.generation!==0
260
+ ||observed.session?.activeChatId!==null
261
+ ||observed.session?.revision!==m.expectedSessionRevision)
262
+ throw Object.assign(Error('V2 source permit not confirmed'),
263
+ {code:'SCOPED_OWNER_PREPERMIT_UNVERIFIED'});
264
+ }
265
+ const committed=writeScopedOwner(s,{
266
+ expectedLedgerRevision:m.expectedLedgerRevision,
267
+ expectedSessionRevision:m.expectedSessionRevision??null});
268
+ write({status:'OK',scope:committing?'TASK_SCOPED_OWNER':'TASK_SCOPED_PREPERMIT',
269
+ ledgerRevision:committed.ledgerRevision,session:committed.session});
270
+ }
271
+ }else if(m.op==='context-control-v2'&&m.command==='run.bind.initial'){
272
+ // Owner promotion requires a prior exact Context permit, then Native
273
+ // may independently assert ownerCommitted for the initial binding.
274
+ // No DOM send occurs here. A failed/UNKNOWN bind remains fail-closed.
275
+ const req=readRequest(m.sourceRequestId),intent=req?.intent;
276
+ const a=m.args;
277
+ if(req?.action!=='start'||intent?.taskFirst!==true
278
+ ||intent.mode!=='adopt'
279
+ ||intent.confirmed!==true||!intent.taskId||!intent.contextLeaseRef
280
+ ||!a||typeof a!=='object'||Array.isArray(a)
281
+ ||a.expectedStoreEpoch!==intent.contextStoreEpoch
282
+ ||a.expectedTaskRevision!==intent.contextTaskRevision
283
+ ||a.expectedBindingRevision!==0
284
+ ||a.actionToken!==m.sourceRequestId
285
+ ||a.leaseRef!==intent.contextLeaseRef
286
+ ||typeof a.runCredential!=='string'
287
+ ||!/^[0-9a-f]{64}$/.test(a.runCredential))
288
+ throw Object.assign(Error('V2 bind intent invalid'),
289
+ {code:'SCOPED_BIND_SOURCE_UNVERIFIED'});
290
+ const scope=readScopedOwner(intent.projectId,intent.taskId),s=scope.session;
291
+ if(!s||s.phase!=='WAITING_REPLY'||s.generation!==0
292
+ ||s.activeChatUrl!==intent.chatUrl
293
+ ||m.expectedSessionRevision!==s.revision)
294
+ throw Object.assign(Error('Native owner not committed'),
295
+ {code:'SCOPED_BIND_OWNER_UNVERIFIED'});
296
+ const reserved=new Set(['projectId','taskId','sessionId',
297
+ 'generation','activeChatId','runRef','ownerCommitted',
298
+ 'role','principal','internalAuthorized','nativeCommitted']);
299
+ if(Object.keys(a).some(k=>reserved.has(k)))
300
+ throw Object.assign(Error('V2 reserved identity'),
301
+ {code:'CONTEXT_IDENTITY_FORBIDDEN'});
302
+ const args={...a,projectId:s.projectId,taskId:s.taskId,
303
+ sessionId:s.sessionId,generation:s.generation,
304
+ activeChatId:s.activeChatId,
305
+ runRef:s.sessionId+':'+s.taskId+':'+s.generation};
306
+ const proof=Object.fromEntries(['projectId','taskId','sessionId',
307
+ 'generation','revision','phase','activeChatId']
308
+ .map(k=>[k,s[k]]));
309
+ const result=await nativeContextControl('run.bind.initial',args,
310
+ {ownerProofV2:proof});
311
+ if(result?.status!=='BOUND'||result.runRef!==args.runRef)
312
+ throw Object.assign(Error('V2 binding not confirmed'),
313
+ {code:'SCOPED_INITIAL_BIND_UNVERIFIED'});
314
+ // Binding may have committed while the Native Owner changed. Its ACK
315
+ // cannot be used as permission to send on a stale Chat or generation.
316
+ const after=readScopedOwner(s.projectId,s.taskId).session;
317
+ if(!after||after.sessionId!==s.sessionId
318
+ ||after.generation!==s.generation
319
+ ||after.revision!==s.revision
320
+ ||after.phase!=='WAITING_REPLY'
321
+ ||after.activeChatId!==s.activeChatId
322
+ ||after.activeChatUrl!==s.activeChatUrl)
323
+ throw Object.assign(Error('Native changed during Context bind'),
324
+ {code:'SCOPED_BIND_OWNER_CHANGED'});
325
+ write({status:'OK',scope:'TASK_SCOPED_BOUND',result,
326
+ sessionRevision:s.revision});
327
+ }else if(m.op==='context-control-v2'){
328
+ // A version-pinned Task Start permit, never inferred from global V1.
329
+ // Only START is supported here; Continue/Handoff/Recovery are not.
330
+ const request=readRequest(m.sourceRequestId),intent=request?.intent;
331
+ if(request?.action!=='start'||intent?.taskFirst!==true
332
+ ||intent.mode!=='adopt'
333
+ ||intent.confirmed!==true||!intent.taskId||!intent.contextLeaseRef
334
+ ||m.command!=='permit.consume'
335
+ ||!m.args||typeof m.args!=='object'||Array.isArray(m.args)
336
+ ||m.args.kind!=='START'||m.args.adopt!==true
337
+ ||m.args.leaseRef!==intent.contextLeaseRef
338
+ ||m.args.expectedStoreEpoch!==intent.contextStoreEpoch
339
+ ||m.args.expectedTaskRevision!==intent.contextTaskRevision
340
+ ||m.args.expectedApprovalRevision!==intent.contextApprovalRevision
341
+ ||m.args.actionToken!==m.sourceRequestId)
342
+ throw Object.assign(Error('V2 permit source invalid'),
343
+ {code:'SCOPED_CONTEXT_PREPERMIT_ONLY'});
344
+ const status=readScopedOwner(intent.projectId,intent.taskId);
345
+ const s=status.session;
346
+ if(!s||s.phase!=='RESERVED'||s.generation!==0
347
+ ||s.activeChatId!==null||s.activeChatUrl!==null
348
+ ||m.expectedSessionRevision!==s.revision)
349
+ throw Object.assign(Error('V2 Native owner mismatch'),
350
+ {code:'SCOPED_CONTEXT_OWNER_MISMATCH'});
351
+ const own=new Set(['projectId','taskId','sessionId','generation',
352
+ 'activeChatId','runRef','role','principal','internalAuthorized',
353
+ 'nativeCommitted','ownerCommitted','sourceRunRef']);
354
+ if(Object.keys(m.args).some(k=>own.has(k)))
355
+ throw Object.assign(Error('Reserved Context identity'),
356
+ {code:'CONTEXT_IDENTITY_FORBIDDEN'});
357
+ const args={...m.args,projectId:s.projectId,taskId:s.taskId,
358
+ sessionId:s.sessionId,generation:s.generation,
359
+ activeChatId:s.activeChatId};
360
+ const proof=Object.fromEntries(['projectId','taskId','sessionId',
361
+ 'generation','revision','phase','activeChatId']
362
+ .map(k=>[k,s[k]]));
363
+ const result=await nativeContextControl(m.command,args,{ownerProofV2:proof});
364
+ if(result?.status!=='PERMITTED')
365
+ throw Object.assign(Error('Context permit was not confirmed'),
366
+ {code:'SCOPED_CONTEXT_PERMIT_UNVERIFIED'});
367
+ // Context wrote its one-use permit; now persist the proof that Native
368
+ // observed that exact result. If this second transaction fails, the
369
+ // session remains fail-closed and the original Context receipt must be
370
+ // investigated. Never reconsume a permit with another token.
371
+ let pinned=null;
372
+ for(let retry=0;retry<3;retry++){
373
+ const observed=readScopedOwner(s.projectId,s.taskId);
374
+ if(observed.session?.revision!==s.revision)
375
+ throw Object.assign(Error('Owner changed after permit'),
376
+ {code:'SCOPED_PERMIT_OWNER_CHANGED'});
377
+ try{
378
+ const {revision,...nextSession}=s;
379
+ pinned=writeScopedOwner({...nextSession,phase:'PENDING',
380
+ updatedAt:Date.now()},{
381
+ expectedLedgerRevision:observed.ledgerRevision,
382
+ expectedSessionRevision:revision});
383
+ break;
384
+ }catch(error){
385
+ if(error?.code!=='OWNER_LEDGER_CAS_MISMATCH'||retry===2)throw error;
386
+ }
387
+ }
388
+ if(pinned?.session.phase!=='PENDING'
389
+ ||pinned.session.revision!==s.revision+1)
390
+ throw Object.assign(Error('Native permit pin not confirmed'),
391
+ {code:'SCOPED_PERMIT_LEDGER_UNVERIFIED'});
392
+ write({status:'OK',result,scope:'TASK_SCOPED_PERMIT',
393
+ sessionRevision:pinned.session.revision});
394
+
395
+ }
396
+ return result;
397
+ };
398
+ }
@@ -0,0 +1,234 @@
1
+ // Stage 06: recover the ORIGINAL Task/Chat after a proven NOT_SENT handoff.
2
+ // Uses the existing signed session Action, Native Owner ledger, and one Context
3
+ // SQLite authority. Never clicks a Chat composer or replays a Handoff.
4
+ export function createScopedRecoveryControl(ports){
5
+ const {readRequest,readScopedOwner,writeScopedOwner,nativeContextControl,
6
+ verifyOriginalAbort}=ports;
7
+ const fail=code=>Object.assign(Error(code),{code});
8
+ const yes=(v,code)=>{if(!v)throw fail(code)};
9
+ const ID=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
10
+ const UUID=/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f-]{12}$/i;
11
+ const HEX=/^[a-f0-9]{32}$/;
12
+ const proof=s=>Object.fromEntries(['projectId','taskId','sessionId',
13
+ 'generation','revision','phase','activeChatId'].map(k=>[k,s[k]]));
14
+ const context=(op,args,s)=>nativeContextControl(op,{
15
+ projectId:s.projectId,taskId:s.taskId,sessionId:s.sessionId,
16
+ generation:s.generation,activeChatId:s.activeChatId,...args
17
+ },{ownerProofV2:proof(s)});
18
+ function source(m,read=false){
19
+ const keys=['op','sourceRequestId','originalAttemptId','originalTurnToken',
20
+ 'projectId','taskId','sessionId','generation','expectedSessionRevision',
21
+ 'expectedStoreEpoch','expectedTaskRevision','expectedBindingRevision',
22
+ 'checkpointId'];
23
+ yes(m&&typeof m==='object'&&!Array.isArray(m)
24
+ &&(read?m.op==='task-recover-read-v2'
25
+ :['task-recover-handoff-v2','task-recover-finalize-v2'].includes(m.op))
26
+ &&Object.keys(m).length===keys.length
27
+ &&keys.every(k=>Object.hasOwn(m,k))
28
+ &&HEX.test(m.sourceRequestId||'')&&HEX.test(m.originalAttemptId||'')
29
+ &&m.sourceRequestId!==m.originalAttemptId
30
+ &&UUID.test(m.originalTurnToken||'')
31
+ &&ID.test(m.projectId||'')&&ID.test(m.taskId||'')
32
+ &&UUID.test(m.sessionId||'')
33
+ &&Number.isSafeInteger(m.generation)&&m.generation>=0
34
+ &&Number.isSafeInteger(m.expectedSessionRevision)
35
+ &&m.expectedSessionRevision>=2
36
+ &&typeof m.expectedStoreEpoch==='string'
37
+ &&m.expectedStoreEpoch.length>=10
38
+ &&Number.isSafeInteger(m.expectedTaskRevision)
39
+ &&m.expectedTaskRevision>=1
40
+ &&Number.isSafeInteger(m.expectedBindingRevision)
41
+ &&m.expectedBindingRevision>=2
42
+ &&ID.test(m.checkpointId||''),'SCOPED_RECOVERY_SOURCE_INVALID');
43
+ const request=readRequest(m.sourceRequestId),intent=request?.intent;
44
+ yes(request?.action==='session'&&intent?.taskFirst===true
45
+ &&intent.operation==='recover-handoff'&&intent.confirmed===true
46
+ &&intent.projectId===m.projectId&&intent.taskId===m.taskId
47
+ &&intent.sessionId===m.sessionId&&intent.generation===m.generation
48
+ &&intent.expectedNativeRevision===m.expectedSessionRevision
49
+ &&intent.originalAttemptId===m.originalAttemptId
50
+ &&/^[0-9a-f]{64}$/.test(intent.newRunCredential||''),
51
+ 'SCOPED_RECOVERY_INTENT_UNVERIFIED');
52
+ return intent;
53
+ }
54
+ function owner(m,phase,revision){
55
+ const current=readScopedOwner(m.projectId,m.taskId);
56
+ const s=current.session;
57
+ yes(s&&s.projectId===m.projectId&&s.taskId===m.taskId
58
+ &&s.sessionId===m.sessionId&&s.generation===m.generation
59
+ &&s.revision===revision&&s.phase===phase
60
+ &&typeof s.activeChatId==='string'&&s.activeChatUrl,
61
+ 'SCOPED_RECOVERY_OWNER_CHANGED');
62
+ return current;
63
+ }
64
+ async function original(m){
65
+ const r=await verifyOriginalAbort({
66
+ op:'handoff-abort-fence-read-v2',
67
+ sourceRequestId:m.originalAttemptId,
68
+ projectId:m.projectId,taskId:m.taskId,sessionId:m.sessionId,
69
+ generation:m.generation,
70
+ expectedSessionRevision:m.expectedSessionRevision-1,
71
+ expectedStoreEpoch:m.expectedStoreEpoch,
72
+ expectedBindingRevision:m.expectedBindingRevision-1,
73
+ turnToken:m.originalTurnToken,
74
+ checkpointId:m.checkpointId,
75
+ fencedBindingRevision:m.expectedBindingRevision
76
+ });
77
+ yes(r?.status==='REVOKED'
78
+ &&r.readOnly===true&&r.scope==='TASK_SCOPED_HANDOFF_ABORT_REVOKED'
79
+ &&r.nativeOwnerRevision===m.expectedSessionRevision,
80
+ 'SCOPED_RECOVERY_ABORT_NOT_PROVEN');
81
+ }
82
+ const healthy=(state,m,s,restored=false)=>state?.projectId===m.projectId
83
+ &&state.taskId===m.taskId&&state.storeEpoch===m.expectedStoreEpoch
84
+ &&state.taskRevision===m.expectedTaskRevision
85
+ &&state.bindingRevision===m.expectedBindingRevision+(restored?1:0)
86
+ &&state.unknownEffectCount===0
87
+ &&state.executionOutcome===null
88
+ &&state.sessionCancellation===null
89
+ &&state.projectRulesDrift===false
90
+ &&state.writerApprovalCurrent===restored
91
+ &&state.pendingHandoff===!restored
92
+ &&(restored?state.runRef===s.sessionId+':'+s.taskId+':'+s.generation
93
+ &&state.pendingCheckpointId===null
94
+ :state.runRef===null&&state.pendingCheckpointId===m.checkpointId
95
+ &&state.pendingAttemptMatches===true);
96
+ function commitOwner(m,s){
97
+ const fresh=owner(m,'BLOCKED',m.expectedSessionRevision);
98
+ const committed=writeScopedOwner({
99
+ projectId:s.projectId,taskId:s.taskId,sessionId:s.sessionId,
100
+ generation:s.generation,phase:'WAITING_REPLY',
101
+ activeChatId:s.activeChatId,activeChatUrl:s.activeChatUrl,
102
+ updatedAt:Date.now()
103
+ },{expectedLedgerRevision:fresh.ledgerRevision,
104
+ expectedSessionRevision:s.revision,
105
+ transitionKind:'CONTEXT_HANDOFF_RECOVERED'});
106
+ yes(committed.session?.phase==='WAITING_REPLY'
107
+ &&committed.session.revision===s.revision+1,
108
+ 'SCOPED_RECOVERY_NATIVE_COMMIT_UNKNOWN');
109
+ return committed.session;
110
+ }
111
+ async function handle(m){
112
+ const intent=source(m);
113
+ const current=owner(m,'BLOCKED',m.expectedSessionRevision),s=current.session;
114
+ await original(m);
115
+ const state=await context('run.terminalStatus',{
116
+ expectedHandoffAttemptId:m.originalAttemptId
117
+ },s);
118
+ yes(healthy(state,m,s),'SCOPED_RECOVERY_CONTEXT_UNVERIFIED');
119
+ yes(readScopedOwner(s.projectId,s.taskId).session?.revision===s.revision,
120
+ 'SCOPED_RECOVERY_OWNER_RACED');
121
+ const permitted=await context('permit.consume',{
122
+ expectedStoreEpoch:m.expectedStoreEpoch,
123
+ expectedTaskRevision:m.expectedTaskRevision,
124
+ expectedApprovalRevision:state.approvalRevision,
125
+ expectedBindingRevision:m.expectedBindingRevision,
126
+ kind:'RECOVER_HANDOFF',actionToken:m.sourceRequestId,
127
+ recoveryOfAttemptId:m.originalAttemptId,
128
+ checkpointId:m.checkpointId,
129
+ writeRequestId:m.sourceRequestId+':recovery-permit'
130
+ },s);
131
+ yes(permitted?.status==='PERMITTED'
132
+ &&permitted.actionToken===m.sourceRequestId,
133
+ 'SCOPED_RECOVERY_PERMIT_UNKNOWN');
134
+ owner(m,'BLOCKED',m.expectedSessionRevision);
135
+ const newCredential=intent.newRunCredential;
136
+ const recovered=await context('run.restore-fenced-handoff',{
137
+ expectedStoreEpoch:m.expectedStoreEpoch,
138
+ expectedTaskRevision:m.expectedTaskRevision,
139
+ expectedBindingRevision:m.expectedBindingRevision,
140
+ expectedApprovalRevision:state.approvalRevision,
141
+ writeRequestId:m.sourceRequestId+':recovery-bind',
142
+ attemptId:m.originalAttemptId,checkpointId:m.checkpointId,
143
+ recoveryActionToken:m.sourceRequestId,
144
+ newRunCredential:newCredential
145
+ },s);
146
+ yes(recovered?.status==='HANDOFF_WRITER_RESTORED'
147
+ &&recovered.runRef===s.sessionId+':'+s.taskId+':'+s.generation
148
+ &&recovered.bindingRevision===m.expectedBindingRevision+1,
149
+ 'SCOPED_RECOVERY_CONTEXT_BIND_UNKNOWN');
150
+ const after=await context('run.terminalStatus',{},s);
151
+ yes(healthy(after,m,s,true),'SCOPED_RECOVERY_CONTEXT_READ_UNKNOWN');
152
+ const committed=commitOwner(m,s);
153
+ return {status:'RECOVERED',scope:'TASK_SCOPED_WRITER_RECOVERED',
154
+ projectId:s.projectId,taskId:s.taskId,sessionId:s.sessionId,
155
+ generation:s.generation,nativeOwnerRevision:committed.revision,
156
+ contextBindingRevision:after.bindingRevision,
157
+ contextStoreEpoch:after.storeEpoch,
158
+ runRef:recovered.runRef,newRunCredential:newCredential};
159
+ }
160
+ async function readCommitted(m){
161
+ source(m,true);
162
+ const s=owner(m,'WAITING_REPLY',m.expectedSessionRevision+1).session;
163
+ const state=await context('run.terminalStatus',{},s);
164
+ yes(healthy(state,m,s,true),'SCOPED_RECOVERY_READ_CONTEXT_UNVERIFIED');
165
+ const permit=await context('permit.status',{
166
+ actionToken:m.sourceRequestId
167
+ },s);
168
+ yes(permit?.status==='RECORDED'&&permit.kind==='USED'
169
+ &&permit.actionToken===m.sourceRequestId
170
+ &&permit.approvalRevision===state.approvalRevision,
171
+ 'SCOPED_RECOVERY_READ_PERMIT_UNVERIFIED');
172
+ owner(m,'WAITING_REPLY',m.expectedSessionRevision+1);
173
+ return {status:'RECOVERED',scope:'TASK_SCOPED_WRITER_RECOVERED',
174
+ nativeOwnerRevision:s.revision,
175
+ contextBindingRevision:state.bindingRevision,readOnly:true};
176
+ }
177
+ async function finalize(m){
178
+ // Original signed request only: reconcile the three durable states.
179
+ // 1. Restored Context + BLOCKED Native -> finish solely Native CAS.
180
+ // 2. Exact unused recovery permit + still-fenced Context -> continue
181
+ // its one-time Context bind, then finish Native CAS.
182
+ // Never reconsume permit.consume, reissue credentials, or click a Chat.
183
+ const intent=source(m),s=owner(m,'BLOCKED',m.expectedSessionRevision).session;
184
+ let state=await context('run.terminalStatus',{
185
+ expectedHandoffAttemptId:m.originalAttemptId
186
+ },s);
187
+ const old=await context('permit.status',{
188
+ actionToken:m.originalAttemptId
189
+ },s);
190
+ let permit=await context('permit.status',{
191
+ actionToken:m.sourceRequestId
192
+ },s);
193
+ yes(old?.status==='RECORDED'&&old.kind==='USED'
194
+ &&old.approvalRevision===state.approvalRevision
195
+ &&permit?.status==='RECORDED'
196
+ &&permit.approvalRevision===state.approvalRevision,
197
+ 'SCOPED_RECOVERY_FINALIZE_PERMIT_UNVERIFIED');
198
+ if(healthy(state,m,s,false)){
199
+ yes(permit.kind==='RECOVER_HANDOFF',
200
+ 'SCOPED_RECOVERY_FINALIZE_PERMIT_NOT_RESERVED');
201
+ await original(m);
202
+ owner(m,'BLOCKED',m.expectedSessionRevision);
203
+ const rebound=await context('run.restore-fenced-handoff',{
204
+ expectedStoreEpoch:m.expectedStoreEpoch,
205
+ expectedTaskRevision:m.expectedTaskRevision,
206
+ expectedBindingRevision:m.expectedBindingRevision,
207
+ expectedApprovalRevision:state.approvalRevision,
208
+ writeRequestId:m.sourceRequestId+':recovery-bind',
209
+ attemptId:m.originalAttemptId,checkpointId:m.checkpointId,
210
+ recoveryActionToken:m.sourceRequestId,
211
+ newRunCredential:intent.newRunCredential
212
+ },s);
213
+ yes(rebound?.status==='HANDOFF_WRITER_RESTORED'
214
+ &&rebound.bindingRevision===m.expectedBindingRevision+1,
215
+ 'SCOPED_RECOVERY_FINALIZE_BIND_UNKNOWN');
216
+ state=await context('run.terminalStatus',{},s);
217
+ permit=await context('permit.status',{
218
+ actionToken:m.sourceRequestId
219
+ },s);
220
+ }
221
+ yes(healthy(state,m,s,true)&&permit.kind==='USED'
222
+ &&permit.approvalRevision===state.approvalRevision,
223
+ 'SCOPED_RECOVERY_FINALIZE_CONTEXT_UNVERIFIED');
224
+ const committed=commitOwner(m,s);
225
+ return {status:'RECOVERED',scope:'TASK_SCOPED_WRITER_RECOVERED',
226
+ projectId:s.projectId,taskId:s.taskId,sessionId:s.sessionId,
227
+ generation:s.generation,nativeOwnerRevision:committed.revision,
228
+ contextBindingRevision:state.bindingRevision,
229
+ contextStoreEpoch:state.storeEpoch,
230
+ runRef:s.sessionId+':'+s.taskId+':'+s.generation,
231
+ newRunCredential:intent.newRunCredential};
232
+ }
233
+ return Object.freeze({handle,readCommitted,finalize});
234
+ }