@tomflow/chatloop-tools 0.4.19 → 0.4.21

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 (30) hide show
  1. package/README.md +89 -3
  2. package/bin/cli.mjs +27 -6
  3. package/lib/context-cli.mjs +2 -0
  4. package/lib/context-control-auth.mjs +40 -0
  5. package/lib/context-control-run.mjs +117 -0
  6. package/lib/context-gateway.mjs +97 -0
  7. package/lib/context-migration.mjs +2 -0
  8. package/lib/context-protocol.mjs +2 -0
  9. package/lib/extension-contract.mjs +16 -0
  10. package/lib/extension-proxy.mjs +11 -2
  11. package/lib/gateway.mjs +89 -4
  12. package/lib/release.mjs +174 -5
  13. package/lib/supervisor.mjs +78 -3
  14. package/lib/task-registry-managed.mjs +38 -0
  15. package/lib/task-registry.mjs +221 -0
  16. package/lib/trace-gateway.mjs +99 -0
  17. package/node_modules/@tomflow/chatloop-context/README.md +204 -0
  18. package/node_modules/@tomflow/chatloop-context/bin/cli.mjs +236 -0
  19. package/node_modules/@tomflow/chatloop-context/lib/context-cli.mjs +301 -0
  20. package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +272 -0
  21. package/node_modules/@tomflow/chatloop-context/lib/context-protocol.mjs +1595 -0
  22. package/node_modules/@tomflow/chatloop-context/lib/methods.mjs +264 -0
  23. package/node_modules/@tomflow/chatloop-context/lib/operations.mjs +219 -0
  24. package/node_modules/@tomflow/chatloop-context/lib/project-diagnostic.mjs +289 -0
  25. package/node_modules/@tomflow/chatloop-context/lib/workspace-operator.mjs +159 -0
  26. package/node_modules/@tomflow/chatloop-context/package.json +21 -0
  27. package/node_modules/@tomflow/chatloop-trace/README.md +13 -0
  28. package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +259 -0
  29. package/node_modules/@tomflow/chatloop-trace/package.json +11 -0
  30. package/package.json +9 -3
