@tomflow/chatloop-tools 0.9.44 → 0.9.46
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 +9 -2
- package/bin/cli.mjs +12 -5
- package/index.mjs +59 -12
- package/lib/adapters/mcp-child.mjs +142 -30
- package/lib/adapters/tunnel.mjs +22 -11
- package/lib/context-control-auth.mjs +0 -5
- package/lib/context-gateway.mjs +14 -1
- package/lib/control.mjs +27 -8
- package/lib/extension-cli-contract.mjs +5 -3
- package/lib/extension-proxy.mjs +80 -10
- package/lib/gateway.mjs +20 -8
- package/lib/release-health-checks.mjs +49 -12
- package/lib/release-owner-preflight.mjs +1 -2
- package/lib/release-upgrade.mjs +6 -2
- package/lib/release.mjs +27 -6
- package/lib/supervisor-observability.mjs +2 -2
- package/lib/supervisor-runtime.mjs +96 -33
- package/lib/trace-gateway.mjs +64 -42
- package/lib/tunnel.mjs +15 -5
- package/node_modules/@tomflow/chatloop-context/README.md +2 -2
- package/node_modules/@tomflow/chatloop-context/docs/interfaces.md +1 -1
- package/node_modules/@tomflow/chatloop-context/docs/operator-and-migration.md +1 -1
- package/node_modules/@tomflow/chatloop-context/lib/api-log.mjs +1 -1
- package/node_modules/@tomflow/chatloop-context/lib/approval-policy.mjs +2 -7
- package/node_modules/@tomflow/chatloop-context/lib/capability-router.mjs +3 -1
- package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +8 -3
- package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +13 -7
- package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +12 -8
- package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +20 -3
- package/node_modules/@tomflow/chatloop-context/lib/project-branch.mjs +8 -4
- package/node_modules/@tomflow/chatloop-context/lib/project-store.mjs +5 -3
- package/node_modules/@tomflow/chatloop-context/package.json +3 -3
- package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +14 -6
- package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +26 -7
- package/node_modules/@tomflow/chatloop-extension/extension/actions/clean.js +6 -3
- package/node_modules/@tomflow/chatloop-extension/extension/actions/common.js +5 -2
- package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +22 -4
- package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +19 -4
- package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +4 -2
- package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +11 -3
- package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +2 -1
- package/node_modules/@tomflow/chatloop-extension/extension/loop/api-observation-queue.generated.js +11 -3
- package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-approval.js +10 -9
- package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +1 -1
- package/node_modules/@tomflow/chatloop-extension/extension/popup.js +9 -3
- package/node_modules/@tomflow/chatloop-extension/extension/worker/action-result.js +2 -2
- package/node_modules/@tomflow/chatloop-extension/extension/worker/action-take.js +8 -10
- package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-prepare.js +7 -2
- package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-recovery.js +2 -1
- package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-result.js +7 -1
- package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +16 -5
- package/node_modules/@tomflow/chatloop-extension/extension/worker/manual.js +5 -7
- package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +12 -3
- package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +35 -21
- package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-finished.js +11 -6
- package/node_modules/@tomflow/chatloop-extension/lib/api-observation-queue.mjs +11 -3
- package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +39 -5
- package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +5 -1
- package/node_modules/@tomflow/chatloop-extension/lib/owner-evidence.mjs +5 -1
- package/node_modules/@tomflow/chatloop-extension/lib/session-file.mjs +27 -3
- package/node_modules/@tomflow/chatloop-extension/package.json +2 -2
- package/node_modules/@tomflow/chatloop-trace/README.md +7 -2
- package/node_modules/@tomflow/chatloop-trace/lib/trace-reader.mjs +66 -36
- package/node_modules/@tomflow/chatloop-trace/lib/trace-retention.mjs +17 -4
- package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +30 -6
- package/node_modules/@tomflow/chatloop-trace/package.json +1 -1
- package/package.json +9 -9
- package/providers/context.mjs +5 -1
- package/providers/desktop.mjs +23 -6
- package/providers/document.mjs +5 -3
- package/providers/extension.mjs +6 -4
- package/providers/form.mjs +5 -3
- package/providers/runtime.mjs +14 -6
- package/providers/trace.mjs +3 -2
|
@@ -1,9 +1,14 @@
|
|
|
1
1
|
import {randomUUID} from 'node:crypto';
|
|
2
|
-
import {closeSync,
|
|
2
|
+
import {closeSync, lstatSync, openSync, readFileSync, unlinkSync, writeFileSync, chmodSync} from 'node:fs';
|
|
3
3
|
import {createServer} from 'node:net';
|
|
4
4
|
import {createSupervisorObservability} from './supervisor-observability.mjs';
|
|
5
5
|
// All internal dependencies are supplied as API contracts by index.mjs.
|
|
6
6
|
// Private modules never import or resolve another private implementation.
|
|
7
|
+
// A dangling symlink is an occupied IPC path, never proof of absence.
|
|
8
|
+
const entryOrMissing=path=>{
|
|
9
|
+
try{return lstatSync(path)}
|
|
10
|
+
catch(error){if(error.code==='ENOENT')return null;throw error}
|
|
11
|
+
};
|
|
7
12
|
let CONTRACT, VERSION, PACKAGE_VERSION, registry, paths, ensurePrivateDir, ACTIONS, createAdapter, createSupervisorTraceBridge, readObservationGrants, loadContextControlSecret, handleContextControl;
|
|
8
13
|
let connected=false;
|
|
9
14
|
export function configureSupervisor(ports){
|
|
@@ -17,26 +22,31 @@ export function configureSupervisor(ports){
|
|
|
17
22
|
|
|
18
23
|
export function runSupervisor(){
|
|
19
24
|
const catalog=registry(), records=new Map(), queues=new Map(), seen=new Map(), receipts=new Map();
|
|
20
|
-
//
|
|
21
|
-
//
|
|
22
|
-
// fails closed rather than re-dispatching a previously executed request.
|
|
25
|
+
// Side-effecting requests retain non-reusable IDs even after their replay
|
|
26
|
+
// cache entries expire. Pure status probes do not consume this finite budget.
|
|
23
27
|
const issuedIds=new Set();
|
|
24
28
|
const MAX_ISSUED_IDS=100000;
|
|
25
29
|
const MAX_REPLAY_RESULTS=128;
|
|
26
|
-
|
|
30
|
+
const REQUEST_ID=/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/;
|
|
31
|
+
function priorRequest(req,payload,readOnly=false){
|
|
27
32
|
const old=seen.get(req.requestId);
|
|
28
33
|
if(old)return old.payload===payload?old.promise:bad(req,'REQUEST_ID_REUSE');
|
|
29
34
|
if(issuedIds.has(req.requestId))return bad(req,'REQUEST_ID_EVICTED');
|
|
30
|
-
if(issuedIds.size>=MAX_ISSUED_IDS)
|
|
35
|
+
if(!readOnly&&issuedIds.size>=MAX_ISSUED_IDS)
|
|
36
|
+
return bad(req,'IDEMPOTENCY_CAPACITY');
|
|
31
37
|
return null;
|
|
32
38
|
}
|
|
33
|
-
function rememberRequest(id,payload,promise){
|
|
34
|
-
issuedIds.add(id);
|
|
39
|
+
function rememberRequest(id,payload,promise,readOnly=false){
|
|
40
|
+
if(!readOnly)issuedIds.add(id);
|
|
35
41
|
seen.set(id,{payload,promise});
|
|
36
42
|
if(seen.size>MAX_REPLAY_RESULTS)seen.delete(seen.keys().next().value);
|
|
37
43
|
}
|
|
38
44
|
const p=paths(), nonce=randomUUID();
|
|
39
|
-
const error=
|
|
45
|
+
const error=code=>{
|
|
46
|
+
const safe=/^[A-Z][A-Z0-9_]{1,95}$/.test(code||'')
|
|
47
|
+
?code:'UNKNOWN_RESULT';
|
|
48
|
+
return {code:safe,message:safe};
|
|
49
|
+
};
|
|
40
50
|
let recoveredGrants={};
|
|
41
51
|
try{recoveredGrants=readObservationGrants()||{}}catch{}
|
|
42
52
|
const observationGrants=Object.keys(recoveredGrants).length
|
|
@@ -52,15 +62,19 @@ const {log,traceHealth,handleTraceObservation,traceNativeReceipt,
|
|
|
52
62
|
recordApiObservation,apiUsage,flushPending}=observability;
|
|
53
63
|
const desiredTunnel=new Set(), recoveryAttempts=new Map();
|
|
54
64
|
let lockFd, server, idleTimer;
|
|
55
|
-
const after=rec=>rec ? rec.state : 'STOPPED';
|
|
56
65
|
function saveReceipt(id,state,result=null,errorCode=null){
|
|
66
|
+
// A confirmed late child reply must never be replaced by an earlier
|
|
67
|
+
// timeout's catch handler. A missing reply or child exit is not proof of
|
|
68
|
+
// failure, and is never promoted to FAILED after an unconfirmed call.
|
|
69
|
+
if(receipts.get(id)?.state==='COMPLETED'&&state!=='COMPLETED')return;
|
|
57
70
|
receipts.delete(id);
|
|
58
71
|
receipts.set(id,{state,result,errorCode});
|
|
59
72
|
if(receipts.size>128)receipts.delete(receipts.keys().next().value);
|
|
60
73
|
}
|
|
61
74
|
function receipt(req){
|
|
62
75
|
const id=req?.targetRequestId;
|
|
63
|
-
if(req?.contract!==CONTRACT||
|
|
76
|
+
if(req?.contract!==CONTRACT||!REQUEST_ID.test(req.requestId||'')
|
|
77
|
+
||!REQUEST_ID.test(id||''))
|
|
64
78
|
return bad(req,'INVALID_ARGUMENT');
|
|
65
79
|
const record=receipts.get(id);
|
|
66
80
|
return {contract:CONTRACT,requestId:req.requestId,status:'OK',
|
|
@@ -106,7 +120,7 @@ const bad=(req,code)=>({contract:CONTRACT,requestId:req?.requestId||null,action:
|
|
|
106
120
|
async function executeCall(req){
|
|
107
121
|
const invalid=()=>bad(req,'INVALID_ARGUMENT');
|
|
108
122
|
if(req.contract!==CONTRACT)return bad(req,'INCOMPATIBLE_VERSION');
|
|
109
|
-
if(
|
|
123
|
+
if(!REQUEST_ID.test(req.requestId||'')||
|
|
110
124
|
req.scope!=='tool'||typeof req.toolId!=='string'||typeof req.name!=='string'||
|
|
111
125
|
!req.args||typeof req.args!=='object'||Array.isArray(req.args)||
|
|
112
126
|
!Number.isInteger(req.deadlineMs)||req.deadlineMs<1000||req.deadlineMs>45000)return invalid();
|
|
@@ -121,18 +135,42 @@ async function executeCall(req){
|
|
|
121
135
|
const promise=serial(tool.id,async()=>{
|
|
122
136
|
try{
|
|
123
137
|
const adapter=adapterFor(tool);
|
|
124
|
-
if(typeof adapter.call!=='function')
|
|
138
|
+
if(typeof adapter.call!=='function'){
|
|
139
|
+
saveReceipt(req.requestId,'FAILED',null,'TOOL_UNAVAILABLE');
|
|
140
|
+
return bad(req,'TOOL_UNAVAILABLE');
|
|
141
|
+
}
|
|
125
142
|
const value=await adapter.call(tool,req.name,req.args,
|
|
126
143
|
{requestId:req.requestId,remaining:()=>Math.max(0,expires-Date.now()),
|
|
127
|
-
onLate:(
|
|
128
|
-
|
|
144
|
+
onLate:(lateError,value)=>{
|
|
145
|
+
const confirmed=!lateError&&value&&typeof value==='object'
|
|
146
|
+
&&Array.isArray(value.content);
|
|
147
|
+
const cause=confirmed?null:error(lateError?.code||'INVALID_REPLY').code;
|
|
148
|
+
saveReceipt(req.requestId,confirmed?'COMPLETED':'UNCONFIRMED',
|
|
149
|
+
confirmed?value:null,cause);
|
|
150
|
+
const childError=confirmed&&value.isError===true;
|
|
151
|
+
log('tool-call-late',{requestId:req.requestId,
|
|
152
|
+
status:confirmed?(childError?'FAILED':'OK'):'UNKNOWN',
|
|
153
|
+
...(childError?{errorCode:'MCP_TOOL_ERROR'}
|
|
154
|
+
:cause?{errorCode:cause}:{})});
|
|
155
|
+
}});
|
|
156
|
+
if(!value||typeof value!=='object'||!Array.isArray(value.content))
|
|
157
|
+
throw Object.assign(Error('MCP reply is not a tool result'),{code:'UNKNOWN_RESULT'});
|
|
129
158
|
saveReceipt(req.requestId,'COMPLETED',value);
|
|
130
|
-
|
|
159
|
+
// A valid child result is a completed transport receipt, but a tool
|
|
160
|
+
// isError payload is not a successful business call. Keep the actual
|
|
161
|
+
// result for its original ID and mark the soft control log FAILED.
|
|
162
|
+
const childError=value.isError===true;
|
|
163
|
+
log('tool-call',{requestId:req.requestId,toolId:tool.id,
|
|
164
|
+
toolName:req.name,status:childError?'FAILED':'OK',
|
|
165
|
+
...(childError?{errorCode:'MCP_TOOL_ERROR'}:{})});
|
|
131
166
|
return {contract:CONTRACT,requestId:req.requestId,status:'OK',result:value};
|
|
132
167
|
}catch(e){
|
|
133
|
-
const code=e
|
|
134
|
-
|
|
135
|
-
|
|
168
|
+
const code=error(e?.code||'UNKNOWN_RESULT').code;
|
|
169
|
+
const uncertain=['TIMEOUT','UNKNOWN_RESULT','TOOL_UNAVAILABLE',
|
|
170
|
+
'MCP_ERROR','INVALID_REPLY'].includes(code);
|
|
171
|
+
saveReceipt(req.requestId,uncertain?'UNCONFIRMED':'FAILED',null,code);
|
|
172
|
+
log('tool-call',{requestId:req.requestId,toolId:tool.id,toolName:req.name,
|
|
173
|
+
status:uncertain?'UNKNOWN':'FAILED',errorCode:code});
|
|
136
174
|
return bad(req,code);
|
|
137
175
|
}
|
|
138
176
|
});
|
|
@@ -148,7 +186,8 @@ async function execute(req){
|
|
|
148
186
|
!Number.isInteger(req.deadlineMs)||req.deadlineMs<1000||req.deadlineMs>30000)return bad(req,'INVALID_ARGUMENT');
|
|
149
187
|
let found;try{found=targets(req);}catch(e){return bad(req,e.code);}
|
|
150
188
|
const payload=JSON.stringify([req.action,req.scope,req.toolId||null,req.deadlineMs]);
|
|
151
|
-
const
|
|
189
|
+
const readOnly=req.action==='status';
|
|
190
|
+
const hit=priorRequest(req,payload,readOnly);
|
|
152
191
|
if(hit)return hit;
|
|
153
192
|
// Read-only status must never cancel idle shutdown.
|
|
154
193
|
if(req.action==='start'||req.action==='restart')clearTimeout(idleTimer);
|
|
@@ -196,7 +235,10 @@ async function execute(req){
|
|
|
196
235
|
}
|
|
197
236
|
return response;
|
|
198
237
|
})();
|
|
199
|
-
|
|
238
|
+
// Status still participates in the bounded replay cache, but cannot
|
|
239
|
+
// consume permanent tombstones reserved for potentially side-effecting
|
|
240
|
+
// requests. Old write IDs remain fenced after the cache evicts them.
|
|
241
|
+
rememberRequest(req.requestId,payload,promise,readOnly);
|
|
200
242
|
return promise;
|
|
201
243
|
}
|
|
202
244
|
async function shutdown(){
|
|
@@ -204,8 +246,17 @@ async function shutdown(){
|
|
|
204
246
|
// Closeout may flush final soft evidence, but never re-authorizes an action.
|
|
205
247
|
flushPending();
|
|
206
248
|
server?.close();
|
|
207
|
-
try{
|
|
208
|
-
|
|
249
|
+
try{
|
|
250
|
+
const socket=entryOrMissing(p.socket);
|
|
251
|
+
if(socket?.isSocket()&&!socket.isSymbolicLink()
|
|
252
|
+
&&(!process.getuid||socket.uid===process.getuid()))unlinkSync(p.socket);
|
|
253
|
+
}catch{}
|
|
254
|
+
try{
|
|
255
|
+
const lock=entryOrMissing(p.lock);
|
|
256
|
+
if(lock?.isFile()&&!lock.isSymbolicLink()&&!(lock.mode&0o077)
|
|
257
|
+
&&(!process.getuid||lock.uid===process.getuid())
|
|
258
|
+
&&JSON.parse(readFileSync(p.lock,'utf8')).nonce===nonce)unlinkSync(p.lock);
|
|
259
|
+
}catch{}
|
|
209
260
|
try{if(lockFd!==undefined)closeSync(lockFd);}catch{}
|
|
210
261
|
process.exit(0);
|
|
211
262
|
}
|
|
@@ -219,9 +270,12 @@ async function main(){
|
|
|
219
270
|
catch(err){if(err.code==='EEXIST')process.exit(0);throw err;}
|
|
220
271
|
writeFileSync(lockFd,JSON.stringify({pid:process.pid,nonce,version:VERSION,at:Date.now()}));
|
|
221
272
|
// A lock ensures no other manager may own this socket.
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
if(!
|
|
273
|
+
const oldSocket=entryOrMissing(p.socket);
|
|
274
|
+
if(oldSocket){
|
|
275
|
+
if(!oldSocket.isSocket()||oldSocket.isSymbolicLink()
|
|
276
|
+
||(oldSocket.mode&0o077)
|
|
277
|
+
||process.getuid&&oldSocket.uid!==process.getuid())
|
|
278
|
+
throw Error('Unknown socket ownership');
|
|
225
279
|
unlinkSync(p.socket);
|
|
226
280
|
}
|
|
227
281
|
server=createServer(socket=>{
|
|
@@ -234,11 +288,17 @@ async function main(){
|
|
|
234
288
|
const n=buf.indexOf('\n');if(n<0)return;
|
|
235
289
|
handled=true;
|
|
236
290
|
let req;try{req=JSON.parse(buf.slice(0,n));}catch{socket.end(JSON.stringify(bad({},'INVALID_ARGUMENT'))+'\n');return;}
|
|
237
|
-
|
|
291
|
+
// Even read-only health/Trace probes may throw synchronously. Convert
|
|
292
|
+
// them to one rejected IPC operation, never an uncaught socket callback.
|
|
293
|
+
let work;
|
|
294
|
+
try{work=req?.action==='__ping'?
|
|
238
295
|
Promise.resolve({contract:CONTRACT,version:VERSION,packageVersion:PACKAGE_VERSION,registrySignature:catalog.map(t=>t.id+':'+t.enabled).join('|'),ownerNonce:nonce,
|
|
239
296
|
managerPid:process.pid,traceHealth:traceHealth()}):req?.action==='__trace_health'
|
|
240
|
-
?Promise.resolve(
|
|
241
|
-
|
|
297
|
+
?Promise.resolve(req.contract===CONTRACT
|
|
298
|
+
&&REQUEST_ID.test(req.requestId||'')
|
|
299
|
+
?{contract:CONTRACT,requestId:req.requestId,
|
|
300
|
+
status:'OK',traceHealth:traceHealth()}
|
|
301
|
+
:bad(req,'INVALID_ARGUMENT'))
|
|
242
302
|
:req?.action==='__trace_observation'
|
|
243
303
|
?Promise.resolve().then(()=>handleTraceObservation(req))
|
|
244
304
|
.catch(e=>bad(req,e.code||'TRACE_RECORD_FAILED'))
|
|
@@ -250,13 +310,16 @@ async function main(){
|
|
|
250
310
|
.catch(e=>bad(req,e.code||'TRACE_USAGE_FAILED'))
|
|
251
311
|
:req?.action==='context-control'
|
|
252
312
|
?handleContextControl(req).then(result=>{
|
|
253
|
-
|
|
313
|
+
// Context already returned its authoritative business receipt.
|
|
314
|
+
// Soft Trace must not turn COMMITTED into FAILED after that point.
|
|
315
|
+
try{traceNativeReceipt(req)}catch{}
|
|
254
316
|
return {contract:CONTRACT,requestId:req.requestId,status:'OK',result};
|
|
255
|
-
}
|
|
256
|
-
log('context-control-error',{status:'FAILED',errorCode:e
|
|
257
|
-
return bad(req,e
|
|
317
|
+
},e=>{
|
|
318
|
+
log('context-control-error',{status:'FAILED',errorCode:e?.code||'CONTEXT_CONTROL_FAILED'});
|
|
319
|
+
return bad(req,e?.code||'CONTEXT_CONTROL_FAILED');
|
|
258
320
|
})
|
|
259
321
|
:req?.action==='call'?executeCall(req):req?.action==='receipt'?Promise.resolve(receipt(req)):execute(req);
|
|
322
|
+
}catch(e){work=Promise.reject(e)}
|
|
260
323
|
work.then(value=>socket.end(JSON.stringify(value)+'\n')).catch(err=>{
|
|
261
324
|
log('ipc-error',{code:err.code||'INTERNAL_ERROR'});
|
|
262
325
|
socket.end(JSON.stringify(bad(req,'INTERNAL_ERROR'))+'\n');
|
package/lib/trace-gateway.mjs
CHANGED
|
@@ -43,14 +43,18 @@ export const traceDiagnoseTool={
|
|
|
43
43
|
const STAGE_NAMES=['intent','project','tooling','requirements','plan','approval'];
|
|
44
44
|
const STAGE_OUTCOMES=['OBSERVED','BLOCKED','UNVERIFIED'];
|
|
45
45
|
const USER_EVIDENCE=/^user:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
46
|
-
const APP_TRACE_REF=new RegExp(UUID);
|
|
46
|
+
const APP_TRACE_REF=new RegExp('^'+UUID+'$');
|
|
47
47
|
const FORM_ID=/^[A-Za-z0-9][A-Za-z0-9_-]{7,79}$/;
|
|
48
48
|
const DOC_ID=/^[A-Za-z0-9][A-Za-z0-9_.-]{7,127}$/;
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
const
|
|
52
|
-
'
|
|
53
|
-
'mcp.
|
|
49
|
+
// The event-to-public-API map is the only catalogue of accepted App event
|
|
50
|
+
// types. Do not maintain a second pair of regex allowlists beside it.
|
|
51
|
+
const APP_EVENT_API=Object.freeze({
|
|
52
|
+
'form.prepared':'mcp.chat_loop_form__prepare',
|
|
53
|
+
'form.rendered':'mcp.chat_loop_form__render',
|
|
54
|
+
'form.submitted':'mcp.chat_loop_form__submit',
|
|
55
|
+
'document.shown':'mcp.chat_loop_document__show',
|
|
56
|
+
'document.rendered':'mcp.chat_loop_document__render'
|
|
57
|
+
});
|
|
54
58
|
export const traceStageTool={
|
|
55
59
|
name:'chat_loop_trace_stage',
|
|
56
60
|
description:'Record an explicitly SOFT agent-stage observation (including R/P revision) in the existing Trace writer. Optional user:<uuid> evidenceRef is a caller assertion, NOT verified host-click provenance; no approval/Owner/content is stored. Return traceId for later calls; never use this as task approval.',
|
|
@@ -73,7 +77,7 @@ export async function runTraceStage(args){
|
|
|
73
77
|
Object.keys(args).some(k=>!Object.hasOwn(traceStageTool.inputSchema.properties,k))||
|
|
74
78
|
!STAGE_NAMES.includes(args.stage)||
|
|
75
79
|
!STAGE_OUTCOMES.includes(args.outcome)||
|
|
76
|
-
args.traceId!==undefined&&!
|
|
80
|
+
args.traceId!==undefined&&!APP_TRACE_REF.test(args.traceId)||
|
|
77
81
|
args.evidenceRef!==undefined&&(!USER_EVIDENCE.test(args.evidenceRef)
|
|
78
82
|
||!['requirements','plan','approval'].includes(args.stage)))
|
|
79
83
|
throw fail('TRACE_INVALID_ARGUMENT');
|
|
@@ -87,8 +91,11 @@ export async function runTraceStage(args){
|
|
|
87
91
|
const r=await talk({contract:CONTRACT,action:'__trace_observation',
|
|
88
92
|
requestId,traceId,projectRef:args.projectRef,event,status,
|
|
89
93
|
...(args.evidenceRef?{evidenceRef:args.evidenceRef}:{})},1800);
|
|
90
|
-
if(r?.
|
|
91
|
-
throw fail(
|
|
94
|
+
if(r?.contract!==CONTRACT||r?.requestId!==requestId)
|
|
95
|
+
throw fail('TRACE_STAGE_RECEIPT_UNVERIFIED');
|
|
96
|
+
if(r.status!=='OK'||!APP_TRACE_REF.test(r.eventId||''))
|
|
97
|
+
throw fail(/^[A-Z][A-Z0-9_]{1,95}$/.test(r.error?.code||'')
|
|
98
|
+
?r.error.code:'TRACE_STAGE_NOT_RECORDED');
|
|
92
99
|
return {status:'RECORDED_SOFT',confidence:'SOFT_AGENT_OBSERVATION',
|
|
93
100
|
traceId,eventId:r.eventId,event,requestId,
|
|
94
101
|
...(args.evidenceRef?{evidenceRef:args.evidenceRef,
|
|
@@ -106,26 +113,28 @@ async function diagnoseAppTrace(args){
|
|
|
106
113
|
const reader=createTraceReader({filePath:paths().log,allowedProjects:['api_system']});
|
|
107
114
|
const base=await reader.diagnose({projectRef:'api_system',
|
|
108
115
|
sessionRef:args.sessionRef,maxEvents:args.maxEvents});
|
|
109
|
-
const appEvents=base.timeline.filter(event=>
|
|
110
|
-
event.sessionRef
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
116
|
+
const appEvents=base.timeline.filter(event=>{
|
|
117
|
+
if(event.sessionRef!==args.sessionRef
|
|
118
|
+
||typeof event.event!=='string')return false;
|
|
119
|
+
const suffix=event.event.slice(event.event.lastIndexOf('.')+1);
|
|
120
|
+
if(suffix!=='soft_observed'&&suffix!=='failed')return false;
|
|
121
|
+
const type=event.event.slice(0,event.event.lastIndexOf('.'));
|
|
122
|
+
if(!Object.hasOwn(APP_EVENT_API,type))return false;
|
|
123
|
+
const idPattern=type.startsWith('form.')?FORM_ID:DOC_ID;
|
|
124
|
+
return idPattern.test(event.evidenceRef||'');
|
|
125
|
+
});
|
|
126
|
+
const kind=appEvents.length
|
|
127
|
+
?appEvents[0].event.startsWith('document.')?'document':'form'
|
|
128
|
+
:'unknown';
|
|
129
|
+
const matching=kind==='unknown'?[]:
|
|
130
|
+
appEvents.filter(event=>event.event.startsWith(kind+'.'));
|
|
115
131
|
const prefix=kind.toUpperCase();
|
|
116
132
|
const gaps=base.gaps.filter(gap=>gap!=='NO_MATCHING_EVENTS');
|
|
117
133
|
const parentKeys=new Map();
|
|
118
134
|
for(const event of matching){
|
|
119
|
-
const
|
|
120
|
-
?'mcp.chat_loop_form__prepare'
|
|
121
|
-
:event.event.startsWith('form.rendered.')
|
|
122
|
-
?'mcp.chat_loop_form__render'
|
|
123
|
-
:event.event.startsWith('form.submitted.')
|
|
124
|
-
?'mcp.chat_loop_form__submit'
|
|
125
|
-
:event.event.startsWith('document.shown.')
|
|
126
|
-
?'mcp.chat_loop_document__show':'mcp.chat_loop_document__render';
|
|
135
|
+
const eventType=event.event.slice(0,event.event.lastIndexOf('.'));
|
|
127
136
|
if(!event.parentSpanId){gaps.push(prefix+'_API_PARENT_MISSING');continue}
|
|
128
|
-
parentKeys.set(event.traceId+':'+event.parentSpanId,
|
|
137
|
+
parentKeys.set(event.traceId+':'+event.parentSpanId,APP_EVENT_API[eventType]);
|
|
129
138
|
}
|
|
130
139
|
const apiEvents=[];
|
|
131
140
|
for(const traceId of new Set(matching.map(event=>event.traceId))){
|
|
@@ -136,8 +145,8 @@ async function diagnoseAppTrace(args){
|
|
|
136
145
|
.includes(gap))gaps.push(gap);
|
|
137
146
|
for(const event of query.timeline){
|
|
138
147
|
const key=event.traceId+':'+event.spanId;
|
|
139
|
-
if(event.event==='typed.api.call'&&parentKeys.get(key)===event.apiName
|
|
140
|
-
|
|
148
|
+
if(event.event==='typed.api.call'&&parentKeys.get(key)===event.apiName)
|
|
149
|
+
apiEvents.push(event);
|
|
141
150
|
}
|
|
142
151
|
}
|
|
143
152
|
for(const [key,apiName] of parentKeys){
|
|
@@ -161,17 +170,16 @@ async function diagnoseAppTrace(args){
|
|
|
161
170
|
const timeline=[...matching,...apiEvents]
|
|
162
171
|
.sort((a,b)=>Date.parse(a.time)-Date.parse(b.time));
|
|
163
172
|
const last=timeline.at(-1)||null;
|
|
173
|
+
const lastConfirmed=timeline.findLast(event=>event.status==='CONFIRMED');
|
|
164
174
|
const unknown=matching.some(event=>['UNKNOWN','BLOCKED'].includes(event.status));
|
|
165
175
|
return {traceId:null,projectRef:'api_system',
|
|
166
176
|
...(kind==='form'?{formTraceRef:args.sessionRef,formId:ids.length===1?ids[0]:null}
|
|
167
|
-
:{documentTraceRef:args.sessionRef,documentId:ids.length===1?ids[0]:null}
|
|
177
|
+
:kind==='document'?{documentTraceRef:args.sessionRef,documentId:ids.length===1?ids[0]:null}
|
|
178
|
+
:{appTraceRef:args.sessionRef,appKind:'UNVERIFIED'}),
|
|
168
179
|
inspected:timeline.length,totalMatched:timeline.length,
|
|
169
|
-
lastConfirmed:
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
time:[...timeline].reverse().find(event=>event.status==='CONFIRMED').time,
|
|
173
|
-
component:[...timeline].reverse().find(event=>event.status==='CONFIRMED').component}
|
|
174
|
-
:null,
|
|
180
|
+
lastConfirmed:lastConfirmed?{eventId:lastConfirmed.eventId,
|
|
181
|
+
event:lastConfirmed.event,time:lastConfirmed.time,
|
|
182
|
+
component:lastConfirmed.component}:null,
|
|
175
183
|
incompleteApiSpans:[],unmatchedApiTerminals:[],lastEvent:last,unknown,
|
|
176
184
|
gaps:[...new Set(gaps)],confidence:gaps.length?'INCOMPLETE':'TRACE_ONLY',
|
|
177
185
|
retryDisposition:unknown||gaps.length
|
|
@@ -195,19 +203,33 @@ export async function runTraceDiagnose(args){
|
|
|
195
203
|
:await createTraceReader({filePath:paths().log,
|
|
196
204
|
allowedProjects:getAllowedProjects()}).diagnose(args);
|
|
197
205
|
try{
|
|
206
|
+
const requestId=randomUUID();
|
|
198
207
|
const response=await talk({contract:CONTRACT,action:'__trace_health',
|
|
199
|
-
requestId
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
208
|
+
requestId},1400);
|
|
209
|
+
const health=response?.contract===CONTRACT
|
|
210
|
+
&&response.requestId===requestId&&response.status==='OK'
|
|
211
|
+
?response.traceHealth:null;
|
|
212
|
+
// The Supervisor reports persisted Writer health; the Gateway may
|
|
213
|
+
// independently degrade because a different App observation was lost.
|
|
214
|
+
// Do not turn process-wide counters into gaps on this traceRef/Project.
|
|
215
|
+
result.writerHealth=health?.writerStatus||health?.status||'UNAVAILABLE';
|
|
216
|
+
result.gatewayHealth=health?.status||'UNAVAILABLE';
|
|
217
|
+
if(health?.errorCode)result.writerErrorCode=health.errorCode;
|
|
218
|
+
const globalWarnings=[];
|
|
219
|
+
if(health?.formObservationLost>0)
|
|
220
|
+
globalWarnings.push('FORM_TRACE_OBSERVATION_LOSS');
|
|
221
|
+
if(health?.documentObservationLost>0)
|
|
222
|
+
globalWarnings.push('DOCUMENT_TRACE_OBSERVATION_LOSS');
|
|
223
|
+
if(globalWarnings.length)result.globalObservationWarnings=globalWarnings;
|
|
224
|
+
if(result.writerHealth==='TRACE_DEGRADED'){
|
|
225
|
+
result.gaps.push(health?.errorCode
|
|
226
|
+
?'TRACE_PIPELINE_HEALTH_DEGRADED'
|
|
227
|
+
:'TRACE_HEALTH_DEGRADED_UNCLASSIFIED');
|
|
228
|
+
}
|
|
205
229
|
}catch{result.writerHealth='UNAVAILABLE'}
|
|
206
230
|
if(result.writerHealth!=='OK'){
|
|
207
231
|
if(['UNKNOWN','UNAVAILABLE'].includes(result.writerHealth))
|
|
208
232
|
result.gaps.push('TRACE_WRITER_UNAVAILABLE');
|
|
209
|
-
if(result.writerHealth==='TRACE_DEGRADED')
|
|
210
|
-
result.gaps.push('TRACE_APP_OBSERVATION_LOSS');
|
|
211
233
|
result.confidence='INCOMPLETE';
|
|
212
234
|
result.retryDisposition='VERIFY_AUTHORITATIVE_RECEIPT_FIRST';
|
|
213
235
|
}
|
|
@@ -232,7 +254,7 @@ export async function observeExtensionResult(name,args,result){
|
|
|
232
254
|
const session=name==='status'&&proof?.session &&
|
|
233
255
|
typeof proof.session==='object'&&!Array.isArray(proof.session)
|
|
234
256
|
?proof.session:proof;
|
|
235
|
-
if(!session||!
|
|
257
|
+
if(!session||!APP_TRACE_REF.test(session.sessionId||''))return;
|
|
236
258
|
const intent=['continue','handoff'].includes(name);
|
|
237
259
|
if(intent&&(!/^[a-f0-9]{32}$/.test(proof.intentId||'')
|
|
238
260
|
||!['QUEUED','STATUS'].includes(proof.status)))return;
|
package/lib/tunnel.mjs
CHANGED
|
@@ -29,7 +29,11 @@ export function tunnelDoctor(){
|
|
|
29
29
|
const b=bundledTunnel();
|
|
30
30
|
return {status:'BUNDLED_READY',release:b.release,platform:b.platform,
|
|
31
31
|
executable:b.binary,cloudflared:b.cloudflared,verified:true,connection:'UNVERIFIED'};
|
|
32
|
-
}catch(e){
|
|
32
|
+
}catch(e){
|
|
33
|
+
const code=typeof e?.code==='string'&&/^[A-Z][A-Z0-9_]{1,95}$/.test(e.code)
|
|
34
|
+
?e.code:'INVALID_BUNDLE';
|
|
35
|
+
return {status:'BLOCKED',code,reason:code};
|
|
36
|
+
}
|
|
33
37
|
}
|
|
34
38
|
// Explicitly scoped to this product. Do not touch a sibling Local Dev profile.
|
|
35
39
|
export async function runTunnel(args){
|
|
@@ -43,11 +47,17 @@ export async function runTunnel(args){
|
|
|
43
47
|
await new Promise((resolve,reject)=>{
|
|
44
48
|
const child=spawn(b.binary,args,{stdio:'inherit',env:process.env,windowsHide:true,
|
|
45
49
|
cwd:b.base}); // Only this package's verified binary. Never use the system PATH.
|
|
46
|
-
child.
|
|
47
|
-
const
|
|
48
|
-
|
|
50
|
+
const forwardInt=()=>child.kill('SIGINT');
|
|
51
|
+
const forwardTerm=()=>child.kill('SIGTERM');
|
|
52
|
+
const cleanup=()=>{
|
|
53
|
+
process.off('SIGINT',forwardInt);process.off('SIGTERM',forwardTerm);
|
|
54
|
+
};
|
|
55
|
+
process.on('SIGINT',forwardInt);process.on('SIGTERM',forwardTerm);
|
|
56
|
+
// Spawn failure does not guarantee an 'exit' event. Never strand
|
|
57
|
+
// process-wide signal handlers after this owned child fails to launch.
|
|
58
|
+
child.once('error',error=>{cleanup();reject(error)});
|
|
49
59
|
child.once('exit',(code,signal)=>{
|
|
50
|
-
|
|
60
|
+
cleanup();
|
|
51
61
|
if(signal){process.exitCode=1;return resolve();}
|
|
52
62
|
process.exitCode=code===null?1:code;
|
|
53
63
|
resolve();
|
|
@@ -182,7 +182,7 @@ The npm executable is `chatloop-context`, installed by a fixed dependency
|
|
|
182
182
|
or invoked separately through a **pinned, available** npm version:
|
|
183
183
|
|
|
184
184
|
```sh
|
|
185
|
-
npm install --save-exact @tomflow/chatloop-context
|
|
185
|
+
npm install --save-exact "@tomflow/chatloop-context@${VERIFIED_CONTEXT_VERSION:?set-exact-verified-version}"
|
|
186
186
|
chatloop-context methods groups
|
|
187
187
|
chatloop-context methods list project
|
|
188
188
|
chatloop-context methods describe project.open
|
|
@@ -223,7 +223,7 @@ ownership boundaries and known coupling risks.
|
|
|
223
223
|
|
|
224
224
|
## Deployment is separate from source
|
|
225
225
|
|
|
226
|
-
|
|
226
|
+
The source version declared in [`package.json`](package.json) does **not** establish the connected MCP
|
|
227
227
|
version. Verify the real `sdk.methods.list` response, Node runtime,
|
|
228
228
|
pinned Tools dependency, package bytes and Project authority before any
|
|
229
229
|
separately authorized installation. Source refactoring does **not** migrate
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Context npm package — actual interface, consumer and dependency map
|
|
2
2
|
|
|
3
|
-
> Applies to the **source** package
|
|
3
|
+
> Applies to the **source** version declared in [`../package.json`](../package.json), not a fixed historical release.
|
|
4
4
|
> The connected MCP may still be running an earlier installed release.
|
|
5
5
|
> This document describes source contracts, not production cutover approval.
|
|
6
6
|
|
|
@@ -262,7 +262,7 @@ fence, R/P approval, UNKNOWN-send or browser Owner guards.
|
|
|
262
262
|
CURRENT ownership, old writers and true operator approval have been reviewed,
|
|
263
263
|
old app/Native/Registry clients fenced, fresh backup plus recovery tested and
|
|
264
264
|
the release/real Chrome E2E gates passed. See P0-02 in
|
|
265
|
-
`docs/research/chat-loop-context-cli-architecture-20261109.md
|
|
265
|
+
`docs/CONTEXT.md`(现行)及 `git show 5ec21b33e9e4:docs/research/chat-loop-context-cli-architecture-20261109.md`(历史).
|
|
266
266
|
|
|
267
267
|
## Safety
|
|
268
268
|
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// belong to the public @tomflow/chatloop-trace API, not a copied runtime.
|
|
4
4
|
import {createApiAspect} from '@tomflow/chatloop-trace';
|
|
5
5
|
|
|
6
|
-
|
|
6
|
+
const API_LOG_CONTRACT='chat-loop.context-api-log.v1';
|
|
7
7
|
const API=/^[a-z][A-Za-z0-9._-]{1,89}$/;
|
|
8
8
|
const REF=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
|
|
9
9
|
const CODE=/^[A-Z][A-Z0-9_]{1,95}$/;
|
|
@@ -1,11 +1,6 @@
|
|
|
1
1
|
// Context owns business approval policy. No SQLite, browser, MCP or Session state.
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
// not changing a count scattered through Run/Permit transactions.
|
|
5
|
-
export const APPROVAL_POLICY_V1=Object.freeze({
|
|
6
|
-
id:'chat-loop.approval.r-p.v1',
|
|
7
|
-
requiredKinds:Object.freeze(['R','P'])
|
|
8
|
-
});
|
|
2
|
+
// Only these enforced predicates (not an unused second policy descriptor)
|
|
3
|
+
// decide whether R and P have distinct genuine user Turns.
|
|
9
4
|
|
|
10
5
|
const fromUser=a=>Boolean(a&&typeof a==='object'
|
|
11
6
|
&&(a.sourceRole===undefined||a.sourceRole==='user')
|
|
@@ -40,7 +40,9 @@ export function createCapabilityRouter(definitions,capabilities){
|
|
|
40
40
|
const source=registry.get(method?.id);
|
|
41
41
|
if(!source||source.entry.mode!==method.mode)
|
|
42
42
|
throw fail('CAPABILITY_METHOD_UNKNOWN');
|
|
43
|
-
|
|
43
|
+
// The capability registry was verified against the build manifest.
|
|
44
|
+
// Never dispatch a supplied method object's mutable route instead.
|
|
45
|
+
const route=source.entry.route;
|
|
44
46
|
if(route.kind==='core'){
|
|
45
47
|
const fn=services?.db?.[route.method];
|
|
46
48
|
if(typeof fn!=='function')throw fail('CAPABILITY_CORE_PROVIDER_MISSING');
|
|
@@ -2,10 +2,15 @@
|
|
|
2
2
|
// Only bin/cli.mjs exports a shell command. index.mjs supplies scoped API
|
|
3
3
|
// dependencies; local admin/SQLite safety gates remain in their owners.
|
|
4
4
|
import {randomUUID,createHash} from 'node:crypto';
|
|
5
|
-
import {
|
|
5
|
+
import {lstatSync,mkdirSync,mkdtempSync,renameSync,rmSync} from 'node:fs';
|
|
6
6
|
import {join} from 'node:path';
|
|
7
7
|
|
|
8
8
|
const fail=code=>Object.assign(new Error(code),{code});
|
|
9
|
+
// Reject dangling target links as occupied rather than replacing them.
|
|
10
|
+
const occupied=path=>{
|
|
11
|
+
try{lstatSync(path);return true}
|
|
12
|
+
catch(error){if(error.code==='ENOENT')return false;throw error}
|
|
13
|
+
};
|
|
9
14
|
let openContextProtocol,contextRoot,allowedProjects,
|
|
10
15
|
verifySourceUnit,createProjectDiagnosticBranch,createManagedProjectBranch,
|
|
11
16
|
fenceLegacyProjectStore,auditLegacyProjectSources,inspectLegacyRegistryReference,
|
|
@@ -44,7 +49,7 @@ async function registerProject(projectId,title,workspaces=[],reviewed=false){
|
|
|
44
49
|
if(process.env.CHAT_LOOP_CONTEXT_DB)throw fail('EXPLICIT_DB_INIT_REQUIRED');
|
|
45
50
|
const refs=canonicalWorkspaceRefs(workspaces,{allowEmpty:!reviewed});
|
|
46
51
|
const root=contextRoot(),final=join(root,projectId);
|
|
47
|
-
if(
|
|
52
|
+
if(occupied(final))throw fail('PROJECT_EXISTS');
|
|
48
53
|
// The user-reviewed entry never creates a Store (or even a directory)
|
|
49
54
|
// before the local operator confirms the exact canonical roots.
|
|
50
55
|
if(reviewed)await confirmWorkspaceOperator('REGISTER',projectId,0,refs);
|
|
@@ -52,7 +57,7 @@ async function registerProject(projectId,title,workspaces=[],reviewed=false){
|
|
|
52
57
|
return withWorkspaceRegistryLock(root,()=>{
|
|
53
58
|
let tmp;
|
|
54
59
|
try{
|
|
55
|
-
if(
|
|
60
|
+
if(occupied(final))throw fail('PROJECT_EXISTS');
|
|
56
61
|
if(reviewed){
|
|
57
62
|
const current=canonicalWorkspaceRefs(workspaces);
|
|
58
63
|
if(JSON.stringify(current)!==JSON.stringify(refs))throw fail('WORKSPACE_CHANGED');
|
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
// Never infer task approvals, Browser Owner, or a runnable checkpoint from
|
|
3
3
|
// Markdown/legacy Registry. Default mode is read-only SHADOW.
|
|
4
4
|
import {createHash,randomUUID} from 'node:crypto';
|
|
5
|
-
import {readFileSync,writeFileSync,mkdirSync,
|
|
6
|
-
realpathSync,
|
|
5
|
+
import {readFileSync,writeFileSync,mkdirSync,lstatSync,copyFileSync,chmodSync,constants,
|
|
6
|
+
realpathSync,linkSync,unlinkSync,openSync,readSync,closeSync} from 'node:fs';
|
|
7
7
|
import {basename,dirname,join,resolve,isAbsolute} from 'node:path';
|
|
8
8
|
import {DatabaseSync,backup} from 'node:sqlite';
|
|
9
9
|
// This module declares ports; index.mjs is the only dependency assembler.
|
|
@@ -23,6 +23,11 @@ const fail=code=>Object.assign(new Error(code),{code});
|
|
|
23
23
|
const assert=(b,c)=>{if(!b)throw fail(c)};
|
|
24
24
|
const hash=x=>createHash('sha256').update(x).digest('hex');
|
|
25
25
|
const ID=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
|
|
26
|
+
// A dangling link is an occupied output path, never an absent artifact.
|
|
27
|
+
const occupied=file=>{
|
|
28
|
+
try{lstatSync(file);return true}
|
|
29
|
+
catch(error){if(error.code==='ENOENT')return false;throw error}
|
|
30
|
+
};
|
|
26
31
|
// Hash large online backups incrementally; never load a 2 GiB database
|
|
27
32
|
// into the Agent/CLI process just to check its integrity.
|
|
28
33
|
const hashLargeFile=(file,max=2*1024*1024*1024)=>{
|
|
@@ -60,7 +65,8 @@ const safeOutput=(file,value)=>{
|
|
|
60
65
|
const tmp=join(dir,'.'+basename(file)+'.'+randomUUID()+'.tmp');
|
|
61
66
|
try{
|
|
62
67
|
writeFileSync(tmp,JSON.stringify(value,null,2)+'\n',{flag:'wx',mode:0o600});
|
|
63
|
-
|
|
68
|
+
// Atomic create-if-absent: rename would replace an existing artifact.
|
|
69
|
+
linkSync(tmp,file);
|
|
64
70
|
}finally{try{unlinkSync(tmp)}catch{}}
|
|
65
71
|
};
|
|
66
72
|
export function scanSourceUnit({sourcePath,projectId,kind}){
|
|
@@ -131,7 +137,7 @@ export function saveShadowManifest(file,items){
|
|
|
131
137
|
status:'SHADOW_RO',sourceUnits:items,permissions:'READ_ONLY',
|
|
132
138
|
taskApprovalsImported:false,ownerImported:false,
|
|
133
139
|
knownWritersStopped:false};
|
|
134
|
-
assert(!
|
|
140
|
+
assert(!occupied(file),'MANIFEST_EXISTS');
|
|
135
141
|
safeOutput(file,manifest);
|
|
136
142
|
return manifest;
|
|
137
143
|
}
|
|
@@ -153,7 +159,7 @@ export function verifyShadowManifest(file){
|
|
|
153
159
|
// SQLite online backup: never copy a live database's main file.
|
|
154
160
|
export async function backupContextDb(dbHandle,targetFile){
|
|
155
161
|
assert(typeof targetFile==='string'&&isAbsolute(targetFile),'BACKUP_PATH_INVALID');
|
|
156
|
-
assert(!
|
|
162
|
+
assert(!occupied(targetFile),'BACKUP_EXISTS');
|
|
157
163
|
privateDirectory(dirname(targetFile));
|
|
158
164
|
try{
|
|
159
165
|
await backup(dbHandle,targetFile);
|
|
@@ -174,7 +180,7 @@ export function restoreBackupToDiagnosticBranch({
|
|
|
174
180
|
&&typeof manifestFile==='string'&&isAbsolute(manifestFile)
|
|
175
181
|
&&typeof expectedBackupHash==='string'&&/^[a-f0-9]{64}$/.test(expectedBackupHash),
|
|
176
182
|
'RESTORE_ARGUMENT_INVALID');
|
|
177
|
-
assert(!
|
|
183
|
+
assert(!occupied(targetDb)&&!occupied(manifestFile),'RESTORE_TARGET_EXISTS');
|
|
178
184
|
const source=hashLargeFile(backupFile);
|
|
179
185
|
assert(source.hash===expectedBackupHash,'BACKUP_HASH_MISMATCH');
|
|
180
186
|
privateDirectory(dirname(targetDb));
|
|
@@ -227,7 +233,7 @@ export function createRecoveryManifest(file,{projectId,taskId,storeEpoch,storeLi
|
|
|
227
233
|
storeEpoch,storeLineage,checkpointRef:checkpointRef??null,
|
|
228
234
|
backupRef,readerVersion,unknownEffects,generatedAt:Date.now(),
|
|
229
235
|
mode:'DIAGNOSTIC_ONLY',canExecute:false};
|
|
230
|
-
assert(!
|
|
236
|
+
assert(!occupied(file),'RECOVERY_MANIFEST_EXISTS');
|
|
231
237
|
safeOutput(file,record);
|
|
232
238
|
return record;
|
|
233
239
|
}
|