@tomflow/chatloop-tools 0.9.20 → 0.9.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 (55) hide show
  1. package/node_modules/@tomflow/chatloop-context/README.md +240 -0
  2. package/node_modules/@tomflow/chatloop-context/bin/cli.mjs +48 -0
  3. package/node_modules/@tomflow/chatloop-context/capabilities/approval.mjs +151 -0
  4. package/node_modules/@tomflow/chatloop-context/capabilities/context.mjs +376 -0
  5. package/node_modules/@tomflow/chatloop-context/capabilities/document.mjs +266 -0
  6. package/node_modules/@tomflow/chatloop-context/capabilities/evidence.mjs +134 -0
  7. package/node_modules/@tomflow/chatloop-context/capabilities/presentation.mjs +82 -0
  8. package/node_modules/@tomflow/chatloop-context/capabilities/project.mjs +349 -0
  9. package/node_modules/@tomflow/chatloop-context/capabilities/sdk.mjs +72 -0
  10. package/node_modules/@tomflow/chatloop-context/capabilities/start.mjs +73 -0
  11. package/node_modules/@tomflow/chatloop-context/capabilities/task.mjs +507 -0
  12. package/node_modules/@tomflow/chatloop-context/capabilities.generated.mjs +11 -0
  13. package/node_modules/@tomflow/chatloop-context/docs/interfaces.md +182 -0
  14. package/node_modules/@tomflow/chatloop-context/docs/operator-and-migration.md +277 -0
  15. package/node_modules/@tomflow/chatloop-context/index.mjs +233 -0
  16. package/node_modules/@tomflow/chatloop-context/lib/api-log.mjs +86 -0
  17. package/node_modules/@tomflow/chatloop-context/lib/approval-policy.mjs +24 -0
  18. package/node_modules/@tomflow/chatloop-context/lib/capability-catalog.generated.json +1989 -0
  19. package/node_modules/@tomflow/chatloop-context/lib/capability-router.mjs +67 -0
  20. package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +280 -0
  21. package/node_modules/@tomflow/chatloop-context/lib/context-cli.mjs +298 -0
  22. package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +280 -0
  23. package/node_modules/@tomflow/chatloop-context/lib/core/context.mjs +115 -0
  24. package/node_modules/@tomflow/chatloop-context/lib/core/evidence.mjs +51 -0
  25. package/node_modules/@tomflow/chatloop-context/lib/core/health.mjs +55 -0
  26. package/node_modules/@tomflow/chatloop-context/lib/core/migration.mjs +262 -0
  27. package/node_modules/@tomflow/chatloop-context/lib/core/project.mjs +246 -0
  28. package/node_modules/@tomflow/chatloop-context/lib/core/review.mjs +147 -0
  29. package/node_modules/@tomflow/chatloop-context/lib/core/run.mjs +343 -0
  30. package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +391 -0
  31. package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +166 -0
  32. package/node_modules/@tomflow/chatloop-context/lib/line-review.mjs +13 -0
  33. package/node_modules/@tomflow/chatloop-context/lib/methods.mjs +111 -0
  34. package/node_modules/@tomflow/chatloop-context/lib/operations.mjs +107 -0
  35. package/node_modules/@tomflow/chatloop-context/lib/orphan-operator.mjs +117 -0
  36. package/node_modules/@tomflow/chatloop-context/lib/process-inventory.mjs +20 -0
  37. package/node_modules/@tomflow/chatloop-context/lib/project-branch.mjs +312 -0
  38. package/node_modules/@tomflow/chatloop-context/lib/project-diagnostic.mjs +153 -0
  39. package/node_modules/@tomflow/chatloop-context/lib/project-guards.mjs +19 -0
  40. package/node_modules/@tomflow/chatloop-context/lib/project-store.mjs +115 -0
  41. package/node_modules/@tomflow/chatloop-context/lib/trusted-run.mjs +86 -0
  42. package/node_modules/@tomflow/chatloop-context/lib/workspace-operator.mjs +169 -0
  43. package/node_modules/@tomflow/chatloop-context/package.json +40 -0
  44. package/node_modules/@tomflow/chatloop-context/scripts/build-capabilities.mjs +114 -0
  45. package/node_modules/@tomflow/chatloop-trace/README.md +105 -0
  46. package/node_modules/@tomflow/chatloop-trace/events/context.api.mjs +23 -0
  47. package/node_modules/@tomflow/chatloop-trace/events/typed.api.call.mjs +22 -0
  48. package/node_modules/@tomflow/chatloop-trace/events.generated.mjs +4 -0
  49. package/node_modules/@tomflow/chatloop-trace/index.mjs +59 -0
  50. package/node_modules/@tomflow/chatloop-trace/lib/api-aspect.mjs +273 -0
  51. package/node_modules/@tomflow/chatloop-trace/lib/trace-reader.mjs +265 -0
  52. package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +205 -0
  53. package/node_modules/@tomflow/chatloop-trace/package.json +30 -0
  54. package/node_modules/@tomflow/chatloop-trace/scripts/build-events.mjs +68 -0
  55. package/package.json +5 -1
