@tomflow/chatloop-tools 0.4.29 → 0.4.30

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.
@@ -1,289 +0,0 @@
1
- // Offline, operator-reviewed extraction of ONE Project from a shared Store.
2
- // This creates a DIAGNOSTIC_ONLY branch, never an active migration or Browser Owner.
3
- import {randomUUID,createHash} from 'node:crypto';
4
- import {DatabaseSync} from 'node:sqlite';
5
- import {existsSync,lstatSync,mkdtempSync,renameSync,rmSync,writeFileSync,
6
- readFileSync} from 'node:fs';
7
- import {isAbsolute,join,basename} from 'node:path';
8
- import {openContextProtocol} from './context-protocol.mjs';
9
- import {backupContextDb,verifySourceUnit,scanSourceUnit} from './context-migration.mjs';
10
-
11
- const ID=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
12
- const fail=code=>Object.assign(new Error(code),{code});
13
- const ensure=(ok,code)=>{if(!ok)throw fail(code)};
14
- const knownTables=new Set(['meta','projects','tasks','documents','issues',
15
- 'artifacts','checkpoints','receipts','migrations','start_leases','permits',
16
- 'project_materials']);
17
- const scopedTables=['checkpoints','documents','issues','artifacts','receipts',
18
- 'migrations','project_materials','permits','start_leases','tasks','projects'];
19
- const count=db=>Object.fromEntries(scopedTables.map(table=>
20
- [table,db.prepare('SELECT COUNT(*) AS n FROM '+table).get().n]));
21
- const scopeCount=(db,projectId)=>Object.fromEntries(scopedTables.map(table=>
22
- [table,db.prepare('SELECT COUNT(*) AS n FROM '+table+' WHERE project_id=?')
23
- .get(projectId).n]));
24
- function privateFile(file){
25
- ensure(typeof file==='string'&&isAbsolute(file),'SOURCE_PATH_INVALID');
26
- const st=lstatSync(file);
27
- ensure(st.isFile()&&!st.isSymbolicLink()&&!(st.mode&0o077)
28
- &&(!process.getuid||st.uid===process.getuid()),'MIGRATION_SOURCE_UNTRUSTED');
29
- }
30
- function privateRoot(root){
31
- ensure(typeof root==='string'&&isAbsolute(root),'MIGRATION_ROOT_INVALID');
32
- const st=lstatSync(root);
33
- ensure(st.isDirectory()&&!st.isSymbolicLink()&&!(st.mode&0o077)
34
- &&(!process.getuid||st.uid===process.getuid()),'MIGRATION_ROOT_UNTRUSTED');
35
- }
36
- function validateSchema(db){
37
- const names=db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")
38
- .all().map(x=>x.name);
39
- ensure(names.length===knownTables.size&&names.every(x=>knownTables.has(x)),
40
- 'MIGRATION_SCHEMA_UNREVIEWED');
41
- const keys=db.prepare('SELECT key FROM meta').all().map(x=>x.key);
42
- ensure(keys.every(x=>['schemaVersion','storeEpoch','storeMode','restoredFromEpoch'].includes(x)),
43
- 'MIGRATION_META_UNREVIEWED');
44
- }
45
- function physicalCheck(db,projectId,expected){
46
- const list=db.prepare('SELECT project_id FROM projects').all();
47
- ensure(list.length===1&&list[0].project_id===projectId,
48
- 'MIGRATION_PROJECT_ISOLATION_FAILED');
49
- const counts=count(db);
50
- for(const [table,n] of Object.entries(expected))
51
- ensure(counts[table]===n,'MIGRATION_ROW_COUNT_MISMATCH');
52
- const integrity=db.prepare('PRAGMA integrity_check').all();
53
- ensure(integrity.length===1&&integrity[0].integrity_check==='ok',
54
- 'MIGRATION_INTEGRITY_FAILED');
55
- ensure(db.prepare('PRAGMA foreign_key_check').all().length===0,
56
- 'MIGRATION_FOREIGN_KEY_FAILED');
57
- return counts;
58
- }
59
- export async function createProjectDiagnosticBranch({
60
- sourceDb,targetRoot,projectId,expectedStoreEpoch,expectedProjectRevision
61
- }){
62
- ensure(ID.test(projectId||''),'INVALID_SCOPE');
63
- ensure(typeof expectedStoreEpoch==='string'&&expectedStoreEpoch.length>=10,
64
- 'STALE_EPOCH');
65
- ensure(Number.isSafeInteger(expectedProjectRevision)&&expectedProjectRevision>=1,
66
- 'PROJECT_VERSION_CONFLICT');
67
- privateFile(sourceDb);privateRoot(targetRoot);
68
- const target=join(targetRoot,projectId);
69
- ensure(!existsSync(target),'MIGRATION_TARGET_EXISTS');
70
- // Preflight may not initialize/repair/change the old Store in any way.
71
- const source=openContextProtocol(sourceDb,{readOnly:true,principalId:'local-operator',
72
- authorizeData:()=>true});
73
- let initial;
74
- try{
75
- const project=source.projectGet(projectId);
76
- ensure(source.mode==='ACTIVE','MIGRATION_SOURCE_NOT_ACTIVE');
77
- ensure(source.epoch===expectedStoreEpoch,'STALE_EPOCH');
78
- ensure(project.projectRevision===expectedProjectRevision,'PROJECT_VERSION_CONFLICT');
79
- initial={epoch:source.epoch,projectRevision:project.projectRevision};
80
- }finally{source.close()}
81
- const stage=mkdtempSync(join(targetRoot,'.diagnostic-'));
82
- const file=join(stage,'context.sqlite');
83
- let published=false;
84
- try{
85
- const sourceReader=new DatabaseSync(sourceDb,{readOnly:true,timeout:3500});
86
- let snapshot;
87
- try{snapshot=await backupContextDb(sourceReader,file)}
88
- finally{sourceReader.close()}
89
- const db=new DatabaseSync(file,{timeout:3500});
90
- let receipt;
91
- try{
92
- validateSchema(db);
93
- const meta=k=>db.prepare('SELECT value FROM meta WHERE key=?').get(k)?.value;
94
- ensure(meta('storeMode')==='ACTIVE','MIGRATION_SOURCE_NOT_ACTIVE');
95
- ensure(meta('storeEpoch')===initial.epoch,'STALE_EPOCH');
96
- const project=db.prepare('SELECT project_revision FROM projects WHERE project_id=?')
97
- .get(projectId);
98
- ensure(project?.project_revision===initial.projectRevision,
99
- 'PROJECT_VERSION_CONFLICT');
100
- const before=scopeCount(db,projectId);
101
- db.exec('PRAGMA journal_mode=DELETE; PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON; PRAGMA secure_delete=ON;');
102
- const newEpoch=randomUUID();
103
- db.exec('BEGIN IMMEDIATE');
104
- try{
105
- for(const table of scopedTables)
106
- db.prepare('DELETE FROM '+table+' WHERE project_id<>?').run(projectId);
107
- db.exec('DELETE FROM permits; DELETE FROM start_leases;');
108
- db.exec(`UPDATE tasks SET writable_ref=NULL,credential_digest=NULL,
109
- writer_approval_revision=NULL,pending_attempt=NULL,
110
- pending_checkpoint=NULL,pending_target_generation=NULL,
111
- pending_credential_digest=NULL,pending_next_ref=NULL,
112
- binding_revision=binding_revision+1;`);
113
- db.prepare("UPDATE meta SET value='DIAGNOSTIC_ONLY' WHERE key='storeMode'").run();
114
- db.prepare("UPDATE meta SET value=? WHERE key='storeEpoch'").run(newEpoch);
115
- db.prepare("INSERT OR REPLACE INTO meta(key,value) VALUES('restoredFromEpoch',?)")
116
- .run(initial.epoch);
117
- db.exec('COMMIT');
118
- }catch(error){try{db.exec('ROLLBACK')}catch{}throw error}
119
- // Rebuild all b-trees and free pages so other projects' deleted rows
120
- // cannot remain readable in SQLite freelist or discarded WAL records.
121
- db.exec('VACUUM;');
122
- const after=physicalCheck(db,projectId,{
123
- ...before,permits:0,start_leases:0
124
- });
125
- receipt={contract:'chat-loop.context-diagnostic-project.v1',
126
- status:'DIAGNOSTIC_ONLY',projectId,sourceStoreEpoch:initial.epoch,
127
- sourceProjectRevision:initial.projectRevision,newStoreEpoch:newEpoch,
128
- sourceSnapshotHash:snapshot.hash,counts:after,
129
- sourceUnitsRequireReview:true,approvalsRevalidated:false,
130
- ownerRestored:false,writeCapabilitiesRestored:false,canExecute:false};
131
- }finally{db.close()}
132
- // Check reopened data in the exact form the normal SDK uses.
133
- const verify=openContextProtocol(file,{readOnly:true,principalId:'local-operator',
134
- authorizeData:()=>true});
135
- try{
136
- ensure(verify.mode==='DIAGNOSTIC_ONLY'&&
137
- verify.epoch===receipt.newStoreEpoch,'MIGRATION_MODE_UNVERIFIED');
138
- ensure(verify.projectList().length===1 &&
139
- verify.projectGet(projectId).projectRevision===initial.projectRevision,
140
- 'MIGRATION_PROJECT_ISOLATION_FAILED');
141
- ensure(verify.projectBusinessAuthority(projectId).writable===false,
142
- 'MIGRATION_WRITE_AUTHORITY_UNSAFE');
143
- }finally{verify.close()}
144
- const manifest=join(stage,'migration-diagnostic.json');
145
- writeFileSync(manifest,JSON.stringify(receipt,null,2)+'\n',{flag:'wx',mode:0o600});
146
- ensure(readFileSync(manifest,'utf8').includes(receipt.sourceSnapshotHash),
147
- 'MIGRATION_RECEIPT_UNVERIFIED');
148
- ensure(!existsSync(target),'MIGRATION_TARGET_EXISTS');
149
- renameSync(stage,target);
150
- published=true;
151
- return {...receipt,projectDirectory:target};
152
- }finally{if(!published)rmSync(stage,{recursive:true,force:true})}
153
- }
154
-
155
- // Read-only migration audit. Never classifies mixed history or certifies writers.
156
- // A verified byte hash proves source identity, not business ownership or approval.
157
- export function auditLegacyProjectSources({sourceDb,projectId,expectedStoreEpoch}){
158
- ensure(ID.test(projectId||''),'INVALID_SCOPE');
159
- ensure(typeof expectedStoreEpoch==='string'&&expectedStoreEpoch.length>=10,
160
- 'STALE_EPOCH');
161
- privateFile(sourceDb);
162
- const source=openContextProtocol(sourceDb,{readOnly:true,principalId:'local-audit',
163
- authorizeData:(_mode,p)=>p===projectId,
164
- authorizeAdmin:(op,p)=>op==='migration.list'&&p===projectId});
165
- try{
166
- ensure(source.epoch===expectedStoreEpoch,'STALE_EPOCH');
167
- const project=source.projectGet(projectId);
168
- const materials=source.projectMaterialList(projectId);
169
- const units=source.migrationList(projectId);
170
- const checks=units.map(unit=>{
171
- let verifyCode='MATCHED';
172
- try{verifySourceUnit(unit.manifest)}
173
- catch(error){verifyCode=/^[A-Z0-9_]+$/.test(error?.code??'')?
174
- error.code:'SOURCE_VERIFY_FAILED'}
175
- const sourceKind=unit.manifest.sourceKind;
176
- const evidenceStored=materials.some(m=>m.sourcePath===unit.sourcePath
177
- &&m.contentHash===unit.sourceHash
178
- &&m.provenance==='LEGACY_UNVERIFIED');
179
- return {sourceUnitId:unit.sourceUnitId,sourceKind,
180
- filename:basename(unit.sourcePath),sourceHash:unit.sourceHash,
181
- migrationStatus:unit.status,migrationRevision:unit.migrationRevision,
182
- sourceVerification:verifyCode,evidenceStored,
183
- mixedHistoryReviewed:sourceKind==='MIXED_CONTEXT'?
184
- unit.manifest.classification?.currentFactsComplete===true:null};
185
- });
186
- // Registry task documents are separate from the Registry JSON itself.
187
- // A changed task document does NOT invalidate an unchanged Registry SHA.
188
- const drift=checks.filter(c=>c.sourceVerification==='LEGACY_REFERENCE_CHANGED');
189
- const failed=checks.filter(c=>!['MATCHED','LEGACY_REFERENCE_CHANGED']
190
- .includes(c.sourceVerification));
191
- const missingBodies=checks.filter(c=>
192
- ['DOCUMENT','MIXED_CONTEXT'].includes(c.sourceKind)&&!c.evidenceStored);
193
- const mixedPending=checks.filter(c=>c.sourceKind==='MIXED_CONTEXT'
194
- &&c.mixedHistoryReviewed!==true);
195
- const pending=checks.filter(c=>c.migrationStatus!=='MANAGED_RW');
196
- return {projectId,storeEpoch:source.epoch,projectRevision:project.projectRevision,
197
- sourceCount:checks.length,checks,
198
- sourceHashesVerified:checks.length>0&&failed.length===0,
199
- sourceReferencesVerified:checks.length>0&&failed.length===0&&drift.length===0,
200
- referenceDriftCount:drift.length,
201
- sourceBodiesPreserved:checks.length>0&&missingBodies.length===0,
202
- mixedReviewRequired:mixedPending.length,
203
- pendingSourceCount:pending.length,
204
- blockers:[
205
- ...(checks.length===0?['NO_SOURCE_UNITS']:[]),
206
- ...(failed.length?['SOURCE_VERIFICATION_FAILED']:[]),
207
- ...(drift.length?['LEGACY_REFERENCE_DRIFT']:[]),
208
- ...(missingBodies.length?['SOURCE_MATERIALS_INCOMPLETE']:[]),
209
- ...(mixedPending.length?['MIXED_OWNERSHIP_REVIEW_REQUIRED']:[]),
210
- ...(pending.length?['SOURCE_UNACTIVATED']:[]),
211
- 'OLD_WRITERS_NOT_INDEPENDENTLY_FENCED',
212
- 'RELEASE_AND_NATIVE_E2E_UNVERIFIED'
213
- ],
214
- status:'BLOCKED',writerAuthority:'NOT_VERIFIED',
215
- canActivate:false,canExecute:false};
216
- }finally{source.close()}
217
- }
218
-
219
- /**
220
- * Produce a bounded, non-authoritative Registry task-reference drift review.
221
- * A matching Recovery Archive proves the original version still exists; it
222
- * never approves its newer version or rewrites a SourceUnit/Task/Receipt.
223
- */
224
- export function inspectLegacyRegistryReference({
225
- sourceDb,projectId,expectedStoreEpoch,sourceUnitId,taskId,archiveFile
226
- }){
227
- ensure(ID.test(projectId||'')&&ID.test(taskId||'')&&
228
- /^[a-f0-9]{64}$/.test(sourceUnitId||''),'INVALID_SCOPE');
229
- ensure(typeof expectedStoreEpoch==='string'&&expectedStoreEpoch.length>=10,
230
- 'STALE_EPOCH');
231
- privateFile(sourceDb);privateFile(archiveFile);
232
- const source=openContextProtocol(sourceDb,{
233
- readOnly:true,principalId:'local-reference-review',
234
- authorizeData:(_mode,p)=>p===projectId,
235
- authorizeAdmin:(op,p)=>op==='migration.list'&&p===projectId
236
- });
237
- try{
238
- ensure(source.epoch===expectedStoreEpoch,'STALE_EPOCH');
239
- source.projectGet(projectId);
240
- const unit=source.migrationList(projectId)
241
- .find(x=>x.sourceUnitId===sourceUnitId);
242
- ensure(unit?.status==='SHADOW_RO'&&
243
- unit.manifest.sourceKind==='REGISTRY_JSON','REGISTRY_SOURCE_NOT_SHADOW');
244
- const old=unit.manifest.tasks?.find(t=>t.taskId===taskId);
245
- ensure(old&&old.taskDocPath&&/^[a-f0-9]{64}$/.test(
246
- old.taskDocumentHash??''),'REGISTRY_REFERENCE_NOT_FOUND');
247
- const original=readFileSync(archiveFile);
248
- ensure(original.length>0&&original.length<=512*1024,'ARCHIVE_UNTRUSTED');
249
- const sha=b=>createHash('sha256').update(b).digest('hex');
250
- ensure(sha(original)===old.taskDocumentHash,'ARCHIVE_HASH_MISMATCH');
251
- const current=scanSourceUnit({sourcePath:unit.sourcePath,
252
- projectId,kind:'REGISTRY_JSON'});
253
- ensure(current.sourceUnitId===unit.sourceUnitId &&
254
- current.sourceHash===unit.sourceHash,'SOURCE_CHANGED');
255
- ensure(current.tasks.length===unit.manifest.tasks.length,
256
- 'REGISTRY_TASK_SET_CHANGED');
257
- for(const before of unit.manifest.tasks){
258
- const after=current.tasks.find(t=>t.taskId===before.taskId);
259
- ensure(after&&Object.keys(before).every(k=>k==='taskDocumentHash'||
260
- JSON.stringify(before[k])===JSON.stringify(after[k])),
261
- 'REGISTRY_TASK_IDENTITY_CHANGED');
262
- }
263
- const after=current.tasks.find(t=>t.taskId===taskId);
264
- ensure(after&&after.taskDocPath===old.taskDocPath,
265
- 'REGISTRY_TASK_IDENTITY_CHANGED');
266
- const latest=readFileSync(after.taskDocPath);
267
- ensure(sha(latest)===after.taskDocumentHash,
268
- 'DOCUMENT_CHANGED_DURING_INSPECTION');
269
- const oldLines=original.toString('utf8').split(/(?<=\n)/);
270
- const newLines=latest.toString('utf8').split(/(?<=\n)/);
271
- // Bounded linear comparison. This is a review hint, NEVER approval.
272
- let i=0;
273
- for(const line of newLines){
274
- if(i<oldLines.length&&oldLines[i]===line)i++;
275
- }
276
- const appendOnly=i===oldLines.length&&newLines.length>=oldLines.length;
277
- return {status:'REVIEW_REQUIRED',projectId,sourceUnitId,taskId,
278
- sourceHash:unit.sourceHash,sourceVerified:true,
279
- archivedTaskHash:old.taskDocumentHash,
280
- currentTaskHash:after.taskDocumentHash,
281
- archivedTaskBytes:original.length,currentTaskBytes:latest.length,
282
- originalLines:oldLines.length,currentLines:newLines.length,
283
- changeKind:old.taskDocumentHash===after.taskDocumentHash?'NONE':
284
- appendOnly?'INSERTIONS_ONLY':'CONTENT_CHANGED',
285
- insertedLines:appendOnly?newLines.length-oldLines.length:null,
286
- archiveVerified:true,reviewed:false,sourceUnitUpdated:false,
287
- approvalsImported:false,canActivate:false,canExecute:false};
288
- }finally{source.close()}
289
- }
@@ -1,159 +0,0 @@
1
- // Operator-only Workspace ownership. Never imported by ordinary MCP.
2
- import {createHash} from 'node:crypto';
3
- import {readdirSync,lstatSync,realpathSync,existsSync,mkdirSync,rmdirSync} from 'node:fs';
4
- import {isAbsolute,join,relative,sep} from 'node:path';
5
- import {createInterface} from 'node:readline/promises';
6
- import {openContextProtocol} from './context-protocol.mjs';
7
- import {contextRoot,dispatchContextCall,allowedProjects} from './operations.mjs';
8
-
9
- const ID=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
10
- const fail=code=>Object.assign(new Error(code),{code});
11
- const assert=(ok,code)=>{if(!ok)throw fail(code)};
12
- const overlap=(a,b)=>a===b||[relative(a,b),relative(b,a)]
13
- .some(r=>r!==''&&r!=='..'&&!r.startsWith('..'+sep)&&!isAbsolute(r));
14
- const trustedDir=path=>{
15
- const s=lstatSync(path);
16
- assert(s.isDirectory()&&!s.isSymbolicLink()&&!(s.mode&0o077)
17
- &&(!process.getuid||s.uid===process.getuid()),'CONTEXT_ROOT_UNTRUSTED');
18
- };
19
- export function canonicalWorkspaceRefs(paths,{allowEmpty=false}={}){
20
- assert(Array.isArray(paths)&&paths.length<=16&&(allowEmpty||paths.length>0),
21
- 'WORKSPACE_BINDING_INVALID');
22
- const refs=paths.map(path=>{
23
- assert(typeof path==='string'&&path.length<=4096&&isAbsolute(path),
24
- 'WORKSPACE_INVALID');
25
- let real,st;
26
- try{st=lstatSync(path);real=realpathSync(path)}
27
- catch{throw fail('WORKSPACE_UNVERIFIED')}
28
- assert(st.isDirectory()&&!st.isSymbolicLink(),'WORKSPACE_SYMLINK_REJECTED');
29
- return real;
30
- });
31
- for(let i=0;i<refs.length;i++)for(let j=0;j<i;j++)
32
- assert(!overlap(refs[i],refs[j]),'WORKSPACE_SCOPE_OVERLAP');
33
- return refs;
34
- }
35
- export function confirmationPhrase(action,projectId,revision,refs){
36
- const hash=createHash('sha256').update(JSON.stringify(
37
- {action,projectId,revision,refs})).digest('hex').slice(0,12);
38
- return 'CONFIRM '+action+' '+projectId+' '+hash;
39
- }
40
- export async function confirmWorkspaceOperator(action,projectId,revision,refs){
41
- if(!process.stdin.isTTY||!process.stderr.isTTY)throw fail('OPERATOR_TTY_REQUIRED');
42
- const phrase=confirmationPhrase(action,projectId,revision,refs);
43
- const rl=createInterface({input:process.stdin,output:process.stderr,terminal:true});
44
- try{
45
- process.stderr.write('Local operator approval only. Project: '+projectId+
46
- '\nAction: '+action+'\nReviewed paths:\n'+
47
- (refs.length?refs.map(x=>' '+x).join('\n'):' (clear all)')+'\n');
48
- const answer=await rl.question('Type '+phrase+' to authorize: ');
49
- assert(answer===phrase,'OPERATOR_CONFIRMATION_MISMATCH');
50
- }finally{rl.close()}
51
- }
52
- export function withWorkspaceRegistryLock(root,fn){
53
- trustedDir(root);
54
- const lock=join(root,'.project-register.lock');
55
- try{mkdirSync(lock,{mode:0o700})}catch{throw fail('PROJECT_REGISTRY_BUSY')}
56
- // Async backups must retain the same global lock through atomic publication.
57
- let deferred=false;
58
- try{
59
- const result=fn();
60
- if(result&&typeof result.then==='function'){
61
- deferred=true;
62
- return result.finally(()=>rmdirSync(lock));
63
- }
64
- return result;
65
- }finally{if(!deferred)rmdirSync(lock)}
66
- }
67
- // Scan all physical project directories, not just the current MCP grant.
68
- // An ungranted Project can still own the same Workspace. Do not auto-pick.
69
- export function assertWorkspaceUnclaimed(root,projectId,refs){
70
- for(const dir of readdirSync(root,{withFileTypes:true})){
71
- if(!ID.test(dir.name)||dir.name===projectId)continue;
72
- assert(dir.isDirectory()&&!dir.isSymbolicLink(),'PROJECT_DIRECTORY_UNTRUSTED');
73
- const file=join(root,dir.name,'context.sqlite');
74
- assert(existsSync(file),'PROJECT_IDENTITY_UNVERIFIED');
75
- const db=openContextProtocol(file,{readOnly:true,principalId:'local-operator',
76
- authorizeData:()=>true});
77
- let list;
78
- try{list=db.projectList()}finally{db.close()}
79
- assert(list.length===1&&list[0].projectId===dir.name,'PROJECT_IDENTITY_MISMATCH');
80
- for(const existing of list[0].sharedContext?.workspaceRefs??[]){
81
- assert(typeof existing==='string'&&isAbsolute(existing),'WORKSPACE_BINDING_INVALID');
82
- let canonical;
83
- try{canonical=realpathSync(existing)}catch{canonical=existing}
84
- for(const current of refs)
85
- assert(!overlap(canonical,current),'WORKSPACE_OWNERSHIP_CONFLICT');
86
- }
87
- }
88
- }
89
- export async function rebindProjectWorkspaces({
90
- projectId,expectedProjectRevision,expectedStoreEpoch,writeRequestId,workspaces
91
- }){
92
- assert(process.env.CHAT_LOOP_CONTEXT_ADMIN_ENABLE==='1','ADMIN_REQUIRED');
93
- assert(ID.test(projectId||'')&&allowedProjects().has(projectId),'PROJECT_ACCESS_DENIED');
94
- assert(Number.isSafeInteger(expectedProjectRevision)&&expectedProjectRevision>=1,
95
- 'PROJECT_REVISION_REQUIRED');
96
- assert(typeof expectedStoreEpoch==='string'&&expectedStoreEpoch.length>=10,
97
- 'STORE_EPOCH_REQUIRED');
98
- assert(typeof writeRequestId==='string'&&writeRequestId.length>=8&&
99
- writeRequestId.length<=128,'REQUEST_ID_REQUIRED');
100
- const refs=canonicalWorkspaceRefs(workspaces,{allowEmpty:true});
101
- const root=contextRoot();
102
- trustedDir(root);
103
- // First pass has no write side effects. Confirmation is bound to exact refs.
104
- const before=await dispatchContextCall('chat_loop_context_get',
105
- {operation:'project.open',projectId});
106
- assert(before.project.projectRevision===expectedProjectRevision,
107
- 'PROJECT_VERSION_CONFLICT');
108
- assert(before.storeEpoch===expectedStoreEpoch,'STALE_EPOCH');
109
- assert(!before.project.archived,'PROJECT_ARCHIVED');
110
- assert(before.authority.writable===true,'PROJECT_CUTOVER_NOT_VERIFIED');
111
- await confirmWorkspaceOperator('BIND',projectId,expectedProjectRevision,refs);
112
- return withWorkspaceRegistryLock(root,()=>{
113
- // Re-read under the *same* global lock as project register; Core CAS
114
- // protects concurrent business writes that do not take this lock.
115
- assertWorkspaceUnclaimed(root,projectId,refs);
116
- const current=canonicalWorkspaceRefs(workspaces,{allowEmpty:true});
117
- assert(JSON.stringify(current)===JSON.stringify(refs),'WORKSPACE_CHANGED');
118
- const file=join(root,projectId,'context.sqlite');
119
- const db=openContextProtocol(file,{principalId:'local-operator',
120
- authorizeData:(_mode,p)=>p===projectId,
121
- authorizeAdmin:(op,p)=>op==='project.bind'&&p===projectId});
122
- try{
123
- const ids=db.projectList();
124
- assert(ids.length===1&&ids[0].projectId===projectId,
125
- 'PROJECT_IDENTITY_MISMATCH');
126
- assert(db.projectBusinessAuthority(projectId).writable===true,
127
- 'PROJECT_CUTOVER_NOT_VERIFIED');
128
- const receipt=db.projectPatch({projectId,expectedProjectRevision,
129
- expectedStoreEpoch,writeRequestId,sharedContext:{workspaceRefs:refs}});
130
- const after=db.projectGet(projectId);
131
- assert(after.projectRevision===receipt.projectRevision&&
132
- JSON.stringify(after.sharedContext.workspaceRefs)===JSON.stringify(refs),
133
- 'WORKSPACE_RECEIPT_UNVERIFIED');
134
- return {...receipt,projectId,workspaceRefs:refs,storeEpoch:expectedStoreEpoch,
135
- writeRequestId};
136
- }finally{db.close()}
137
- });
138
- }
139
-
140
- // Read-only recovery for an operator write whose CLI result was lost.
141
- // Receipt uses the SAME local-operator principal, not the model MCP principal.
142
- export async function readOperatorWorkspaceReceipt({projectId,storeEpoch,writeRequestId}){
143
- assert(process.env.CHAT_LOOP_CONTEXT_ADMIN_ENABLE==='1','ADMIN_REQUIRED');
144
- assert(ID.test(projectId||'')&&allowedProjects().has(projectId),'PROJECT_ACCESS_DENIED');
145
- assert(typeof storeEpoch==='string'&&storeEpoch.length>=10,'STORE_EPOCH_REQUIRED');
146
- assert(typeof writeRequestId==='string'&&writeRequestId.length>=8&&
147
- writeRequestId.length<=128,'REQUEST_ID_REQUIRED');
148
- const opened=await dispatchContextCall('chat_loop_context_get',
149
- {operation:'project.open',projectId});
150
- assert(opened.storeEpoch===storeEpoch,'STALE_EPOCH');
151
- const file=join(contextRoot(),projectId,'context.sqlite');
152
- const db=openContextProtocol(file,{readOnly:true,principalId:'local-operator',
153
- authorizeData:(_mode,p)=>p===projectId});
154
- try{
155
- return {projectId,storeEpoch,writeRequestId,
156
- receipt:db.requestStatus({projectId,storeEpoch,writeRequestId}),
157
- project:db.projectGet(projectId)};
158
- }finally{db.close()}
159
- }
@@ -1,21 +0,0 @@
1
- {
2
- "name": "@tomflow/chatloop-context",
3
- "version": "0.1.0",
4
- "type": "module",
5
- "description": "Independent local Context SDK and short-lived CLI for Chat Loop projects",
6
- "publishConfig": {"access": "public"},
7
- "engines": {"node": ">=20"},
8
- "bin": {"chatloop-context": "./bin/cli.mjs"},
9
- "exports": {
10
- ".": "./lib/context-protocol.mjs",
11
- "./protocol": "./lib/context-protocol.mjs",
12
- "./migration": "./lib/context-migration.mjs",
13
- "./admin": "./lib/context-cli.mjs",
14
- "./methods": "./lib/methods.mjs",
15
- "./operations": "./lib/operations.mjs",
16
- "./cli": "./bin/cli.mjs",
17
- "./package.json": "./package.json"
18
- },
19
- "files": ["lib/", "bin/", "README.md"],
20
- "scripts": {"test": "node --test ./test/*.test.mjs"}
21
- }
@@ -1,13 +0,0 @@
1
- # @tomflow/chatloop-trace
2
-
3
- Node 20+ SDK imported by existing Chat Loop Tools. No CLI, daemon,
4
- network service, separate tunnel, SQLite data store, or Browser Owner rights.
5
-
6
- - createTraceWriter({filePath}): single existing Supervisor writes events.
7
- - createTraceReader({filePath,allowedProjects}): Gateway performs scoped
8
- read-only diagnostics, never a write or browser retry.
9
- - createTrace(): creates opaque correlation IDs, not credentials.
10
-
11
- The existing private events.jsonl is the only event file. Legacy lines remain
12
- readable but cannot be attributed to a new trace. Raw user content, tool
13
- arguments, cookies, credentials and arbitrary data are never accepted.