@tomflow/chatloop-context 0.1.4 → 0.1.5

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.
package/bin/cli.mjs CHANGED
@@ -10,7 +10,8 @@ import {CONTEXT_CONTRACT,CONTEXT_PACKAGE_VERSION,methodById,validateContextCall,
10
10
  let openContextProtocol,dispatchContextCall,contextRoot,allowedProjects,
11
11
  verifySourceUnit,
12
12
  createProjectDiagnosticBranch,createManagedProjectBranch,fenceLegacyProjectStore,
13
- auditLegacyProjectSources,inspectLegacyRegistryReference,activeLegacyWriters;
13
+ auditLegacyProjectSources,inspectLegacyRegistryReference,activeLegacyWriters,
14
+ fenceOrphanRunOperator;
14
15
  const fail=code=>Object.assign(new Error(code),{code});
15
16
  const requestLimit=5*1024*1024;
16
17
  const output=o=>process.stdout.write(JSON.stringify({
@@ -80,6 +81,7 @@ try{
80
81
  auditLegacyProjectSources,inspectLegacyRegistryReference}=
81
82
  await import('../lib/project-diagnostic.mjs'));
82
83
  ({activeLegacyWriters}=await import('../lib/context-cli.mjs'));
84
+ ({fenceOrphanRunOperator}=await import('../lib/orphan-operator.mjs'));
83
85
  }
84
86
  const [command,sub,...rest]=args;
85
87
  let value;
@@ -98,6 +100,24 @@ try{
98
100
  'chat_loop_context_mutate':'chat_loop_context_get',payload);
99
101
  value=await dispatchContextCall(method.mode==='write'?
100
102
  'chat_loop_context_mutate':'chat_loop_context_get',payload);
103
+ }else if(command==='task'&&sub==='fence-orphan'&&rest.length===10){
104
+ const [projectId,taskId,expectedRunRef,revision,bindingRevision,
105
+ expectedStoreEpoch,evidenceDocumentId,evidenceVersion,evidenceHash,
106
+ writeRequestId]=rest;
107
+ value=await fenceOrphanRunOperator({projectId,taskId,expectedRunRef,
108
+ expectedTaskRevision:Number(revision),
109
+ expectedBindingRevision:Number(bindingRevision),
110
+ expectedStoreEpoch,evidenceDocumentId,
111
+ evidenceVersion:Number(evidenceVersion),evidenceHash,writeRequestId});
112
+ }else if(command==='task'&&sub==='orphan-receipt'&&rest.length===3){
113
+ const [projectId,storeEpoch,writeRequestId]=rest;
114
+ if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
115
+ if(process.env.CHAT_LOOP_CONTEXT_DB)throw fail('EXPLICIT_DB_INIT_REQUIRED');
116
+ const file=join(contextRoot(),projectId,'context.sqlite');
117
+ const db=openContextProtocol(file,{readOnly:true,principalId:'local-operator',
118
+ authorizeData:(_mode,p)=>p===projectId});
119
+ try{value=db.requestStatus({projectId,storeEpoch,writeRequestId})}
120
+ finally{db.close()}
101
121
  }else if(command==='project'&&sub==='init'&&(rest.length===2||rest.length===3))
102
122
  value=await registerProject(rest[0],rest[1],rest.slice(2));
103
123
  else if(command==='project'&&sub==='register'&&rest.length>=3&&rest.length<=18)
@@ -1463,6 +1463,76 @@ export function openContextProtocol(file,{authorizeInternal=()=>false,authorizeD
1463
1463
  bindingRevision:r.binding_revision};
1464
1464
  });
1465
1465
  },
