@tomflow/chatloop-context 0.1.4 → 0.6.0
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/README.md +240 -271
- package/bin/cli.mjs +25 -250
- package/capabilities/approval.mjs +151 -0
- package/capabilities/context.mjs +376 -0
- package/capabilities/document.mjs +266 -0
- package/capabilities/evidence.mjs +134 -0
- package/capabilities/presentation.mjs +82 -0
- package/capabilities/project.mjs +349 -0
- package/capabilities/sdk.mjs +72 -0
- package/capabilities/start.mjs +73 -0
- package/capabilities/task.mjs +507 -0
- package/capabilities.generated.mjs +11 -0
- package/docs/interfaces.md +182 -0
- package/docs/operator-and-migration.md +277 -0
- package/index.mjs +236 -0
- package/lib/api-aspect.mjs +190 -0
- package/lib/api-log.mjs +161 -0
- package/lib/approval-policy.mjs +24 -0
- package/lib/capability-catalog.generated.json +1989 -0
- package/lib/capability-router.mjs +67 -0
- package/lib/cli-commands.mjs +280 -0
- package/lib/context-cli.mjs +16 -19
- package/lib/context-migration.mjs +17 -9
- package/lib/core/context.mjs +115 -0
- package/lib/core/evidence.mjs +51 -0
- package/lib/core/health.mjs +55 -0
- package/lib/core/migration.mjs +262 -0
- package/lib/core/project.mjs +246 -0
- package/lib/core/review.mjs +147 -0
- package/lib/core/run.mjs +343 -0
- package/lib/core/store.mjs +391 -0
- package/lib/core/task.mjs +166 -0
- package/lib/line-review.mjs +13 -0
- package/lib/methods.mjs +49 -202
- package/lib/operations.mjs +33 -145
- package/lib/orphan-operator.mjs +117 -0
- package/lib/process-inventory.mjs +20 -0
- package/lib/project-branch.mjs +312 -0
- package/lib/project-diagnostic.mjs +26 -328
- package/lib/project-guards.mjs +19 -0
- package/lib/project-store.mjs +115 -0
- package/lib/trusted-run.mjs +86 -0
- package/lib/workspace-operator.mjs +12 -2
- package/package.json +32 -14
- package/scripts/build-capabilities.mjs +114 -0
- package/lib/context-protocol.mjs +0 -1617
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// Explicit ps-list dependency. This is a bounded observation, NOT a stop receipt.
|
|
2
|
+
import psList from 'ps-list';
|
|
3
|
+
const fail=code=>Object.assign(new Error(code),{code});
|
|
4
|
+
// Process observation uses the declared ps-list provider, not /bin/ps.
|
|
5
|
+
// Never treat a momentary empty snapshot as proof of all future writers.
|
|
6
|
+
export async function activeLegacyWriters(){
|
|
7
|
+
if(process.platform==='win32')throw fail('PROCESS_COMMAND_UNAVAILABLE');
|
|
8
|
+
let processes;
|
|
9
|
+
try{processes=await psList({all:false})}
|
|
10
|
+
catch{throw fail('PROCESS_INVENTORY_UNAVAILABLE')}
|
|
11
|
+
if(!Array.isArray(processes))throw fail('PROCESS_INVENTORY_UNAVAILABLE');
|
|
12
|
+
return processes.filter(p=>Number.isSafeInteger(p.pid)&&p.pid>1
|
|
13
|
+
&&p.pid!==process.pid&&typeof p.cmd==='string'
|
|
14
|
+
&&(/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(p.cmd)))
|
|
15
|
+
.slice(0,20).map(p=>p.pid);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// Internal seam for isolated fixture tests. Not part of npm entrypoints or
|
|
19
|
+
// the migration arguments; callers cannot provide a fake writer predicate.
|
|
20
|
+
export const knownWriterInventory={scan:activeLegacyWriters};
|
|
@@ -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
|
+
}
|