@tomflow/chatloop-tools 0.4.28 → 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,301 +0,0 @@
1
- // Local-only Context Manager administration. Never exposed through MCP tools.
2
- // Activation requires explicit terminal operator consent and known-writer check.
3
- // This is a SAME-UID trust boundary, not a proof of ChatGPT user identity.
4
- import {realpathSync,existsSync,lstatSync,readFileSync} from 'node:fs';
5
- import {randomUUID,createHash} from 'node:crypto';
6
- import {execFileSync} from 'node:child_process';
7
- import {createInterface} from 'node:readline/promises';
8
- import {isAbsolute,resolve} from 'node:path';
9
- import {DatabaseSync} from 'node:sqlite';
10
- import {openContextProtocol} from './context-protocol.mjs';
11
- import {parseContextAllowedProjects} from './methods.mjs';
12
- import {scanSourceUnit,saveShadowManifest,readShadowManifest,
13
- verifyShadowManifest,backupContextDb,createRecoveryManifest,restoreBackupToDiagnosticBranch} from './context-migration.mjs';
14
- const fail=code=>Object.assign(new Error(code),{code});
15
- const hash=x=>createHash('sha256').update(x).digest('hex');
16
- const ID=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
17
- const allowed=()=>parseContextAllowedProjects(process.env.CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS);
18
- const verified=(projectId)=>{if(!allowed().has(projectId)||!ID.test(projectId||''))
19
- throw fail('PROJECT_NOT_AUTHORIZED')};
20
- async function operatorConfirm(expected){
21
- if(!process.stdin.isTTY||!process.stdout.isTTY)throw fail('OPERATOR_TTY_REQUIRED');
22
- const rl=createInterface({input:process.stdin,output:process.stdout});
23
- try{
24
- const answer=await rl.question('Confirm local Context cutover by typing '+expected+': ');
25
- if(answer!==expected)throw fail('OPERATOR_CONFIRMATION_MISMATCH');
26
- }finally{rl.close()}
27
- }
28
- function activeLegacyWriters(){
29
- // Observable supported-client process inventory, NOT proof of every old
30
- // npx cache or arbitrary same-UID shell. Operator must verify those too.
31
- const output=execFileSync('/bin/ps',['-axo','pid=,command='],
32
- {encoding:'utf8',timeout:5000,maxBuffer:2*1024*1024});
33
- const pid=process.pid;
34
- return output.split('\n').map(x=>x.trim()).filter(Boolean).filter(line=>{
35
- const match=line.match(/^(\d+)\s+(.+)$/);
36
- return match&&Number(match[1])!==pid
37
- &&(/chatloop-tools\/bin\/cli\.mjs\s+mcp|@tomflow\/chatloop-tools.*\/bin\/cli\.mjs\s+mcp|chat-loop-local-tools.*\/bin\/cli\.mjs\s+mcp/.test(match[2]));
38
- }).slice(0,20);
39
- }
40
- const open=(allowCreate=false)=>openContextProtocol(process.env.CHAT_LOOP_CONTEXT_DB,{
41
- allowCreate,
42
- principalId:'local-operator',
43
- authorizeData:(_,p)=>allowed().has(p),
44
- authorizeAdmin:()=>true
45
- });
46
- const readBytes=(file)=>{
47
- const st=lstatSync(file);
48
- if(!st.isFile()||st.isSymbolicLink())throw fail('SOURCE_UNTRUSTED');
49
- return readFileSync(file);
50
- };
51
- const readOperatorReview=(file)=>{
52
- if(!isAbsolute(file))throw fail('REVIEW_PATH_INVALID');
53
- const st=lstatSync(file);
54
- if(!st.isFile()||st.isSymbolicLink()||(st.mode&0o077)
55
- ||(process.getuid&&st.uid!==process.getuid())
56
- ||st.size===0||st.size>1024*1024)throw fail('REVIEW_FILE_UNTRUSTED');
57
- let reviewed;
58
- try{reviewed=JSON.parse(readFileSync(file,'utf8'))}
59
- catch{throw fail('REVIEW_FILE_INVALID')}
60
- return reviewed;
61
- };
62
- const write=(a,o={})=>({projectId:a.projectId,expectedStoreEpoch:o.epoch,
63
- writeRequestId:randomUUID(),...a});
64
- export async function runContextCli(argv,{confirm=operatorConfirm}={}){
65
- if(Number(process.versions.node.split('.')[0])<24)throw fail('CONTEXT_RUNTIME_UNSUPPORTED');
66
- if(!process.env.CHAT_LOOP_CONTEXT_DB||!isAbsolute(process.env.CHAT_LOOP_CONTEXT_DB))
67
- throw fail('CONTEXT_DB_NOT_CONFIGURED');
68
- allowed(); // Reject malformed or ambiguous grants before all admin actions.
69
- const [action,...params]=argv;
70
- if(action==='doctor'){
71
- if(params.length)throw fail('INVALID_ARGUMENT');
72
- const db=open();
73
- try{return {status:'INSPECTED',...db.integrity(),pragmas:db.pragmas()}}
74
- finally{db.close()}
75
- }
76
- if(action==='init'){
77
- if(params.length)throw fail('INVALID_ARGUMENT');
78
- const db=open(true);
79
- try{return {status:'READY',storeEpoch:db.epoch,pragmas:db.pragmas()}}
80
- finally{db.close()}
81
- }
82
- if(action==='scan'){
83
- if(params.length!==4)throw fail('INVALID_ARGUMENT');
84
- const [projectId,kind,path,manifestPath]=params;
85
- verified(projectId);
86
- const source=scanSourceUnit({projectId,kind,sourcePath:path});
87
- const manifest=saveShadowManifest(manifestPath,[source]);
88
- return {status:'SHADOW_RO',sourceUnit:source,manifestPath,
89
- manifestId:manifest.instanceLineage};
90
- }
91
- if(action==='backup'){
92
- if(params.length!==1)throw fail('INVALID_ARGUMENT');
93
- const db=open(),target=params[0];db.close();
94
- const raw=new DatabaseSync(process.env.CHAT_LOOP_CONTEXT_DB);
95
- try{return await backupContextDb(raw,target)}
96
- finally{raw.close()}
97
- }
98
- if(action==='restore-branch'){
99
- if(params.length!==4)throw fail('INVALID_ARGUMENT');
100
- const [backupFile,targetDb,expectedBackupHash,manifestFile]=params;
101
- // Recovery branch creation never imports Browser Owner and never opens
102
- // this branch for business writes until reauthorization/reconciliation.
103
- await confirm('RESTORE_DIAGNOSTIC '+targetDb);
104
- return restoreBackupToDiagnosticBranch({
105
- backupFile,targetDb,expectedBackupHash,manifestFile});
106
- }
107
- if(action==='project-create'){
108
- if(params.length!==2)throw fail('INVALID_ARGUMENT');
109
- const [projectId,title]=params;verified(projectId);
110
- const db=open();
111
- try{return db.projectCreate(write({projectId,title},{epoch:db.epoch}))}
112
- finally{db.close()}
113
- }
114
- if(action==='shadow'){
115
- if(params.length!==2)throw fail('INVALID_ARGUMENT');
116
- const [projectId,manifestPath]=params;verified(projectId);
117
- const manifest=readShadowManifest(manifestPath);
118
- if(manifest.sourceUnits.length!==1)throw fail('ONE_SOURCE_UNIT_REQUIRED');
119
- const one=manifest.sourceUnits[0];
120
- if(one.projectId!==projectId)throw fail('PROJECT_MISMATCH');
121
- verifyShadowManifest(manifestPath);
122
- const db=open();
123
- try{return db.migrationShadow(write({projectId,...one,manifest:one},{epoch:db.epoch}))}
124
- finally{db.close()}
125
- }
126
- if(action==='status'){
127
- if(params.length!==1)throw fail('INVALID_ARGUMENT');
128
- const projectId=params[0];verified(projectId);
129
- const db=open();
130
- try{
131
- const sourceUnits=db.migrationList(projectId);
132
- const materials=db.projectMaterialList(projectId);
133
- const project=db.projectGet(projectId);
134
- const tasks=db.taskList(projectId);
135
- return {status:'OK',projectId,storeMode:db.mode,
136
- projectRevision:project.projectRevision,
137
- authority:db.registryAuthority(projectId),
138
- businessAuthority:db.projectBusinessAuthority(projectId),
139
- // Registry authority is NOT the authority of every physical SourceUnit.
140
- sourceUnits,materialCount:materials.length,materials,
141
- taskCount:tasks.length,taskRefs:tasks.map(t=>({taskId:t.taskId,
142
- taskRevision:t.taskRevision}))};
143
- }
144
- finally{db.close()}
145
- }
146
- if(action==='classify'){
147
- if(params.length!==3)throw fail('INVALID_ARGUMENT');
148
- const [projectId,manifestPath,reviewPath]=params;verified(projectId);
149
- verifyShadowManifest(manifestPath);
150
- const manifest=readShadowManifest(manifestPath);
151
- if(manifest.sourceUnits.length!==1)throw fail('ONE_SOURCE_UNIT_REQUIRED');
152
- const unit=manifest.sourceUnits[0];
153
- if(unit.projectId!==projectId||unit.sourceKind!=='MIXED_CONTEXT')
154
- throw fail('MIXED_SOURCE_REQUIRED');
155
- const classification=readOperatorReview(reviewPath);
156
- const db=open();
157
- try{
158
- const stage=db.migrationList(projectId).find(r=>r.sourceUnitId===unit.sourceUnitId);
159
- if(stage?.status!=='SHADOW_RO')throw fail('MIGRATION_STAGE_MISMATCH');
160
- if(stage.sourceHash!==unit.sourceHash)throw fail('SOURCE_CHANGED');
161
- // The operator reviews exactly one physical source and its full
162
- // EvidenceOnly reference; this does NOT certify historical authorship.
163
- await confirm('CLASSIFY '+projectId+' '+unit.sourceUnitId);
164
- verifyShadowManifest(manifestPath);
165
- return db.migrationClassify(write({
166
- projectId,sourceUnitId:unit.sourceUnitId,sourceHash:unit.sourceHash,
167
- expectedMigrationRevision:stage.migrationRevision,classification
168
- },{epoch:db.epoch}));
169
- }finally{db.close()}
170
- }
171
- if(action==='import-sources'){
172
- if(params.length!==2)throw fail('INVALID_ARGUMENT');
173
- const [projectId,reviewPath]=params;verified(projectId);
174
- const review=readOperatorReview(reviewPath);
175
- if(review?.projectId!==projectId||!Array.isArray(review.materials)
176
- ||review.materials.length<1||review.materials.length>128)
177
- throw fail('SOURCE_IMPORT_REVIEW_INVALID');
178
- const root=realpathSync(review.sourceRoot);
179
- const seen=new Set();
180
- // Hash-check the FULL bytes before prompting. Never infer R/P approvals,
181
- // task identities or an active checkpoint from legacy Markdown.
182
- const materials=review.materials.map(item=>{
183
- if(typeof item.materialId!=='string'||!ID.test(item.materialId)
184
- ||seen.has(item.materialId)||!['INSTRUCTIONS','HISTORY','LEGACY_EVIDENCE','REFERENCE'].includes(item.kind)
185
- ||typeof item.path!=='string'||!isAbsolute(item.path)
186
- ||typeof item.sha256!=='string'||!/^[a-f0-9]{64}$/.test(item.sha256))
187
- throw fail('SOURCE_IMPORT_REVIEW_INVALID');
188
- seen.add(item.materialId);
189
- const original=realpathSync(item.path);
190
- if(!original.startsWith(root+'/'))throw fail('SOURCE_OUTSIDE_ROOT');
191
- const bytes=readBytes(item.path);
192
- if(bytes.length>4*1024*1024)throw fail('SOURCE_TOO_LARGE');
193
- if(hash(bytes)!==item.sha256)throw fail('SOURCE_CHANGED');
194
- const body=bytes.toString('utf8');
195
- if(!Buffer.from(body,'utf8').equals(bytes))throw fail('SOURCE_NOT_UTF8');
196
- return {materialId:item.materialId,kind:item.kind,body,
197
- contentHash:item.sha256,sourcePath:original};
198
- });
199
- const db=open();
200
- try{
201
- const before=db.projectMaterialList(projectId);
202
- for(const item of materials){
203
- const prev=before.find(v=>v.materialId===item.materialId&&v.version===1);
204
- if(prev && (prev.contentHash!==item.contentHash||prev.kind!==item.kind
205
- ||prev.sourcePath!==item.sourcePath))
206
- throw fail('IMPORTED_SOURCE_CONFLICT');
207
- }
208
- await confirm('IMPORT_SOURCES '+projectId);
209
- // The operator may spend time reviewing the manifest. Ensure no source
210
- // changed between preflight and the first durable Store mutation.
211
- for(const item of materials)
212
- if(hash(readBytes(item.sourcePath))!==item.contentHash)
213
- throw fail('SOURCE_CHANGED');
214
- const imported=[];
215
- for(const item of materials){
216
- const prior=db.projectMaterialList(projectId)
217
- .find(v=>v.materialId===item.materialId&&v.version===1);
218
- if(!prior){
219
- const version=db.projectGet(projectId).projectRevision;
220
- db.projectMaterialPut(write({...item,projectId,version:1,
221
- expectedProjectRevision:version,provenance:'LEGACY_UNVERIFIED'},
222
- {epoch:db.epoch}));
223
- }
224
- const readBack=db.projectMaterialGet(projectId,item.materialId,1);
225
- if(hash(Buffer.from(readBack.body,'utf8'))!==item.contentHash)
226
- throw fail('SOURCE_IMPORT_VERIFY_FAILED');
227
- imported.push({materialId:item.materialId,sha256:item.contentHash,
228
- provenance:'LEGACY_UNVERIFIED'});
229
- }
230
- return {status:'EVIDENCE_STAGED_NOT_CUTOVER',projectId,imported,
231
- approvalsImported:false,ownerImported:false,checkpointImported:false,
232
- currentAuthority:'LEGACY_RW'};
233
- }finally{db.close()}
234
- }
235
- if(action==='prepare'){
236
- if(params.length!==5)throw fail('INVALID_ARGUMENT');
237
- const [projectId,sourceUnitId,manifestPath,backupPath,recoveryPath]=params;
238
- verified(projectId);
239
- verifyShadowManifest(manifestPath);
240
- const manifest=readShadowManifest(manifestPath);
241
- const unit=manifest.sourceUnits.find(x=>x.sourceUnitId===sourceUnitId
242
- &&x.projectId===projectId);
243
- if(!unit)throw fail('SOURCE_UNIT_NOT_FOUND');
244
- // Fail BEFORE creating backup/recovery artifacts if classification or
245
- // revision is already known to be ineligible for a write cutover.
246
- const preflight=open();
247
- try{
248
- const stage=preflight.migrationList(projectId).find(r=>r.sourceUnitId===sourceUnitId);
249
- if(stage?.status!=='SHADOW_RO')throw fail('MIGRATION_STAGE_MISMATCH');
250
- if(stage.sourceHash!==unit.sourceHash)throw fail('SOURCE_CHANGED');
251
- if(unit.sourceKind==='MIXED_CONTEXT' &&
252
- stage.manifest.classification?.currentFactsComplete!==true)
253
- throw fail('MIXED_SOURCE_UNCLASSIFIED');
254
- }finally{preflight.close()}
255
- await confirm('PREPARE '+projectId+' '+sourceUnitId);
256
- const raw=new DatabaseSync(process.env.CHAT_LOOP_CONTEXT_DB);
257
- let backup;
258
- try{backup=await backupContextDb(raw,backupPath)}
259
- finally{raw.close()}
260
- const db=open();
261
- try{
262
- const stage=db.migrationList(projectId).find(r=>r.sourceUnitId===sourceUnitId);
263
- if(stage?.status!=='SHADOW_RO')throw fail('MIGRATION_STAGE_MISMATCH');
264
- if(stage.sourceHash!==unit.sourceHash)throw fail('SOURCE_CHANGED');
265
- const recovery=createRecoveryManifest(recoveryPath,{
266
- projectId,taskId:'migration-meta',storeEpoch:db.epoch,
267
- storeLineage:manifest.instanceLineage,
268
- checkpointRef:null,backupRef:backup,
269
- unknownEffects:unit.unknownItems??[]});
270
- return db.migrationPrepare(write({projectId,sourceUnitId,
271
- expectedMigrationRevision:stage.migrationRevision,sourceHash:unit.sourceHash,
272
- backupHash:backup.hash,recoveryManifestHash:hash(readBytes(recoveryPath))},
273
- {epoch:db.epoch}));
274
- }finally{db.close()}
275
- }
276
- if(action==='activate'){
277
- if(params.length!==3)throw fail('INVALID_ARGUMENT');
278
- const [projectId,sourceUnitId,manifestPath]=params;verified(projectId);
279
- verifyShadowManifest(manifestPath);
280
- const manifest=readShadowManifest(manifestPath);
281
- const unit=manifest.sourceUnits.find(x=>x.sourceUnitId===sourceUnitId
282
- &&x.projectId===projectId);
283
- if(!unit)throw fail('SOURCE_UNIT_NOT_FOUND');
284
- const writers=activeLegacyWriters();
285
- if(writers.length)throw Object.assign(fail('KNOWN_LEGACY_WRITER_ACTIVE'),{writers});
286
- const db=open();
287
- try{
288
- const stage=db.migrationList(projectId).find(r=>r.sourceUnitId===sourceUnitId);
289
- if(stage?.status!=='CUTOVER_FENCED')throw fail('MIGRATION_STAGE_MISMATCH');
290
- if(stage?.sourceHash!==unit.sourceHash)throw fail('SOURCE_CHANGED');
291
- // No model payload grants authorization; operator confirms exact physical
292
- // unit after inspecting old clients/caches and the private backup.
293
- await confirm('ACTIVATE '+projectId+' '+sourceUnitId);
294
- if(activeLegacyWriters().length)throw fail('KNOWN_LEGACY_WRITER_ACTIVE');
295
- return db.migrationActivate(write({projectId,sourceUnitId,
296
- expectedMigrationRevision:stage.migrationRevision,sourceHash:unit.sourceHash},
297
- {epoch:db.epoch}));
298
- }finally{db.close()}
299
- }
300
- throw fail('CONTEXT_ADMIN_OPERATION_UNKNOWN');
301
- }
@@ -1,272 +0,0 @@
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
- }