@tomflow/chatloop-tools 0.4.19 → 0.4.23
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 +93 -3
- package/bin/cli.mjs +27 -6
- package/lib/adapters/mcp-child.mjs +17 -7
- package/lib/context-cli.mjs +2 -0
- package/lib/context-control-auth.mjs +40 -0
- package/lib/context-control-run.mjs +117 -0
- package/lib/context-gateway.mjs +97 -0
- package/lib/context-migration.mjs +2 -0
- package/lib/context-protocol.mjs +2 -0
- package/lib/extension-contract.mjs +16 -0
- package/lib/extension-proxy.mjs +11 -2
- package/lib/gateway.mjs +93 -4
- package/lib/release.mjs +177 -5
- package/lib/supervisor.mjs +78 -3
- package/lib/task-registry-managed.mjs +38 -0
- package/lib/task-registry.mjs +221 -0
- package/lib/terminal-app-policy.mjs +18 -0
- package/lib/trace-gateway.mjs +99 -0
- package/node_modules/@tomflow/chatloop-context/README.md +204 -0
- package/node_modules/@tomflow/chatloop-context/bin/cli.mjs +236 -0
- package/node_modules/@tomflow/chatloop-context/lib/context-cli.mjs +301 -0
- package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +272 -0
- package/node_modules/@tomflow/chatloop-context/lib/context-protocol.mjs +1595 -0
- package/node_modules/@tomflow/chatloop-context/lib/methods.mjs +264 -0
- package/node_modules/@tomflow/chatloop-context/lib/operations.mjs +219 -0
- package/node_modules/@tomflow/chatloop-context/lib/project-diagnostic.mjs +289 -0
- package/node_modules/@tomflow/chatloop-context/lib/workspace-operator.mjs +159 -0
- package/node_modules/@tomflow/chatloop-context/package.json +21 -0
- package/node_modules/@tomflow/chatloop-trace/README.md +13 -0
- package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +259 -0
- package/node_modules/@tomflow/chatloop-trace/package.json +11 -0
- package/package.json +9 -3
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// One invocation = one bounded Context SDK request; never a background server.
|
|
3
|
+
import {randomUUID,createHash} from 'node:crypto';
|
|
4
|
+
import {existsSync,mkdirSync,mkdtempSync,renameSync,rmSync} from 'node:fs';
|
|
5
|
+
import {join} from 'node:path';
|
|
6
|
+
let canonicalWorkspaceRefs,confirmWorkspaceOperator,assertWorkspaceUnclaimed,
|
|
7
|
+
withWorkspaceRegistryLock,rebindProjectWorkspaces,readOperatorWorkspaceReceipt;
|
|
8
|
+
import {CONTEXT_CONTRACT,CONTEXT_PACKAGE_VERSION,methodById,validateContextCall,listMethods,describeMethod} from '../lib/methods.mjs';
|
|
9
|
+
// Catalog is Node 20-compatible; SQLite operations load only after Node 24 preflight.
|
|
10
|
+
let openContextProtocol,dispatchContextCall,contextRoot,allowedProjects,
|
|
11
|
+
verifySourceUnit,
|
|
12
|
+
createProjectDiagnosticBranch,auditLegacyProjectSources,
|
|
13
|
+
inspectLegacyRegistryReference;
|
|
14
|
+
const fail=code=>Object.assign(new Error(code),{code});
|
|
15
|
+
const requestLimit=5*1024*1024;
|
|
16
|
+
const output=o=>process.stdout.write(JSON.stringify({
|
|
17
|
+
contract:CONTEXT_CONTRACT,packageVersion:CONTEXT_PACKAGE_VERSION,...o
|
|
18
|
+
})+'\n');
|
|
19
|
+
async function stdinJson(){
|
|
20
|
+
let bytes=0,parts=[];
|
|
21
|
+
for await(const chunk of process.stdin){
|
|
22
|
+
bytes+=chunk.length;
|
|
23
|
+
if(bytes>requestLimit)throw fail('REQUEST_TOO_LARGE');
|
|
24
|
+
parts.push(chunk);
|
|
25
|
+
}
|
|
26
|
+
if(!bytes)throw fail('REQUEST_REQUIRED');
|
|
27
|
+
try{return JSON.parse(Buffer.concat(parts).toString('utf8'))}
|
|
28
|
+
catch{throw fail('INVALID_JSON')}
|
|
29
|
+
}
|
|
30
|
+
async function registerProject(projectId,title,workspaces=[],reviewed=false){
|
|
31
|
+
if(process.env.CHAT_LOOP_CONTEXT_ADMIN_ENABLE!=='1')throw fail('ADMIN_REQUIRED');
|
|
32
|
+
if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
|
|
33
|
+
if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(projectId))throw fail('INVALID_SCOPE');
|
|
34
|
+
if(typeof title!=='string'||!title.trim()||title.length>200)throw fail('INVALID_TITLE');
|
|
35
|
+
if(process.env.CHAT_LOOP_CONTEXT_DB)throw fail('EXPLICIT_DB_INIT_REQUIRED');
|
|
36
|
+
const refs=canonicalWorkspaceRefs(workspaces,{allowEmpty:!reviewed});
|
|
37
|
+
const root=contextRoot(),final=join(root,projectId);
|
|
38
|
+
if(existsSync(final))throw fail('PROJECT_EXISTS');
|
|
39
|
+
// The user-reviewed entry never creates a Store (or even a directory)
|
|
40
|
+
// before the local operator confirms the exact canonical roots.
|
|
41
|
+
if(reviewed)await confirmWorkspaceOperator('REGISTER',projectId,0,refs);
|
|
42
|
+
mkdirSync(root,{recursive:true,mode:0o700});
|
|
43
|
+
return withWorkspaceRegistryLock(root,()=>{
|
|
44
|
+
let tmp;
|
|
45
|
+
try{
|
|
46
|
+
if(existsSync(final))throw fail('PROJECT_EXISTS');
|
|
47
|
+
if(reviewed){
|
|
48
|
+
const current=canonicalWorkspaceRefs(workspaces);
|
|
49
|
+
if(JSON.stringify(current)!==JSON.stringify(refs))throw fail('WORKSPACE_CHANGED');
|
|
50
|
+
assertWorkspaceUnclaimed(root,projectId,refs);
|
|
51
|
+
}
|
|
52
|
+
tmp=mkdtempSync(join(root,'.register-'));
|
|
53
|
+
const db=openContextProtocol(join(tmp,'context.sqlite'),{
|
|
54
|
+
allowCreate:true,authorizeData:()=>true,principalId:'local-operator'});
|
|
55
|
+
let result;
|
|
56
|
+
try{
|
|
57
|
+
result=db.projectCreate({projectId,title,sharedContext:{workspaceRefs:refs},
|
|
58
|
+
expectedStoreEpoch:db.epoch,writeRequestId:randomUUID()});
|
|
59
|
+
}finally{db.close()}
|
|
60
|
+
renameSync(tmp,final);tmp=null;
|
|
61
|
+
return {...result,workspaceRefs:refs,projectDirectory:final};
|
|
62
|
+
}finally{
|
|
63
|
+
// Incomplete staging is diagnostic only, never silently promoted.
|
|
64
|
+
if(tmp)rmSync(tmp,{recursive:true,force:true});
|
|
65
|
+
}
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
const args=process.argv.slice(2);
|
|
69
|
+
try{
|
|
70
|
+
const node24=Number(process.versions.node.split('.')[0])>=24;
|
|
71
|
+
if(!node24&&args[0]!=='methods')throw fail('CONTEXT_RUNTIME_UNSUPPORTED');
|
|
72
|
+
if(node24){
|
|
73
|
+
({openContextProtocol}=await import('../lib/context-protocol.mjs'));
|
|
74
|
+
({verifySourceUnit}=await import('../lib/context-migration.mjs'));
|
|
75
|
+
({dispatchContextCall,contextRoot,allowedProjects}=await import('../lib/operations.mjs'));
|
|
76
|
+
({canonicalWorkspaceRefs,confirmWorkspaceOperator,assertWorkspaceUnclaimed,
|
|
77
|
+
withWorkspaceRegistryLock,rebindProjectWorkspaces,readOperatorWorkspaceReceipt}=
|
|
78
|
+
await import('../lib/workspace-operator.mjs'));
|
|
79
|
+
({createProjectDiagnosticBranch,auditLegacyProjectSources,
|
|
80
|
+
inspectLegacyRegistryReference}=
|
|
81
|
+
await import('../lib/project-diagnostic.mjs'));
|
|
82
|
+
}
|
|
83
|
+
const [command,sub,...rest]=args;
|
|
84
|
+
let value;
|
|
85
|
+
if(command==='methods'&&sub==='list'&&rest.length<=1)
|
|
86
|
+
value=listMethods(rest[0]==='--json'?undefined:rest[0]);
|
|
87
|
+
else if(command==='methods'&&sub==='describe'&&rest.length===1)
|
|
88
|
+
value=describeMethod(rest[0]);
|
|
89
|
+
else if(command==='request'&&sub==='--json'&&rest.length===0){
|
|
90
|
+
const payload=await stdinJson();
|
|
91
|
+
if(!payload||typeof payload!=='object'||Array.isArray(payload))throw fail('INVALID_ARGUMENT');
|
|
92
|
+
const method=validateContextCall(
|
|
93
|
+
payload.operation&&['sdk.methods.list','sdk.methods.describe'].includes(payload.operation)?
|
|
94
|
+
'chat_loop_context_get':
|
|
95
|
+
// A method is always assigned a fixed read/write mode by the SDK Catalog.
|
|
96
|
+
methodById.get(payload.operation)?.mode==='write'?
|
|
97
|
+
'chat_loop_context_mutate':'chat_loop_context_get',payload);
|
|
98
|
+
value=await dispatchContextCall(method.mode==='write'?
|
|
99
|
+
'chat_loop_context_mutate':'chat_loop_context_get',payload);
|
|
100
|
+
}else if(command==='project'&&sub==='init'&&(rest.length===2||rest.length===3))
|
|
101
|
+
value=await registerProject(rest[0],rest[1],rest.slice(2));
|
|
102
|
+
else if(command==='project'&&sub==='register'&&rest.length>=3&&rest.length<=18)
|
|
103
|
+
value=await registerProject(rest[0],rest[1],rest.slice(2),true);
|
|
104
|
+
else if(command==='project'&&sub==='bind'&&rest.length>=4&&rest.length<=20){
|
|
105
|
+
const [projectId,revision,epoch,requestId,...paths]=rest;
|
|
106
|
+
if(paths.length===1&&paths[0]==='--clear')paths.length=0;
|
|
107
|
+
value=await rebindProjectWorkspaces({projectId,
|
|
108
|
+
expectedProjectRevision:Number(revision),expectedStoreEpoch:epoch,
|
|
109
|
+
writeRequestId:requestId,workspaces:paths});
|
|
110
|
+
}else if(command==='project'&&sub==='receipt'&&rest.length===3)
|
|
111
|
+
value=await readOperatorWorkspaceReceipt({projectId:rest[0],
|
|
112
|
+
storeEpoch:rest[1],writeRequestId:rest[2]});
|
|
113
|
+
else if(command==='project'&&sub==='reconcile-reference'&&rest.length===10){
|
|
114
|
+
const [projectId,sourceDb,expectedStoreEpoch,sourceUnitId,revision,
|
|
115
|
+
taskId,originalArchivePath,expectedCurrentHash,reviewRef,writeRequestId]=rest;
|
|
116
|
+
if(process.env.CHAT_LOOP_CONTEXT_ADMIN_ENABLE!=='1')throw fail('ADMIN_REQUIRED');
|
|
117
|
+
if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
|
|
118
|
+
if(process.env.CHAT_LOOP_CONTEXT_DB)throw fail('EXPLICIT_DB_INIT_REQUIRED');
|
|
119
|
+
const expectedMigrationRevision=Number(revision);
|
|
120
|
+
if(!Number.isSafeInteger(expectedMigrationRevision)||expectedMigrationRevision<1)
|
|
121
|
+
throw fail('MIGRATION_VERSION_CONFLICT');
|
|
122
|
+
// Fail closed before any writable handle exists. Review is NOT user R/P.
|
|
123
|
+
const evidence=inspectLegacyRegistryReference({sourceDb,projectId,
|
|
124
|
+
expectedStoreEpoch,sourceUnitId,taskId,archiveFile:originalArchivePath});
|
|
125
|
+
if(evidence.changeKind!=='INSERTIONS_ONLY'||
|
|
126
|
+
evidence.currentTaskHash!==expectedCurrentHash)
|
|
127
|
+
throw fail('REGISTRY_REFERENCE_VERSION_CONFLICT');
|
|
128
|
+
await confirmWorkspaceOperator('RECONCILE_REFERENCE',projectId,
|
|
129
|
+
expectedMigrationRevision,[sourceDb,sourceUnitId,taskId,
|
|
130
|
+
evidence.archivedTaskHash,expectedCurrentHash,reviewRef]);
|
|
131
|
+
const db=openContextProtocol(sourceDb,{principalId:'local-operator',
|
|
132
|
+
authorizeData:(_mode,p)=>p===projectId,
|
|
133
|
+
authorizeAdmin:(op,p)=>p===projectId&&[
|
|
134
|
+
'migration.reference.reconcile',
|
|
135
|
+
'migration.reference.reconcile.reviewed'].includes(op)});
|
|
136
|
+
try{
|
|
137
|
+
value=db.migrationReconcileReference({projectId,sourceUnitId,
|
|
138
|
+
expectedMigrationRevision,expectedStoreEpoch,writeRequestId,
|
|
139
|
+
taskId,originalArchivePath,expectedCurrentHash,
|
|
140
|
+
sourceHash:evidence.sourceHash,reviewRef});
|
|
141
|
+
}finally{db.close()}
|
|
142
|
+
}else if(command==='project'&&['reconcile-receipt','migration-receipt'].includes(sub)&&rest.length===4){
|
|
143
|
+
const [projectId,sourceDb,storeEpoch,writeRequestId]=rest;
|
|
144
|
+
if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
|
|
145
|
+
const db=openContextProtocol(sourceDb,{readOnly:true,
|
|
146
|
+
principalId:'local-operator',
|
|
147
|
+
authorizeData:(_mode,p)=>p===projectId});
|
|
148
|
+
try{value=db.requestStatus({projectId,storeEpoch,writeRequestId})}
|
|
149
|
+
finally{db.close()}
|
|
150
|
+
}else if(command==='project'&&sub==='classify-evidence'&&rest.length===8){
|
|
151
|
+
const [projectId,sourceDb,expectedStoreEpoch,sourceUnitId,revision,
|
|
152
|
+
sourceHash,reviewRef,writeRequestId]=rest;
|
|
153
|
+
if(process.env.CHAT_LOOP_CONTEXT_ADMIN_ENABLE!=='1')throw fail('ADMIN_REQUIRED');
|
|
154
|
+
if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
|
|
155
|
+
if(process.env.CHAT_LOOP_CONTEXT_DB)throw fail('EXPLICIT_DB_INIT_REQUIRED');
|
|
156
|
+
const expectedMigrationRevision=Number(revision);
|
|
157
|
+
if(!Number.isSafeInteger(expectedMigrationRevision)||expectedMigrationRevision<1)
|
|
158
|
+
throw fail('MIGRATION_VERSION_CONFLICT');
|
|
159
|
+
if(typeof reviewRef!=='string'||reviewRef.length<8||reviewRef.length>256)
|
|
160
|
+
throw fail('REVIEW_REFERENCE_REQUIRED');
|
|
161
|
+
// The historical body's original bytes must already be a matching
|
|
162
|
+
// LEGACY_UNVERIFIED Project Material, never a synthesized current Task.
|
|
163
|
+
const reader=openContextProtocol(sourceDb,{readOnly:true,
|
|
164
|
+
principalId:'local-operator',authorizeData:(_mode,p)=>p===projectId,
|
|
165
|
+
authorizeAdmin:(op,p)=>op==='migration.list'&&p===projectId});
|
|
166
|
+
let unit;
|
|
167
|
+
try{
|
|
168
|
+
if(reader.mode!=='ACTIVE')throw fail('STORE_DIAGNOSTIC_ONLY');
|
|
169
|
+
if(reader.epoch!==expectedStoreEpoch)throw fail('STALE_EPOCH');
|
|
170
|
+
unit=reader.migrationList(projectId).find(x=>x.sourceUnitId===sourceUnitId);
|
|
171
|
+
if(!unit||unit.status!=='SHADOW_RO'||
|
|
172
|
+
unit.manifest.sourceKind!=='MIXED_CONTEXT')
|
|
173
|
+
throw fail('MIXED_SOURCE_NOT_SHADOW');
|
|
174
|
+
if(unit.migrationRevision!==expectedMigrationRevision)
|
|
175
|
+
throw fail('MIGRATION_VERSION_CONFLICT');
|
|
176
|
+
if(unit.sourceHash!==sourceHash)throw fail('SOURCE_CHANGED');
|
|
177
|
+
verifySourceUnit(unit.manifest);
|
|
178
|
+
const material=reader.projectMaterialList(projectId).filter(m=>
|
|
179
|
+
m.sourcePath===unit.sourcePath&&m.contentHash===sourceHash&&
|
|
180
|
+
m.provenance==='LEGACY_UNVERIFIED');
|
|
181
|
+
if(!material.some(m=>createHash('sha256').update(
|
|
182
|
+
reader.projectMaterialGet(projectId,m.materialId,m.version).body
|
|
183
|
+
).digest('hex')===sourceHash))throw fail('MIGRATION_BODY_NOT_IMPORTED');
|
|
184
|
+
}finally{reader.close()}
|
|
185
|
+
// Human-reviewed disposition: preserve FULL mixed history as
|
|
186
|
+
// EvidenceOnly/UNKNOWN. Do not assert any current Task or R/P fact.
|
|
187
|
+
await confirmWorkspaceOperator('CLASSIFY_EVIDENCE_ONLY',projectId,
|
|
188
|
+
expectedMigrationRevision,[sourceDb,sourceUnitId,sourceHash,reviewRef]);
|
|
189
|
+
const db=openContextProtocol(sourceDb,{principalId:'local-operator',
|
|
190
|
+
authorizeData:(_mode,p)=>p===projectId,
|
|
191
|
+
authorizeAdmin:(op,p)=>p===projectId&&
|
|
192
|
+
['migration.classify','migration.classify.reviewed'].includes(op)});
|
|
193
|
+
try{
|
|
194
|
+
value=db.migrationClassify({projectId,sourceUnitId,sourceHash,
|
|
195
|
+
expectedStoreEpoch,expectedMigrationRevision,writeRequestId,
|
|
196
|
+
classification:{projectId,sourceUnitId,sourceHash,
|
|
197
|
+
currentFactsComplete:true,reviewRef,taskContexts:[],
|
|
198
|
+
projectSharedContext:{},
|
|
199
|
+
unknownHistoryRefs:[{locator:unit.sourcePath,sourceHash}]}});
|
|
200
|
+
}finally{db.close()}
|
|
201
|
+
}else if(command==='project'&&sub==='inspect-reference'&&rest.length===6){
|
|
202
|
+
const [projectId,sourceDb,expectedStoreEpoch,sourceUnitId,taskId,archiveFile]=rest;
|
|
203
|
+
if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
|
|
204
|
+
value=inspectLegacyRegistryReference({projectId,sourceDb,
|
|
205
|
+
expectedStoreEpoch,sourceUnitId,taskId,archiveFile});
|
|
206
|
+
}else if(command==='project'&&sub==='audit-sources'&&rest.length===3){
|
|
207
|
+
const [projectId,sourceDb,expectedStoreEpoch]=rest;
|
|
208
|
+
if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
|
|
209
|
+
value=auditLegacyProjectSources({projectId,sourceDb,expectedStoreEpoch});
|
|
210
|
+
}else if(command==='project'&&sub==='stage-diagnostic'&&rest.length===4){
|
|
211
|
+
const [projectId,sourceDb,expectedStoreEpoch,revision]=rest;
|
|
212
|
+
if(process.env.CHAT_LOOP_CONTEXT_ADMIN_ENABLE!=='1')throw fail('ADMIN_REQUIRED');
|
|
213
|
+
if(!allowedProjects().has(projectId))throw fail('PROJECT_ACCESS_DENIED');
|
|
214
|
+
if(process.env.CHAT_LOOP_CONTEXT_DB)throw fail('EXPLICIT_DB_INIT_REQUIRED');
|
|
215
|
+
const expectedProjectRevision=Number(revision);
|
|
216
|
+
if(!Number.isSafeInteger(expectedProjectRevision)||expectedProjectRevision<1)
|
|
217
|
+
throw fail('PROJECT_VERSION_CONFLICT');
|
|
218
|
+
// This is an offline diagnostic extract; NEVER a source cutover.
|
|
219
|
+
// The operator must review the exact source path and source CAS identity.
|
|
220
|
+
await confirmWorkspaceOperator('STAGE_DIAGNOSTIC',projectId,
|
|
221
|
+
expectedProjectRevision,[sourceDb,expectedStoreEpoch]);
|
|
222
|
+
const root=contextRoot();
|
|
223
|
+
mkdirSync(root,{recursive:true,mode:0o700});
|
|
224
|
+
value=await withWorkspaceRegistryLock(root,()=>createProjectDiagnosticBranch({
|
|
225
|
+
sourceDb,targetRoot:root,projectId,expectedStoreEpoch,expectedProjectRevision
|
|
226
|
+
}));
|
|
227
|
+
}else if(command==='doctor'&&sub==='--json'&&rest.length===0)
|
|
228
|
+
value={status:'READY',packageVersion:CONTEXT_PACKAGE_VERSION,projectRoot:contextRoot()};
|
|
229
|
+
else throw fail('UNKNOWN_COMMAND');
|
|
230
|
+
output({ok:true,result:value});
|
|
231
|
+
}catch(error){
|
|
232
|
+
// Never expose arbitrary OS/SQLite exception messages, paths or user data.
|
|
233
|
+
const code=error.code||'CONTEXT_FAILED';
|
|
234
|
+
output({ok:false,error:{code:/^[A-Z0-9_]+$/.test(code)?code:'CONTEXT_FAILED'}});
|
|
235
|
+
process.exitCode=1;
|
|
236
|
+
}
|
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
// Local-only Context Manager administration. Never exposed through MCP tools.
|
|
2
|
+
// Activation requires explicit terminal operator consent and known-writer check.
|
|
3
|
+
// This is a SAME-UID trust boundary, not a proof of ChatGPT user identity.
|
|
4
|
+
import {realpathSync,existsSync,lstatSync,readFileSync} from 'node:fs';
|
|
5
|
+
import {randomUUID,createHash} from 'node:crypto';
|
|
6
|
+
import {execFileSync} from 'node:child_process';
|
|
7
|
+
import {createInterface} from 'node:readline/promises';
|
|
8
|
+
import {isAbsolute,resolve} from 'node:path';
|
|
9
|
+
import {DatabaseSync} from 'node:sqlite';
|
|
10
|
+
import {openContextProtocol} from './context-protocol.mjs';
|
|
11
|
+
import {parseContextAllowedProjects} from './methods.mjs';
|
|
12
|
+
import {scanSourceUnit,saveShadowManifest,readShadowManifest,
|
|
13
|
+
verifyShadowManifest,backupContextDb,createRecoveryManifest,restoreBackupToDiagnosticBranch} from './context-migration.mjs';
|
|
14
|
+
const fail=code=>Object.assign(new Error(code),{code});
|
|
15
|
+
const hash=x=>createHash('sha256').update(x).digest('hex');
|
|
16
|
+
const ID=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
|
|
17
|
+
const allowed=()=>parseContextAllowedProjects(process.env.CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS);
|
|
18
|
+
const verified=(projectId)=>{if(!allowed().has(projectId)||!ID.test(projectId||''))
|
|
19
|
+
throw fail('PROJECT_NOT_AUTHORIZED')};
|
|
20
|
+
async function operatorConfirm(expected){
|
|
21
|
+
if(!process.stdin.isTTY||!process.stdout.isTTY)throw fail('OPERATOR_TTY_REQUIRED');
|
|
22
|
+
const rl=createInterface({input:process.stdin,output:process.stdout});
|
|
23
|
+
try{
|
|
24
|
+
const answer=await rl.question('Confirm local Context cutover by typing '+expected+': ');
|
|
25
|
+
if(answer!==expected)throw fail('OPERATOR_CONFIRMATION_MISMATCH');
|
|
26
|
+
}finally{rl.close()}
|
|
27
|
+
}
|
|
28
|
+
function activeLegacyWriters(){
|
|
29
|
+
// Observable supported-client process inventory, NOT proof of every old
|
|
30
|
+
// npx cache or arbitrary same-UID shell. Operator must verify those too.
|
|
31
|
+
const output=execFileSync('/bin/ps',['-axo','pid=,command='],
|
|
32
|
+
{encoding:'utf8',timeout:5000,maxBuffer:2*1024*1024});
|
|
33
|
+
const pid=process.pid;
|
|
34
|
+
return output.split('\n').map(x=>x.trim()).filter(Boolean).filter(line=>{
|
|
35
|
+
const match=line.match(/^(\d+)\s+(.+)$/);
|
|
36
|
+
return match&&Number(match[1])!==pid
|
|
37
|
+
&&(/chatloop-tools\/bin\/cli\.mjs\s+mcp|@tomflow\/chatloop-tools.*\/bin\/cli\.mjs\s+mcp|chat-loop-local-tools.*\/bin\/cli\.mjs\s+mcp/.test(match[2]));
|
|
38
|
+
}).slice(0,20);
|
|
39
|
+
}
|
|
40
|
+
const open=(allowCreate=false)=>openContextProtocol(process.env.CHAT_LOOP_CONTEXT_DB,{
|
|
41
|
+
allowCreate,
|
|
42
|
+
principalId:'local-operator',
|
|
43
|
+
authorizeData:(_,p)=>allowed().has(p),
|
|
44
|
+
authorizeAdmin:()=>true
|
|
45
|
+
});
|
|
46
|
+
const readBytes=(file)=>{
|
|
47
|
+
const st=lstatSync(file);
|
|
48
|
+
if(!st.isFile()||st.isSymbolicLink())throw fail('SOURCE_UNTRUSTED');
|
|
49
|
+
return readFileSync(file);
|
|
50
|
+
};
|
|
51
|
+
const readOperatorReview=(file)=>{
|
|
52
|
+
if(!isAbsolute(file))throw fail('REVIEW_PATH_INVALID');
|
|
53
|
+
const st=lstatSync(file);
|
|
54
|
+
if(!st.isFile()||st.isSymbolicLink()||(st.mode&0o077)
|
|
55
|
+
||(process.getuid&&st.uid!==process.getuid())
|
|
56
|
+
||st.size===0||st.size>1024*1024)throw fail('REVIEW_FILE_UNTRUSTED');
|
|
57
|
+
let reviewed;
|
|
58
|
+
try{reviewed=JSON.parse(readFileSync(file,'utf8'))}
|
|
59
|
+
catch{throw fail('REVIEW_FILE_INVALID')}
|
|
60
|
+
return reviewed;
|
|
61
|
+
};
|
|
62
|
+
const write=(a,o={})=>({projectId:a.projectId,expectedStoreEpoch:o.epoch,
|
|
63
|
+
writeRequestId:randomUUID(),...a});
|
|
64
|
+
export async function runContextCli(argv,{confirm=operatorConfirm}={}){
|
|
65
|
+
if(Number(process.versions.node.split('.')[0])<24)throw fail('CONTEXT_RUNTIME_UNSUPPORTED');
|
|
66
|
+
if(!process.env.CHAT_LOOP_CONTEXT_DB||!isAbsolute(process.env.CHAT_LOOP_CONTEXT_DB))
|
|
67
|
+
throw fail('CONTEXT_DB_NOT_CONFIGURED');
|
|
68
|
+
allowed(); // Reject malformed or ambiguous grants before all admin actions.
|
|
69
|
+
const [action,...params]=argv;
|
|
70
|
+
if(action==='doctor'){
|
|
71
|
+
if(params.length)throw fail('INVALID_ARGUMENT');
|
|
72
|
+
const db=open();
|
|
73
|
+
try{return {status:'INSPECTED',...db.integrity(),pragmas:db.pragmas()}}
|
|
74
|
+
finally{db.close()}
|
|
75
|
+
}
|
|
76
|
+
if(action==='init'){
|
|
77
|
+
if(params.length)throw fail('INVALID_ARGUMENT');
|
|
78
|
+
const db=open(true);
|
|
79
|
+
try{return {status:'READY',storeEpoch:db.epoch,pragmas:db.pragmas()}}
|
|
80
|
+
finally{db.close()}
|
|
81
|
+
}
|
|
82
|
+
if(action==='scan'){
|
|
83
|
+
if(params.length!==4)throw fail('INVALID_ARGUMENT');
|
|
84
|
+
const [projectId,kind,path,manifestPath]=params;
|
|
85
|
+
verified(projectId);
|
|
86
|
+
const source=scanSourceUnit({projectId,kind,sourcePath:path});
|
|
87
|
+
const manifest=saveShadowManifest(manifestPath,[source]);
|
|
88
|
+
return {status:'SHADOW_RO',sourceUnit:source,manifestPath,
|
|
89
|
+
manifestId:manifest.instanceLineage};
|
|
90
|
+
}
|
|
91
|
+
if(action==='backup'){
|
|
92
|
+
if(params.length!==1)throw fail('INVALID_ARGUMENT');
|
|
93
|
+
const db=open(),target=params[0];db.close();
|
|
94
|
+
const raw=new DatabaseSync(process.env.CHAT_LOOP_CONTEXT_DB);
|
|
95
|
+
try{return await backupContextDb(raw,target)}
|
|
96
|
+
finally{raw.close()}
|
|
97
|
+
}
|
|
98
|
+
if(action==='restore-branch'){
|
|
99
|
+
if(params.length!==4)throw fail('INVALID_ARGUMENT');
|
|
100
|
+
const [backupFile,targetDb,expectedBackupHash,manifestFile]=params;
|
|
101
|
+
// Recovery branch creation never imports Browser Owner and never opens
|
|
102
|
+
// this branch for business writes until reauthorization/reconciliation.
|
|
103
|
+
await confirm('RESTORE_DIAGNOSTIC '+targetDb);
|
|
104
|
+
return restoreBackupToDiagnosticBranch({
|
|
105
|
+
backupFile,targetDb,expectedBackupHash,manifestFile});
|
|
106
|
+
}
|
|
107
|
+
if(action==='project-create'){
|
|
108
|
+
if(params.length!==2)throw fail('INVALID_ARGUMENT');
|
|
109
|
+
const [projectId,title]=params;verified(projectId);
|
|
110
|
+
const db=open();
|
|
111
|
+
try{return db.projectCreate(write({projectId,title},{epoch:db.epoch}))}
|
|
112
|
+
finally{db.close()}
|
|
113
|
+
}
|
|
114
|
+
if(action==='shadow'){
|
|
115
|
+
if(params.length!==2)throw fail('INVALID_ARGUMENT');
|
|
116
|
+
const [projectId,manifestPath]=params;verified(projectId);
|
|
117
|
+
const manifest=readShadowManifest(manifestPath);
|
|
118
|
+
if(manifest.sourceUnits.length!==1)throw fail('ONE_SOURCE_UNIT_REQUIRED');
|
|
119
|
+
const one=manifest.sourceUnits[0];
|
|
120
|
+
if(one.projectId!==projectId)throw fail('PROJECT_MISMATCH');
|
|
121
|
+
verifyShadowManifest(manifestPath);
|
|
122
|
+
const db=open();
|
|
123
|
+
try{return db.migrationShadow(write({projectId,...one,manifest:one},{epoch:db.epoch}))}
|
|
124
|
+
finally{db.close()}
|
|
125
|
+
}
|
|
126
|
+
if(action==='status'){
|
|
127
|
+
if(params.length!==1)throw fail('INVALID_ARGUMENT');
|
|
128
|
+
const projectId=params[0];verified(projectId);
|
|
129
|
+
const db=open();
|
|
130
|
+
try{
|
|
131
|
+
const sourceUnits=db.migrationList(projectId);
|
|
132
|
+
const materials=db.projectMaterialList(projectId);
|
|
133
|
+
const project=db.projectGet(projectId);
|
|
134
|
+
const tasks=db.taskList(projectId);
|
|
135
|
+
return {status:'OK',projectId,storeMode:db.mode,
|
|
136
|
+
projectRevision:project.projectRevision,
|
|
137
|
+
authority:db.registryAuthority(projectId),
|
|
138
|
+
businessAuthority:db.projectBusinessAuthority(projectId),
|
|
139
|
+
// Registry authority is NOT the authority of every physical SourceUnit.
|
|
140
|
+
sourceUnits,materialCount:materials.length,materials,
|
|
141
|
+
taskCount:tasks.length,taskRefs:tasks.map(t=>({taskId:t.taskId,
|
|
142
|
+
taskRevision:t.taskRevision}))};
|
|
143
|
+
}
|
|
144
|
+
finally{db.close()}
|
|
145
|
+
}
|
|
146
|
+
if(action==='classify'){
|
|
147
|
+
if(params.length!==3)throw fail('INVALID_ARGUMENT');
|
|
148
|
+
const [projectId,manifestPath,reviewPath]=params;verified(projectId);
|
|
149
|
+
verifyShadowManifest(manifestPath);
|
|
150
|
+
const manifest=readShadowManifest(manifestPath);
|
|
151
|
+
if(manifest.sourceUnits.length!==1)throw fail('ONE_SOURCE_UNIT_REQUIRED');
|
|
152
|
+
const unit=manifest.sourceUnits[0];
|
|
153
|
+
if(unit.projectId!==projectId||unit.sourceKind!=='MIXED_CONTEXT')
|
|
154
|
+
throw fail('MIXED_SOURCE_REQUIRED');
|
|
155
|
+
const classification=readOperatorReview(reviewPath);
|
|
156
|
+
const db=open();
|
|
157
|
+
try{
|
|
158
|
+
const stage=db.migrationList(projectId).find(r=>r.sourceUnitId===unit.sourceUnitId);
|
|
159
|
+
if(stage?.status!=='SHADOW_RO')throw fail('MIGRATION_STAGE_MISMATCH');
|
|
160
|
+
if(stage.sourceHash!==unit.sourceHash)throw fail('SOURCE_CHANGED');
|
|
161
|
+
// The operator reviews exactly one physical source and its full
|
|
162
|
+
// EvidenceOnly reference; this does NOT certify historical authorship.
|
|
163
|
+
await confirm('CLASSIFY '+projectId+' '+unit.sourceUnitId);
|
|
164
|
+
verifyShadowManifest(manifestPath);
|
|
165
|
+
return db.migrationClassify(write({
|
|
166
|
+
projectId,sourceUnitId:unit.sourceUnitId,sourceHash:unit.sourceHash,
|
|
167
|
+
expectedMigrationRevision:stage.migrationRevision,classification
|
|
168
|
+
},{epoch:db.epoch}));
|
|
169
|
+
}finally{db.close()}
|
|
170
|
+
}
|
|
171
|
+
if(action==='import-sources'){
|
|
172
|
+
if(params.length!==2)throw fail('INVALID_ARGUMENT');
|
|
173
|
+
const [projectId,reviewPath]=params;verified(projectId);
|
|
174
|
+
const review=readOperatorReview(reviewPath);
|
|
175
|
+
if(review?.projectId!==projectId||!Array.isArray(review.materials)
|
|
176
|
+
||review.materials.length<1||review.materials.length>128)
|
|
177
|
+
throw fail('SOURCE_IMPORT_REVIEW_INVALID');
|
|
178
|
+
const root=realpathSync(review.sourceRoot);
|
|
179
|
+
const seen=new Set();
|
|
180
|
+
// Hash-check the FULL bytes before prompting. Never infer R/P approvals,
|
|
181
|
+
// task identities or an active checkpoint from legacy Markdown.
|
|
182
|
+
const materials=review.materials.map(item=>{
|
|
183
|
+
if(typeof item.materialId!=='string'||!ID.test(item.materialId)
|
|
184
|
+
||seen.has(item.materialId)||!['INSTRUCTIONS','HISTORY','LEGACY_EVIDENCE','REFERENCE'].includes(item.kind)
|
|
185
|
+
||typeof item.path!=='string'||!isAbsolute(item.path)
|
|
186
|
+
||typeof item.sha256!=='string'||!/^[a-f0-9]{64}$/.test(item.sha256))
|
|
187
|
+
throw fail('SOURCE_IMPORT_REVIEW_INVALID');
|
|
188
|
+
seen.add(item.materialId);
|
|
189
|
+
const original=realpathSync(item.path);
|
|
190
|
+
if(!original.startsWith(root+'/'))throw fail('SOURCE_OUTSIDE_ROOT');
|
|
191
|
+
const bytes=readBytes(item.path);
|
|
192
|
+
if(bytes.length>4*1024*1024)throw fail('SOURCE_TOO_LARGE');
|
|
193
|
+
if(hash(bytes)!==item.sha256)throw fail('SOURCE_CHANGED');
|
|
194
|
+
const body=bytes.toString('utf8');
|
|
195
|
+
if(!Buffer.from(body,'utf8').equals(bytes))throw fail('SOURCE_NOT_UTF8');
|
|
196
|
+
return {materialId:item.materialId,kind:item.kind,body,
|
|
197
|
+
contentHash:item.sha256,sourcePath:original};
|
|
198
|
+
});
|
|
199
|
+
const db=open();
|
|
200
|
+
try{
|
|
201
|
+
const before=db.projectMaterialList(projectId);
|
|
202
|
+
for(const item of materials){
|
|
203
|
+
const prev=before.find(v=>v.materialId===item.materialId&&v.version===1);
|
|
204
|
+
if(prev && (prev.contentHash!==item.contentHash||prev.kind!==item.kind
|
|
205
|
+
||prev.sourcePath!==item.sourcePath))
|
|
206
|
+
throw fail('IMPORTED_SOURCE_CONFLICT');
|
|
207
|
+
}
|
|
208
|
+
await confirm('IMPORT_SOURCES '+projectId);
|
|
209
|
+
// The operator may spend time reviewing the manifest. Ensure no source
|
|
210
|
+
// changed between preflight and the first durable Store mutation.
|
|
211
|
+
for(const item of materials)
|
|
212
|
+
if(hash(readBytes(item.sourcePath))!==item.contentHash)
|
|
213
|
+
throw fail('SOURCE_CHANGED');
|
|
214
|
+
const imported=[];
|
|
215
|
+
for(const item of materials){
|
|
216
|
+
const prior=db.projectMaterialList(projectId)
|
|
217
|
+
.find(v=>v.materialId===item.materialId&&v.version===1);
|
|
218
|
+
if(!prior){
|
|
219
|
+
const version=db.projectGet(projectId).projectRevision;
|
|
220
|
+
db.projectMaterialPut(write({...item,projectId,version:1,
|
|
221
|
+
expectedProjectRevision:version,provenance:'LEGACY_UNVERIFIED'},
|
|
222
|
+
{epoch:db.epoch}));
|
|
223
|
+
}
|
|
224
|
+
const readBack=db.projectMaterialGet(projectId,item.materialId,1);
|
|
225
|
+
if(hash(Buffer.from(readBack.body,'utf8'))!==item.contentHash)
|
|
226
|
+
throw fail('SOURCE_IMPORT_VERIFY_FAILED');
|
|
227
|
+
imported.push({materialId:item.materialId,sha256:item.contentHash,
|
|
228
|
+
provenance:'LEGACY_UNVERIFIED'});
|
|
229
|
+
}
|
|
230
|
+
return {status:'EVIDENCE_STAGED_NOT_CUTOVER',projectId,imported,
|
|
231
|
+
approvalsImported:false,ownerImported:false,checkpointImported:false,
|
|
232
|
+
currentAuthority:'LEGACY_RW'};
|
|
233
|
+
}finally{db.close()}
|
|
234
|
+
}
|
|
235
|
+
if(action==='prepare'){
|
|
236
|
+
if(params.length!==5)throw fail('INVALID_ARGUMENT');
|
|
237
|
+
const [projectId,sourceUnitId,manifestPath,backupPath,recoveryPath]=params;
|
|
238
|
+
verified(projectId);
|
|
239
|
+
verifyShadowManifest(manifestPath);
|
|
240
|
+
const manifest=readShadowManifest(manifestPath);
|
|
241
|
+
const unit=manifest.sourceUnits.find(x=>x.sourceUnitId===sourceUnitId
|
|
242
|
+
&&x.projectId===projectId);
|
|
243
|
+
if(!unit)throw fail('SOURCE_UNIT_NOT_FOUND');
|
|
244
|
+
// Fail BEFORE creating backup/recovery artifacts if classification or
|
|
245
|
+
// revision is already known to be ineligible for a write cutover.
|
|
246
|
+
const preflight=open();
|
|
247
|
+
try{
|
|
248
|
+
const stage=preflight.migrationList(projectId).find(r=>r.sourceUnitId===sourceUnitId);
|
|
249
|
+
if(stage?.status!=='SHADOW_RO')throw fail('MIGRATION_STAGE_MISMATCH');
|
|
250
|
+
if(stage.sourceHash!==unit.sourceHash)throw fail('SOURCE_CHANGED');
|
|
251
|
+
if(unit.sourceKind==='MIXED_CONTEXT' &&
|
|
252
|
+
stage.manifest.classification?.currentFactsComplete!==true)
|
|
253
|
+
throw fail('MIXED_SOURCE_UNCLASSIFIED');
|
|
254
|
+
}finally{preflight.close()}
|
|
255
|
+
await confirm('PREPARE '+projectId+' '+sourceUnitId);
|
|
256
|
+
const raw=new DatabaseSync(process.env.CHAT_LOOP_CONTEXT_DB);
|
|
257
|
+
let backup;
|
|
258
|
+
try{backup=await backupContextDb(raw,backupPath)}
|
|
259
|
+
finally{raw.close()}
|
|
260
|
+
const db=open();
|
|
261
|
+
try{
|
|
262
|
+
const stage=db.migrationList(projectId).find(r=>r.sourceUnitId===sourceUnitId);
|
|
263
|
+
if(stage?.status!=='SHADOW_RO')throw fail('MIGRATION_STAGE_MISMATCH');
|
|
264
|
+
if(stage.sourceHash!==unit.sourceHash)throw fail('SOURCE_CHANGED');
|
|
265
|
+
const recovery=createRecoveryManifest(recoveryPath,{
|
|
266
|
+
projectId,taskId:'migration-meta',storeEpoch:db.epoch,
|
|
267
|
+
storeLineage:manifest.instanceLineage,
|
|
268
|
+
checkpointRef:null,backupRef:backup,
|
|
269
|
+
unknownEffects:unit.unknownItems??[]});
|
|
270
|
+
return db.migrationPrepare(write({projectId,sourceUnitId,
|
|
271
|
+
expectedMigrationRevision:stage.migrationRevision,sourceHash:unit.sourceHash,
|
|
272
|
+
backupHash:backup.hash,recoveryManifestHash:hash(readBytes(recoveryPath))},
|
|
273
|
+
{epoch:db.epoch}));
|
|
274
|
+
}finally{db.close()}
|
|
275
|
+
}
|
|
276
|
+
if(action==='activate'){
|
|
277
|
+
if(params.length!==3)throw fail('INVALID_ARGUMENT');
|
|
278
|
+
const [projectId,sourceUnitId,manifestPath]=params;verified(projectId);
|
|
279
|
+
verifyShadowManifest(manifestPath);
|
|
280
|
+
const manifest=readShadowManifest(manifestPath);
|
|
281
|
+
const unit=manifest.sourceUnits.find(x=>x.sourceUnitId===sourceUnitId
|
|
282
|
+
&&x.projectId===projectId);
|
|
283
|
+
if(!unit)throw fail('SOURCE_UNIT_NOT_FOUND');
|
|
284
|
+
const writers=activeLegacyWriters();
|
|
285
|
+
if(writers.length)throw Object.assign(fail('KNOWN_LEGACY_WRITER_ACTIVE'),{writers});
|
|
286
|
+
const db=open();
|
|
287
|
+
try{
|
|
288
|
+
const stage=db.migrationList(projectId).find(r=>r.sourceUnitId===sourceUnitId);
|
|
289
|
+
if(stage?.status!=='CUTOVER_FENCED')throw fail('MIGRATION_STAGE_MISMATCH');
|
|
290
|
+
if(stage?.sourceHash!==unit.sourceHash)throw fail('SOURCE_CHANGED');
|
|
291
|
+
// No model payload grants authorization; operator confirms exact physical
|
|
292
|
+
// unit after inspecting old clients/caches and the private backup.
|
|
293
|
+
await confirm('ACTIVATE '+projectId+' '+sourceUnitId);
|
|
294
|
+
if(activeLegacyWriters().length)throw fail('KNOWN_LEGACY_WRITER_ACTIVE');
|
|
295
|
+
return db.migrationActivate(write({projectId,sourceUnitId,
|
|
296
|
+
expectedMigrationRevision:stage.migrationRevision,sourceHash:unit.sourceHash},
|
|
297
|
+
{epoch:db.epoch}));
|
|
298
|
+
}finally{db.close()}
|
|
299
|
+
}
|
|
300
|
+
throw fail('CONTEXT_ADMIN_OPERATION_UNKNOWN');
|
|
301
|
+
}
|