@@ -0,0 +1,312 @@
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,mkdtempSync,renameSync,rmSync,writeFileSync,
7
+ readFileSync} from 'node:fs';
8
+ import {join,dirname} from 'node:path';
9
+ // This module declares ports; index.mjs is the only dependency assembler.
10
+ // No implementation module imports another implementation module.
11
+ let knownWriterInventory, openContextProtocol, backupContextDb, verifySourceUnit, scanSourceUnit, ID, ensure, privateFile, privateRoot;
12
+ let connected=false;
13
+ export function configureProjectBranch(capabilities){
14
+ if(connected)throw Error('CONTEXT_MODULE_ALREADY_COMPOSED');
15
+ for(const name of ['knownWriterInventory', 'openContextProtocol', 'backupContextDb', 'verifySourceUnit', 'scanSourceUnit', 'ID', 'ensure', 'privateFile', 'privateRoot']){
16
+ if(capabilities?.[name]===undefined)throw Error('CONTEXT_MODULE_PORT_MISSING:'+name);
17
+ }
18
+ ({knownWriterInventory, openContextProtocol, backupContextDb, verifySourceUnit, scanSourceUnit, ID, ensure, privateFile, privateRoot}=capabilities);
19
+ connected=true;
20
+ }
21
+
22
+ const knownTables=new Set(['meta','projects','tasks','documents','issues',
23
+ 'artifacts','checkpoints','receipts','migrations','start_leases','permits',
24
+ 'project_materials']);
25
+ const scopedTables=['checkpoints','documents','issues','artifacts','receipts',
26
+ 'migrations','project_materials','permits','start_leases','tasks','projects'];
27
+ const allTables=['meta',...scopedTables];
28
+ const shaFile=file=>createHash('sha256').update(readFileSync(file)).digest('hex');
29
+ function logicalDigest(db){
30
+ const digest=createHash('sha256');
31
+ for(const table of allTables){
32
+ digest.update(table+'\n');
33
+ for(const row of db.prepare('SELECT * FROM '+table+' ORDER BY rowid').iterate())
34
+ digest.update(JSON.stringify(row)+'\n');
35
+ }
36
+ return digest.digest('hex');
37
+ }
38
+ const count=db=>Object.fromEntries(scopedTables.map(table=>
39
+ [table,db.prepare('SELECT COUNT(*) AS n FROM '+table).get().n]));
40
+ const scopeCount=(db,projectId)=>Object.fromEntries(scopedTables.map(table=>
41
+ [table,db.prepare('SELECT COUNT(*) AS n FROM '+table+' WHERE project_id=?')
42
+ .get(projectId).n]));
43
+ function validateSchema(db){
44
+ const names=db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")
45
+ .all().map(x=>x.name);
46
+ ensure(names.length===knownTables.size&&names.every(x=>knownTables.has(x)),
47
+ 'MIGRATION_SCHEMA_UNREVIEWED');
48
+ const keys=db.prepare('SELECT key FROM meta').all().map(x=>x.key);
49
+ ensure(keys.every(x=>['schemaVersion','storeEpoch','storeMode','restoredFromEpoch'].includes(x)),
50
+ 'MIGRATION_META_UNREVIEWED');
51
+ }
52
+ function physicalCheck(db,projectId,expected){
53
+ const list=db.prepare('SELECT project_id FROM projects').all();
54
+ ensure(list.length===1&&list[0].project_id===projectId,
55
+ 'MIGRATION_PROJECT_ISOLATION_FAILED');
56
+ const counts=count(db);
57
+ for(const [table,n] of Object.entries(expected))
58
+ ensure(counts[table]===n,'MIGRATION_ROW_COUNT_MISMATCH');
59
+ const integrity=db.prepare('PRAGMA integrity_check').all();
60
+ ensure(integrity.length===1&&integrity[0].integrity_check==='ok',
61
+ 'MIGRATION_INTEGRITY_FAILED');
62
+ ensure(db.prepare('PRAGMA foreign_key_check').all().length===0,
63
+ 'MIGRATION_FOREIGN_KEY_FAILED');
64
+ return counts;
65
+ }
66
+ async function extractProjectBranch({
67
+ sourceDb,targetRoot,projectId,expectedStoreEpoch,expectedProjectRevision,
68
+ managed=false,sealManifest=null,expectedSealHash=null
69
+ }){
70
+ ensure(ID.test(projectId||''),'INVALID_SCOPE');
71
+ ensure(typeof expectedStoreEpoch==='string'&&expectedStoreEpoch.length>=10,
72
+ 'STALE_EPOCH');
73
+ ensure(Number.isSafeInteger(expectedProjectRevision)&&expectedProjectRevision>=1,
74
+ 'PROJECT_VERSION_CONFLICT');
75
+ privateFile(sourceDb);privateRoot(targetRoot);
76
+ const target=join(targetRoot,projectId);
77
+ ensure(!existsSync(target),'MIGRATION_TARGET_EXISTS');
78
+ // Preflight may not initialize/repair/change the old Store in any way.
79
+ const source=openContextProtocol(sourceDb,{readOnly:true,principalId:'local-operator',
80
+ authorizeData:()=>true,authorizeAdmin:()=>true});
81
+ let initial;
82
+ let expectedFencedDigest;
83
+ try{
84
+ const project=source.projectGet(projectId);
85
+ ensure(source.mode===(managed?'CUTOVER_FENCED':'ACTIVE'),
86
+ 'MIGRATION_SOURCE_MODE_MISMATCH');
87
+ if(managed){
88
+ ensure(source.projectList().length===1,
89
+ 'MIGRATION_SHARED_SOURCE_NOT_EXCLUSIVE');
90
+ const units=source.migrationList(projectId);
91
+ ensure(units.length>0&&units.every(u=>u.status==='MANAGED_RW'),
92
+ 'MIGRATION_UNACTIVATED');
93
+ for(const unit of units)verifySourceUnit(unit.manifest);
94
+ }
95
+ ensure(source.epoch===expectedStoreEpoch,'STALE_EPOCH');
96
+ ensure(project.projectRevision===expectedProjectRevision,'PROJECT_VERSION_CONFLICT');
97
+ initial={epoch:source.epoch,projectRevision:project.projectRevision};
98
+ if(managed){
99
+ privateFile(sealManifest);
100
+ ensure(shaFile(sealManifest)===expectedSealHash,'CUTOVER_SEAL_HASH_MISMATCH');
101
+ const record=JSON.parse(readFileSync(sealManifest,'utf8'));
102
+ ensure(record.contract==='chat-loop.context-source-seal.v1'&&
103
+ record.status==='CUTOVER_FENCED'&&record.sourceDb===sourceDb&&
104
+ record.projectId===projectId&&record.sourceStoreEpoch===source.epoch&&
105
+ record.sourceProjectRevision===project.projectRevision,
106
+ 'CUTOVER_SEAL_INVALID');
107
+ privateFile(record.backupPath);
108
+ ensure(shaFile(record.backupPath)===record.backupHash,
109
+ 'CUTOVER_BACKUP_CHANGED');
110
+ const verify=new DatabaseSync(sourceDb,{readOnly:true});
111
+ try{ensure(logicalDigest(verify)===record.fencedLogicalHash,
112
+ 'CUTOVER_SOURCE_CHANGED')}
113
+ finally{verify.close()}
114
+ expectedFencedDigest=record.fencedLogicalHash;
115
+ ensure((await knownWriterInventory.scan()).length===0,'KNOWN_LEGACY_WRITER_ACTIVE');
116
+ }
117
+ }finally{source.close()}
118
+ const stage=mkdtempSync(join(targetRoot,managed?'.managed-':'.diagnostic-'));
119
+ const file=join(stage,'context.sqlite');
120
+ let published=false;
121
+ try{
122
+ const sourceReader=new DatabaseSync(sourceDb,{readOnly:true,timeout:3500});
123
+ let snapshot;
124
+ try{snapshot=await backupContextDb(sourceReader,file)}
125
+ finally{sourceReader.close()}
126
+ const db=new DatabaseSync(file,{timeout:3500});
127
+ let receipt;
128
+ try{
129
+ validateSchema(db);
130
+ // Detect a source mutation that occurs after the preflight snapshot.
131
+ if(managed)ensure(logicalDigest(db)===expectedFencedDigest,
132
+ 'CUTOVER_SOURCE_CHANGED');
133
+ const meta=k=>db.prepare('SELECT value FROM meta WHERE key=?').get(k)?.value;
134
+ ensure(meta('storeMode')===(managed?'CUTOVER_FENCED':'ACTIVE'),
135
+ 'MIGRATION_SOURCE_MODE_MISMATCH');
136
+ ensure(meta('storeEpoch')===initial.epoch,'STALE_EPOCH');
137
+ const project=db.prepare('SELECT project_revision FROM projects WHERE project_id=?')
138
+ .get(projectId);
139
+ ensure(project?.project_revision===initial.projectRevision,
140
+ 'PROJECT_VERSION_CONFLICT');
141
+ const before=scopeCount(db,projectId);
142
+ if(managed){
143
+ ensure(db.prepare('SELECT COUNT(*) AS n FROM projects').get().n===1,
144
+ 'MIGRATION_SHARED_SOURCE_NOT_EXCLUSIVE');
145
+ ensure(db.prepare("SELECT COUNT(*) AS n FROM migrations WHERE project_id=? AND status<>'MANAGED_RW'")
146
+ .get(projectId).n===0&&before.migrations>0,'MIGRATION_UNACTIVATED');
147
+ }
148
+ db.exec('PRAGMA journal_mode=DELETE; PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON; PRAGMA secure_delete=ON;');
149
+ const newEpoch=randomUUID();
150
+ db.exec('BEGIN IMMEDIATE');
151
+ try{
152
+ for(const table of scopedTables)
153
+ db.prepare('DELETE FROM '+table+' WHERE project_id<>?').run(projectId);
154
+ db.exec('DELETE FROM permits; DELETE FROM start_leases;');
155
+ db.exec(`UPDATE tasks SET writable_ref=NULL,credential_digest=NULL,
156
+ writer_approval_revision=NULL,pending_attempt=NULL,
157
+ pending_checkpoint=NULL,pending_target_generation=NULL,
158
+ pending_credential_digest=NULL,pending_next_ref=NULL,
159
+ binding_revision=binding_revision+1;`);
160
+ db.prepare("UPDATE meta SET value=? WHERE key='storeMode'")
161
+ .run(managed?'ACTIVE':'DIAGNOSTIC_ONLY');
162
+ if(managed)db.exec("UPDATE tasks SET approval_json='[]',approval_revision=approval_revision+1; UPDATE issues SET state='PENDING';");
163
+ db.prepare("UPDATE meta SET value=? WHERE key='storeEpoch'").run(newEpoch);
164
+ db.prepare("INSERT OR REPLACE INTO meta(key,value) VALUES('restoredFromEpoch',?)")
165
+ .run(initial.epoch);
166
+ db.exec('COMMIT');
167
+ }catch(error){try{db.exec('ROLLBACK')}catch{}throw error}
168
+ // Rebuild all b-trees and free pages so other projects' deleted rows
169
+ // cannot remain readable in SQLite freelist or discarded WAL records.
170
+ db.exec('VACUUM;');
171
+ const after=physicalCheck(db,projectId,{
172
+ ...before,permits:0,start_leases:0
173
+ });
174
+ receipt={contract:managed?'chat-loop.context-managed-project.v1':
175
+ 'chat-loop.context-diagnostic-project.v1',
176
+ status:managed?'MANAGED_RW':'DIAGNOSTIC_ONLY',projectId,sourceStoreEpoch:initial.epoch,
177
+ sourceProjectRevision:initial.projectRevision,newStoreEpoch:newEpoch,
178
+ sourceSnapshotHash:snapshot.hash,counts:after,
179
+ sourceUnitsRequireReview:!managed,approvalsRevalidated:false,
180
+ ownerRestored:false,writeCapabilitiesRestored:managed,
181
+ canExecute:false};
182
+ }finally{db.close()}
183
+ // Check reopened data in the exact form the normal SDK uses.
184
+ const verify=openContextProtocol(file,{readOnly:true,principalId:'local-operator',
185
+ authorizeData:()=>true});
186
+ try{
187
+ ensure(verify.mode===(managed?'ACTIVE':'DIAGNOSTIC_ONLY')&&
188
+ verify.epoch===receipt.newStoreEpoch,'MIGRATION_MODE_UNVERIFIED');
189
+ ensure(verify.projectList().length===1 &&
190
+ verify.projectGet(projectId).projectRevision===initial.projectRevision,
191
+ 'MIGRATION_PROJECT_ISOLATION_FAILED');
192
+ const authority=verify.projectBusinessAuthority(projectId);
193
+ ensure(managed?authority.status==='MANAGED_RW'&&authority.writable===true:
194
+ authority.writable===false,'MIGRATION_WRITE_AUTHORITY_UNSAFE');
195
+ if(managed){
196
+ const check=new DatabaseSync(file,{readOnly:true});
197
+ try{
198
+ 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")
199
+ .get().n===0,'MIGRATION_APPROVAL_OR_OWNER_RESTORED');
200
+ }finally{check.close()}
201
+ }
202
+ }finally{verify.close()}
203
+ const manifest=join(stage,managed?'migration-managed.json':'migration-diagnostic.json');
204
+ writeFileSync(manifest,JSON.stringify(receipt,null,2)+'\n',{flag:'wx',mode:0o600});
205
+ ensure(readFileSync(manifest,'utf8').includes(receipt.sourceSnapshotHash),
206
+ 'MIGRATION_RECEIPT_UNVERIFIED');
207
+ ensure(!existsSync(target),'MIGRATION_TARGET_EXISTS');
208
+ renameSync(stage,target);
209
+ published=true;
210
+ return {...receipt,projectDirectory:target};
211
+ }finally{if(!published)rmSync(stage,{recursive:true,force:true})}
212
+ }
213
+
214
+ // The diagnostic export is intentionally not publishable. A managed export is
215
+ // a separate, terminal-reviewed action over an already fenced whole Store.
216
+ export const createProjectDiagnosticBranch=args=>extractProjectBranch(args);
217
+ export const createManagedProjectBranch=args=>extractProjectBranch({
218
+ ...args,managed:true
219
+ });
220
+
221
+ // Freeze a SINGLE-Project legacy Store BEFORE publishing a separate authority.
222
+ // Crash after the freeze is safe: the original stays read-only until reviewed
223
+ // recovery, and no target is published merely because this function ran.
224
+ export async function fenceLegacyProjectStore({
225
+ sourceDb,projectId,expectedStoreEpoch,expectedProjectRevision,
226
+ backupPath,sealManifestPath
227
+ }){
228
+ ensure(ID.test(projectId||''),'INVALID_SCOPE');
229
+ ensure(typeof expectedStoreEpoch==='string'&&expectedStoreEpoch.length>=10,
230
+ 'STALE_EPOCH');
231
+ ensure(Number.isSafeInteger(expectedProjectRevision)&&expectedProjectRevision>=1,
232
+ 'PROJECT_VERSION_CONFLICT');
233
+ privateFile(sourceDb);
234
+ privateRoot(dirname(backupPath));
235
+ privateRoot(dirname(sealManifestPath));
236
+ ensure(!existsSync(backupPath)&&!existsSync(sealManifestPath),
237
+ 'CUTOVER_EVIDENCE_EXISTS');
238
+ const reader=openContextProtocol(sourceDb,{readOnly:true,principalId:'local-operator',
239
+ authorizeData:()=>true,authorizeAdmin:()=>true});
240
+ let sources;
241
+ try{
242
+ ensure(reader.mode==='ACTIVE','MIGRATION_SOURCE_NOT_ACTIVE');
243
+ ensure(reader.epoch===expectedStoreEpoch,'STALE_EPOCH');
244
+ const project=reader.projectGet(projectId);
245
+ ensure(project.projectRevision===expectedProjectRevision&&!project.archived,
246
+ 'PROJECT_VERSION_CONFLICT');
247
+ ensure(reader.projectList().length===1,'MIGRATION_SHARED_SOURCE_NOT_EXCLUSIVE');
248
+ sources=reader.migrationList(projectId);
249
+ ensure(sources.length>0&&sources.every(s=>s.status==='MANAGED_RW'),
250
+ 'MIGRATION_UNACTIVATED');
251
+ for(const source of sources)verifySourceUnit(source.manifest);
252
+ ensure(reader.projectBusinessAuthority(projectId).status==='MANAGED_RW',
253
+ 'MIGRATION_NOT_MANAGED');
254
+ }finally{reader.close()}
255
+ // An active MCP writer must be stopped by the independent operator first.
256
+ ensure((await knownWriterInventory.scan()).length===0,'KNOWN_LEGACY_WRITER_ACTIVE');
257
+ const db=new DatabaseSync(sourceDb,{timeout:3500});
258
+ try{
259
+ const originalDigest=logicalDigest(db);
260
+ // Back up without holding a write transaction (sqlite backup cannot
261
+ // safely snapshot its own live writer). Recheck inside the lock below.
262
+ const snapshot=await backupContextDb(db,backupPath);
263
+ // An online backup is not cutover evidence until the recovered logical
264
+ // rows match the source that was reviewed before taking the write lock.
265
+ const backedUp=new DatabaseSync(backupPath,{readOnly:true});
266
+ try{
267
+ validateSchema(backedUp);
268
+ ensure(logicalDigest(backedUp)===originalDigest,
269
+ 'CUTOVER_BACKUP_CONTENT_MISMATCH');
270
+ ensure(backedUp.prepare('PRAGMA integrity_check').get()?.integrity_check==='ok'
271
+ &&backedUp.prepare('PRAGMA foreign_key_check').all().length===0,
272
+ 'CUTOVER_BACKUP_INTEGRITY_FAILED');
273
+ }finally{backedUp.close()}
274
+ db.exec('BEGIN IMMEDIATE');
275
+ try{
276
+ const get=k=>db.prepare('SELECT value FROM meta WHERE key=?').get(k)?.value;
277
+ ensure(logicalDigest(db)===originalDigest,'CUTOVER_SOURCE_CHANGED');
278
+ for(const unit of sources)verifySourceUnit(unit.manifest);
279
+ ensure(get('storeMode')==='ACTIVE','MIGRATION_SOURCE_NOT_ACTIVE');
280
+ ensure(get('storeEpoch')===expectedStoreEpoch,'STALE_EPOCH');
281
+ const projects=db.prepare('SELECT project_id,project_revision,archived FROM projects').all();
282
+ ensure(projects.length===1&&projects[0].project_id===projectId,
283
+ 'MIGRATION_SHARED_SOURCE_NOT_EXCLUSIVE');
284
+ ensure(projects[0].project_revision===expectedProjectRevision&&
285
+ projects[0].archived===0,'PROJECT_VERSION_CONFLICT');
286
+ ensure(db.prepare('SELECT COUNT(*) AS n FROM migrations WHERE project_id=?').get(projectId).n
287
+ ===sources.length,'MIGRATION_SOURCE_CHANGED');
288
+ ensure(db.prepare("SELECT COUNT(*) AS n FROM migrations WHERE project_id=? AND status<>'MANAGED_RW'")
289
+ .get(projectId).n===0,'MIGRATION_UNACTIVATED');
290
+ 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)')
291
+ .get(projectId).n===0,'CUTOVER_ACTIVE_RUN');
292
+ ensure(db.prepare('SELECT COUNT(*) AS n FROM start_leases').get().n===0
293
+ &&db.prepare('SELECT COUNT(*) AS n FROM permits').get().n===0,
294
+ 'CUTOVER_ACTIVE_PERMIT');
295
+ ensure((await knownWriterInventory.scan()).length===0,'KNOWN_LEGACY_WRITER_ACTIVE');
296
+ // Source did not change between the backed-up snapshot and fence lock.
297
+ db.prepare("UPDATE meta SET value='CUTOVER_FENCED' WHERE key='storeMode'").run();
298
+ db.exec('COMMIT');
299
+ const record={contract:'chat-loop.context-source-seal.v1',
300
+ status:'CUTOVER_FENCED',projectId,sourceDb,sourceStoreEpoch:expectedStoreEpoch,
301
+ sourceProjectRevision:expectedProjectRevision,sourceUnits:sources.length,
302
+ backupPath,backupHash:snapshot.hash,fencedLogicalHash:logicalDigest(db),
303
+ approvalsRevalidated:false,ownerRestored:false,canExecute:false};
304
+ writeFileSync(sealManifestPath,JSON.stringify(record,null,2)+'\n',
305
+ {flag:'wx',mode:0o600});
306
+ return {...record,sealManifestPath,sealManifestHash:shaFile(sealManifestPath)};
307
+ }catch(error){
308
+ try{db.exec('ROLLBACK')}catch{}
309
+ throw error;
310
+ }
311
+ }finally{db.close()}
312
+ }
@@ -0,0 +1,153 @@
1
+ // Read-only historical evidence audit. Database staging and cutover live
2
+ // in the operator-only project-branch module; API exports remain compatible.
3
+ import {createHash} from 'node:crypto';
4
+ import {readFileSync} from 'node:fs';
5
+ import {basename} from 'node:path';
6
+ // This module declares ports; index.mjs is the only dependency assembler.
7
+ // No implementation module imports another implementation module.
8
+ let openContextProtocol, verifySourceUnit, scanSourceUnit, reviewPreservedLines, ID, ensure, privateFile;
9
+ let connected=false;
10
+ export function configureProjectDiagnostic(capabilities){
11
+ if(connected)throw Error('CONTEXT_MODULE_ALREADY_COMPOSED');
12
+ for(const name of ['openContextProtocol', 'verifySourceUnit', 'scanSourceUnit', 'reviewPreservedLines', 'ID', 'ensure', 'privateFile']){
13
+ if(capabilities?.[name]===undefined)throw Error('CONTEXT_MODULE_PORT_MISSING:'+name);
14
+ }
15
+ ({openContextProtocol, verifySourceUnit, scanSourceUnit, reviewPreservedLines, ID, ensure, privateFile}=capabilities);
16
+ if(!capabilities.projectBranch)throw Error('CONTEXT_MODULE_PORT_MISSING:projectBranch');
17
+ projectBranch=capabilities.projectBranch;
18
+ connected=true;
19
+ }
20
+ let projectBranch;
21
+ export const createProjectDiagnosticBranch=(...args)=>projectBranch.createProjectDiagnosticBranch(...args);
22
+ export const createManagedProjectBranch=(...args)=>projectBranch.createManagedProjectBranch(...args);
23
+ export const fenceLegacyProjectStore=(...args)=>projectBranch.fenceLegacyProjectStore(...args);
24
+
25
+ // Read-only migration audit. Never classifies mixed history or certifies writers.
26
+ // A verified byte hash proves source identity, not business ownership or approval.
27
+ export function auditLegacyProjectSources({sourceDb,projectId,expectedStoreEpoch}){
28
+ ensure(ID.test(projectId||''),'INVALID_SCOPE');
29
+ ensure(typeof expectedStoreEpoch==='string'&&expectedStoreEpoch.length>=10,
30
+ 'STALE_EPOCH');
31
+ privateFile(sourceDb);
32
+ const source=openContextProtocol(sourceDb,{readOnly:true,principalId:'local-audit',
33
+ authorizeData:(_mode,p)=>p===projectId,
34
+ authorizeAdmin:(op,p)=>op==='migration.list'&&p===projectId});
35
+ try{
36
+ ensure(source.epoch===expectedStoreEpoch,'STALE_EPOCH');
37
+ const project=source.projectGet(projectId);
38
+ const materials=source.projectMaterialList(projectId);
39
+ const units=source.migrationList(projectId);
40
+ const checks=units.map(unit=>{
41
+ let verifyCode='MATCHED';
42
+ try{verifySourceUnit(unit.manifest)}
43
+ catch(error){verifyCode=/^[A-Z0-9_]+$/.test(error?.code??'')?
44
+ error.code:'SOURCE_VERIFY_FAILED'}
45
+ const sourceKind=unit.manifest.sourceKind;
46
+ const evidenceStored=materials.some(m=>m.sourcePath===unit.sourcePath
47
+ &&m.contentHash===unit.sourceHash
48
+ &&m.provenance==='LEGACY_UNVERIFIED');
49
+ return {sourceUnitId:unit.sourceUnitId,sourceKind,
50
+ filename:basename(unit.sourcePath),sourceHash:unit.sourceHash,
51
+ migrationStatus:unit.status,migrationRevision:unit.migrationRevision,
52
+ sourceVerification:verifyCode,evidenceStored,
53
+ mixedHistoryReviewed:sourceKind==='MIXED_CONTEXT'?
54
+ unit.manifest.classification?.currentFactsComplete===true:null};
55
+ });
56
+ // Registry task documents are separate from the Registry JSON itself.
57
+ // A changed task document does NOT invalidate an unchanged Registry SHA.
58
+ const drift=checks.filter(c=>c.sourceVerification==='LEGACY_REFERENCE_CHANGED');
59
+ const failed=checks.filter(c=>!['MATCHED','LEGACY_REFERENCE_CHANGED']
60
+ .includes(c.sourceVerification));
61
+ const missingBodies=checks.filter(c=>
62
+ ['DOCUMENT','MIXED_CONTEXT'].includes(c.sourceKind)&&!c.evidenceStored);
63
+ const mixedPending=checks.filter(c=>c.sourceKind==='MIXED_CONTEXT'
64
+ &&c.mixedHistoryReviewed!==true);
65
+ const pending=checks.filter(c=>c.migrationStatus!=='MANAGED_RW');
66
+ return {projectId,storeEpoch:source.epoch,projectRevision:project.projectRevision,
67
+ sourceCount:checks.length,checks,
68
+ sourceHashesVerified:checks.length>0&&failed.length===0,
69
+ sourceReferencesVerified:checks.length>0&&failed.length===0&&drift.length===0,
70
+ referenceDriftCount:drift.length,
71
+ sourceBodiesPreserved:checks.length>0&&missingBodies.length===0,
72
+ mixedReviewRequired:mixedPending.length,
73
+ pendingSourceCount:pending.length,
74
+ blockers:[
75
+ ...(checks.length===0?['NO_SOURCE_UNITS']:[]),
76
+ ...(failed.length?['SOURCE_VERIFICATION_FAILED']:[]),
77
+ ...(drift.length?['LEGACY_REFERENCE_DRIFT']:[]),
78
+ ...(missingBodies.length?['SOURCE_MATERIALS_INCOMPLETE']:[]),
79
+ ...(mixedPending.length?['MIXED_OWNERSHIP_REVIEW_REQUIRED']:[]),
80
+ ...(pending.length?['SOURCE_UNACTIVATED']:[]),
81
+ 'OLD_WRITERS_NOT_INDEPENDENTLY_FENCED',
82
+ 'RELEASE_AND_NATIVE_E2E_UNVERIFIED'
83
+ ],
84
+ status:'BLOCKED',writerAuthority:'NOT_VERIFIED',
85
+ canActivate:false,canExecute:false};
86
+ }finally{source.close()}
87
+ }
88
+
89
+ /**
90
+ * Produce a bounded, non-authoritative Registry task-reference drift review.
91
+ * A matching Recovery Archive proves the original version still exists; it
92
+ * never approves its newer version or rewrites a SourceUnit/Task/Receipt.
93
+ */
94
+ export function inspectLegacyRegistryReference({
95
+ sourceDb,projectId,expectedStoreEpoch,sourceUnitId,taskId,archiveFile
96
+ }){
97
+ ensure(ID.test(projectId||'')&&ID.test(taskId||'')&&
98
+ /^[a-f0-9]{64}$/.test(sourceUnitId||''),'INVALID_SCOPE');
99
+ ensure(typeof expectedStoreEpoch==='string'&&expectedStoreEpoch.length>=10,
100
+ 'STALE_EPOCH');
101
+ privateFile(sourceDb);privateFile(archiveFile);
102
+ const source=openContextProtocol(sourceDb,{
103
+ readOnly:true,principalId:'local-reference-review',
104
+ authorizeData:(_mode,p)=>p===projectId,
105
+ authorizeAdmin:(op,p)=>op==='migration.list'&&p===projectId
106
+ });
107
+ try{
108
+ ensure(source.epoch===expectedStoreEpoch,'STALE_EPOCH');
109
+ source.projectGet(projectId);
110
+ const unit=source.migrationList(projectId)
111
+ .find(x=>x.sourceUnitId===sourceUnitId);
112
+ ensure(unit?.status==='SHADOW_RO'&&
113
+ unit.manifest.sourceKind==='REGISTRY_JSON','REGISTRY_SOURCE_NOT_SHADOW');
114
+ const old=unit.manifest.tasks?.find(t=>t.taskId===taskId);
115
+ ensure(old&&old.taskDocPath&&/^[a-f0-9]{64}$/.test(
116
+ old.taskDocumentHash??''),'REGISTRY_REFERENCE_NOT_FOUND');
117
+ const original=readFileSync(archiveFile);
118
+ ensure(original.length>0&&original.length<=512*1024,'ARCHIVE_UNTRUSTED');
119
+ const sha=b=>createHash('sha256').update(b).digest('hex');
120
+ ensure(sha(original)===old.taskDocumentHash,'ARCHIVE_HASH_MISMATCH');
121
+ const current=scanSourceUnit({sourcePath:unit.sourcePath,
122
+ projectId,kind:'REGISTRY_JSON'});
123
+ ensure(current.sourceUnitId===unit.sourceUnitId &&
124
+ current.sourceHash===unit.sourceHash,'SOURCE_CHANGED');
125
+ ensure(current.tasks.length===unit.manifest.tasks.length,
126
+ 'REGISTRY_TASK_SET_CHANGED');
127
+ for(const before of unit.manifest.tasks){
128
+ const after=current.tasks.find(t=>t.taskId===before.taskId);
129
+ ensure(after&&Object.keys(before).every(k=>k==='taskDocumentHash'||
130
+ JSON.stringify(before[k])===JSON.stringify(after[k])),
131
+ 'REGISTRY_TASK_IDENTITY_CHANGED');
132
+ }
133
+ const after=current.tasks.find(t=>t.taskId===taskId);
134
+ ensure(after&&after.taskDocPath===old.taskDocPath,
135
+ 'REGISTRY_TASK_IDENTITY_CHANGED');
136
+ const latest=readFileSync(after.taskDocPath);
137
+ ensure(sha(latest)===after.taskDocumentHash,
138
+ 'DOCUMENT_CHANGED_DURING_INSPECTION');
139
+ // A read-only evidence hint, not a migration or approval decision.
140
+ const lines=reviewPreservedLines(original,latest);
141
+ return {status:'REVIEW_REQUIRED',projectId,sourceUnitId,taskId,
142
+ sourceHash:unit.sourceHash,sourceVerified:true,
143
+ archivedTaskHash:old.taskDocumentHash,
144
+ currentTaskHash:after.taskDocumentHash,
145
+ archivedTaskBytes:original.length,currentTaskBytes:latest.length,
146
+ originalLines:lines.originalLines,currentLines:lines.currentLines,
147
+ changeKind:old.taskDocumentHash===after.taskDocumentHash?'NONE':
148
+ lines.insertionsOnly?'INSERTIONS_ONLY':'CONTENT_CHANGED',
149
+ insertedLines:lines.insertedLines,
150
+ archiveVerified:true,reviewed:false,sourceUnitUpdated:false,
151
+ approvalsImported:false,canActivate:false,canExecute:false};
152
+ }finally{source.close()}
153
+ }
@@ -0,0 +1,19 @@
1
+ // The only shared trust boundary for operator file/Project identity.
2
+ import {lstatSync} from 'node:fs';
3
+ import {isAbsolute} from 'node:path';
4
+
5
+ export const ID=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
6
+ const fail=code=>Object.assign(new Error(code),{code});
7
+ export const ensure=(ok,code)=>{if(!ok)throw fail(code)};
8
+ export function privateFile(file){
9
+ ensure(typeof file==='string'&&isAbsolute(file),'SOURCE_PATH_INVALID');
10
+ const st=lstatSync(file);
11
+ ensure(st.isFile()&&!st.isSymbolicLink()&&!(st.mode&0o077)
12
+ &&(!process.getuid||st.uid===process.getuid()),'MIGRATION_SOURCE_UNTRUSTED');
13
+ }
14
+ export function privateRoot(root){
15
+ ensure(typeof root==='string'&&isAbsolute(root),'MIGRATION_ROOT_INVALID');
16
+ const st=lstatSync(root);
17
+ ensure(st.isDirectory()&&!st.isSymbolicLink()&&!(st.mode&0o077)
18
+ &&(!process.getuid||st.uid===process.getuid()),'MIGRATION_ROOT_UNTRUSTED');
19
+ }
@@ -0,0 +1,115 @@
1
+ // Private Project storage identity and path guard. Never a second DB writer.
2
+ import {DatabaseSync} from 'node:sqlite';
3
+ import {lstatSync,realpathSync} from 'node:fs';
4
+ import {homedir} from 'node:os';
5
+ import {isAbsolute,join,resolve} from 'node:path';
6
+ // This module declares ports; index.mjs is the only dependency assembler.
7
+ // No implementation module imports another implementation module.
8
+ let parseContextAllowedProjects;
9
+ let connected=false;
10
+ export function configureProjectStore(capabilities){
11
+ if(connected)throw Error('CONTEXT_MODULE_ALREADY_COMPOSED');
12
+ for(const name of ['parseContextAllowedProjects']){
13
+ if(capabilities?.[name]===undefined)throw Error('CONTEXT_MODULE_PORT_MISSING:'+name);
14
+ }
15
+ ({parseContextAllowedProjects}=capabilities);
16
+ connected=true;
17
+ }
18
+
19
+ const ID=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
20
+ const fail=code=>Object.assign(new Error(code),{code});
21
+ // existsSync follows symlinks and reports a dangling link as absent. Inspect
22
+ // the actual directory entry so every untrusted root/project/store fails closed.
23
+ function entryOrMissing(path){
24
+ try{return lstatSync(path)}catch(error){
25
+ if(error?.code==='ENOENT')return null;
26
+ throw error;
27
+ }
28
+ }
29
+ export function verifiedStoreFile(file,missingCode=null){
30
+ const st=entryOrMissing(file);
31
+ if(!st){
32
+ if(missingCode)throw fail(missingCode);
33
+ return false;
34
+ }
35
+ if(!st.isFile()||st.isSymbolicLink()||(st.mode&0o077))
36
+ throw fail('STORE_FILE_UNTRUSTED');
37
+ return true;
38
+ }
39
+ export const contextRoot=()=>resolve(process.env.CHAT_LOOP_CONTEXT_ROOT||join(homedir(),'.chat-loop','context'));
40
+ export const allowedProjects=()=>parseContextAllowedProjects(process.env.CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS);
41
+ export function projectDatabase(projectId){
42
+ if(!ID.test(projectId||''))throw fail('INVALID_SCOPE');
43
+ // Never silently keep routing to an old shared Store when a per-Project
44
+ // root was configured for cutover. Two data roots are not a valid mode.
45
+ if(process.env.CHAT_LOOP_CONTEXT_DB&&process.env.CHAT_LOOP_CONTEXT_ROOT)
46
+ throw fail('CONTEXT_SOURCE_AMBIGUOUS');
47
+ const explicit=process.env.CHAT_LOOP_CONTEXT_DB;
48
+ if(explicit){
49
+ if(!isAbsolute(explicit))throw fail('CONTEXT_DB_NOT_ABSOLUTE');
50
+ return explicit; // Explicit legacy Store is a separately verified transition mode.
51
+ }
52
+ const root=contextRoot();
53
+ const rootEntry=entryOrMissing(root);
54
+ if(rootEntry&&(!rootEntry.isDirectory()||rootEntry.isSymbolicLink()
55
+ ||(rootEntry.mode&0o077)))throw fail('CONTEXT_ROOT_UNTRUSTED');
56
+ const dir=join(root,projectId);
57
+ const projectEntry=entryOrMissing(dir);
58
+ if(projectEntry&&(!projectEntry.isDirectory()||projectEntry.isSymbolicLink()
59
+ ||(projectEntry.mode&0o077)))throw fail('PROJECT_DIRECTORY_UNTRUSTED');
60
+ return join(dir,'context.sqlite');
61
+ }
62
+ // Real read-only SQLite discovery: never initializes a missing database or turns WAL on.
63
+ export function projectMeta(projectId){
64
+ const file=projectDatabase(projectId);
65
+ if(!verifiedStoreFile(file))return null;
66
+ const db=new DatabaseSync(file,{readOnly:true,timeout:3500});
67
+ try{
68
+ db.exec('PRAGMA query_only=ON');
69
+ if(!db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='projects'").get())
70
+ throw fail('STORE_SCHEMA_UNKNOWN');
71
+ const schema=db.prepare("SELECT value FROM meta WHERE key='schemaVersion'").get()?.value;
72
+ if(schema!=='6')throw fail('STORE_SCHEMA_MISMATCH');
73
+ const r=db.prepare('SELECT project_id,title,project_revision,shared_context_json,archived FROM projects WHERE project_id=?').get(projectId);
74
+ if(!r)throw fail('PROJECT_IDENTITY_MISMATCH');
75
+ if(!process.env.CHAT_LOOP_CONTEXT_DB){
76
+ const others=db.prepare('SELECT project_id FROM projects WHERE project_id<>?').all(projectId);
77
+ if(others.length)throw fail('PROJECT_IDENTITY_MISMATCH');
78
+ }
79
+ const sharedContext=JSON.parse(r.shared_context_json);
80
+ return {projectId,title:r.title,projectRevision:r.project_revision,
81
+ sharedContext,workspaceRefs:Array.isArray(sharedContext.workspaceRefs)?
82
+ sharedContext.workspaceRefs:[],archived:!!r.archived};
83
+ }finally{db.close()}
84
+ }
85
+ // Shared, security-reviewed Project identity resolver for the private Native
86
+ // adapter. It must never create a Store or resolve a different Project's DB.
87
+ export function resolveVerifiedProjectDatabase(projectId){
88
+ if(!projectMeta(projectId))throw fail('STORE_MISSING');
89
+ return projectDatabase(projectId);
90
+ }
91
+ export function resolveProjects(a,allowed){
92
+ if(!Array.isArray(a.workspaceRoots)||!a.workspaceRoots.length)throw fail('WORKSPACE_REQUIRED');
93
+ const roots=a.workspaceRoots.map(s=>{
94
+ if(typeof s!=='string'||!isAbsolute(s))throw fail('WORKSPACE_INVALID');
95
+ try{return realpathSync(s)}catch{throw fail('WORKSPACE_UNVERIFIED')}
96
+ });
97
+ const matches=[];
98
+ for(const id of allowed){
99
+ const meta=projectMeta(id);
100
+ if(!meta||meta.archived)continue;
101
+ // Ignore stale registered paths without creating extra lists or turning
102
+ // them into accidental Project matches; a caller path must still exist.
103
+ const resolvedRoots=new Set();
104
+ for(const ref of meta.workspaceRefs){
105
+ if(typeof ref!=='string'||!isAbsolute(ref))continue;
106
+ try{resolvedRoots.add(realpathSync(ref))}catch{ /* stale binding: no match */ }
107
+ }
108
+ const matchingRoots=roots.filter(root=>resolvedRoots.has(root));
109
+ if(matchingRoots.length){
110
+ const {sharedContext,...publicMeta}=meta;
111
+ matches.push({...publicMeta,matchingRoots});
112
+ }
113
+ }
114
+ return {candidates:matches,ambiguous:matches.length!==1};
115
+ }