@tomflow/chatloop-tools 0.9.43 → 0.9.45
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 +6 -2
- package/bin/cli.mjs +12 -5
- package/index.mjs +60 -33
- 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 +70 -45
- package/lib/trace-observation.mjs +5 -3
- 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 +6 -6
- package/providers/context.mjs +5 -1
- package/providers/desktop.mjs +23 -6
- package/providers/document.mjs +31 -5
- 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
|
@@ -24,7 +24,7 @@ export const traceGatewayEnabled=()=>process.env.CHAT_LOOP_TRACE_API_ENABLE==='1
|
|
|
24
24
|
&&getAllowedProjects().length===1;
|
|
25
25
|
export const traceDiagnoseTool={
|
|
26
26
|
name:'chat_loop_trace_diagnose',
|
|
27
|
-
description:'Read-only Trace timeline for an explicitly authorized Project. A separate api_system lookup is allowed
|
|
27
|
+
description:'Read-only Trace timeline for an explicitly authorized Project. A separate api_system lookup is allowed with the unguessable Form/Document traceRef returned by Prepare/Show; exposes only that App instance and matching parent MCP API spans.',
|
|
28
28
|
inputSchema:{
|
|
29
29
|
type:'object',additionalProperties:false,
|
|
30
30
|
required:['projectRef'],
|
|
@@ -43,10 +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
|
|
46
|
+
const APP_TRACE_REF=new RegExp(UUID);
|
|
47
47
|
const FORM_ID=/^[A-Za-z0-9][A-Za-z0-9_-]{7,79}$/;
|
|
48
|
-
const
|
|
49
|
-
|
|
48
|
+
const DOC_ID=/^[A-Za-z0-9][A-Za-z0-9_.-]{7,127}$/;
|
|
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
|
+
});
|
|
50
58
|
export const traceStageTool={
|
|
51
59
|
name:'chat_loop_trace_stage',
|
|
52
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.',
|
|
@@ -69,7 +77,7 @@ export async function runTraceStage(args){
|
|
|
69
77
|
Object.keys(args).some(k=>!Object.hasOwn(traceStageTool.inputSchema.properties,k))||
|
|
70
78
|
!STAGE_NAMES.includes(args.stage)||
|
|
71
79
|
!STAGE_OUTCOMES.includes(args.outcome)||
|
|
72
|
-
args.traceId!==undefined&&!
|
|
80
|
+
args.traceId!==undefined&&!APP_TRACE_REF.test(args.traceId)||
|
|
73
81
|
args.evidenceRef!==undefined&&(!USER_EVIDENCE.test(args.evidenceRef)
|
|
74
82
|
||!['requirements','plan','approval'].includes(args.stage)))
|
|
75
83
|
throw fail('TRACE_INVALID_ARGUMENT');
|
|
@@ -83,8 +91,11 @@ export async function runTraceStage(args){
|
|
|
83
91
|
const r=await talk({contract:CONTRACT,action:'__trace_observation',
|
|
84
92
|
requestId,traceId,projectRef:args.projectRef,event,status,
|
|
85
93
|
...(args.evidenceRef?{evidenceRef:args.evidenceRef}:{})},1800);
|
|
86
|
-
if(r?.
|
|
87
|
-
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');
|
|
88
99
|
return {status:'RECORDED_SOFT',confidence:'SOFT_AGENT_OBSERVATION',
|
|
89
100
|
traceId,eventId:r.eventId,event,requestId,
|
|
90
101
|
...(args.evidenceRef?{evidenceRef:args.evidenceRef,
|
|
@@ -98,25 +109,32 @@ const getAllowedProjects=()=>{
|
|
|
98
109
|
// syntax; filtering entries could silently broaden a malformed config.
|
|
99
110
|
return entries.length===1&&PROJECT.test(entries[0])?entries:[];
|
|
100
111
|
};
|
|
101
|
-
async function
|
|
112
|
+
async function diagnoseAppTrace(args){
|
|
102
113
|
const reader=createTraceReader({filePath:paths().log,allowedProjects:['api_system']});
|
|
103
114
|
const base=await reader.diagnose({projectRef:'api_system',
|
|
104
115
|
sessionRef:args.sessionRef,maxEvents:args.maxEvents});
|
|
105
|
-
const
|
|
106
|
-
event.sessionRef
|
|
107
|
-
|
|
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[0]?.event.startsWith('document.')?'document':'form';
|
|
127
|
+
const matching=appEvents.filter(event=>event.event.startsWith(kind+'.'));
|
|
128
|
+
const prefix=kind.toUpperCase();
|
|
108
129
|
const gaps=base.gaps.filter(gap=>gap!=='NO_MATCHING_EVENTS');
|
|
109
130
|
const parentKeys=new Map();
|
|
110
|
-
for(const event of
|
|
111
|
-
const
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
?'mcp.chat_loop_form__render':'mcp.chat_loop_form__submit';
|
|
115
|
-
if(!event.parentSpanId){gaps.push('FORM_API_PARENT_MISSING');continue}
|
|
116
|
-
parentKeys.set(event.traceId+':'+event.parentSpanId,apiName);
|
|
131
|
+
for(const event of matching){
|
|
132
|
+
const eventType=event.event.slice(0,event.event.lastIndexOf('.'));
|
|
133
|
+
if(!event.parentSpanId){gaps.push(prefix+'_API_PARENT_MISSING');continue}
|
|
134
|
+
parentKeys.set(event.traceId+':'+event.parentSpanId,APP_EVENT_API[eventType]);
|
|
117
135
|
}
|
|
118
136
|
const apiEvents=[];
|
|
119
|
-
for(const traceId of new Set(
|
|
137
|
+
for(const traceId of new Set(matching.map(event=>event.traceId))){
|
|
120
138
|
const query=await reader.diagnose({projectRef:'api_system',traceId,maxEvents:200});
|
|
121
139
|
for(const gap of query.gaps)
|
|
122
140
|
if(['TRACE_MALFORMED_LINES','TRACE_WINDOW_TRUNCATED',
|
|
@@ -124,8 +142,8 @@ async function diagnoseFormTrace(args){
|
|
|
124
142
|
.includes(gap))gaps.push(gap);
|
|
125
143
|
for(const event of query.timeline){
|
|
126
144
|
const key=event.traceId+':'+event.spanId;
|
|
127
|
-
if(event.event==='typed.api.call'&&parentKeys.get(key)===event.apiName
|
|
128
|
-
|
|
145
|
+
if(event.event==='typed.api.call'&&parentKeys.get(key)===event.apiName)
|
|
146
|
+
apiEvents.push(event);
|
|
129
147
|
}
|
|
130
148
|
}
|
|
131
149
|
for(const [key,apiName] of parentKeys){
|
|
@@ -136,28 +154,28 @@ async function diagnoseFormTrace(args){
|
|
|
136
154
|
const terminals=linked.filter(event=>
|
|
137
155
|
['CONFIRMED','FAILED'].includes(event.status));
|
|
138
156
|
if(begins.length!==1||terminals.length!==1)
|
|
139
|
-
gaps.push('
|
|
157
|
+
gaps.push(prefix+'_API_PARENT_GAP');
|
|
140
158
|
const terminal=terminals[0];
|
|
141
|
-
if(terminal&&
|
|
159
|
+
if(terminal&&matching.some(event=>event.traceId===traceId
|
|
142
160
|
&&event.parentSpanId===spanId&&event.status!==terminal.status))
|
|
143
|
-
gaps.push('
|
|
161
|
+
gaps.push(prefix+'_API_STATUS_MISMATCH');
|
|
144
162
|
}
|
|
145
|
-
const
|
|
146
|
-
if(
|
|
147
|
-
if(
|
|
148
|
-
|
|
163
|
+
const ids=[...new Set(matching.map(event=>event.evidenceRef))];
|
|
164
|
+
if(ids.length>1)gaps.push(prefix+'_TRACE_REF_REUSED');
|
|
165
|
+
if(appEvents.length!==matching.length)gaps.push('APP_TRACE_REF_CROSS_KIND');
|
|
166
|
+
if(!matching.length)gaps.push('NO_MATCHING_EVENTS');
|
|
167
|
+
const timeline=[...matching,...apiEvents]
|
|
149
168
|
.sort((a,b)=>Date.parse(a.time)-Date.parse(b.time));
|
|
150
169
|
const last=timeline.at(-1)||null;
|
|
151
|
-
const
|
|
152
|
-
|
|
153
|
-
|
|
170
|
+
const lastConfirmed=timeline.findLast(event=>event.status==='CONFIRMED');
|
|
171
|
+
const unknown=matching.some(event=>['UNKNOWN','BLOCKED'].includes(event.status));
|
|
172
|
+
return {traceId:null,projectRef:'api_system',
|
|
173
|
+
...(kind==='form'?{formTraceRef:args.sessionRef,formId:ids.length===1?ids[0]:null}
|
|
174
|
+
:{documentTraceRef:args.sessionRef,documentId:ids.length===1?ids[0]:null}),
|
|
154
175
|
inspected:timeline.length,totalMatched:timeline.length,
|
|
155
|
-
lastConfirmed:
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
time:[...timeline].reverse().find(event=>event.status==='CONFIRMED').time,
|
|
159
|
-
component:[...timeline].reverse().find(event=>event.status==='CONFIRMED').component}
|
|
160
|
-
:null,
|
|
176
|
+
lastConfirmed:lastConfirmed?{eventId:lastConfirmed.eventId,
|
|
177
|
+
event:lastConfirmed.event,time:lastConfirmed.time,
|
|
178
|
+
component:lastConfirmed.component}:null,
|
|
161
179
|
incompleteApiSpans:[],unmatchedApiTerminals:[],lastEvent:last,unknown,
|
|
162
180
|
gaps:[...new Set(gaps)],confidence:gaps.length?'INCOMPLETE':'TRACE_ONLY',
|
|
163
181
|
retryDisposition:unknown||gaps.length
|
|
@@ -169,29 +187,36 @@ export async function runTraceDiagnose(args){
|
|
|
169
187
|
throw fail('TRACE_INVALID_ARGUMENT');
|
|
170
188
|
if(args.projectRef==='api_system'){
|
|
171
189
|
if(args.traceId!==undefined||typeof args.sessionRef!=='string'
|
|
172
|
-
||!
|
|
173
|
-
throw fail('
|
|
190
|
+
||!APP_TRACE_REF.test(args.sessionRef))
|
|
191
|
+
throw fail('TRACE_APP_LOOKUP_INVALID');
|
|
174
192
|
}else{
|
|
175
193
|
if(!traceGatewayEnabled())throw fail('TRACE_API_DISABLED');
|
|
176
194
|
if(typeof args.projectRef!=='string'||!getAllowedProjects().includes(args.projectRef))
|
|
177
195
|
throw fail('TRACE_PROJECT_ACCESS_DENIED');
|
|
178
196
|
}
|
|
179
197
|
const result=args.projectRef==='api_system'
|
|
180
|
-
?await
|
|
198
|
+
?await diagnoseAppTrace(args)
|
|
181
199
|
:await createTraceReader({filePath:paths().log,
|
|
182
200
|
allowedProjects:getAllowedProjects()}).diagnose(args);
|
|
183
201
|
try{
|
|
202
|
+
const requestId=randomUUID();
|
|
184
203
|
const response=await talk({contract:CONTRACT,action:'__trace_health',
|
|
185
|
-
requestId
|
|
186
|
-
result.writerHealth=response
|
|
187
|
-
|
|
204
|
+
requestId},1400);
|
|
205
|
+
result.writerHealth=response?.contract===CONTRACT
|
|
206
|
+
&&response.requestId===requestId&&response.status==='OK'
|
|
207
|
+
?response.traceHealth?.status||'UNKNOWN':'UNAVAILABLE';
|
|
208
|
+
if(result.writerHealth!=='UNAVAILABLE'&&args.projectRef==='api_system'
|
|
209
|
+
&&response.traceHealth?.formObservationLost>0)
|
|
188
210
|
result.gaps.push('FORM_TRACE_OBSERVATION_LOSS');
|
|
211
|
+
if(result.writerHealth!=='UNAVAILABLE'&&args.projectRef==='api_system'
|
|
212
|
+
&&response.traceHealth?.documentObservationLost>0)
|
|
213
|
+
result.gaps.push('DOCUMENT_TRACE_OBSERVATION_LOSS');
|
|
189
214
|
}catch{result.writerHealth='UNAVAILABLE'}
|
|
190
215
|
if(result.writerHealth!=='OK'){
|
|
191
216
|
if(['UNKNOWN','UNAVAILABLE'].includes(result.writerHealth))
|
|
192
217
|
result.gaps.push('TRACE_WRITER_UNAVAILABLE');
|
|
193
218
|
if(result.writerHealth==='TRACE_DEGRADED')
|
|
194
|
-
result.gaps.push('
|
|
219
|
+
result.gaps.push('TRACE_APP_OBSERVATION_LOSS');
|
|
195
220
|
result.confidence='INCOMPLETE';
|
|
196
221
|
result.retryDisposition='VERIFY_AUTHORITATIVE_RECEIPT_FIRST';
|
|
197
222
|
}
|
|
@@ -216,7 +241,7 @@ export async function observeExtensionResult(name,args,result){
|
|
|
216
241
|
const session=name==='status'&&proof?.session &&
|
|
217
242
|
typeof proof.session==='object'&&!Array.isArray(proof.session)
|
|
218
243
|
?proof.session:proof;
|
|
219
|
-
if(!session||!
|
|
244
|
+
if(!session||!APP_TRACE_REF.test(session.sessionId||''))return;
|
|
220
245
|
const intent=['continue','handoff'].includes(name);
|
|
221
246
|
if(intent&&(!/^[a-f0-9]{32}$/.test(proof.intentId||'')
|
|
222
247
|
||!['QUEUED','STATUS'].includes(proof.status)))return;
|
|
@@ -18,6 +18,7 @@ export function createSupervisorTraceBridge({traceWriter,contract,error,
|
|
|
18
18
|
// not become reachable merely because Context collection is active.
|
|
19
19
|
const isContextApi=req?.event==='context.api';
|
|
20
20
|
const form=/^form\.(prepared|rendered|submitted)\.(soft_observed|failed)$/.test(req?.event||'');
|
|
21
|
+
const document=/^document\.(shown|rendered)\.(soft_observed|failed)$/.test(req?.event||'');
|
|
21
22
|
const contextGrant=observationGrants.CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS;
|
|
22
23
|
const contextAuthorized=observationGrants.CHAT_LOOP_CONTEXT_API_ENABLE==='1'
|
|
23
24
|
&&typeof contextGrant==='string'
|
|
@@ -27,7 +28,7 @@ export function createSupervisorTraceBridge({traceWriter,contract,error,
|
|
|
27
28
|
// Keep them in the existing api_system Writer without requiring a
|
|
28
29
|
// per-Project Trace grant or exposing Project/Chat/task identifiers.
|
|
29
30
|
if(isContextApi?!contextAuthorized:
|
|
30
|
-
form?req?.projectRef!=='api_system':
|
|
31
|
+
form||document?req?.projectRef!=='api_system':
|
|
31
32
|
!traceEnabled()||!allowedTraceProjects().has(req?.projectRef))
|
|
32
33
|
throw error('TRACE_PROJECT_ACCESS_DENIED');
|
|
33
34
|
// Context call observation has a stable event ID and typed API fields.
|
|
@@ -73,7 +74,7 @@ export function createSupervisorTraceBridge({traceWriter,contract,error,
|
|
|
73
74
|
return {contract:CONTRACT,requestId:req.requestId,status:'OK',
|
|
74
75
|
eventId:recorded.eventId};
|
|
75
76
|
}
|
|
76
|
-
if(form){
|
|
77
|
+
if(form||document){
|
|
77
78
|
const success=req.event.endsWith('.soft_observed');
|
|
78
79
|
const allowed=new Set(['contract','action','requestId','traceId','spanId',
|
|
79
80
|
'projectRef','sessionRef','evidenceRef','event','status','errorCode']);
|
|
@@ -84,7 +85,8 @@ export function createSupervisorTraceBridge({traceWriter,contract,error,
|
|
|
84
85
|
||!UUID_RE.test(req.requestId||'')||!UUID_RE.test(req.traceId||'')
|
|
85
86
|
||!UUID_RE.test(req.spanId||'')
|
|
86
87
|
||!UUID_RE.test(req.sessionRef||'')
|
|
87
|
-
||!(
|
|
88
|
+
||!(document?/^[A-Za-z0-9][A-Za-z0-9_.-]{7,127}$/:
|
|
89
|
+
/^[A-Za-z0-9][A-Za-z0-9_-]{7,79}$/).test(req.evidenceRef||'')
|
|
88
90
|
||(success?req.errorCode!==undefined:!validError)
|
|
89
91
|
||Object.keys(req).some(k=>!allowed.has(k)))
|
|
90
92
|
throw error('TRACE_INVALID_ARGUMENT');
|
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');
|