@tomflow/chatloop-tools 0.4.32 → 0.4.33
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/node_modules/@tomflow/chatloop-context/README.md +271 -0
- package/node_modules/@tomflow/chatloop-context/bin/cli.mjs +273 -0
- package/node_modules/@tomflow/chatloop-context/lib/context-cli.mjs +301 -0
- package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +272 -0
- package/node_modules/@tomflow/chatloop-context/lib/context-protocol.mjs +1615 -0
- package/node_modules/@tomflow/chatloop-context/lib/methods.mjs +264 -0
- package/node_modules/@tomflow/chatloop-context/lib/operations.mjs +219 -0
- package/node_modules/@tomflow/chatloop-context/lib/project-diagnostic.mjs +455 -0
- package/node_modules/@tomflow/chatloop-context/lib/workspace-operator.mjs +159 -0
- package/node_modules/@tomflow/chatloop-context/package.json +21 -0
- package/node_modules/@tomflow/chatloop-trace/README.md +13 -0
- package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +259 -0
- package/node_modules/@tomflow/chatloop-trace/package.json +11 -0
- package/package.json +6 -2
|
@@ -0,0 +1,455 @@
|
|
|
1
|
+
// Offline Context extraction: diagnostic-only by default. A separate local
|
|
2
|
+
// operator seal + publish flow can create one new managed Project authority;
|
|
3
|
+
// neither path grants Browser Owner or carries forward R/P approvals.
|
|
4
|
+
import {randomUUID,createHash} from 'node:crypto';
|
|
5
|
+
import {DatabaseSync} from 'node:sqlite';
|
|
6
|
+
import {existsSync,lstatSync,mkdtempSync,renameSync,rmSync,writeFileSync,
|
|
7
|
+
readFileSync} from 'node:fs';
|
|
8
|
+
import {isAbsolute,join,basename,dirname} from 'node:path';
|
|
9
|
+
import {activeLegacyWriters} from './context-cli.mjs';
|
|
10
|
+
import {openContextProtocol} from './context-protocol.mjs';
|
|
11
|
+
import {backupContextDb,verifySourceUnit,scanSourceUnit} from './context-migration.mjs';
|
|
12
|
+
|
|
13
|
+
const ID=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
|
|
14
|
+
const fail=code=>Object.assign(new Error(code),{code});
|
|
15
|
+
const ensure=(ok,code)=>{if(!ok)throw fail(code)};
|
|
16
|
+
const knownTables=new Set(['meta','projects','tasks','documents','issues',
|
|
17
|
+
'artifacts','checkpoints','receipts','migrations','start_leases','permits',
|
|
18
|
+
'project_materials']);
|
|
19
|
+
const scopedTables=['checkpoints','documents','issues','artifacts','receipts',
|
|
20
|
+
'migrations','project_materials','permits','start_leases','tasks','projects'];
|
|
21
|
+
const allTables=['meta',...scopedTables];
|
|
22
|
+
const shaFile=file=>createHash('sha256').update(readFileSync(file)).digest('hex');
|
|
23
|
+
function logicalDigest(db){
|
|
24
|
+
const digest=createHash('sha256');
|
|
25
|
+
for(const table of allTables){
|
|
26
|
+
digest.update(table+'\n');
|
|
27
|
+
for(const row of db.prepare('SELECT * FROM '+table+' ORDER BY rowid').iterate())
|
|
28
|
+
digest.update(JSON.stringify(row)+'\n');
|
|
29
|
+
}
|
|
30
|
+
return digest.digest('hex');
|
|
31
|
+
}
|
|
32
|
+
const count=db=>Object.fromEntries(scopedTables.map(table=>
|
|
33
|
+
[table,db.prepare('SELECT COUNT(*) AS n FROM '+table).get().n]));
|
|
34
|
+
const scopeCount=(db,projectId)=>Object.fromEntries(scopedTables.map(table=>
|
|
35
|
+
[table,db.prepare('SELECT COUNT(*) AS n FROM '+table+' WHERE project_id=?')
|
|
36
|
+
.get(projectId).n]));
|
|
37
|
+
function privateFile(file){
|
|
38
|
+
ensure(typeof file==='string'&&isAbsolute(file),'SOURCE_PATH_INVALID');
|
|
39
|
+
const st=lstatSync(file);
|
|
40
|
+
ensure(st.isFile()&&!st.isSymbolicLink()&&!(st.mode&0o077)
|
|
41
|
+
&&(!process.getuid||st.uid===process.getuid()),'MIGRATION_SOURCE_UNTRUSTED');
|
|
42
|
+
}
|
|
43
|
+
function privateRoot(root){
|
|
44
|
+
ensure(typeof root==='string'&&isAbsolute(root),'MIGRATION_ROOT_INVALID');
|
|
45
|
+
const st=lstatSync(root);
|
|
46
|
+
ensure(st.isDirectory()&&!st.isSymbolicLink()&&!(st.mode&0o077)
|
|
47
|
+
&&(!process.getuid||st.uid===process.getuid()),'MIGRATION_ROOT_UNTRUSTED');
|
|
48
|
+
}
|
|
49
|
+
function validateSchema(db){
|
|
50
|
+
const names=db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")
|
|
51
|
+
.all().map(x=>x.name);
|
|
52
|
+
ensure(names.length===knownTables.size&&names.every(x=>knownTables.has(x)),
|
|
53
|
+
'MIGRATION_SCHEMA_UNREVIEWED');
|
|
54
|
+
const keys=db.prepare('SELECT key FROM meta').all().map(x=>x.key);
|
|
55
|
+
ensure(keys.every(x=>['schemaVersion','storeEpoch','storeMode','restoredFromEpoch'].includes(x)),
|
|
56
|
+
'MIGRATION_META_UNREVIEWED');
|
|
57
|
+
}
|
|
58
|
+
function physicalCheck(db,projectId,expected){
|
|
59
|
+
const list=db.prepare('SELECT project_id FROM projects').all();
|
|
60
|
+
ensure(list.length===1&&list[0].project_id===projectId,
|
|
61
|
+
'MIGRATION_PROJECT_ISOLATION_FAILED');
|
|
62
|
+
const counts=count(db);
|
|
63
|
+
for(const [table,n] of Object.entries(expected))
|
|
64
|
+
ensure(counts[table]===n,'MIGRATION_ROW_COUNT_MISMATCH');
|
|
65
|
+
const integrity=db.prepare('PRAGMA integrity_check').all();
|
|
66
|
+
ensure(integrity.length===1&&integrity[0].integrity_check==='ok',
|
|
67
|
+
'MIGRATION_INTEGRITY_FAILED');
|
|
68
|
+
ensure(db.prepare('PRAGMA foreign_key_check').all().length===0,
|
|
69
|
+
'MIGRATION_FOREIGN_KEY_FAILED');
|
|
70
|
+
return counts;
|
|
71
|
+
}
|
|
72
|
+
async function extractProjectBranch({
|
|
73
|
+
sourceDb,targetRoot,projectId,expectedStoreEpoch,expectedProjectRevision,
|
|
74
|
+
managed=false,sealManifest=null,expectedSealHash=null,
|
|
75
|
+
knownWriters=activeLegacyWriters
|
|
76
|
+
}){
|
|
77
|
+
ensure(ID.test(projectId||''),'INVALID_SCOPE');
|
|
78
|
+
ensure(typeof expectedStoreEpoch==='string'&&expectedStoreEpoch.length>=10,
|
|
79
|
+
'STALE_EPOCH');
|
|
80
|
+
ensure(Number.isSafeInteger(expectedProjectRevision)&&expectedProjectRevision>=1,
|
|
81
|
+
'PROJECT_VERSION_CONFLICT');
|
|
82
|
+
privateFile(sourceDb);privateRoot(targetRoot);
|
|
83
|
+
const target=join(targetRoot,projectId);
|
|
84
|
+
ensure(!existsSync(target),'MIGRATION_TARGET_EXISTS');
|
|
85
|
+
// Preflight may not initialize/repair/change the old Store in any way.
|
|
86
|
+
const source=openContextProtocol(sourceDb,{readOnly:true,principalId:'local-operator',
|
|
87
|
+
authorizeData:()=>true,authorizeAdmin:()=>true});
|
|
88
|
+
let initial;
|
|
89
|
+
let expectedFencedDigest;
|
|
90
|
+
try{
|
|
91
|
+
const project=source.projectGet(projectId);
|
|
92
|
+
ensure(source.mode===(managed?'CUTOVER_FENCED':'ACTIVE'),
|
|
93
|
+
'MIGRATION_SOURCE_MODE_MISMATCH');
|
|
94
|
+
if(managed){
|
|
95
|
+
ensure(source.projectList().length===1,
|
|
96
|
+
'MIGRATION_SHARED_SOURCE_NOT_EXCLUSIVE');
|
|
97
|
+
const units=source.migrationList(projectId);
|
|
98
|
+
ensure(units.length>0&&units.every(u=>u.status==='MANAGED_RW'),
|
|
99
|
+
'MIGRATION_UNACTIVATED');
|
|
100
|
+
for(const unit of units)verifySourceUnit(unit.manifest);
|
|
101
|
+
}
|
|
102
|
+
ensure(source.epoch===expectedStoreEpoch,'STALE_EPOCH');
|
|
103
|
+
ensure(project.projectRevision===expectedProjectRevision,'PROJECT_VERSION_CONFLICT');
|
|
104
|
+
initial={epoch:source.epoch,projectRevision:project.projectRevision};
|
|
105
|
+
if(managed){
|
|
106
|
+
privateFile(sealManifest);
|
|
107
|
+
ensure(shaFile(sealManifest)===expectedSealHash,'CUTOVER_SEAL_HASH_MISMATCH');
|
|
108
|
+
const record=JSON.parse(readFileSync(sealManifest,'utf8'));
|
|
109
|
+
ensure(record.contract==='chat-loop.context-source-seal.v1'&&
|
|
110
|
+
record.status==='CUTOVER_FENCED'&&record.sourceDb===sourceDb&&
|
|
111
|
+
record.projectId===projectId&&record.sourceStoreEpoch===source.epoch&&
|
|
112
|
+
record.sourceProjectRevision===project.projectRevision,
|
|
113
|
+
'CUTOVER_SEAL_INVALID');
|
|
114
|
+
privateFile(record.backupPath);
|
|
115
|
+
ensure(shaFile(record.backupPath)===record.backupHash,
|
|
116
|
+
'CUTOVER_BACKUP_CHANGED');
|
|
117
|
+
const verify=new DatabaseSync(sourceDb,{readOnly:true});
|
|
118
|
+
try{ensure(logicalDigest(verify)===record.fencedLogicalHash,
|
|
119
|
+
'CUTOVER_SOURCE_CHANGED')}
|
|
120
|
+
finally{verify.close()}
|
|
121
|
+
expectedFencedDigest=record.fencedLogicalHash;
|
|
122
|
+
ensure(knownWriters().length===0,'KNOWN_LEGACY_WRITER_ACTIVE');
|
|
123
|
+
}
|
|
124
|
+
}finally{source.close()}
|
|
125
|
+
const stage=mkdtempSync(join(targetRoot,managed?'.managed-':'.diagnostic-'));
|
|
126
|
+
const file=join(stage,'context.sqlite');
|
|
127
|
+
let published=false;
|
|
128
|
+
try{
|
|
129
|
+
const sourceReader=new DatabaseSync(sourceDb,{readOnly:true,timeout:3500});
|
|
130
|
+
let snapshot;
|
|
131
|
+
try{snapshot=await backupContextDb(sourceReader,file)}
|
|
132
|
+
finally{sourceReader.close()}
|
|
133
|
+
const db=new DatabaseSync(file,{timeout:3500});
|
|
134
|
+
let receipt;
|
|
135
|
+
try{
|
|
136
|
+
validateSchema(db);
|
|
137
|
+
// Detect a source mutation that occurs after the preflight snapshot.
|
|
138
|
+
if(managed)ensure(logicalDigest(db)===expectedFencedDigest,
|
|
139
|
+
'CUTOVER_SOURCE_CHANGED');
|
|
140
|
+
const meta=k=>db.prepare('SELECT value FROM meta WHERE key=?').get(k)?.value;
|
|
141
|
+
ensure(meta('storeMode')===(managed?'CUTOVER_FENCED':'ACTIVE'),
|
|
142
|
+
'MIGRATION_SOURCE_MODE_MISMATCH');
|
|
143
|
+
ensure(meta('storeEpoch')===initial.epoch,'STALE_EPOCH');
|
|
144
|
+
const project=db.prepare('SELECT project_revision FROM projects WHERE project_id=?')
|
|
145
|
+
.get(projectId);
|
|
146
|
+
ensure(project?.project_revision===initial.projectRevision,
|
|
147
|
+
'PROJECT_VERSION_CONFLICT');
|
|
148
|
+
const before=scopeCount(db,projectId);
|
|
149
|
+
if(managed){
|
|
150
|
+
ensure(db.prepare('SELECT COUNT(*) AS n FROM projects').get().n===1,
|
|
151
|
+
'MIGRATION_SHARED_SOURCE_NOT_EXCLUSIVE');
|
|
152
|
+
ensure(db.prepare("SELECT COUNT(*) AS n FROM migrations WHERE project_id=? AND status<>'MANAGED_RW'")
|
|
153
|
+
.get(projectId).n===0&&before.migrations>0,'MIGRATION_UNACTIVATED');
|
|
154
|
+
}
|
|
155
|
+
db.exec('PRAGMA journal_mode=DELETE; PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON; PRAGMA secure_delete=ON;');
|
|
156
|
+
const newEpoch=randomUUID();
|
|
157
|
+
db.exec('BEGIN IMMEDIATE');
|
|
158
|
+
try{
|
|
159
|
+
for(const table of scopedTables)
|
|
160
|
+
db.prepare('DELETE FROM '+table+' WHERE project_id<>?').run(projectId);
|
|
161
|
+
db.exec('DELETE FROM permits; DELETE FROM start_leases;');
|
|
162
|
+
db.exec(`UPDATE tasks SET writable_ref=NULL,credential_digest=NULL,
|
|
163
|
+
writer_approval_revision=NULL,pending_attempt=NULL,
|
|
164
|
+
pending_checkpoint=NULL,pending_target_generation=NULL,
|
|
165
|
+
pending_credential_digest=NULL,pending_next_ref=NULL,
|
|
166
|
+
binding_revision=binding_revision+1;`);
|
|
167
|
+
db.prepare("UPDATE meta SET value=? WHERE key='storeMode'")
|
|
168
|
+
.run(managed?'ACTIVE':'DIAGNOSTIC_ONLY');
|
|
169
|
+
if(managed)db.exec("UPDATE tasks SET approval_json='[]',approval_revision=approval_revision+1; UPDATE issues SET state='PENDING';");
|
|
170
|
+
db.prepare("UPDATE meta SET value=? WHERE key='storeEpoch'").run(newEpoch);
|
|
171
|
+
db.prepare("INSERT OR REPLACE INTO meta(key,value) VALUES('restoredFromEpoch',?)")
|
|
172
|
+
.run(initial.epoch);
|
|
173
|
+
db.exec('COMMIT');
|
|
174
|
+
}catch(error){try{db.exec('ROLLBACK')}catch{}throw error}
|
|
175
|
+
// Rebuild all b-trees and free pages so other projects' deleted rows
|
|
176
|
+
// cannot remain readable in SQLite freelist or discarded WAL records.
|
|
177
|
+
db.exec('VACUUM;');
|
|
178
|
+
const after=physicalCheck(db,projectId,{
|
|
179
|
+
...before,permits:0,start_leases:0
|
|
180
|
+
});
|
|
181
|
+
receipt={contract:managed?'chat-loop.context-managed-project.v1':
|
|
182
|
+
'chat-loop.context-diagnostic-project.v1',
|
|
183
|
+
status:managed?'MANAGED_RW':'DIAGNOSTIC_ONLY',projectId,sourceStoreEpoch:initial.epoch,
|
|
184
|
+
sourceProjectRevision:initial.projectRevision,newStoreEpoch:newEpoch,
|
|
185
|
+
sourceSnapshotHash:snapshot.hash,counts:after,
|
|
186
|
+
sourceUnitsRequireReview:!managed,approvalsRevalidated:false,
|
|
187
|
+
ownerRestored:false,writeCapabilitiesRestored:managed,
|
|
188
|
+
canExecute:false};
|
|
189
|
+
}finally{db.close()}
|
|
190
|
+
// Check reopened data in the exact form the normal SDK uses.
|
|
191
|
+
const verify=openContextProtocol(file,{readOnly:true,principalId:'local-operator',
|
|
192
|
+
authorizeData:()=>true});
|
|
193
|
+
try{
|
|
194
|
+
ensure(verify.mode===(managed?'ACTIVE':'DIAGNOSTIC_ONLY')&&
|
|
195
|
+
verify.epoch===receipt.newStoreEpoch,'MIGRATION_MODE_UNVERIFIED');
|
|
196
|
+
ensure(verify.projectList().length===1 &&
|
|
197
|
+
verify.projectGet(projectId).projectRevision===initial.projectRevision,
|
|
198
|
+
'MIGRATION_PROJECT_ISOLATION_FAILED');
|
|
199
|
+
const authority=verify.projectBusinessAuthority(projectId);
|
|
200
|
+
ensure(managed?authority.status==='MANAGED_RW'&&authority.writable===true:
|
|
201
|
+
authority.writable===false,'MIGRATION_WRITE_AUTHORITY_UNSAFE');
|
|
202
|
+
if(managed){
|
|
203
|
+
const check=new DatabaseSync(file,{readOnly:true});
|
|
204
|
+
try{
|
|
205
|
+
ensure(check.prepare("SELECT COUNT(*) AS n FROM tasks WHERE approval_json<>'[]' OR writable_ref IS NOT NULL OR credential_digest IS NOT NULL OR pending_attempt IS NOT NULL OR pending_credential_digest IS NOT NULL")
|
|
206
|
+
.get().n===0,'MIGRATION_APPROVAL_OR_OWNER_RESTORED');
|
|
207
|
+
}finally{check.close()}
|
|
208
|
+
}
|
|
209
|
+
}finally{verify.close()}
|
|
210
|
+
const manifest=join(stage,managed?'migration-managed.json':'migration-diagnostic.json');
|
|
211
|
+
writeFileSync(manifest,JSON.stringify(receipt,null,2)+'\n',{flag:'wx',mode:0o600});
|
|
212
|
+
ensure(readFileSync(manifest,'utf8').includes(receipt.sourceSnapshotHash),
|
|
213
|
+
'MIGRATION_RECEIPT_UNVERIFIED');
|
|
214
|
+
ensure(!existsSync(target),'MIGRATION_TARGET_EXISTS');
|
|
215
|
+
renameSync(stage,target);
|
|
216
|
+
published=true;
|
|
217
|
+
return {...receipt,projectDirectory:target};
|
|
218
|
+
}finally{if(!published)rmSync(stage,{recursive:true,force:true})}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// The diagnostic export is intentionally not publishable. A managed export is
|
|
222
|
+
// a separate, terminal-reviewed action over an already fenced whole Store.
|
|
223
|
+
export const createProjectDiagnosticBranch=args=>extractProjectBranch(args);
|
|
224
|
+
export const createManagedProjectBranch=args=>extractProjectBranch({
|
|
225
|
+
...args,managed:true
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
// Freeze a SINGLE-Project legacy Store BEFORE publishing a separate authority.
|
|
229
|
+
// Crash after the freeze is safe: the original stays read-only until reviewed
|
|
230
|
+
// recovery, and no target is published merely because this function ran.
|
|
231
|
+
export async function fenceLegacyProjectStore({
|
|
232
|
+
sourceDb,projectId,expectedStoreEpoch,expectedProjectRevision,
|
|
233
|
+
backupPath,sealManifestPath,knownWriters=activeLegacyWriters
|
|
234
|
+
}){
|
|
235
|
+
ensure(ID.test(projectId||''),'INVALID_SCOPE');
|
|
236
|
+
ensure(typeof expectedStoreEpoch==='string'&&expectedStoreEpoch.length>=10,
|
|
237
|
+
'STALE_EPOCH');
|
|
238
|
+
ensure(Number.isSafeInteger(expectedProjectRevision)&&expectedProjectRevision>=1,
|
|
239
|
+
'PROJECT_VERSION_CONFLICT');
|
|
240
|
+
privateFile(sourceDb);
|
|
241
|
+
privateRoot(dirname(backupPath));
|
|
242
|
+
privateRoot(dirname(sealManifestPath));
|
|
243
|
+
ensure(!existsSync(backupPath)&&!existsSync(sealManifestPath),
|
|
244
|
+
'CUTOVER_EVIDENCE_EXISTS');
|
|
245
|
+
const reader=openContextProtocol(sourceDb,{readOnly:true,principalId:'local-operator',
|
|
246
|
+
authorizeData:()=>true,authorizeAdmin:()=>true});
|
|
247
|
+
let sources;
|
|
248
|
+
try{
|
|
249
|
+
ensure(reader.mode==='ACTIVE','MIGRATION_SOURCE_NOT_ACTIVE');
|
|
250
|
+
ensure(reader.epoch===expectedStoreEpoch,'STALE_EPOCH');
|
|
251
|
+
const project=reader.projectGet(projectId);
|
|
252
|
+
ensure(project.projectRevision===expectedProjectRevision&&!project.archived,
|
|
253
|
+
'PROJECT_VERSION_CONFLICT');
|
|
254
|
+
ensure(reader.projectList().length===1,'MIGRATION_SHARED_SOURCE_NOT_EXCLUSIVE');
|
|
255
|
+
sources=reader.migrationList(projectId);
|
|
256
|
+
ensure(sources.length>0&&sources.every(s=>s.status==='MANAGED_RW'),
|
|
257
|
+
'MIGRATION_UNACTIVATED');
|
|
258
|
+
for(const source of sources)verifySourceUnit(source.manifest);
|
|
259
|
+
ensure(reader.projectBusinessAuthority(projectId).status==='MANAGED_RW',
|
|
260
|
+
'MIGRATION_NOT_MANAGED');
|
|
261
|
+
}finally{reader.close()}
|
|
262
|
+
// An active MCP writer must be stopped by the independent operator first.
|
|
263
|
+
ensure(knownWriters().length===0,'KNOWN_LEGACY_WRITER_ACTIVE');
|
|
264
|
+
const db=new DatabaseSync(sourceDb,{timeout:3500});
|
|
265
|
+
try{
|
|
266
|
+
const originalDigest=logicalDigest(db);
|
|
267
|
+
// Back up without holding a write transaction (sqlite backup cannot
|
|
268
|
+
// safely snapshot its own live writer). Recheck inside the lock below.
|
|
269
|
+
const snapshot=await backupContextDb(db,backupPath);
|
|
270
|
+
// An online backup is not cutover evidence until the recovered logical
|
|
271
|
+
// rows match the source that was reviewed before taking the write lock.
|
|
272
|
+
const backedUp=new DatabaseSync(backupPath,{readOnly:true});
|
|
273
|
+
try{
|
|
274
|
+
validateSchema(backedUp);
|
|
275
|
+
ensure(logicalDigest(backedUp)===originalDigest,
|
|
276
|
+
'CUTOVER_BACKUP_CONTENT_MISMATCH');
|
|
277
|
+
ensure(backedUp.prepare('PRAGMA integrity_check').get()?.integrity_check==='ok'
|
|
278
|
+
&&backedUp.prepare('PRAGMA foreign_key_check').all().length===0,
|
|
279
|
+
'CUTOVER_BACKUP_INTEGRITY_FAILED');
|
|
280
|
+
}finally{backedUp.close()}
|
|
281
|
+
db.exec('BEGIN IMMEDIATE');
|
|
282
|
+
try{
|
|
283
|
+
const get=k=>db.prepare('SELECT value FROM meta WHERE key=?').get(k)?.value;
|
|
284
|
+
ensure(logicalDigest(db)===originalDigest,'CUTOVER_SOURCE_CHANGED');
|
|
285
|
+
for(const unit of sources)verifySourceUnit(unit.manifest);
|
|
286
|
+
ensure(get('storeMode')==='ACTIVE','MIGRATION_SOURCE_NOT_ACTIVE');
|
|
287
|
+
ensure(get('storeEpoch')===expectedStoreEpoch,'STALE_EPOCH');
|
|
288
|
+
const projects=db.prepare('SELECT project_id,project_revision,archived FROM projects').all();
|
|
289
|
+
ensure(projects.length===1&&projects[0].project_id===projectId,
|
|
290
|
+
'MIGRATION_SHARED_SOURCE_NOT_EXCLUSIVE');
|
|
291
|
+
ensure(projects[0].project_revision===expectedProjectRevision&&
|
|
292
|
+
projects[0].archived===0,'PROJECT_VERSION_CONFLICT');
|
|
293
|
+
ensure(db.prepare('SELECT COUNT(*) AS n FROM migrations WHERE project_id=?').get(projectId).n
|
|
294
|
+
===sources.length,'MIGRATION_SOURCE_CHANGED');
|
|
295
|
+
ensure(db.prepare("SELECT COUNT(*) AS n FROM migrations WHERE project_id=? AND status<>'MANAGED_RW'")
|
|
296
|
+
.get(projectId).n===0,'MIGRATION_UNACTIVATED');
|
|
297
|
+
ensure(db.prepare('SELECT COUNT(*) AS n FROM tasks WHERE project_id=? AND (writable_ref IS NOT NULL OR credential_digest IS NOT NULL OR writer_approval_revision IS NOT NULL OR pending_attempt IS NOT NULL OR pending_checkpoint IS NOT NULL OR pending_target_generation IS NOT NULL OR pending_credential_digest IS NOT NULL OR pending_next_ref IS NOT NULL)')
|
|
298
|
+
.get(projectId).n===0,'CUTOVER_ACTIVE_RUN');
|
|
299
|
+
ensure(db.prepare('SELECT COUNT(*) AS n FROM start_leases').get().n===0
|
|
300
|
+
&&db.prepare('SELECT COUNT(*) AS n FROM permits').get().n===0,
|
|
301
|
+
'CUTOVER_ACTIVE_PERMIT');
|
|
302
|
+
ensure(knownWriters().length===0,'KNOWN_LEGACY_WRITER_ACTIVE');
|
|
303
|
+
// Source did not change between the backed-up snapshot and fence lock.
|
|
304
|
+
db.prepare("UPDATE meta SET value='CUTOVER_FENCED' WHERE key='storeMode'").run();
|
|
305
|
+
db.exec('COMMIT');
|
|
306
|
+
const record={contract:'chat-loop.context-source-seal.v1',
|
|
307
|
+
status:'CUTOVER_FENCED',projectId,sourceDb,sourceStoreEpoch:expectedStoreEpoch,
|
|
308
|
+
sourceProjectRevision:expectedProjectRevision,sourceUnits:sources.length,
|
|
309
|
+
backupPath,backupHash:snapshot.hash,fencedLogicalHash:logicalDigest(db),
|
|
310
|
+
approvalsRevalidated:false,ownerRestored:false,canExecute:false};
|
|
311
|
+
writeFileSync(sealManifestPath,JSON.stringify(record,null,2)+'\n',
|
|
312
|
+
{flag:'wx',mode:0o600});
|
|
313
|
+
return {...record,sealManifestPath,sealManifestHash:shaFile(sealManifestPath)};
|
|
314
|
+
}catch(error){
|
|
315
|
+
try{db.exec('ROLLBACK')}catch{}
|
|
316
|
+
throw error;
|
|
317
|
+
}
|
|
318
|
+
}finally{db.close()}
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
// Read-only migration audit. Never classifies mixed history or certifies writers.
|
|
322
|
+
// A verified byte hash proves source identity, not business ownership or approval.
|
|
323
|
+
export function auditLegacyProjectSources({sourceDb,projectId,expectedStoreEpoch}){
|
|
324
|
+
ensure(ID.test(projectId||''),'INVALID_SCOPE');
|
|
325
|
+
ensure(typeof expectedStoreEpoch==='string'&&expectedStoreEpoch.length>=10,
|
|
326
|
+
'STALE_EPOCH');
|
|
327
|
+
privateFile(sourceDb);
|
|
328
|
+
const source=openContextProtocol(sourceDb,{readOnly:true,principalId:'local-audit',
|
|
329
|
+
authorizeData:(_mode,p)=>p===projectId,
|
|
330
|
+
authorizeAdmin:(op,p)=>op==='migration.list'&&p===projectId});
|
|
331
|
+
try{
|
|
332
|
+
ensure(source.epoch===expectedStoreEpoch,'STALE_EPOCH');
|
|
333
|
+
const project=source.projectGet(projectId);
|
|
334
|
+
const materials=source.projectMaterialList(projectId);
|
|
335
|
+
const units=source.migrationList(projectId);
|
|
336
|
+
const checks=units.map(unit=>{
|
|
337
|
+
let verifyCode='MATCHED';
|
|
338
|
+
try{verifySourceUnit(unit.manifest)}
|
|
339
|
+
catch(error){verifyCode=/^[A-Z0-9_]+$/.test(error?.code??'')?
|
|
340
|
+
error.code:'SOURCE_VERIFY_FAILED'}
|
|
341
|
+
const sourceKind=unit.manifest.sourceKind;
|
|
342
|
+
const evidenceStored=materials.some(m=>m.sourcePath===unit.sourcePath
|
|
343
|
+
&&m.contentHash===unit.sourceHash
|
|
344
|
+
&&m.provenance==='LEGACY_UNVERIFIED');
|
|
345
|
+
return {sourceUnitId:unit.sourceUnitId,sourceKind,
|
|
346
|
+
filename:basename(unit.sourcePath),sourceHash:unit.sourceHash,
|
|
347
|
+
migrationStatus:unit.status,migrationRevision:unit.migrationRevision,
|
|
348
|
+
sourceVerification:verifyCode,evidenceStored,
|
|
349
|
+
mixedHistoryReviewed:sourceKind==='MIXED_CONTEXT'?
|
|
350
|
+
unit.manifest.classification?.currentFactsComplete===true:null};
|
|
351
|
+
});
|
|
352
|
+
// Registry task documents are separate from the Registry JSON itself.
|
|
353
|
+
// A changed task document does NOT invalidate an unchanged Registry SHA.
|
|
354
|
+
const drift=checks.filter(c=>c.sourceVerification==='LEGACY_REFERENCE_CHANGED');
|
|
355
|
+
const failed=checks.filter(c=>!['MATCHED','LEGACY_REFERENCE_CHANGED']
|
|
356
|
+
.includes(c.sourceVerification));
|
|
357
|
+
const missingBodies=checks.filter(c=>
|
|
358
|
+
['DOCUMENT','MIXED_CONTEXT'].includes(c.sourceKind)&&!c.evidenceStored);
|
|
359
|
+
const mixedPending=checks.filter(c=>c.sourceKind==='MIXED_CONTEXT'
|
|
360
|
+
&&c.mixedHistoryReviewed!==true);
|
|
361
|
+
const pending=checks.filter(c=>c.migrationStatus!=='MANAGED_RW');
|
|
362
|
+
return {projectId,storeEpoch:source.epoch,projectRevision:project.projectRevision,
|
|
363
|
+
sourceCount:checks.length,checks,
|
|
364
|
+
sourceHashesVerified:checks.length>0&&failed.length===0,
|
|
365
|
+
sourceReferencesVerified:checks.length>0&&failed.length===0&&drift.length===0,
|
|
366
|
+
referenceDriftCount:drift.length,
|
|
367
|
+
sourceBodiesPreserved:checks.length>0&&missingBodies.length===0,
|
|
368
|
+
mixedReviewRequired:mixedPending.length,
|
|
369
|
+
pendingSourceCount:pending.length,
|
|
370
|
+
blockers:[
|
|
371
|
+
...(checks.length===0?['NO_SOURCE_UNITS']:[]),
|
|
372
|
+
...(failed.length?['SOURCE_VERIFICATION_FAILED']:[]),
|
|
373
|
+
...(drift.length?['LEGACY_REFERENCE_DRIFT']:[]),
|
|
374
|
+
...(missingBodies.length?['SOURCE_MATERIALS_INCOMPLETE']:[]),
|
|
375
|
+
...(mixedPending.length?['MIXED_OWNERSHIP_REVIEW_REQUIRED']:[]),
|
|
376
|
+
...(pending.length?['SOURCE_UNACTIVATED']:[]),
|
|
377
|
+
'OLD_WRITERS_NOT_INDEPENDENTLY_FENCED',
|
|
378
|
+
'RELEASE_AND_NATIVE_E2E_UNVERIFIED'
|
|
379
|
+
],
|
|
380
|
+
status:'BLOCKED',writerAuthority:'NOT_VERIFIED',
|
|
381
|
+
canActivate:false,canExecute:false};
|
|
382
|
+
}finally{source.close()}
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/**
|
|
386
|
+
* Produce a bounded, non-authoritative Registry task-reference drift review.
|
|
387
|
+
* A matching Recovery Archive proves the original version still exists; it
|
|
388
|
+
* never approves its newer version or rewrites a SourceUnit/Task/Receipt.
|
|
389
|
+
*/
|
|
390
|
+
export function inspectLegacyRegistryReference({
|
|
391
|
+
sourceDb,projectId,expectedStoreEpoch,sourceUnitId,taskId,archiveFile
|
|
392
|
+
}){
|
|
393
|
+
ensure(ID.test(projectId||'')&&ID.test(taskId||'')&&
|
|
394
|
+
/^[a-f0-9]{64}$/.test(sourceUnitId||''),'INVALID_SCOPE');
|
|
395
|
+
ensure(typeof expectedStoreEpoch==='string'&&expectedStoreEpoch.length>=10,
|
|
396
|
+
'STALE_EPOCH');
|
|
397
|
+
privateFile(sourceDb);privateFile(archiveFile);
|
|
398
|
+
const source=openContextProtocol(sourceDb,{
|
|
399
|
+
readOnly:true,principalId:'local-reference-review',
|
|
400
|
+
authorizeData:(_mode,p)=>p===projectId,
|
|
401
|
+
authorizeAdmin:(op,p)=>op==='migration.list'&&p===projectId
|
|
402
|
+
});
|
|
403
|
+
try{
|
|
404
|
+
ensure(source.epoch===expectedStoreEpoch,'STALE_EPOCH');
|
|
405
|
+
source.projectGet(projectId);
|
|
406
|
+
const unit=source.migrationList(projectId)
|
|
407
|
+
.find(x=>x.sourceUnitId===sourceUnitId);
|
|
408
|
+
ensure(unit?.status==='SHADOW_RO'&&
|
|
409
|
+
unit.manifest.sourceKind==='REGISTRY_JSON','REGISTRY_SOURCE_NOT_SHADOW');
|
|
410
|
+
const old=unit.manifest.tasks?.find(t=>t.taskId===taskId);
|
|
411
|
+
ensure(old&&old.taskDocPath&&/^[a-f0-9]{64}$/.test(
|
|
412
|
+
old.taskDocumentHash??''),'REGISTRY_REFERENCE_NOT_FOUND');
|
|
413
|
+
const original=readFileSync(archiveFile);
|
|
414
|
+
ensure(original.length>0&&original.length<=512*1024,'ARCHIVE_UNTRUSTED');
|
|
415
|
+
const sha=b=>createHash('sha256').update(b).digest('hex');
|
|
416
|
+
ensure(sha(original)===old.taskDocumentHash,'ARCHIVE_HASH_MISMATCH');
|
|
417
|
+
const current=scanSourceUnit({sourcePath:unit.sourcePath,
|
|
418
|
+
projectId,kind:'REGISTRY_JSON'});
|
|
419
|
+
ensure(current.sourceUnitId===unit.sourceUnitId &&
|
|
420
|
+
current.sourceHash===unit.sourceHash,'SOURCE_CHANGED');
|
|
421
|
+
ensure(current.tasks.length===unit.manifest.tasks.length,
|
|
422
|
+
'REGISTRY_TASK_SET_CHANGED');
|
|
423
|
+
for(const before of unit.manifest.tasks){
|
|
424
|
+
const after=current.tasks.find(t=>t.taskId===before.taskId);
|
|
425
|
+
ensure(after&&Object.keys(before).every(k=>k==='taskDocumentHash'||
|
|
426
|
+
JSON.stringify(before[k])===JSON.stringify(after[k])),
|
|
427
|
+
'REGISTRY_TASK_IDENTITY_CHANGED');
|
|
428
|
+
}
|
|
429
|
+
const after=current.tasks.find(t=>t.taskId===taskId);
|
|
430
|
+
ensure(after&&after.taskDocPath===old.taskDocPath,
|
|
431
|
+
'REGISTRY_TASK_IDENTITY_CHANGED');
|
|
432
|
+
const latest=readFileSync(after.taskDocPath);
|
|
433
|
+
ensure(sha(latest)===after.taskDocumentHash,
|
|
434
|
+
'DOCUMENT_CHANGED_DURING_INSPECTION');
|
|
435
|
+
const oldLines=original.toString('utf8').split(/(?<=\n)/);
|
|
436
|
+
const newLines=latest.toString('utf8').split(/(?<=\n)/);
|
|
437
|
+
// Bounded linear comparison. This is a review hint, NEVER approval.
|
|
438
|
+
let i=0;
|
|
439
|
+
for(const line of newLines){
|
|
440
|
+
if(i<oldLines.length&&oldLines[i]===line)i++;
|
|
441
|
+
}
|
|
442
|
+
const appendOnly=i===oldLines.length&&newLines.length>=oldLines.length;
|
|
443
|
+
return {status:'REVIEW_REQUIRED',projectId,sourceUnitId,taskId,
|
|
444
|
+
sourceHash:unit.sourceHash,sourceVerified:true,
|
|
445
|
+
archivedTaskHash:old.taskDocumentHash,
|
|
446
|
+
currentTaskHash:after.taskDocumentHash,
|
|
447
|
+
archivedTaskBytes:original.length,currentTaskBytes:latest.length,
|
|
448
|
+
originalLines:oldLines.length,currentLines:newLines.length,
|
|
449
|
+
changeKind:old.taskDocumentHash===after.taskDocumentHash?'NONE':
|
|
450
|
+
appendOnly?'INSERTIONS_ONLY':'CONTENT_CHANGED',
|
|
451
|
+
insertedLines:appendOnly?newLines.length-oldLines.length:null,
|
|
452
|
+
archiveVerified:true,reviewed:false,sourceUnitUpdated:false,
|
|
453
|
+
approvalsImported:false,canActivate:false,canExecute:false};
|
|
454
|
+
}finally{source.close()}
|
|
455
|
+
}
|
|
@@ -0,0 +1,159 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@tomflow/chatloop-context",
|
|
3
|
+
"version": "0.1.3",
|
|
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
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
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.
|