@tomflow/chatloop-context 0.1.0 → 0.1.1
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 +63 -8
- package/bin/cli.mjs +41 -4
- package/lib/context-cli.mjs +1 -1
- package/lib/context-protocol.mjs +22 -10
- package/lib/project-diagnostic.mjs +173 -18
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -126,12 +126,17 @@ proof of a platform-authenticated ChatGPT user approval, so it MUST NOT be used
|
|
|
126
126
|
by an autonomous agent to authorize production cutover.
|
|
127
127
|
The audit reads source bytes and Registry-linked Task documents, checks exact
|
|
128
128
|
Project Material hash/path coverage, and distinguishes a changed Registry
|
|
129
|
-
file from drift in a linked task document.
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
129
|
+
file from drift in a linked task document. Its CLI receipt also includes
|
|
130
|
+
`supportedWriterObservation: {status,pids}` from the same bounded process
|
|
131
|
+
inventory used by `activate` (PID only; never argv). `MATCHED` reports a known
|
|
132
|
+
writer still running; `NO_SUPPORTED_PROCESS_MATCH` is **not proof** that all
|
|
133
|
+
legacy writers were independently fenced, and `UNVERIFIED` means the process
|
|
134
|
+
scan itself failed. It reports mixed CURRENT items still requiring human
|
|
135
|
+
classification, without revealing historical document bodies or treating a
|
|
136
|
+
recovered user Turn as fresh approval. Its `BLOCKED` status intentionally
|
|
137
|
+
includes independent old-writer fencing and release/E2E gates that a local
|
|
138
|
+
file scan cannot prove. It never creates a Store or modifies SourceUnits,
|
|
139
|
+
revisions, permissions, Owner or approvals.
|
|
135
140
|
|
|
136
141
|
**Mixed CURRENT EvidenceOnly classification (local operator only):** when
|
|
137
142
|
the complete, exact historical Markdown bytes are already stored as a
|
|
@@ -184,11 +189,61 @@ The source is left untouched. An invalid SourceUnit, unexpected schema,
|
|
|
184
189
|
stale revision, missing operator approval or existing target fails closed;
|
|
185
190
|
incomplete staging is removed. This command is not exposed through MCP.
|
|
186
191
|
|
|
192
|
+
## Reviewed single-Project release (local operator, not MCP)
|
|
193
|
+
|
|
194
|
+
A diagnostic branch is **never** promoted. A separate terminal-only release
|
|
195
|
+
works exclusively with an already reviewed legacy SQLite containing **exactly
|
|
196
|
+
one Project**. The existing `project audit-sources` must show source hashes,
|
|
197
|
+
reference checks, mixed evidence and bodies reviewed, and every SourceUnit
|
|
198
|
+
must already be `MANAGED_RW`. All known Gateway writers must be stopped, any
|
|
199
|
+
unknown legacy clients independently fenced, and all running Task leases/
|
|
200
|
+
permits/UNKNOWN effects reconciled before sealing. If any requirement fails,
|
|
201
|
+
do not run these commands.
|
|
202
|
+
|
|
203
|
+
With `CHAT_LOOP_CONTEXT_ADMIN_ENABLE=1` and a single explicit Project grant,
|
|
204
|
+
and **without** `CHAT_LOOP_CONTEXT_DB`, the local operator first confirms
|
|
205
|
+
the exact source Epoch/revision, backup path and output receipt in a real TTY:
|
|
206
|
+
|
|
207
|
+
chatloop-context project seal-source <projectId> <sourceDb> <epoch> \
|
|
208
|
+
<projectRevision> <privateBackup.sqlite> <privateSeal.json>
|
|
209
|
+
|
|
210
|
+
Sealing makes a fresh private SQLite online backup, verifies the source again
|
|
211
|
+
under an exclusive write transaction, and durably sets the single old Store
|
|
212
|
+
to `CUTOVER_FENCED`. The old Store then rejects ordinary and internal writes
|
|
213
|
+
even when the old Epoch is supplied. This is **not** SourceUnit approval and
|
|
214
|
+
does not restore any Browser Owner. If the command reports UNKNOWN, inspect
|
|
215
|
+
the old Store mode and original private receipt; never remove the fence or
|
|
216
|
+
retry with a new Project/backup path.
|
|
217
|
+
|
|
218
|
+
Only when the seal receipt and its SHA-256 are independently verified, the
|
|
219
|
+
operator may separately confirm:
|
|
220
|
+
|
|
221
|
+
chatloop-context project publish-managed <projectId> <sourceDb> <epoch> \
|
|
222
|
+
<projectRevision> <privateSeal.json> <sealSha256>
|
|
223
|
+
|
|
224
|
+
Publication accepts only a sealed, **single-Project** source, exact backup
|
|
225
|
+
hash, unchanged logical source hash, all reviewed SourceUnits and no known
|
|
226
|
+
live MCP writer. It creates a new-Epoch `ACTIVE` single-Project SQLite under
|
|
227
|
+
the canonical Context root, with an atomic directory rename, zero foreign
|
|
228
|
+
projects, zero runnable permits/leases and **zero inherited R/P approvals or
|
|
229
|
+
run credentials**. The original old Store stays `CUTOVER_FENCED`; no dual
|
|
230
|
+
write. The published Project can use Context business writes, but its old
|
|
231
|
+
approvals are untrusted: Workspace binding and **fresh** R/P presentation,
|
|
232
|
+
confirmation, Native Owner and Chrome E2E must each be validated separately.
|
|
233
|
+
The response deliberately sets `canExecute:false`.
|
|
234
|
+
|
|
235
|
+
If publication fails after sealing, preserve the sealed source, existing
|
|
236
|
+
private backup and seal receipt for offline recovery; never copy/rename a
|
|
237
|
+
`DIAGNOSTIC_ONLY` Store into production or flip `storeMode` directly.
|
|
238
|
+
The CLI rejects non-TTY callers and the module is not exposed via ordinary
|
|
239
|
+
MCP. Same-UID local operator confirmation alone is **not** proof of an
|
|
240
|
+
independent ChatGPT user authorization. This route must not be executed by an
|
|
241
|
+
autonomous Agent against production Context.
|
|
242
|
+
|
|
187
243
|
**Production remains BLOCKED** until the physical source hashes, mixed
|
|
188
244
|
CURRENT ownership, old writers and true operator approval have been reviewed,
|
|
189
245
|
old app/Native/Registry clients fenced, fresh backup plus recovery tested and
|
|
190
|
-
the release/real Chrome E2E gates passed.
|
|
191
|
-
as cutover authorization. See the P0-02 gate in the existing
|
|
246
|
+
the release/real Chrome E2E gates passed. See P0-02 in
|
|
192
247
|
`docs/research/chat-loop-context-cli-architecture-20261109.md`.
|
|
193
248
|
|
|
194
249
|
## Safety
|
package/bin/cli.mjs
CHANGED
|
@@ -9,8 +9,8 @@ import {CONTEXT_CONTRACT,CONTEXT_PACKAGE_VERSION,methodById,validateContextCall,
|
|
|
9
9
|
// Catalog is Node 20-compatible; SQLite operations load only after Node 24 preflight.
|
|
10
10
|
let openContextProtocol,dispatchContextCall,contextRoot,allowedProjects,
|
|
11
11
|
verifySourceUnit,
|
|
12
|
-
createProjectDiagnosticBranch,
|
|
13
|
-
inspectLegacyRegistryReference;
|
|
12
|
+
createProjectDiagnosticBranch,createManagedProjectBranch,fenceLegacyProjectStore,
|
|
13
|
+
auditLegacyProjectSources,inspectLegacyRegistryReference,activeLegacyWriters;
|
|
14
14
|
const fail=code=>Object.assign(new Error(code),{code});
|
|
15
15
|
const requestLimit=5*1024*1024;
|
|
16
16
|
const output=o=>process.stdout.write(JSON.stringify({
|
|
@@ -76,9 +76,10 @@ try{
|
|
|
76
76
|
({canonicalWorkspaceRefs,confirmWorkspaceOperator,assertWorkspaceUnclaimed,
|
|
77
77
|
withWorkspaceRegistryLock,rebindProjectWorkspaces,readOperatorWorkspaceReceipt}=
|
|
78
78
|
await import('../lib/workspace-operator.mjs'));
|
|
79
|
-
({createProjectDiagnosticBranch,
|
|
80
|
-
inspectLegacyRegistryReference}=
|
|
79
|
+
({createProjectDiagnosticBranch,createManagedProjectBranch,fenceLegacyProjectStore,
|
|
80
|
+
auditLegacyProjectSources,inspectLegacyRegistryReference}=
|
|
81
81
|
await import('../lib/project-diagnostic.mjs'));
|
|
82
|
+
({activeLegacyWriters}=await import('../lib/context-cli.mjs'));
|
|
82
83
|
}
|
|
83
84
|
const [command,sub,...rest]=args;
|
|
84
85
|
let value;
|
|
@@ -207,6 +208,42 @@ try{
|
|
|
207
208
|
const [projectId,sourceDb,expectedStoreEpoch]=rest;
|
|
208
209
|
if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
|
|
209
210
|
value=auditLegacyProjectSources({projectId,sourceDb,expectedStoreEpoch});
|
|
211
|
+
// Observe known, supported MCP writers without claiming an independent
|
|
212
|
+
// old-writer fence. Only PIDs are returned, never process argv or secrets.
|
|
213
|
+
let writerObservation;
|
|
214
|
+
try{
|
|
215
|
+
const pids=activeLegacyWriters().map(line=>Number(line.match(/^\d+/)[0]));
|
|
216
|
+
writerObservation={status:pids.length?'MATCHED':'NO_SUPPORTED_PROCESS_MATCH',pids};
|
|
217
|
+
}catch{writerObservation={status:'UNVERIFIED',pids:[]}}
|
|
218
|
+
value={...value,supportedWriterObservation:writerObservation};
|
|
219
|
+
}else if(command==='project'&&sub==='seal-source'&&rest.length===6){
|
|
220
|
+
const [projectId,sourceDb,epoch,revision,backupPath,sealManifestPath]=rest;
|
|
221
|
+
if(process.env.CHAT_LOOP_CONTEXT_ADMIN_ENABLE!=='1')throw fail('ADMIN_REQUIRED');
|
|
222
|
+
if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
|
|
223
|
+
if(process.env.CHAT_LOOP_CONTEXT_DB)throw fail('EXPLICIT_DB_INIT_REQUIRED');
|
|
224
|
+
const expectedProjectRevision=Number(revision);
|
|
225
|
+
if(!Number.isSafeInteger(expectedProjectRevision)||expectedProjectRevision<1)
|
|
226
|
+
throw fail('PROJECT_VERSION_CONFLICT');
|
|
227
|
+
await confirmWorkspaceOperator('SEAL_SOURCE',projectId,
|
|
228
|
+
expectedProjectRevision,[sourceDb,epoch,backupPath,sealManifestPath]);
|
|
229
|
+
value=await fenceLegacyProjectStore({sourceDb,projectId,
|
|
230
|
+
expectedStoreEpoch:epoch,expectedProjectRevision,backupPath,sealManifestPath});
|
|
231
|
+
}else if(command==='project'&&sub==='publish-managed'&&rest.length===6){
|
|
232
|
+
const [projectId,sourceDb,epoch,revision,sealManifest,expectedSealHash]=rest;
|
|
233
|
+
if(process.env.CHAT_LOOP_CONTEXT_ADMIN_ENABLE!=='1')throw fail('ADMIN_REQUIRED');
|
|
234
|
+
if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
|
|
235
|
+
if(process.env.CHAT_LOOP_CONTEXT_DB)throw fail('EXPLICIT_DB_INIT_REQUIRED');
|
|
236
|
+
const expectedProjectRevision=Number(revision);
|
|
237
|
+
if(!Number.isSafeInteger(expectedProjectRevision)||expectedProjectRevision<1)
|
|
238
|
+
throw fail('PROJECT_VERSION_CONFLICT');
|
|
239
|
+
await confirmWorkspaceOperator('PUBLISH_MANAGED',projectId,
|
|
240
|
+
expectedProjectRevision,[sourceDb,epoch,sealManifest,expectedSealHash]);
|
|
241
|
+
const root=contextRoot();
|
|
242
|
+
mkdirSync(root,{recursive:true,mode:0o700});
|
|
243
|
+
value=await withWorkspaceRegistryLock(root,()=>createManagedProjectBranch({
|
|
244
|
+
sourceDb,targetRoot:root,projectId,expectedStoreEpoch:epoch,
|
|
245
|
+
expectedProjectRevision,sealManifest,expectedSealHash
|
|
246
|
+
}));
|
|
210
247
|
}else if(command==='project'&&sub==='stage-diagnostic'&&rest.length===4){
|
|
211
248
|
const [projectId,sourceDb,expectedStoreEpoch,revision]=rest;
|
|
212
249
|
if(process.env.CHAT_LOOP_CONTEXT_ADMIN_ENABLE!=='1')throw fail('ADMIN_REQUIRED');
|
package/lib/context-cli.mjs
CHANGED
|
@@ -25,7 +25,7 @@ async function operatorConfirm(expected){
|
|
|
25
25
|
if(answer!==expected)throw fail('OPERATOR_CONFIRMATION_MISMATCH');
|
|
26
26
|
}finally{rl.close()}
|
|
27
27
|
}
|
|
28
|
-
function activeLegacyWriters(){
|
|
28
|
+
export function activeLegacyWriters(){
|
|
29
29
|
// Observable supported-client process inventory, NOT proof of every old
|
|
30
30
|
// npx cache or arbitrary same-UID shell. Operator must verify those too.
|
|
31
31
|
const output=execFileSync('/bin/ps',['-axo','pid=,command='],
|
package/lib/context-protocol.mjs
CHANGED
|
@@ -49,7 +49,7 @@ export function openContextProtocol(file,{authorizeInternal=()=>false,authorizeD
|
|
|
49
49
|
const previousEpoch=db.prepare("SELECT value FROM meta WHERE key='storeEpoch'").get()?.value;
|
|
50
50
|
if(version!=='6'||!previousEpoch){db.close();throw fail('STORE_SCHEMA_MISMATCH');}
|
|
51
51
|
const previousMode=db.prepare("SELECT value FROM meta WHERE key='storeMode'").get()?.value;
|
|
52
|
-
if(!['ACTIVE','DIAGNOSTIC_ONLY'].includes(previousMode)){
|
|
52
|
+
if(!['ACTIVE','DIAGNOSTIC_ONLY','CUTOVER_FENCED'].includes(previousMode)){
|
|
53
53
|
db.close();throw fail('STORE_MODE_UNKNOWN');
|
|
54
54
|
}
|
|
55
55
|
const mandatory=['meta','projects','tasks','documents','issues','artifacts',
|
|
@@ -206,7 +206,7 @@ export function openContextProtocol(file,{authorizeInternal=()=>false,authorizeD
|
|
|
206
206
|
const storeMode=db.prepare("SELECT value FROM meta WHERE key='storeMode'").get()?.value;
|
|
207
207
|
// Missing authority mode is not evidence of an ACTIVE database. In
|
|
208
208
|
// particular, never promote a partial/restored v5 Store by default.
|
|
209
|
-
if(!['ACTIVE','DIAGNOSTIC_ONLY'].includes(storeMode)){
|
|
209
|
+
if(!['ACTIVE','DIAGNOSTIC_ONLY','CUTOVER_FENCED'].includes(storeMode)){
|
|
210
210
|
db.close();throw fail('STORE_MODE_UNKNOWN');
|
|
211
211
|
}
|
|
212
212
|
const row=(p,t)=>db.prepare('SELECT * FROM tasks WHERE project_id=? AND task_id=?').get(p,t);
|
|
@@ -220,9 +220,17 @@ export function openContextProtocol(file,{authorizeInternal=()=>false,authorizeD
|
|
|
220
220
|
:{projectRevision:r.adopted_project_revision,
|
|
221
221
|
adoptedProjectRevision:r.adopted_project_revision,projectDrift:false};
|
|
222
222
|
};
|
|
223
|
+
const currentMode=()=>db.prepare("SELECT value FROM meta WHERE key='storeMode'")
|
|
224
|
+
.get()?.value;
|
|
225
|
+
const assertWriteMode=()=>{
|
|
226
|
+
const mode=currentMode();
|
|
227
|
+
assert(storeMode==='ACTIVE'&&mode==='ACTIVE',
|
|
228
|
+
mode==='CUTOVER_FENCED'||storeMode==='CUTOVER_FENCED'?
|
|
229
|
+
'STORE_CUTOVER_FENCED':'STORE_DIAGNOSTIC_ONLY');
|
|
230
|
+
};
|
|
223
231
|
const tx=fn=>{
|
|
224
232
|
db.exec('BEGIN IMMEDIATE');
|
|
225
|
-
try{const v=fn();db.exec('COMMIT');return v;}
|
|
233
|
+
try{assertWriteMode();const v=fn();db.exec('COMMIT');return v;}
|
|
226
234
|
catch(e){try{db.exec('ROLLBACK')}catch{}throw e}
|
|
227
235
|
};
|
|
228
236
|
const checkIds=(p,t)=>assert(ID.test(p||'')&&ID.test(t||''),'INVALID_SCOPE');
|
|
@@ -230,7 +238,7 @@ export function openContextProtocol(file,{authorizeInternal=()=>false,authorizeD
|
|
|
230
238
|
assert(req&&typeof req==='object','INVALID_ARGUMENT');
|
|
231
239
|
// Restored snapshots are a read-only diagnostic fork; they cannot be
|
|
232
240
|
// reauthorized by supplying the NEW epoch, a new token, or fake owner.
|
|
233
|
-
|
|
241
|
+
assertWriteMode();
|
|
234
242
|
const {projectId,taskId,expectedStoreEpoch,writeRequestId}=req;
|
|
235
243
|
assert(!Object.hasOwn(req,'principal'),'PRINCIPAL_FORBIDDEN');
|
|
236
244
|
assert(authorizeData('write',projectId,taskId,op)===true,'PROJECT_ACCESS_DENIED');
|
|
@@ -257,6 +265,7 @@ export function openContextProtocol(file,{authorizeInternal=()=>false,authorizeD
|
|
|
257
265
|
});
|
|
258
266
|
};
|
|
259
267
|
const internal=(op,a)=>{
|
|
268
|
+
assertWriteMode();
|
|
260
269
|
const decision=authorizeInternal(op,a);
|
|
261
270
|
assert(decision===true,'INTERNAL_ONLY');
|
|
262
271
|
};
|
|
@@ -416,9 +425,11 @@ export function openContextProtocol(file,{authorizeInternal=()=>false,authorizeD
|
|
|
416
425
|
.includes(shared.legacyAuthority);
|
|
417
426
|
const completed=pending.length===0&&missing.length===0
|
|
418
427
|
&&(!retired||sources.length>0&&sources.every(x=>x.status==='MANAGED_RW'));
|
|
419
|
-
const
|
|
420
|
-
|
|
421
|
-
|
|
428
|
+
const mode=currentMode();
|
|
429
|
+
const writable=completed&&mode==='ACTIVE';
|
|
430
|
+
return {writable,status:mode==='CUTOVER_FENCED'?'CUTOVER_FENCED':
|
|
431
|
+
!completed?'MIGRATION_NOT_MANAGED':
|
|
432
|
+
mode==='DIAGNOSTIC_ONLY'?'DIAGNOSTIC_ONLY':
|
|
422
433
|
sources.length?'MANAGED_RW':'NEW_PROJECT',
|
|
423
434
|
sourceCount:sources.length,pendingSourceCount:pending.length,
|
|
424
435
|
unverifiedMaterialCount:missing.length};
|
|
@@ -427,7 +438,8 @@ export function openContextProtocol(file,{authorizeInternal=()=>false,authorizeD
|
|
|
427
438
|
assert(ID.test(projectId||''),'INVALID_SCOPE');
|
|
428
439
|
readAuth(projectId,null,'registry.authority');
|
|
429
440
|
// A restored diagnostic Store can never authorize the old JSON writer.
|
|
430
|
-
if(
|
|
441
|
+
if(currentMode()==='DIAGNOSTIC_ONLY')return 'RESTORED_DIAGNOSTIC';
|
|
442
|
+
if(currentMode()==='CUTOVER_FENCED')return 'CUTOVER_FENCED';
|
|
431
443
|
const records=db.prepare('SELECT status,manifest_json FROM migrations WHERE project_id=?')
|
|
432
444
|
.all(projectId);
|
|
433
445
|
const registry=records.filter(r=>parse(r.manifest_json).sourceKind==='REGISTRY_JSON');
|
|
@@ -1145,8 +1157,8 @@ export function openContextProtocol(file,{authorizeInternal=()=>false,authorizeD
|
|
|
1145
1157
|
.get(a.projectId,a.taskId,issue.document_id,issue.version);
|
|
1146
1158
|
assert(doc&&doc.content_hash===issue.content_hash,'DOCUMENT_CHANGED');
|
|
1147
1159
|
if(a.decision!=='APPROVE'){
|
|
1148
|
-
|
|
1149
|
-
|
|
1160
|
+
// The legacy CUSTOM decision has the same meaning as a change request.
|
|
1161
|
+
const issueStatus=a.decision==='REJECT'?'REJECTED':'CHANGE_REQUESTED';
|
|
1150
1162
|
db.prepare('UPDATE issues SET state=?,presented_ref=? WHERE project_id=? AND task_id=? AND issue_id=?')
|
|
1151
1163
|
.run(issueStatus,a.presentedAssistantRef,a.projectId,a.taskId,a.issueId);
|
|
1152
1164
|
db.prepare('UPDATE tasks SET business_revision=business_revision+1 WHERE project_id=? AND task_id=?')
|
|
@@ -1,10 +1,12 @@
|
|
|
1
|
-
// Offline
|
|
2
|
-
//
|
|
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.
|
|
3
4
|
import {randomUUID,createHash} from 'node:crypto';
|
|
4
5
|
import {DatabaseSync} from 'node:sqlite';
|
|
5
6
|
import {existsSync,lstatSync,mkdtempSync,renameSync,rmSync,writeFileSync,
|
|
6
7
|
readFileSync} from 'node:fs';
|
|
7
|
-
import {isAbsolute,join,basename} from 'node:path';
|
|
8
|
+
import {isAbsolute,join,basename,dirname} from 'node:path';
|
|
9
|
+
import {activeLegacyWriters} from './context-cli.mjs';
|
|
8
10
|
import {openContextProtocol} from './context-protocol.mjs';
|
|
9
11
|
import {backupContextDb,verifySourceUnit,scanSourceUnit} from './context-migration.mjs';
|
|
10
12
|
|
|
@@ -16,6 +18,17 @@ const knownTables=new Set(['meta','projects','tasks','documents','issues',
|
|
|
16
18
|
'project_materials']);
|
|
17
19
|
const scopedTables=['checkpoints','documents','issues','artifacts','receipts',
|
|
18
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
|
+
}
|
|
19
32
|
const count=db=>Object.fromEntries(scopedTables.map(table=>
|
|
20
33
|
[table,db.prepare('SELECT COUNT(*) AS n FROM '+table).get().n]));
|
|
21
34
|
const scopeCount=(db,projectId)=>Object.fromEntries(scopedTables.map(table=>
|
|
@@ -56,8 +69,10 @@ function physicalCheck(db,projectId,expected){
|
|
|
56
69
|
'MIGRATION_FOREIGN_KEY_FAILED');
|
|
57
70
|
return counts;
|
|
58
71
|
}
|
|
59
|
-
|
|
60
|
-
sourceDb,targetRoot,projectId,expectedStoreEpoch,expectedProjectRevision
|
|
72
|
+
async function extractProjectBranch({
|
|
73
|
+
sourceDb,targetRoot,projectId,expectedStoreEpoch,expectedProjectRevision,
|
|
74
|
+
managed=false,sealManifest=null,expectedSealHash=null,
|
|
75
|
+
knownWriters=activeLegacyWriters
|
|
61
76
|
}){
|
|
62
77
|
ensure(ID.test(projectId||''),'INVALID_SCOPE');
|
|
63
78
|
ensure(typeof expectedStoreEpoch==='string'&&expectedStoreEpoch.length>=10,
|
|
@@ -69,16 +84,45 @@ export async function createProjectDiagnosticBranch({
|
|
|
69
84
|
ensure(!existsSync(target),'MIGRATION_TARGET_EXISTS');
|
|
70
85
|
// Preflight may not initialize/repair/change the old Store in any way.
|
|
71
86
|
const source=openContextProtocol(sourceDb,{readOnly:true,principalId:'local-operator',
|
|
72
|
-
authorizeData:()=>true});
|
|
87
|
+
authorizeData:()=>true,authorizeAdmin:()=>true});
|
|
73
88
|
let initial;
|
|
89
|
+
let expectedFencedDigest;
|
|
74
90
|
try{
|
|
75
91
|
const project=source.projectGet(projectId);
|
|
76
|
-
ensure(source.mode==='
|
|
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
|
+
}
|
|
77
102
|
ensure(source.epoch===expectedStoreEpoch,'STALE_EPOCH');
|
|
78
103
|
ensure(project.projectRevision===expectedProjectRevision,'PROJECT_VERSION_CONFLICT');
|
|
79
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
|
+
}
|
|
80
124
|
}finally{source.close()}
|
|
81
|
-
const stage=mkdtempSync(join(targetRoot,'.diagnostic-'));
|
|
125
|
+
const stage=mkdtempSync(join(targetRoot,managed?'.managed-':'.diagnostic-'));
|
|
82
126
|
const file=join(stage,'context.sqlite');
|
|
83
127
|
let published=false;
|
|
84
128
|
try{
|
|
@@ -90,14 +134,24 @@ export async function createProjectDiagnosticBranch({
|
|
|
90
134
|
let receipt;
|
|
91
135
|
try{
|
|
92
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');
|
|
93
140
|
const meta=k=>db.prepare('SELECT value FROM meta WHERE key=?').get(k)?.value;
|
|
94
|
-
ensure(meta('storeMode')==='
|
|
141
|
+
ensure(meta('storeMode')===(managed?'CUTOVER_FENCED':'ACTIVE'),
|
|
142
|
+
'MIGRATION_SOURCE_MODE_MISMATCH');
|
|
95
143
|
ensure(meta('storeEpoch')===initial.epoch,'STALE_EPOCH');
|
|
96
144
|
const project=db.prepare('SELECT project_revision FROM projects WHERE project_id=?')
|
|
97
145
|
.get(projectId);
|
|
98
146
|
ensure(project?.project_revision===initial.projectRevision,
|
|
99
147
|
'PROJECT_VERSION_CONFLICT');
|
|
100
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
|
+
}
|
|
101
155
|
db.exec('PRAGMA journal_mode=DELETE; PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON; PRAGMA secure_delete=ON;');
|
|
102
156
|
const newEpoch=randomUUID();
|
|
103
157
|
db.exec('BEGIN IMMEDIATE');
|
|
@@ -110,7 +164,9 @@ export async function createProjectDiagnosticBranch({
|
|
|
110
164
|
pending_checkpoint=NULL,pending_target_generation=NULL,
|
|
111
165
|
pending_credential_digest=NULL,pending_next_ref=NULL,
|
|
112
166
|
binding_revision=binding_revision+1;`);
|
|
113
|
-
db.prepare("UPDATE meta SET value
|
|
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';");
|
|
114
170
|
db.prepare("UPDATE meta SET value=? WHERE key='storeEpoch'").run(newEpoch);
|
|
115
171
|
db.prepare("INSERT OR REPLACE INTO meta(key,value) VALUES('restoredFromEpoch',?)")
|
|
116
172
|
.run(initial.epoch);
|
|
@@ -122,26 +178,36 @@ export async function createProjectDiagnosticBranch({
|
|
|
122
178
|
const after=physicalCheck(db,projectId,{
|
|
123
179
|
...before,permits:0,start_leases:0
|
|
124
180
|
});
|
|
125
|
-
receipt={contract:'chat-loop.context-
|
|
126
|
-
|
|
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,
|
|
127
184
|
sourceProjectRevision:initial.projectRevision,newStoreEpoch:newEpoch,
|
|
128
185
|
sourceSnapshotHash:snapshot.hash,counts:after,
|
|
129
|
-
sourceUnitsRequireReview
|
|
130
|
-
ownerRestored:false,writeCapabilitiesRestored:
|
|
186
|
+
sourceUnitsRequireReview:!managed,approvalsRevalidated:false,
|
|
187
|
+
ownerRestored:false,writeCapabilitiesRestored:managed,
|
|
188
|
+
canExecute:false};
|
|
131
189
|
}finally{db.close()}
|
|
132
190
|
// Check reopened data in the exact form the normal SDK uses.
|
|
133
191
|
const verify=openContextProtocol(file,{readOnly:true,principalId:'local-operator',
|
|
134
192
|
authorizeData:()=>true});
|
|
135
193
|
try{
|
|
136
|
-
ensure(verify.mode==='DIAGNOSTIC_ONLY'&&
|
|
194
|
+
ensure(verify.mode===(managed?'ACTIVE':'DIAGNOSTIC_ONLY')&&
|
|
137
195
|
verify.epoch===receipt.newStoreEpoch,'MIGRATION_MODE_UNVERIFIED');
|
|
138
196
|
ensure(verify.projectList().length===1 &&
|
|
139
197
|
verify.projectGet(projectId).projectRevision===initial.projectRevision,
|
|
140
198
|
'MIGRATION_PROJECT_ISOLATION_FAILED');
|
|
141
|
-
|
|
142
|
-
|
|
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
|
+
}
|
|
143
209
|
}finally{verify.close()}
|
|
144
|
-
const manifest=join(stage,'migration-diagnostic.json');
|
|
210
|
+
const manifest=join(stage,managed?'migration-managed.json':'migration-diagnostic.json');
|
|
145
211
|
writeFileSync(manifest,JSON.stringify(receipt,null,2)+'\n',{flag:'wx',mode:0o600});
|
|
146
212
|
ensure(readFileSync(manifest,'utf8').includes(receipt.sourceSnapshotHash),
|
|
147
213
|
'MIGRATION_RECEIPT_UNVERIFIED');
|
|
@@ -152,6 +218,95 @@ export async function createProjectDiagnosticBranch({
|
|
|
152
218
|
}finally{if(!published)rmSync(stage,{recursive:true,force:true})}
|
|
153
219
|
}
|
|
154
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
|
+
db.exec('BEGIN IMMEDIATE');
|
|
271
|
+
try{
|
|
272
|
+
const get=k=>db.prepare('SELECT value FROM meta WHERE key=?').get(k)?.value;
|
|
273
|
+
ensure(logicalDigest(db)===originalDigest,'CUTOVER_SOURCE_CHANGED');
|
|
274
|
+
for(const unit of sources)verifySourceUnit(unit.manifest);
|
|
275
|
+
ensure(get('storeMode')==='ACTIVE','MIGRATION_SOURCE_NOT_ACTIVE');
|
|
276
|
+
ensure(get('storeEpoch')===expectedStoreEpoch,'STALE_EPOCH');
|
|
277
|
+
const projects=db.prepare('SELECT project_id,project_revision,archived FROM projects').all();
|
|
278
|
+
ensure(projects.length===1&&projects[0].project_id===projectId,
|
|
279
|
+
'MIGRATION_SHARED_SOURCE_NOT_EXCLUSIVE');
|
|
280
|
+
ensure(projects[0].project_revision===expectedProjectRevision&&
|
|
281
|
+
projects[0].archived===0,'PROJECT_VERSION_CONFLICT');
|
|
282
|
+
ensure(db.prepare('SELECT COUNT(*) AS n FROM migrations WHERE project_id=?').get(projectId).n
|
|
283
|
+
===sources.length,'MIGRATION_SOURCE_CHANGED');
|
|
284
|
+
ensure(db.prepare("SELECT COUNT(*) AS n FROM migrations WHERE project_id=? AND status<>'MANAGED_RW'")
|
|
285
|
+
.get(projectId).n===0,'MIGRATION_UNACTIVATED');
|
|
286
|
+
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)')
|
|
287
|
+
.get(projectId).n===0,'CUTOVER_ACTIVE_RUN');
|
|
288
|
+
ensure(db.prepare('SELECT COUNT(*) AS n FROM start_leases').get().n===0
|
|
289
|
+
&&db.prepare('SELECT COUNT(*) AS n FROM permits').get().n===0,
|
|
290
|
+
'CUTOVER_ACTIVE_PERMIT');
|
|
291
|
+
ensure(knownWriters().length===0,'KNOWN_LEGACY_WRITER_ACTIVE');
|
|
292
|
+
// Source did not change between the backed-up snapshot and fence lock.
|
|
293
|
+
db.prepare("UPDATE meta SET value='CUTOVER_FENCED' WHERE key='storeMode'").run();
|
|
294
|
+
db.exec('COMMIT');
|
|
295
|
+
const record={contract:'chat-loop.context-source-seal.v1',
|
|
296
|
+
status:'CUTOVER_FENCED',projectId,sourceDb,sourceStoreEpoch:expectedStoreEpoch,
|
|
297
|
+
sourceProjectRevision:expectedProjectRevision,sourceUnits:sources.length,
|
|
298
|
+
backupPath,backupHash:snapshot.hash,fencedLogicalHash:logicalDigest(db),
|
|
299
|
+
approvalsRevalidated:false,ownerRestored:false,canExecute:false};
|
|
300
|
+
writeFileSync(sealManifestPath,JSON.stringify(record,null,2)+'\n',
|
|
301
|
+
{flag:'wx',mode:0o600});
|
|
302
|
+
return {...record,sealManifestPath,sealManifestHash:shaFile(sealManifestPath)};
|
|
303
|
+
}catch(error){
|
|
304
|
+
try{db.exec('ROLLBACK')}catch{}
|
|
305
|
+
throw error;
|
|
306
|
+
}
|
|
307
|
+
}finally{db.close()}
|
|
308
|
+
}
|
|
309
|
+
|
|
155
310
|
// Read-only migration audit. Never classifies mixed history or certifies writers.
|
|
156
311
|
// A verified byte hash proves source identity, not business ownership or approval.
|
|
157
312
|
export function auditLegacyProjectSources({sourceDb,projectId,expectedStoreEpoch}){
|