1466
+ fenceOrphan(a){
1467
+ // LOCAL OPERATOR ONLY. Recover a stale writer whose Native Owner was
1468
+ // replaced by another Project. This explicitly does NOT deliver Task
1469
+ // work or manufacture a missing same-Session terminal fence.
1470
+ admin('run.orphan.fence',a.projectId);
1471
+ admin('run.orphan.fence.reviewed',a.projectId);
1472
+ return receipt(a,'run.orphan.fence',()=>{
1473
+ const r=scope(a);
1474
+ expectedBusiness(r,a.expectedTaskRevision);
1475
+ expectedBinding(r,a.expectedBindingRevision);
1476
+ assert(r.writable_ref===a.expectedRunRef&&!!a.expectedRunRef
1477
+ &&r.pending_attempt===null,'ORPHAN_RUN_NOT_BOUND');
1478
+ assert(typeof a.oldSessionId==='string'
1479
+ &&a.expectedRunRef.startsWith(a.oldSessionId+':'+a.taskId+':'),
1480
+ 'ORPHAN_SOURCE_MISMATCH');
1481
+ assert(typeof a.nativeSessionId==='string'
1482
+ &&a.nativeSessionId!==a.oldSessionId
1483
+ &&typeof a.nativeProjectId==='string'
1484
+ &&a.nativeProjectId!==a.projectId
1485
+ &&a.nativePhase==='DONE'
1486
+ &&Number.isSafeInteger(a.nativeUpdatedAt),
1487
+ 'ORPHAN_NATIVE_NOT_TERMINAL');
1488
+ assert(!projectDrift(r).projectDrift,'PROJECT_RULES_DRIFT');
1489
+ assert(this.projectBusinessAuthority(a.projectId).writable,
1490
+ 'PROJECT_CUTOVER_NOT_VERIFIED');
1491
+ const current=parse(r.context_json);
1492
+ assert(current.executionOutcome!=='DONE'&&!current.deliveryRef
1493
+ &&current.stage!=='DELIVERED','ORPHAN_ALREADY_DELIVERED');
1494
+ assert(unresolvedEffects(current).length===0,'UNKNOWN_EFFECTS_UNRESOLVED');
1495
+ assert(typeof a.evidenceDocumentId==='string'
1496
+ &&ID.test(a.evidenceDocumentId)
1497
+ &&Number.isInteger(a.evidenceVersion)&&a.evidenceVersion>0
1498
+ &&/^[0-9a-f]{64}$/.test(a.evidenceHash||''),
1499
+ 'ORPHAN_EVIDENCE_INVALID');
1500
+ const proof=db.prepare(
1501
+ 'SELECT kind,body,content_hash FROM documents WHERE project_id=? AND task_id=? AND document_id=? AND version=?')
1502
+ .get(a.projectId,a.taskId,a.evidenceDocumentId,a.evidenceVersion);
1503
+ assert(proof&&proof.kind==='REFERENCE'
1504
+ &&proof.content_hash===a.evidenceHash
1505
+ &&proof.body.includes(a.expectedRunRef),
1506
+ 'ORPHAN_EVIDENCE_UNVERIFIED');
1507
+ const blockers=Array.isArray(current.blockers)?current.blockers:[];
1508
+ const orphanRef={runRef:a.expectedRunRef,oldSessionId:a.oldSessionId,
1509
+ currentNativeSessionId:a.nativeSessionId,
1510
+ currentNativeProjectId:a.nativeProjectId,
1511
+ currentNativeUpdatedAt:a.nativeUpdatedAt,
1512
+ evidenceDocumentId:a.evidenceDocumentId,
1513
+ evidenceVersion:a.evidenceVersion,evidenceHash:a.evidenceHash,
1514
+ status:'FENCED_NOT_DELIVERED',operator:'USER_DELEGATED_AGENT',
1515
+ at:Date.now()};
1516
+ const next={...current,
1517
+ blockers:[...blockers.filter(x=>x!=='ORPHAN_RUN_FENCED'),
1518
+ 'ORPHAN_RUN_FENCED'],
1519
+ orphanRunRecovery:orphanRef,
1520
+ nextStep:'Obtain a new verified R/P-authorized Owner before delivery; no old send replay.'};
1521
+ db.prepare(`UPDATE tasks SET writable_ref=NULL,credential_digest=NULL,
1522
+ writer_approval_revision=NULL,binding_revision=binding_revision+1,
1523
+ business_revision=business_revision+1,context_json=?
1524
+ WHERE project_id=? AND task_id=?`)
1525
+ .run(JSON.stringify(next),a.projectId,a.taskId);
1526
+ db.prepare("UPDATE permits SET kind='USED' WHERE project_id=? AND task_id=?")
1527
+ .run(a.projectId,a.taskId);
1528
+ db.prepare('DELETE FROM start_leases WHERE project_id=? AND task_id=?')
1529
+ .run(a.projectId,a.taskId);
1530
+ return {status:'ORPHAN_FENCED',projectId:a.projectId,taskId:a.taskId,
1531
+ oldRunRef:a.expectedRunRef,
1532
+ taskRevision:r.business_revision+1,bindingRevision:r.binding_revision+1,
1533
+ executionOutcome:null,deliveryRef:null};
1534
+ });
1535
+ },
1466
1536
  fence(a){
1467
1537
  internal('run.fence',a);
1468
1538
  return receipt(a,'run.fence',()=>{
@@ -0,0 +1,151 @@
1
+ // Restricted LOCAL OPERATOR path for orphaned Managed Run writer fencing.
2
+ // Not reachable through public Context MCP, and never asserts Task DONE.
3
+ import {execFileSync} from 'node:child_process';
4
+ import {createHash,randomUUID} from 'node:crypto';
5
+ import {DatabaseSync,backup} from 'node:sqlite';
6
+ import {chmodSync,existsSync,lstatSync,mkdirSync,readFileSync,writeFileSync} from 'node:fs';
7
+ import {homedir} from 'node:os';
8
+ import {join} from 'node:path';
9
+ import {openContextProtocol} from './context-protocol.mjs';
10
+ import {contextRoot,allowedProjects} from './operations.mjs';
11
+ import {confirmWorkspaceOperator} from './workspace-operator.mjs';
12
+
13
+ const fail=code=>Object.assign(Error(code),{code});
14
+ const assert=(ok,code)=>{if(!ok)throw fail(code)};
15
+ const SHA=/^[0-9a-f]{64}$/;
16
+ const ID=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
17
+ const sha=buf=>createHash('sha256').update(buf).digest('hex');
18
+ const nativePath=()=>join(homedir(),'.chat-loop','session','active-session.json');
19
+ const readTrustedNative=()=>{
20
+ const file=nativePath(),stat=lstatSync(file);
21
+ assert(stat.isFile()&&!stat.isSymbolicLink()
22
+ &&!(stat.mode&0o077)&&(!process.getuid||stat.uid===process.getuid()),
23
+ 'NATIVE_POINTER_UNTRUSTED');
24
+ const raw=readFileSync(file);
25
+ const x=JSON.parse(raw.toString('utf8'));
26
+ assert(x?.phase==='DONE'&&typeof x.sessionId==='string'
27
+ &&typeof x.projectId==='string'&&Number.isSafeInteger(x.updatedAt),
28
+ 'NATIVE_NOT_TERMINAL');
29
+ return {sessionId:x.sessionId,projectId:x.projectId,taskId:x.taskId||null,
30
+ phase:x.phase,updatedAt:x.updatedAt,rawHash:sha(raw)};
31
+ };
32
+ const readExtensionIdle=()=>{
33
+ const cli=join(homedir(),'.chat-loop','extension','npm','node_modules',
34
+ '@tomflow','chatloop-extension','bin','cli.mjs');
35
+ const st=lstatSync(cli);
36
+ assert(st.isFile()&&!st.isSymbolicLink(),'EXTENSION_CLI_UNTRUSTED');
37
+ const out=execFileSync(process.execPath,[cli,'extension','status'],{
38
+ encoding:'utf8',timeout:14000,maxBuffer:524288,stdio:['ignore','pipe','pipe']});
39
+ const rows=out.trim().split('\n').map(s=>JSON.parse(s));
40
+ const result=rows.findLast(x=>x.event==='RESULT');
41
+ assert(result?.ok===true&&result.value?.verified===true
42
+ &&result.value?.truncated===false,'EXTENSION_STATUS_UNVERIFIED');
43
+ const v=JSON.parse(result.value.content||'{}');
44
+ assert(v.status==='OK'&&v.state==='IDLE'
45
+ &&v.lastSession?.phase==='DONE','EXTENSION_OWNER_NOT_IDLE');
46
+ return v;
47
+ };
48
+ const verifyExternal=(oldRunRef,projectId)=>{
49
+ const native=readTrustedNative(),extension=readExtensionIdle();
50
+ const oldId=oldRunRef.split(':')[0];
51
+ assert(native.sessionId!==oldId&&native.projectId!==projectId,
52
+ 'ORPHAN_OWNER_STILL_CURRENT');
53
+ assert(extension.lastSession.sessionId===native.sessionId
54
+ &&extension.lastSession.projectId===native.projectId
55
+ &&extension.lastSession.updatedAt===native.updatedAt
56
+ &&extension.lastSession.activeChatId===JSON.parse(
57
+ readFileSync(nativePath(),'utf8')).activeChatId,
58
+ 'EXTENSION_NATIVE_POINTER_MISMATCH');
59
+ return native;
60
+ };
61
+
62
+ export async function fenceOrphanRunOperator({
63
+ projectId,taskId,expectedRunRef,expectedTaskRevision,
64
+ expectedBindingRevision,expectedStoreEpoch,evidenceDocumentId,
65
+ evidenceVersion,evidenceHash,writeRequestId
66
+ }){
67
+ assert(process.env.CHAT_LOOP_CONTEXT_ADMIN_ENABLE==='1','ADMIN_REQUIRED');
68
+ assert(!process.env.CHAT_LOOP_CONTEXT_DB,'EXPLICIT_DB_INIT_REQUIRED');
69
+ assert(ID.test(projectId||'')&&ID.test(taskId||'')
70
+ &&allowedProjects().has(projectId),'PROJECT_ACCESS_DENIED');
71
+ assert(Number.isSafeInteger(expectedTaskRevision)&&expectedTaskRevision>=1
72
+ &&Number.isSafeInteger(expectedBindingRevision)&&expectedBindingRevision>=1
73
+ &&typeof expectedStoreEpoch==='string'&&expectedStoreEpoch.length>=10
74
+ &&typeof expectedRunRef==='string'&&expectedRunRef.length>=12
75
+ &&ID.test(evidenceDocumentId||'')&&Number.isSafeInteger(evidenceVersion)
76
+ &&evidenceVersion>0&&SHA.test(evidenceHash||'')
77
+ &&typeof writeRequestId==='string'&&writeRequestId.length>=8
78
+ &&writeRequestId.length<=128,'ORPHAN_ARGUMENT_INVALID');
79
+ const oldSessionId=expectedRunRef.split(':')[0];
80
+ assert(/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(oldSessionId)
81
+ &&expectedRunRef===oldSessionId+':'+taskId+':0','ORPHAN_RUN_REF_INVALID');
82
+ const before=verifyExternal(expectedRunRef,projectId);
83
+ const file=join(contextRoot(),projectId,'context.sqlite');
84
+ const reader=openContextProtocol(file,{readOnly:true,principalId:'local-operator',
85
+ authorizeData:(_mode,p)=>p===projectId});
86
+ try{
87
+ assert(reader.epoch===expectedStoreEpoch,'STALE_EPOCH');
88
+ assert(reader.projectBusinessAuthority(projectId).writable,
89
+ 'PROJECT_CUTOVER_NOT_VERIFIED');
90
+ const task=reader.get(projectId,taskId);
91
+ assert(task.taskRevision===expectedTaskRevision
92
+ &&task.bindingRevision===expectedBindingRevision
93
+ &&task.runRef===expectedRunRef,'ORPHAN_CAS_STALE');
94
+ const evidence=reader.documentGet(projectId,taskId,evidenceDocumentId,evidenceVersion);
95
+ assert(evidence.kind==='REFERENCE'&&evidence.contentHash===evidenceHash
96
+ &&evidence.body.includes(expectedRunRef),'ORPHAN_EVIDENCE_UNVERIFIED');
97
+ }finally{reader.close()}
98
+ // Local operator approval is explicitly USER_DELEGATED_AGENT, not a
99
+ // platform-authenticated human R/P approval or an execution permission.
100
+ await confirmWorkspaceOperator('FENCE_ORPHAN',projectId,expectedTaskRevision,
101
+ [taskId,expectedRunRef,evidenceDocumentId,evidenceHash,before.sessionId]);
102
+ const after=verifyExternal(expectedRunRef,projectId);
103
+ assert(JSON.stringify(after)===JSON.stringify(before),
104
+ 'NATIVE_CHANGED_DURING_REVIEW');
105
+ const archiveRoot=join(homedir(),'.chat-loop','backups');
106
+ const archive=join(archiveRoot,'orphan-fence-'+projectId+'-'+taskId+'-'+
107
+ expectedTaskRevision);
108
+ assert(!existsSync(archive),'ORPHAN_BACKUP_ALREADY_EXISTS');
109
+ mkdirSync(archive,{recursive:false,mode:0o700});
110
+ const dest=join(archive,'context-before.sqlite');
111
+ const source=new DatabaseSync(file,{readOnly:true});
112
+ try{await backup(source,dest)}finally{source.close()}
113
+ chmodSync(dest,0o600);
114
+ const backupHash=sha(readFileSync(dest));
115
+ const record={contract:'chat-loop.orphan-fence-operator.v1',
116
+ operator:'USER_DELEGATED_AGENT',projectId,taskId,oldSessionId,
117
+ expectedRunRef,expectedTaskRevision,expectedBindingRevision,
118
+ expectedStoreEpoch,evidenceDocumentId,evidenceVersion,evidenceHash,
119
+ currentNative:after,backup:dest,backupHash,
120
+ result:'PENDING',createdAt:new Date().toISOString()};
121
+ const manifest=join(archive,'manifest.json');
122
+ writeFileSync(manifest,JSON.stringify(record,null,2)+'\n',{mode:0o600,flag:'wx'});
123
+ const last=verifyExternal(expectedRunRef,projectId);
124
+ assert(JSON.stringify(last)===JSON.stringify(before),
125
+ 'NATIVE_CHANGED_BEFORE_FENCE');
126
+ const db=openContextProtocol(file,{principalId:'local-operator',
127
+ authorizeData:(_mode,p)=>p===projectId,
128
+ authorizeAdmin:(op,p)=>p===projectId&&
129
+ ['run.orphan.fence','run.orphan.fence.reviewed'].includes(op)
130
+ &&JSON.stringify(readTrustedNative())===JSON.stringify(before)});
131
+ let result;
132
+ try{
133
+ result=db.fenceOrphan({projectId,taskId,oldSessionId,
134
+ expectedRunRef,expectedTaskRevision,expectedBindingRevision,
135
+ expectedStoreEpoch,evidenceDocumentId,evidenceVersion,evidenceHash,
136
+ nativeSessionId:last.sessionId,nativeProjectId:last.projectId,
137
+ nativePhase:last.phase,nativeUpdatedAt:last.updatedAt,writeRequestId});
138
+ const checked=db.get(projectId,taskId);
139
+ assert(checked.runRef===null
140
+ &&checked.bindingRevision===result.bindingRevision
141
+ &&checked.currentContext.executionOutcome!=='DONE',
142
+ 'ORPHAN_FENCE_RECEIPT_UNVERIFIED');
143
+ }finally{db.close()}
144
+ // Record final durable result without updating or replaying the receipt.
145
+ record.result=result;
146
+ const completion=join(archive,'completed.json');
147
+ writeFileSync(completion,JSON.stringify(record,null,2)+'\n',
148
+ {mode:0o600,flag:'wx'});
149
+ return {...result,backupManifest:manifest,completionReceipt:completion,
150
+ backupHash,operator:'USER_DELEGATED_AGENT'};
151
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tomflow/chatloop-context",
3
- "version": "0.1.4",
3
+ "version": "0.1.5",
4
4
  "type": "module",
5
5
  "description": "Independent local Context SDK and short-lived CLI for Chat Loop projects",
6
6
  "publishConfig": {"access": "public"},