@@ -0,0 +1,272 @@
1
+ // SourceUnit migration helpers shared by Chat Loop self-host and user projects.
2
+ // Never infer task approvals, Browser Owner, or a runnable checkpoint from
3
+ // Markdown/legacy Registry. Default mode is read-only SHADOW.
4
+ import {createHash,randomUUID} from 'node:crypto';
5
+ import {readFileSync,writeFileSync,mkdirSync,existsSync,lstatSync,copyFileSync,chmodSync,constants,
6
+ realpathSync,renameSync,unlinkSync,openSync,readSync,closeSync} from 'node:fs';
7
+ import {basename,dirname,join,resolve,isAbsolute} from 'node:path';
8
+ import {DatabaseSync,backup} from 'node:sqlite';
9
+ const fail=code=>Object.assign(new Error(code),{code});
10
+ const assert=(b,c)=>{if(!b)throw fail(c)};
11
+ const hash=x=>createHash('sha256').update(x).digest('hex');
12
+ const ID=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
13
+ // Hash large online backups incrementally; never load a 2 GiB database
14
+ // into the Agent/CLI process just to check its integrity.
15
+ const hashLargeFile=(file,max=2*1024*1024*1024)=>{
16
+ assert(typeof file==='string'&&isAbsolute(file),'SOURCE_PATH_INVALID');
17
+ const st=lstatSync(file);
18
+ assert(st.isFile()&&!st.isSymbolicLink()&&st.size>0&&st.size<=max,
19
+ 'BACKUP_SOURCE_UNTRUSTED');
20
+ const fd=openSync(file,constants.O_RDONLY);
21
+ const hasher=createHash('sha256'),chunk=Buffer.alloc(64*1024);
22
+ let length=0;
23
+ try{
24
+ let n;
25
+ while((n=readSync(fd,chunk,0,chunk.length,null))>0){
26
+ hasher.update(chunk.subarray(0,n));length+=n;
27
+ assert(length<=max,'BACKUP_TOO_LARGE');
28
+ }
29
+ }finally{closeSync(fd)}
30
+ assert(length===st.size,'BACKUP_CHANGED_WHILE_READING');
31
+ return {path:realpathSync(file),hash:hasher.digest('hex'),bytes:length};
32
+ };
33
+ const safeRead=(file,max=4*1024*1024)=>{
34
+ assert(typeof file==='string'&&isAbsolute(file),'SOURCE_PATH_INVALID');
35
+ const st=lstatSync(file);
36
+ assert(st.isFile()&&!st.isSymbolicLink()&&st.size>0&&st.size<=max,'SOURCE_UNTRUSTED');
37
+ return {stat:st,bytes:readFileSync(file),path:realpathSync(file)};
38
+ };
39
+ const privateDirectory=dir=>{
40
+ mkdirSync(dir,{recursive:true,mode:0o700});
41
+ const st=lstatSync(dir);
42
+ assert(st.isDirectory()&&!st.isSymbolicLink()&&!(st.mode&0o077)
43
+ &&(!process.getuid||st.uid===process.getuid()),'PRIVATE_DIR_UNTRUSTED');
44
+ };
45
+ const safeOutput=(file,value)=>{
46
+ const dir=dirname(file);privateDirectory(dir);
47
+ const tmp=join(dir,'.'+basename(file)+'.'+randomUUID()+'.tmp');
48
+ try{
49
+ writeFileSync(tmp,JSON.stringify(value,null,2)+'\n',{flag:'wx',mode:0o600});
50
+ renameSync(tmp,file);
51
+ }finally{try{unlinkSync(tmp)}catch{}}
52
+ };
53
+ export function scanSourceUnit({sourcePath,projectId,kind}){
54
+ assert(ID.test(projectId||''),'PROJECT_ID_INVALID');
55
+ assert(['REGISTRY_JSON','MIXED_CONTEXT','DOCUMENT'].includes(kind),'SOURCE_KIND_INVALID');
56
+ const source=safeRead(sourcePath,kind==='MIXED_CONTEXT'?8*1024*1024:4*1024*1024);
57
+ const evidence={sourceUnitId:hash(source.path),sourcePath:source.path,
58
+ projectId,sourceHash:hash(source.bytes),sourceSize:source.stat.size,
59
+ sourceKind:kind,sourceScope:kind==='MIXED_CONTEXT'?'PROJECT_SHARED':'SOURCE_FILE',
60
+ observedAt:Date.now(),status:'SHADOW_RO',ownership:'EVIDENCE_ONLY',
61
+ tasks:[],unknownItems:[],knownWriters:['legacy-gateway','file-tools','user-editor'],
62
+ provenance:'SOURCE_READ_ONLY'};
63
+ if(kind!=='REGISTRY_JSON'){
64
+ // A mixed CURRENT can span Projects/Tasks; never parse arbitrary prose
65
+ // into a verified Task or R/P/approval fact.
66
+ evidence.unknownItems.push({reason:'UNCLASSIFIED_HISTORICAL_CONTENT',
67
+ sourcePath:source.path,sourceHash:evidence.sourceHash});
68
+ return evidence;
69
+ }
70
+ let legacy;
71
+ try{legacy=JSON.parse(source.bytes.toString('utf8'))}catch{throw fail('LEGACY_REGISTRY_CORRUPT')}
72
+ assert(legacy?.schemaVersion===1&&legacy.projects&&typeof legacy.projects==='object'
73
+ &&!Array.isArray(legacy.projects),'LEGACY_REGISTRY_INVALID');
74
+ const legacyProject=legacy.projects[projectId];
75
+ if(!legacyProject){
76
+ evidence.unknownItems.push({reason:'PROJECT_NOT_IN_REGISTRY',sourceHash:evidence.sourceHash});
77
+ return evidence;
78
+ }
79
+ assert(legacyProject.tasks&&typeof legacyProject.tasks==='object'
80
+ &&!Array.isArray(legacyProject.tasks),'LEGACY_TASK_MAP_INVALID');
81
+ evidence.ownership='VERIFIED_REGISTRY_IDENTITIES_ONLY';
82
+ for(const [taskId,t] of Object.entries(legacyProject.tasks)){
83
+ assert(ID.test(taskId),'LEGACY_TASK_ID_INVALID');
84
+ // The only guaranteed importable fact is the old registry's identity
85
+ // and source reference. Approval/status/Owner are NEVER synthesized.
86
+ assert(t.taskId===taskId&&t.projectId===projectId,'LEGACY_TASK_ID_MISMATCH');
87
+ const doc=safeRead(t.taskDocPath,512*1024);
88
+ const labels=[...doc.bytes.toString('utf8').matchAll(
89
+ /^\s*(?:[-*]\s*)?taskId\s*[::]\s*["'\x60]?([a-zA-Z0-9][a-zA-Z0-9._-]*)/gmi)];
90
+ assert(labels.length===1&&labels[0][1]===taskId,'LEGACY_DOCUMENT_TASK_ID_UNVERIFIED');
91
+ evidence.tasks.push({taskId,title:t.title,taskDocPath:doc.path,
92
+ taskDocumentHash:hash(doc.bytes),parentTaskId:t.parentTaskId??null,
93
+ legacyRevision:t.revision,
94
+ documents:(t.documents??[]).map(d=>({role:d.role,locator:d.sourcePath,
95
+ versionRef:d.versionRef??null,sourceStatus:'UNVERIFIED'})),
96
+ approvalStatus:'UNVERIFIED',executionOutcome:'UNVERIFIED'});
97
+ }
98
+ return evidence;
99
+ }
100
+ export function verifySourceUnit(manifest){
101
+ const current=scanSourceUnit({sourcePath:manifest.sourcePath,
102
+ projectId:manifest.projectId,kind:manifest.sourceKind});
103
+ assert(current.sourceHash===manifest.sourceHash,'SOURCE_CHANGED');
104
+ assert(current.sourceUnitId===manifest.sourceUnitId,'SOURCE_REPLACED');
105
+ if(manifest.sourceKind==='REGISTRY_JSON'){
106
+ assert(JSON.stringify(current.tasks)===JSON.stringify(manifest.tasks),
107
+ 'LEGACY_REFERENCE_CHANGED');
108
+ }
109
+ return {status:'MATCHED',sourceUnitId:manifest.sourceUnitId,
110
+ sourceHash:current.sourceHash};
111
+ }
112
+ export function saveShadowManifest(file,items){
113
+ assert(Array.isArray(items)&&items.length>0&&items.length<=128,'MANIFEST_INVALID');
114
+ const unique=new Set(items.map(x=>x.sourceUnitId));
115
+ assert(unique.size===items.length,'SOURCE_UNIT_DUPLICATED');
116
+ const manifest={contract:'chat-loop.context-source-units.v1',
117
+ instanceLineage:randomUUID(),createdAt:Date.now(),
118
+ status:'SHADOW_RO',sourceUnits:items,permissions:'READ_ONLY',
119
+ taskApprovalsImported:false,ownerImported:false,
120
+ knownWritersStopped:false};
121
+ assert(!existsSync(file),'MANIFEST_EXISTS');
122
+ safeOutput(file,manifest);
123
+ return manifest;
124
+ }
125
+ export function readShadowManifest(file){
126
+ const path=resolve(file),st=lstatSync(path);
127
+ assert(st.isFile()&&!st.isSymbolicLink()&&!(st.mode&0o077)
128
+ &&(!process.getuid||st.uid===process.getuid()),'MANIFEST_UNTRUSTED');
129
+ const manifest=JSON.parse(readFileSync(path,'utf8'));
130
+ assert(manifest?.contract==='chat-loop.context-source-units.v1'
131
+ &&Array.isArray(manifest.sourceUnits)&&manifest.sourceUnits.length>0,
132
+ 'MANIFEST_SCHEMA_INVALID');
133
+ return manifest;
134
+ }
135
+ export function verifyShadowManifest(file){
136
+ const m=readShadowManifest(file);
137
+ return {status:'SHADOW_MATCHED',checks:m.sourceUnits.map(verifySourceUnit),
138
+ sourceUnits:m.sourceUnits.length};
139
+ }
140
+ // SQLite online backup: never copy a live database's main file.
141
+ export async function backupContextDb(dbHandle,targetFile){
142
+ assert(typeof targetFile==='string'&&isAbsolute(targetFile),'BACKUP_PATH_INVALID');
143
+ assert(!existsSync(targetFile),'BACKUP_EXISTS');
144
+ privateDirectory(dirname(targetFile));
145
+ try{
146
+ await backup(dbHandle,targetFile);
147
+ chmodSync(targetFile,0o600);
148
+ const st=lstatSync(targetFile);
149
+ assert(st.isFile()&&!st.isSymbolicLink(),'BACKUP_UNTRUSTED');
150
+ const ready=hashLargeFile(targetFile);
151
+ return {...ready,status:'BACKED_UP'};
152
+ }catch(e){try{unlinkSync(targetFile)}catch{}throw e}
153
+ }
154
+ // Restore is an OFFLINE fork with a fresh Store epoch, never an in-place
155
+ // replacement of an active database or a Browser Owner resurrector.
156
+ export function restoreBackupToDiagnosticBranch({
157
+ backupFile,targetDb,expectedBackupHash,manifestFile
158
+ }){
159
+ assert(typeof backupFile==='string'&&isAbsolute(backupFile)
160
+ &&typeof targetDb==='string'&&isAbsolute(targetDb)
161
+ &&typeof manifestFile==='string'&&isAbsolute(manifestFile)
162
+ &&typeof expectedBackupHash==='string'&&/^[a-f0-9]{64}$/.test(expectedBackupHash),
163
+ 'RESTORE_ARGUMENT_INVALID');
164
+ assert(!existsSync(targetDb)&&!existsSync(manifestFile),'RESTORE_TARGET_EXISTS');
165
+ const source=hashLargeFile(backupFile);
166
+ assert(source.hash===expectedBackupHash,'BACKUP_HASH_MISMATCH');
167
+ privateDirectory(dirname(targetDb));
168
+ copyFileSync(source.path,targetDb,constants.COPYFILE_EXCL);
169
+ chmodSync(targetDb,0o600);
170
+ let db;
171
+ try{
172
+ db=new DatabaseSync(targetDb);
173
+ const version=db.prepare("SELECT value FROM meta WHERE key='schemaVersion'").get()?.value;
174
+ const previousEpoch=db.prepare("SELECT value FROM meta WHERE key='storeEpoch'").get()?.value;
175
+ assert(version==='6'&&typeof previousEpoch==='string'&&previousEpoch.length>0,
176
+ 'BACKUP_SCHEMA_UNSUPPORTED');
177
+ const integrity=db.prepare('PRAGMA integrity_check').all();
178
+ assert(integrity.length===1&&integrity[0].integrity_check==='ok','BACKUP_CORRUPT');
179
+ const newEpoch=randomUUID();
180
+ db.exec('PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON;');
181
+ db.exec('BEGIN IMMEDIATE');
182
+ try{
183
+ db.prepare("UPDATE meta SET value=? WHERE key='storeEpoch'").run(newEpoch);
184
+ db.prepare("INSERT OR REPLACE INTO meta(key,value) VALUES('storeMode','DIAGNOSTIC_ONLY')").run();
185
+ db.prepare("INSERT OR REPLACE INTO meta(key,value) VALUES('restoredFromEpoch',?)")
186
+ .run(previousEpoch);
187
+ db.exec(`UPDATE tasks SET writable_ref=NULL,credential_digest=NULL,
188
+ writer_approval_revision=NULL,pending_attempt=NULL,pending_checkpoint=NULL,pending_target_generation=NULL,
189
+ pending_credential_digest=NULL,pending_next_ref=NULL,binding_revision=binding_revision+1;
190
+ DELETE FROM permits;DELETE FROM start_leases;
191
+ UPDATE migrations SET status='RESTORED_DIAGNOSTIC',
192
+ migration_revision=migration_revision+1,updated_at=0;`);
193
+ db.exec('COMMIT');
194
+ }catch(e){db.exec('ROLLBACK');throw e}
195
+ const record={contract:'chat-loop.context-restore.v1',
196
+ status:'RESTORED_DIAGNOSTIC',previousEpoch,newEpoch,
197
+ sourceBackup:{path:backupFile,hash:expectedBackupHash},
198
+ targetDb,ownerRestored:false,writeCapabilitiesRestored:false,
199
+ sourceUnitsRequireRevalidation:true,
200
+ canExecute:false,generatedAt:Date.now()};
201
+ safeOutput(manifestFile,record);
202
+ return record;
203
+ }catch(e){
204
+ try{unlinkSync(targetDb)}catch{}
205
+ throw e;
206
+ }finally{try{db?.close()}catch{}}
207
+ }
208
+ export function createRecoveryManifest(file,{projectId,taskId,storeEpoch,storeLineage,
209
+ checkpointRef,backupRef,readerVersion='context-v1',unknownEffects=[]}){
210
+ assert(ID.test(projectId||'')&&ID.test(taskId||'')&&
211
+ typeof storeEpoch==='string'&&storeEpoch.length>0,'RECOVERY_ID_INVALID');
212
+ assert(Array.isArray(unknownEffects)&&unknownEffects.length<=500,'RECOVERY_UNKNOWN_INVALID');
213
+ const record={contract:'chat-loop.context-recovery.v1',projectId,taskId,
214
+ storeEpoch,storeLineage,checkpointRef:checkpointRef??null,
215
+ backupRef,readerVersion,unknownEffects,generatedAt:Date.now(),
216
+ mode:'DIAGNOSTIC_ONLY',canExecute:false};
217
+ assert(!existsSync(file),'RECOVERY_MANIFEST_EXISTS');
218
+ safeOutput(file,record);
219
+ return record;
220
+ }
221
+
222
+ /**
223
+ * Legacy Registry references may drift when a source document gets a benign
224
+ * superseded note. Compare the original archive, the unchanged Registry and
225
+ * its current task document. The result is evidence, not permission to cut over.
226
+ * A trusted operator may later use it under the Core's revision/CAS receipt.
227
+ */
228
+ export function inspectRegistryReferenceForReview(manifest,{
229
+ taskId,archiveFile,expectedCurrentHash
230
+ }){
231
+ assert(manifest?.sourceKind==='REGISTRY_JSON'&&
232
+ typeof taskId==='string'&&ID.test(taskId),'REGISTRY_REVIEW_INVALID');
233
+ const source=scanSourceUnit({sourcePath:manifest.sourcePath,
234
+ projectId:manifest.projectId,kind:'REGISTRY_JSON'});
235
+ assert(source.sourceHash===manifest.sourceHash&&
236
+ source.sourceUnitId===manifest.sourceUnitId,'SOURCE_CHANGED');
237
+ assert(source.tasks.length===manifest.tasks.length,'REGISTRY_TASK_SET_CHANGED');
238
+ const previous=manifest.tasks.find(t=>t.taskId===taskId);
239
+ const current=source.tasks.find(t=>t.taskId===taskId);
240
+ assert(previous&&current,'REGISTRY_TASK_NOT_FOUND');
241
+ for(const old of manifest.tasks){
242
+ const next=source.tasks.find(t=>t.taskId===old.taskId);
243
+ assert(next&&Object.keys(old).every(k=>
244
+ (k==='taskDocumentHash'&&old.taskId===taskId)
245
+ ||JSON.stringify(next[k])===JSON.stringify(old[k])),
246
+ 'REGISTRY_TASK_IDENTITY_CHANGED');
247
+ }
248
+ assert(/^[a-f0-9]{64}$/.test(previous.taskDocumentHash??'')&&
249
+ typeof expectedCurrentHash==='string'&&
250
+ expectedCurrentHash===current.taskDocumentHash&&
251
+ current.taskDocPath===previous.taskDocPath,
252
+ 'REGISTRY_REFERENCE_VERSION_CONFLICT');
253
+ const archive=safeRead(archiveFile,512*1024);
254
+ assert(hash(archive.bytes)===previous.taskDocumentHash,
255
+ 'ARCHIVE_HASH_MISMATCH');
256
+ const newest=safeRead(current.taskDocPath,512*1024);
257
+ assert(hash(newest.bytes)===expectedCurrentHash,
258
+ 'DOCUMENT_CHANGED_DURING_REVIEW');
259
+ const oldLines=archive.bytes.toString('utf8').split(/(?<=\n)/);
260
+ const newLines=newest.bytes.toString('utf8').split(/(?<=\n)/);
261
+ let position=0;
262
+ for(const line of newLines){
263
+ if(position<oldLines.length&&oldLines[position]===line)position++;
264
+ }
265
+ assert(position===oldLines.length&&newLines.length>oldLines.length,
266
+ 'REGISTRY_REVIEW_NOT_INSERTIONS_ONLY');
267
+ return {currentTasks:source.tasks,originalHash:previous.taskDocumentHash,
268
+ currentHash:expectedCurrentHash,originalArchiveHash:hash(archive.bytes),
269
+ originalArchivePath:archive.path,insertedLines:newLines.length-oldLines.length,
270
+ originalLines:oldLines.length,currentLines:newLines.length,
271
+ sourceHash:source.sourceHash};
272
+ }