@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,316 @@
1
+ // V2 Native Chat-claim ledger. Data is browser ownership, NOT business Task state.
2
+ import {openSync,closeSync,readFileSync,writeFileSync,renameSync,unlinkSync,
3
+ lstatSync,mkdirSync,fsyncSync} from 'node:fs';
4
+ import {homedir} from 'node:os';
5
+ import {join} from 'node:path';
6
+ import {randomUUID} from 'node:crypto';
7
+ import {withOwnerKernelLock} from './owner-kernel-lock.mjs';
8
+ const ID=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
9
+ const UUID=/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
10
+ const CHAT=/^[0-9a-f-]{12,}$/i;
11
+ const URL=/^https:\/\/chatgpt\.com\/(?:c\/[0-9a-f-]{12,}|g\/[^/]+\/c\/[0-9a-f-]{12,})$/i;
12
+ const PHASE=new Set(['STARTING','RESERVED','PENDING','WAITING_REPLY','DONE','BLOCKED','CANCELLED']);
13
+ // These are only the phases implemented by the current V2 Start route.
14
+ // Recovery, HANDOFF and terminal fencing require independently reviewed
15
+ // Context proof contracts; no generic backward "resume" is admitted here.
16
+ const NEXT=Object.freeze({
17
+ STARTING:['STARTING','RESERVED','BLOCKED'],
18
+ RESERVED:['RESERVED','PENDING','BLOCKED'],
19
+ PENDING:['PENDING','WAITING_REPLY','BLOCKED'],
20
+ // A new user Turn needs a versioned Context permit + send fence;
21
+ // the current V2 Start-only contract cannot re-enter PENDING.
22
+ WAITING_REPLY:['WAITING_REPLY','BLOCKED','DONE'],
23
+ BLOCKED:['BLOCKED']
24
+ });
25
+ const fail=code=>Object.assign(Error(code),{code});
26
+ const assert=(ok,code)=>{if(!ok)throw fail(code);};
27
+ const directory=()=>join(homedir(),'.chat-loop','session');
28
+ export const ownerLedgerPath=()=>join(directory(),'owner-ledger-v2.json');
29
+ export const ownerLedgerLockPath=()=>join(directory(),'owner-registry.lock');
30
+ export const taskOwnerKey=(projectId,taskId)=>JSON.stringify([projectId,taskId]);
31
+ const terminal=phase=>phase==='DONE'||phase==='CANCELLED';
32
+ const retiredKey=(s)=>JSON.stringify([s.projectId,s.taskId,s.sessionId,s.revision]);
33
+ const RETIRE_HISTORY_LIMIT=256;
34
+ // Small Native-only receipts close the gap when a terminal deletion commits
35
+ // but the one-shot Native ACK is lost before Worker Task Store cleanup.
36
+ const statOrNull=p=>{try{return lstatSync(p);}catch(e){if(e.code==='ENOENT')return null;throw e;}};
37
+ function verifyDir(create=false){
38
+ const dir=directory();
39
+ let st=statOrNull(dir);
40
+ if(!st&&create){mkdirSync(dir,{recursive:true,mode:0o700});st=statOrNull(dir);}
41
+ if(st)assert(st.isDirectory()&&!st.isSymbolicLink()&&
42
+ (!process.getuid||st.uid===process.getuid())&&
43
+ (process.platform==='win32'||!(st.mode&0o077)),'OWNER_DIRECTORY_UNTRUSTED');
44
+ return Boolean(st);
45
+ }
46
+ function checkedFile(file){
47
+ const st=statOrNull(file);
48
+ if(!st)return null;
49
+ assert(st.isFile()&&!st.isSymbolicLink()&&st.size<=128*1024&&
50
+ (!process.getuid||st.uid===process.getuid())&&
51
+ (process.platform==='win32'||!(st.mode&0o077)),'OWNER_FILE_UNTRUSTED');
52
+ return readFileSync(file,'utf8');
53
+ }
54
+ // V1/V2 write wrappers share one Darwin kernel lock; never use the old
55
+ // unlink-on-exit O_EXCL lock or clear a legacy lock based on age/PID.
56
+ function commitOwnerLedger(ledger){
57
+ const encoded=JSON.stringify(ledger)+'\n';
58
+ assert(Buffer.byteLength(encoded)<=128*1024,'OWNER_LEDGER_SIZE_LIMIT');
59
+ const temp=join(directory(),'.owner-ledger-'+randomUUID()+'.tmp');
60
+ try{
61
+ const out=openSync(temp,'wx',0o600);
62
+ try{writeFileSync(out,encoded);fsyncSync(out);}
63
+ finally{closeSync(out);}
64
+ renameSync(temp,ownerLedgerPath());
65
+ const dirFd=openSync(directory(),'r');
66
+ try{fsyncSync(dirFd);}finally{closeSync(dirFd);}
67
+ }finally{try{unlinkSync(temp);}catch{}}
68
+ }
69
+ function validSession(s,persisted=false){
70
+ const names=['projectId','taskId','sessionId','generation','phase',
71
+ 'activeChatId','activeChatUrl','updatedAt',...(persisted?['revision']:[])];
72
+ assert(s&&typeof s==='object'&&!Array.isArray(s)&&
73
+ Object.keys(s).length===names.length&&
74
+ names.every(n=>Object.hasOwn(s,n))&&
75
+ ID.test(s.projectId)&&ID.test(s.taskId)&&UUID.test(s.sessionId)&&
76
+ Number.isSafeInteger(s.generation)&&s.generation>=0&&
77
+ PHASE.has(s.phase)&&Number.isSafeInteger(s.updatedAt)&&s.updatedAt>0&&
78
+ (!persisted||Number.isSafeInteger(s.revision)&&s.revision>=1),'OWNER_SESSION_INVALID');
79
+ assert((s.activeChatId===null&&s.activeChatUrl===null)||
80
+ (typeof s.activeChatId==='string'&&CHAT.test(s.activeChatId)&&
81
+ typeof s.activeChatUrl==='string'&&URL.test(s.activeChatUrl)&&
82
+ s.activeChatUrl.endsWith('/'+s.activeChatId)),'OWNER_CHAT_INVALID');
83
+ assert(s.phase!=='WAITING_REPLY'||s.activeChatId!==null,'OWNER_CHAT_INVALID');
84
+ return Object.fromEntries(names.map(n=>[n,s[n]]));
85
+ }
86
+ function validateLedger(obj){
87
+ assert(obj&&typeof obj==='object'&&!Array.isArray(obj)&&
88
+ [3,4].includes(Object.keys(obj).length)
89
+ &&Object.keys(obj).every(k=>['schemaVersion','ledgerRevision',
90
+ 'sessions','retired'].includes(k))
91
+ &&obj.schemaVersion===2&&
92
+ Number.isSafeInteger(obj.ledgerRevision)&&obj.ledgerRevision>=0&&
93
+ obj.sessions&&typeof obj.sessions==='object'&&!Array.isArray(obj.sessions),
94
+ 'OWNER_LEDGER_INVALID');
95
+ const entries=Object.entries(obj.sessions);
96
+ assert(entries.length<=64,'OWNER_LEDGER_CAPACITY');
97
+ const rawRetired=obj.retired??{};
98
+ assert(rawRetired&&typeof rawRetired==='object'
99
+ &&!Array.isArray(rawRetired)
100
+ &&Object.keys(rawRetired).length<=RETIRE_HISTORY_LIMIT
101
+ &&(obj.retired===undefined||Object.hasOwn(obj,'retired')),
102
+ 'OWNER_RETIRE_HISTORY_INVALID');
103
+ const retired=Object.create(null);
104
+ for(const [key,r] of Object.entries(rawRetired)){
105
+ assert(r&&typeof r==='object'&&!Array.isArray(r)
106
+ &&Object.keys(r).length===7
107
+ &&ID.test(r.projectId||'')&&ID.test(r.taskId||'')
108
+ &&UUID.test(r.sessionId||'')
109
+ &&Number.isSafeInteger(r.generation)&&r.generation>=0
110
+ &&Number.isSafeInteger(r.revision)&&r.revision>=1
111
+ &&terminal(r.phase)
112
+ &&Number.isSafeInteger(r.retiredAt)&&r.retiredAt>0
113
+ &&key===retiredKey(r),'OWNER_RETIRE_HISTORY_INVALID');
114
+ retired[key]={...r};
115
+ }
116
+ const sessions=Object.create(null),claims=new Set(),sessionIds=new Set();
117
+ let active=0;
118
+ for(const [key,raw] of entries){
119
+ const s=validSession(raw,true);
120
+ assert(key===taskOwnerKey(s.projectId,s.taskId),'OWNER_TASK_KEY_INVALID');
121
+ const sessionKey=s.sessionId.toLowerCase();
122
+ assert(!sessionIds.has(sessionKey),'OWNER_SESSION_DUPLICATE');
123
+ sessionIds.add(sessionKey);
124
+ if(!terminal(s.phase)){
125
+ active++;
126
+ if(s.activeChatId!==null){
127
+ const claim=s.activeChatId.toLowerCase();
128
+ assert(!claims.has(claim),'OWNER_CHAT_DUPLICATE');
129
+ claims.add(claim);
130
+ }
131
+ }
132
+ sessions[key]=s;
133
+ }
134
+ assert(active<=32,'OWNER_LEDGER_CAPACITY');
135
+ return {schemaVersion:2,ledgerRevision:obj.ledgerRevision,
136
+ sessions,retired};
137
+ }
138
+ export function readOwnerLedger(){
139
+ if(!verifyDir())return null;
140
+ const raw=checkedFile(ownerLedgerPath());
141
+ if(raw===null)return null;
142
+ try{return validateLedger(JSON.parse(raw));}
143
+ catch(e){if(e.code)throw e;throw fail('OWNER_LEDGER_CORRUPT');}
144
+ }
145
+ export function readOwnerLedgerTask(projectId,taskId){
146
+ assert(typeof projectId==='string'&&ID.test(projectId)&&
147
+ typeof taskId==='string'&&ID.test(taskId),'OWNER_TASK_SCOPE_INVALID');
148
+ const ledger=readOwnerLedger();
149
+ return {ledgerRevision:ledger?.ledgerRevision??0,
150
+ session:ledger?.sessions[taskOwnerKey(projectId,taskId)]??null};
151
+ }
152
+ export function hasActiveLedgerOwner(){
153
+ const ledger=readOwnerLedger();
154
+ return Boolean(ledger&&Object.values(ledger.sessions).some(s=>!terminal(s.phase)));
155
+ }
156
+ function assertLegacyInactive(){
157
+ // No V1/V2 split brain: a BLOCKED or UNKNOWN legacy owner stays fenced.
158
+ const raw=checkedFile(join(directory(),'active-session.json'));
159
+ if(raw===null)return;
160
+ let old;
161
+ try{old=JSON.parse(raw);}catch{throw fail('LEGACY_OWNER_UNVERIFIED');}
162
+ assert(old&&terminal(old.phase)&&UUID.test(old.sessionId||''),
163
+ 'LEGACY_OWNER_NOT_TERMINAL');
164
+ }
165
+ export function writeOwnerLedgerSession(input,options={}){
166
+ return withOwnerKernelLock('scoped-write',[input,options]);
167
+ }
168
+ export function writeOwnerLedgerSessionLocked(input,{expectedLedgerRevision,
169
+ expectedSessionRevision=null,transitionKind=null}={}){
170
+ const next=validSession(input);
171
+ assert(Number.isSafeInteger(expectedLedgerRevision)&&expectedLedgerRevision>=0,
172
+ 'OWNER_LEDGER_CAS_REQUIRED');
173
+ assert(expectedSessionRevision===null||
174
+ Number.isSafeInteger(expectedSessionRevision)&&expectedSessionRevision>=1,
175
+ 'OWNER_SESSION_CAS_REQUIRED');
176
+ assert(transitionKind===null
177
+ ||['CONTEXT_CONTINUE_PERMITTED','CONTEXT_HANDOFF_PERMITTED',
178
+ 'CONTEXT_IDLE_CANCELLED','CONTEXT_HANDOFF_RECOVERED'].includes(transitionKind),
179
+ 'OWNER_TRANSITION_AUTHORITY_INVALID');
180
+ verifyDir(true);
181
+ // All Owner transitions still wait only before entering the CAS; a lost
182
+ // post-commit ACK must be investigated, never blindly retried.
183
+ {
184
+ assertLegacyInactive();
185
+ const prior=readOwnerLedger()||{schemaVersion:2,ledgerRevision:0,sessions:{}};
186
+ // The OS-wide lock serializes commits. Global revision is a snapshot
187
+ // watermark, not a reason to reject an unrelated Task's valid Session
188
+ // CAS; cross-Task Chat/Session conflicts are checked against latest data.
189
+ assert(expectedLedgerRevision<=prior.ledgerRevision,'OWNER_LEDGER_CAS_MISMATCH');
190
+ const key=taskOwnerKey(next.projectId,next.taskId),old=prior.sessions[key]||null;
191
+ assert((old?.revision??null)===expectedSessionRevision,
192
+ 'OWNER_SESSION_CAS_MISMATCH');
193
+ if(old){
194
+ if(terminal(old.phase)){
195
+ // A later execution Session for this Task must be a fresh, unsent
196
+ // generation-zero reservation. Context must separately approve it.
197
+ assert(old.sessionId.toLowerCase()!==next.sessionId.toLowerCase()
198
+ &&next.generation===0&&
199
+ next.phase==='STARTING'&&next.activeChatId===null,
200
+ 'OWNER_RESTART_REQUIRES_PREPERMIT');
201
+ }else{
202
+ const permittedContinue=['CONTEXT_CONTINUE_PERMITTED',
203
+ 'CONTEXT_HANDOFF_PERMITTED'].includes(transitionKind)
204
+ &&old.phase==='WAITING_REPLY'&&next.phase==='PENDING'
205
+ &&old.sessionId===next.sessionId
206
+ &&old.generation===next.generation
207
+ &&old.activeChatId===next.activeChatId
208
+ &&old.activeChatUrl===next.activeChatUrl;
209
+ const permittedRecover=transitionKind==='CONTEXT_HANDOFF_RECOVERED'
210
+ &&old.phase==='BLOCKED'&&next.phase==='WAITING_REPLY'
211
+ &&old.sessionId===next.sessionId
212
+ &&old.generation===next.generation
213
+ &&old.activeChatId===next.activeChatId
214
+ &&old.activeChatUrl===next.activeChatUrl;
215
+ const permittedCancel=transitionKind==='CONTEXT_IDLE_CANCELLED'
216
+ &&old.phase==='BLOCKED'&&next.phase==='CANCELLED'
217
+ &&old.sessionId===next.sessionId
218
+ &&old.generation===next.generation
219
+ &&old.activeChatId===next.activeChatId
220
+ &&old.activeChatUrl===next.activeChatUrl;
221
+ assert((transitionKind===null&&NEXT[old.phase]?.includes(next.phase))
222
+ ||permittedContinue||permittedCancel||permittedRecover,
223
+ 'OWNER_PHASE_TRANSITION_INVALID');
224
+ assert(old.sessionId===next.sessionId,
225
+ 'OWNER_SESSION_REPLACEMENT_REQUIRES_FENCE');
226
+ assert(next.generation>=old.generation&&next.generation<=old.generation+1,
227
+ 'OWNER_GENERATION_MISMATCH');
228
+ if(next.generation===old.generation)
229
+ assert(old.activeChatId===null||next.activeChatId===old.activeChatId
230
+ &&next.activeChatUrl===old.activeChatUrl,
231
+ 'OWNER_CHAT_CHANGED_WITHOUT_HANDOFF');
232
+ else assert(old.activeChatId&&next.activeChatId&&
233
+ old.activeChatId.toLowerCase()!==next.activeChatId.toLowerCase(),
234
+ 'OWNER_HANDOFF_UNVERIFIED');
235
+ }
236
+ }
237
+ for(const [otherKey,owner] of Object.entries(prior.sessions)){
238
+ if(otherKey!==key&&!terminal(owner.phase)&&next.activeChatId&&
239
+ next.activeChatId.toLowerCase()===owner.activeChatId?.toLowerCase()
240
+ &&!terminal(next.phase))
241
+ throw fail('OWNER_CHAT_ALREADY_CLAIMED');
242
+ }
243
+ // Repeated status/projection sync is not a new Native owner CAS event.
244
+ // An unacknowledged changed transition must still re-read exact revision.
245
+ if(old&&['projectId','taskId','sessionId','generation','phase',
246
+ 'activeChatId','activeChatUrl'].every(k=>next[k]===old[k]))
247
+ return {ledgerRevision:prior.ledgerRevision,session:old};
248
+ const updated={...next,revision:(old?.revision||0)+1,
249
+ updatedAt:Math.max(next.updatedAt,(old?.updatedAt||0)+1)};
250
+ const sessions={...prior.sessions,[key]:updated};
251
+ const ledger=validateLedger({schemaVersion:2,
252
+ ledgerRevision:prior.ledgerRevision+1,sessions,
253
+ retired:prior.retired??{}});
254
+ commitOwnerLedger(ledger);
255
+ return {ledgerRevision:ledger.ledgerRevision,session:updated};
256
+ }
257
+ }
258
+
259
+ // Explicit terminal retirement; called only after Native independently
260
+ // verifies Context's durable delivery/cancel fence. Never prune BLOCKED.
261
+ export function retireOwnerLedgerTerminal(projectId,taskId,options={}){
262
+ return withOwnerKernelLock('scoped-retire',[projectId,taskId,options]);
263
+ }
264
+ export function retireOwnerLedgerTerminalLocked(projectId,taskId,{
265
+ expectedSessionId,expectedGeneration,expectedSessionRevision
266
+ }={}){
267
+ assert(ID.test(projectId||'')&&ID.test(taskId||'')
268
+ &&UUID.test(expectedSessionId||'')
269
+ &&Number.isSafeInteger(expectedGeneration)&&expectedGeneration>=0
270
+ &&Number.isSafeInteger(expectedSessionRevision)
271
+ &&expectedSessionRevision>=1,'OWNER_RETIRE_SCOPE_INVALID');
272
+ verifyDir(true);
273
+ {
274
+ const prior=readOwnerLedger();
275
+ assert(prior,'OWNER_LEDGER_MISSING');
276
+ const key=taskOwnerKey(projectId,taskId),old=prior.sessions[key];
277
+ const receiptKey=retiredKey({projectId,taskId,
278
+ sessionId:expectedSessionId,revision:expectedSessionRevision});
279
+ if(!old){
280
+ // A prior retirement may have committed while its Native reply was
281
+ // lost. An exact in-ledger receipt is read-only, never a new deletion.
282
+ const priorReceipt=prior.retired?.[receiptKey];
283
+ assert(priorReceipt
284
+ &&priorReceipt.generation===expectedGeneration,
285
+ 'OWNER_RETIRE_TERMINAL_CAS_MISMATCH');
286
+ return {status:'RETIRED',projectId,taskId,
287
+ sessionId:priorReceipt.sessionId,terminal:priorReceipt.phase,
288
+ ledgerRevision:prior.ledgerRevision,alreadyRetired:true};
289
+ }
290
+ assert(terminal(old.phase)
291
+ &&old.sessionId===expectedSessionId
292
+ &&old.generation===expectedGeneration
293
+ &&old.revision===expectedSessionRevision,
294
+ 'OWNER_RETIRE_TERMINAL_CAS_MISMATCH');
295
+ const sessions={...prior.sessions};
296
+ delete sessions[key];
297
+ // A bounded Native receipt outlives one-shot IPC loss. No arbitrary
298
+ // GC of unresolved or in-flight Task sessions.
299
+ const retired={...prior.retired};
300
+ const oldReceipts=Object.entries(retired).filter(([,item])=>
301
+ Date.now()-item.retiredAt>180*24*60*60*1000);
302
+ for(const [key] of oldReceipts)delete retired[key];
303
+ assert(Object.keys(retired).length<RETIRE_HISTORY_LIMIT,
304
+ 'OWNER_RETIRE_HISTORY_FULL');
305
+ retired[receiptKey]={projectId,taskId,
306
+ sessionId:old.sessionId,generation:old.generation,
307
+ revision:old.revision,phase:old.phase,retiredAt:Date.now()};
308
+ const ledger=validateLedger({schemaVersion:2,
309
+ ledgerRevision:prior.ledgerRevision+1,sessions,retired});
310
+ commitOwnerLedger(ledger);
311
+ return {status:'RETIRED',projectId,taskId,
312
+ sessionId:old.sessionId,terminal:old.phase,
313
+ ledgerRevision:ledger.ledgerRevision};
314
+ }
315
+ }
316
+
@@ -0,0 +1,30 @@
1
+ // Private one-shot subprocess, invoked only under macOS lockf -k by
2
+ // owner-kernel-lock.mjs. No independent CLI, MCP tool, service or store.
3
+ // All CAS, legacy exclusion, disk fsync and receipt checks remain in the
4
+ // original V1/V2 domain implementations.
5
+ import {readFileSync} from 'node:fs';
6
+ import {writeSessionLocked} from './session-file.mjs';
7
+ import {writeOwnerLedgerSessionLocked,retireOwnerLedgerTerminalLocked}
8
+ from './owner-ledger.mjs';
9
+ try{
10
+ const raw=readFileSync(0,'utf8');
11
+ if(Buffer.byteLength(raw)>128*1024)throw Error('OWNER_LOCK_REQUEST_TOO_LARGE');
12
+ const request=JSON.parse(raw);
13
+ if(!request||typeof request!=='object'||Array.isArray(request)
14
+ ||Object.keys(request).length!==2
15
+ ||!Array.isArray(request.args)||request.args.length>8)
16
+ throw Error('OWNER_LOCK_REQUEST_INVALID');
17
+ const fn={
18
+ 'legacy-write':writeSessionLocked,
19
+ 'scoped-write':writeOwnerLedgerSessionLocked,
20
+ 'scoped-retire':retireOwnerLedgerTerminalLocked
21
+ }[request.kind];
22
+ if(typeof fn!=='function')throw Error('OWNER_LOCK_REQUEST_INVALID');
23
+ const result=fn(...request.args);
24
+ process.stdout.write(JSON.stringify({status:'OK',result})+'\n');
25
+ }catch(e){
26
+ const code=/^[A-Z][A-Z0-9_]{1,95}$/.test(e?.code||'')?e.code
27
+ :/^[A-Z][A-Z0-9_]{1,95}$/.test(e?.message||'')?e.message
28
+ :'OWNER_WRITE_FAILED';
29
+ process.stdout.write(JSON.stringify({status:'FAILED',code})+'\n');
30
+ }
@@ -0,0 +1,190 @@
1
+ // Original approved Task/Session idle Adopt cancellation: Native Owner CAS,
2
+ // existing Context run.fence.cancel and exact post-fence terminal verification.
3
+ // No browser send, no Task DONE, no automatic recovery from UNKNOWN.
4
+ export function createScopedCancelControl(ports){
5
+ const {readRequest,readScopedOwner,writeScopedOwner,nativeContextControl}=ports;
6
+ const fail=code=>Object.assign(Error(code),{code});
7
+ const yes=(v,code)=>{if(!v)throw fail(code)};
8
+ const ID=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
9
+ const UUID=/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f-]{12}$/i;
10
+ const proof=s=>Object.fromEntries(['projectId','taskId','sessionId',
11
+ 'generation','revision','phase','activeChatId'].map(k=>[k,s[k]]));
12
+ async function context(command,s,args){
13
+ return nativeContextControl(command,{
14
+ projectId:s.projectId,taskId:s.taskId,
15
+ sessionId:s.sessionId,generation:s.generation,
16
+ activeChatId:s.activeChatId,...args
17
+ },{ownerProofV2:proof(s)});
18
+ }
19
+ async function handle(m){
20
+ yes(m&&Object.keys(m).length===11&&m.op==='task-cancel-v2'
21
+ &&/^[a-f0-9]{32}$/.test(m.sourceRequestId||'')
22
+ &&ID.test(m.projectId||'')&&ID.test(m.taskId||'')
23
+ &&UUID.test(m.sessionId||'')
24
+ &&Number.isSafeInteger(m.generation)&&m.generation>=0
25
+ &&Number.isSafeInteger(m.expectedSessionRevision)
26
+ &&m.expectedSessionRevision>=1
27
+ &&typeof m.expectedStoreEpoch==='string'
28
+ &&m.expectedStoreEpoch.length>=10
29
+ &&Number.isSafeInteger(m.expectedTaskRevision)
30
+ &&m.expectedTaskRevision>=1
31
+ &&Number.isSafeInteger(m.expectedBindingRevision)
32
+ &&m.expectedBindingRevision>=1
33
+ &&/^[a-f0-9]{32}$/.test(m.startRequestId||''),
34
+ 'SCOPED_CANCEL_SOURCE_INVALID');
35
+ const request=readRequest(m.sourceRequestId),intent=request?.intent;
36
+ yes(request?.action==='session'&&intent?.taskFirst===true
37
+ &&intent.operation==='cancel'&&intent.confirmed===true
38
+ &&intent.projectId===m.projectId&&intent.taskId===m.taskId
39
+ &&intent.sessionId===m.sessionId
40
+ &&intent.generation===m.generation
41
+ &&intent.expectedNativeRevision===m.expectedSessionRevision
42
+ &&intent.contextStoreEpoch===m.expectedStoreEpoch
43
+ &&intent.expectedTaskRevision===m.expectedTaskRevision
44
+ &&intent.expectedBindingRevision===m.expectedBindingRevision,
45
+ 'SCOPED_CANCEL_INTENT_UNVERIFIED');
46
+ const previous=readScopedOwner(m.projectId,m.taskId),s=previous.session;
47
+ yes(s&&s.sessionId===m.sessionId&&s.generation===m.generation
48
+ &&s.revision===m.expectedSessionRevision
49
+ &&s.phase==='WAITING_REPLY'
50
+ &&typeof s.activeChatId==='string'
51
+ &&typeof s.activeChatUrl==='string',
52
+ 'SCOPED_CANCEL_OWNER_CHANGED');
53
+ // The authoritative Task must show ONLY its consumed START permit.
54
+ // Any CONTINUE/HANDOFF/other permit makes idle cancellation unsafe.
55
+ const history=await context('run.idleStartPermitStatus',s,{
56
+ startActionToken:m.startRequestId});
57
+ yes(history?.projectId===s.projectId&&history.taskId===s.taskId
58
+ &&history.startOnly===true,'SCOPED_CANCEL_EXECUTION_PERMIT_EXISTS');
59
+ const state=await context('run.terminalStatus',s,{});
60
+ yes(state?.projectId===s.projectId&&state.taskId===s.taskId
61
+ &&state.storeEpoch===m.expectedStoreEpoch
62
+ &&state.taskRevision===m.expectedTaskRevision
63
+ &&state.bindingRevision===m.expectedBindingRevision
64
+ &&state.runRef===s.sessionId+':'+s.taskId+':'+s.generation
65
+ &&state.pendingHandoff===false
66
+ &&state.pendingCheckpointId===null
67
+ &&state.unknownEffectCount===0
68
+ &&state.executionOutcome===null
69
+ &&state.sessionCancellation===null
70
+ &&state.writerApprovalCurrent===true
71
+ &&state.projectRulesDrift===false,
72
+ 'SCOPED_CANCEL_CONTEXT_NOT_IDLE');
73
+ const fresh=readScopedOwner(s.projectId,s.taskId);
74
+ yes(fresh.session?.revision===s.revision
75
+ &&fresh.session.phase==='WAITING_REPLY',
76
+ 'SCOPED_CANCEL_OWNER_RACED');
77
+ // Fence all sends FIRST. If Context fails, the old Owner stays BLOCKED.
78
+ const stopped=writeScopedOwner({
79
+ projectId:s.projectId,taskId:s.taskId,sessionId:s.sessionId,
80
+ generation:s.generation,phase:'BLOCKED',
81
+ activeChatId:s.activeChatId,activeChatUrl:s.activeChatUrl,
82
+ updatedAt:Date.now()},{
83
+ expectedLedgerRevision:fresh.ledgerRevision,
84
+ expectedSessionRevision:s.revision});
85
+ yes(stopped.session.phase==='BLOCKED'
86
+ &&stopped.session.revision===s.revision+1,
87
+ 'SCOPED_CANCEL_FREEZE_UNKNOWN');
88
+ const writeRequestId='cancel-'+m.sourceRequestId;
89
+ const cancelled=await context('run.fence.cancel',stopped.session,{
90
+ expectedStoreEpoch:m.expectedStoreEpoch,
91
+ expectedTaskRevision:m.expectedTaskRevision,
92
+ expectedBindingRevision:m.expectedBindingRevision,
93
+ writeRequestId,actionToken:m.sourceRequestId,
94
+ scopedStartActionToken:m.startRequestId,
95
+ reason:'USER_CANCELLED',runRef:state.runRef});
96
+ yes(cancelled?.status==='CANCEL_FENCED',
97
+ 'SCOPED_CANCEL_CONTEXT_FENCE_UNKNOWN');
98
+ const after=await context('run.terminalStatus',stopped.session,{});
99
+ const c=after?.sessionCancellation;
100
+ yes(after?.runRef===null&&after.executionOutcome===null
101
+ &&after.unknownEffectCount===0
102
+ &&c?.status==='CANCELLED_NOT_DELIVERED'
103
+ &&c.requestId===writeRequestId
104
+ &&c.sessionId===s.sessionId&&c.generation===s.generation,
105
+ 'SCOPED_CANCEL_CONTEXT_RECEIPT_UNVERIFIED');
106
+ const final=readScopedOwner(s.projectId,s.taskId);
107
+ yes(final.session?.revision===stopped.session.revision
108
+ &&final.session.phase==='BLOCKED',
109
+ 'SCOPED_CANCEL_FINAL_OWNER_RACED');
110
+ const committed=writeScopedOwner({
111
+ projectId:s.projectId,taskId:s.taskId,sessionId:s.sessionId,
112
+ generation:s.generation,phase:'CANCELLED',
113
+ activeChatId:s.activeChatId,activeChatUrl:s.activeChatUrl,
114
+ updatedAt:Date.now()},{
115
+ expectedLedgerRevision:final.ledgerRevision,
116
+ expectedSessionRevision:stopped.session.revision,
117
+ transitionKind:'CONTEXT_IDLE_CANCELLED'});
118
+ yes(committed.session.phase==='CANCELLED'
119
+ &&committed.session.revision===stopped.session.revision+1
120
+ &&after.bindingRevision===m.expectedBindingRevision+1,
121
+ 'SCOPED_CANCEL_NATIVE_UNKNOWN');
122
+ return {status:'CONFIRMED',scope:'TASK_SCOPED_CANCELLED_NOT_DELIVERED',
123
+ nativeOwnerRevision:committed.session.revision,
124
+ contextBindingRevision:after.bindingRevision,
125
+ taskRevision:after.taskRevision};
126
+ }
127
+ async function readCommitted(m){
128
+ // Recover ONLY an already-committed cancellation. The original
129
+ // signed user decision must be present in durable Context evidence;
130
+ // this branch never calls run.fence.cancel or mutates Native Owner.
131
+ yes(m&&Object.keys(m).length===9
132
+ &&m.op==='task-cancel-read-v2'
133
+ &&/^[a-f0-9]{32}$/.test(m.sourceRequestId||'')
134
+ &&ID.test(m.projectId||'')&&ID.test(m.taskId||'')
135
+ &&UUID.test(m.sessionId||'')
136
+ &&Number.isSafeInteger(m.generation)&&m.generation>=0
137
+ &&Number.isSafeInteger(m.expectedPriorSessionRevision)
138
+ &&m.expectedPriorSessionRevision>=1
139
+ &&Number.isSafeInteger(m.expectedBindingRevision)
140
+ &&m.expectedBindingRevision>=1
141
+ &&typeof m.expectedActiveChatUrl==='string'
142
+ &&/^https:\/\/chatgpt\.com\/(?:c\/[0-9a-f-]{12,}|g\/[^/]+\/c\/[0-9a-f-]{12,})$/i
143
+ .test(m.expectedActiveChatUrl),
144
+ 'SCOPED_CANCEL_READ_SCOPE_INVALID');
145
+ // A read-only reconciliation is not an unscoped status endpoint:
146
+ // require the SAME private, explicitly confirmed cancel request.
147
+ // No other Task's request ID may query this Owner's terminal proof.
148
+ const request=readRequest(m.sourceRequestId),intent=request?.intent;
149
+ yes(request?.action==='session'&&intent?.taskFirst===true
150
+ &&intent.operation==='cancel'&&intent.confirmed===true
151
+ &&intent.projectId===m.projectId&&intent.taskId===m.taskId
152
+ &&intent.sessionId===m.sessionId
153
+ &&intent.generation===m.generation
154
+ &&intent.expectedNativeRevision===m.expectedPriorSessionRevision
155
+ &&intent.expectedBindingRevision===m.expectedBindingRevision,
156
+ 'SCOPED_CANCEL_READ_INTENT_UNVERIFIED');
157
+ const s=readScopedOwner(m.projectId,m.taskId).session;
158
+ yes(s&&s.projectId===m.projectId&&s.taskId===m.taskId
159
+ &&s.sessionId===m.sessionId&&s.generation===m.generation
160
+ &&s.phase==='CANCELLED'
161
+ &&s.activeChatUrl===m.expectedActiveChatUrl
162
+ &&s.revision===m.expectedPriorSessionRevision+2,
163
+ 'SCOPED_CANCEL_READ_OWNER_NOT_TERMINAL');
164
+ const state=await context('run.terminalStatus',s,{});
165
+ const c=state?.sessionCancellation;
166
+ yes(state?.projectId===m.projectId&&state.taskId===m.taskId
167
+ &&state.runRef===null
168
+ &&state.executionOutcome===null
169
+ &&state.unknownEffectCount===0
170
+ &&state.pendingHandoff===false
171
+ &&state.pendingCheckpointId===null
172
+ &&state.bindingRevision===m.expectedBindingRevision+1
173
+ &&c?.status==='CANCELLED_NOT_DELIVERED'
174
+ &&c.requestId==='cancel-'+m.sourceRequestId
175
+ &&c.reason==='USER_CANCELLED'
176
+ &&c.sessionId===m.sessionId&&c.generation===m.generation,
177
+ 'SCOPED_CANCEL_READ_CONTEXT_NOT_COMMITTED');
178
+ const after=readScopedOwner(m.projectId,m.taskId).session;
179
+ yes(after?.sessionId===s.sessionId
180
+ &&after.generation===s.generation
181
+ &&after.phase===s.phase&&after.revision===s.revision,
182
+ 'SCOPED_CANCEL_READ_OWNER_RACED');
183
+ return {status:'CONFIRMED',
184
+ scope:'TASK_SCOPED_CANCELLED_NOT_DELIVERED',
185
+ nativeOwnerRevision:s.revision,
186
+ contextBindingRevision:state.bindingRevision,
187
+ taskRevision:state.taskRevision,readOnly:true};
188
+ }
189
+ return Object.freeze({handle,readCommitted});
190
+ }