@tomflow/chatloop-tools 0.9.19 → 0.9.21

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.
Files changed (65) hide show
  1. package/README.md +8 -3
  2. package/index.mjs +49 -9
  3. package/lib/supervisor-observability.mjs +157 -0
  4. package/lib/supervisor-runtime.mjs +14 -111
  5. package/lib/trace-gateway.mjs +90 -11
  6. package/lib/trace-observation.mjs +17 -8
  7. package/node_modules/@tomflow/chatloop-context/README.md +240 -0
  8. package/node_modules/@tomflow/chatloop-context/bin/cli.mjs +48 -0
  9. package/node_modules/@tomflow/chatloop-context/capabilities/approval.mjs +151 -0
  10. package/node_modules/@tomflow/chatloop-context/capabilities/context.mjs +376 -0
  11. package/node_modules/@tomflow/chatloop-context/capabilities/document.mjs +266 -0
  12. package/node_modules/@tomflow/chatloop-context/capabilities/evidence.mjs +134 -0
  13. package/node_modules/@tomflow/chatloop-context/capabilities/presentation.mjs +82 -0
  14. package/node_modules/@tomflow/chatloop-context/capabilities/project.mjs +349 -0
  15. package/node_modules/@tomflow/chatloop-context/capabilities/sdk.mjs +72 -0
  16. package/node_modules/@tomflow/chatloop-context/capabilities/start.mjs +73 -0
  17. package/node_modules/@tomflow/chatloop-context/capabilities/task.mjs +507 -0
  18. package/node_modules/@tomflow/chatloop-context/capabilities.generated.mjs +11 -0
  19. package/node_modules/@tomflow/chatloop-context/docs/interfaces.md +182 -0
  20. package/node_modules/@tomflow/chatloop-context/docs/operator-and-migration.md +277 -0
  21. package/node_modules/@tomflow/chatloop-context/index.mjs +233 -0
  22. package/node_modules/@tomflow/chatloop-context/lib/api-log.mjs +86 -0
  23. package/node_modules/@tomflow/chatloop-context/lib/approval-policy.mjs +24 -0
  24. package/node_modules/@tomflow/chatloop-context/lib/capability-catalog.generated.json +1989 -0
  25. package/node_modules/@tomflow/chatloop-context/lib/capability-router.mjs +67 -0
  26. package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +280 -0
  27. package/node_modules/@tomflow/chatloop-context/lib/context-cli.mjs +298 -0
  28. package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +280 -0
  29. package/node_modules/@tomflow/chatloop-context/lib/core/context.mjs +115 -0
  30. package/node_modules/@tomflow/chatloop-context/lib/core/evidence.mjs +51 -0
  31. package/node_modules/@tomflow/chatloop-context/lib/core/health.mjs +55 -0
  32. package/node_modules/@tomflow/chatloop-context/lib/core/migration.mjs +262 -0
  33. package/node_modules/@tomflow/chatloop-context/lib/core/project.mjs +246 -0
  34. package/node_modules/@tomflow/chatloop-context/lib/core/review.mjs +147 -0
  35. package/node_modules/@tomflow/chatloop-context/lib/core/run.mjs +343 -0
  36. package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +391 -0
  37. package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +166 -0
  38. package/node_modules/@tomflow/chatloop-context/lib/line-review.mjs +13 -0
  39. package/node_modules/@tomflow/chatloop-context/lib/methods.mjs +111 -0
  40. package/node_modules/@tomflow/chatloop-context/lib/operations.mjs +107 -0
  41. package/node_modules/@tomflow/chatloop-context/lib/orphan-operator.mjs +117 -0
  42. package/node_modules/@tomflow/chatloop-context/lib/process-inventory.mjs +20 -0
  43. package/node_modules/@tomflow/chatloop-context/lib/project-branch.mjs +312 -0
  44. package/node_modules/@tomflow/chatloop-context/lib/project-diagnostic.mjs +153 -0
  45. package/node_modules/@tomflow/chatloop-context/lib/project-guards.mjs +19 -0
  46. package/node_modules/@tomflow/chatloop-context/lib/project-store.mjs +115 -0
  47. package/node_modules/@tomflow/chatloop-context/lib/trusted-run.mjs +86 -0
  48. package/node_modules/@tomflow/chatloop-context/lib/workspace-operator.mjs +169 -0
  49. package/node_modules/@tomflow/chatloop-context/package.json +40 -0
  50. package/node_modules/@tomflow/chatloop-context/scripts/build-capabilities.mjs +114 -0
  51. package/node_modules/@tomflow/chatloop-trace/README.md +105 -0
  52. package/node_modules/@tomflow/chatloop-trace/events/context.api.mjs +23 -0
  53. package/node_modules/@tomflow/chatloop-trace/events/typed.api.call.mjs +22 -0
  54. package/node_modules/@tomflow/chatloop-trace/events.generated.mjs +4 -0
  55. package/node_modules/@tomflow/chatloop-trace/index.mjs +59 -0
  56. package/node_modules/@tomflow/chatloop-trace/lib/api-aspect.mjs +273 -0
  57. package/node_modules/@tomflow/chatloop-trace/lib/trace-reader.mjs +265 -0
  58. package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +205 -0
  59. package/node_modules/@tomflow/chatloop-trace/package.json +30 -0
  60. package/node_modules/@tomflow/chatloop-trace/scripts/build-events.mjs +68 -0
  61. package/package.json +5 -1
  62. package/providers/form.mjs +85 -206
  63. package/providers/trace.mjs +5 -2
  64. package/ui/form/review-app.js +59 -44
  65. package/ui/form/review.html +1 -1
@@ -0,0 +1,273 @@
1
+ // Canonical Node AOP observer exported by Trace; only MV3 uses a generated copy.
2
+ // Soft evidence only: no parameters, results, URLs, secrets or model content.
3
+ const SAFE=/^[a-zA-Z][a-zA-Z0-9_.:-]{0,126}$/;
4
+ const PACKAGE=/^@[a-z0-9][a-z0-9._-]{0,45}\/[a-z0-9][a-z0-9._-]{0,80}$/;
5
+ const UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
6
+ const safe=(s,fallback='api.unknown')=>typeof s==='string'&&SAFE.test(s)?s:fallback;
7
+ const code=e=>typeof e?.code==='string'&&/^[A-Z][A-Z0-9_]{1,95}$/.test(e.code)
8
+ ?e.code:'API_FAILED';
9
+ const uid=()=>{
10
+ try{return globalThis.crypto.randomUUID()}catch{
11
+ const hex='0123456789abcdef',h=n=>Array.from({length:n},
12
+ ()=>hex[Math.floor(Math.random()*16)]).join('');
13
+ return h(8)+'-'+h(4)+'-4'+h(3)+'-a'+h(3)+'-'+h(12);
14
+ }
15
+ };
16
+ const schedule=typeof setImmediate==='function'?setImmediate:fn=>setTimeout(fn,0);
17
+ const clock=()=>typeof performance!=='undefined'&&typeof performance.now==='function'
18
+ ?performance.now():Date.now();
19
+ const MAX_PENDING=4096,MAX_BATCH=128;
20
+ const CONTEXT_KEY=Symbol.for('chat-loop.observation.async-context.v1');
21
+ // Process-local correlation only, never an authorization or plugin registry.
22
+ const contextStore=()=>{
23
+ if(typeof process==='undefined'||typeof process.getBuiltinModule!=='function')return null;
24
+ try{
25
+ if(!process[CONTEXT_KEY]){
26
+ const {AsyncLocalStorage}=process.getBuiltinModule('node:async_hooks');
27
+ Object.defineProperty(process,CONTEXT_KEY,{
28
+ value:new AsyncLocalStorage(),enumerable:false,configurable:false
29
+ });
30
+ }
31
+ return process[CONTEXT_KEY];
32
+ }catch{return null}
33
+ };
34
+ const validParent=v=>v&&UUID.test(v.traceId||'')&&UUID.test(v.spanId||'');
35
+ export function currentApiTrace(){
36
+ try{
37
+ const local=contextStore()?.getStore();
38
+ if(validParent(local))return {traceId:local.traceId,spanId:local.spanId};
39
+ // Child-process context is sanitized correlation metadata, not trust.
40
+ const value=typeof process!=='undefined'?process.env?.CHAT_LOOP_API_PARENT:null;
41
+ if(typeof value!=='string'||value.length>180)return null;
42
+ const parsed=JSON.parse(value);
43
+ return validParent(parsed)?{traceId:parsed.traceId,spanId:parsed.spanId}:null;
44
+ }catch{return null}
45
+ }
46
+ export function withApiTraceParent(parent,fn){
47
+ if(typeof fn!=='function')throw TypeError('API_TRACE_CALLBACK_REQUIRED');
48
+ if(!validParent(parent))throw TypeError('API_TRACE_PARENT_INVALID');
49
+ const storage=contextStore();
50
+ return storage?storage.run({traceId:parent.traceId,spanId:parent.spanId},fn):fn();
51
+ }
52
+ export function createApiAspect(packageName,{sink,bufferUntilSubscribe=false}={}){
53
+ const packageId=typeof packageName==='string'&&PACKAGE.test(packageName)
54
+ ?packageName:'unknown';
55
+ const queue=[],bootstrap=[],listeners=new Set(),inFlight=new Set(),
56
+ stats={emitted:0,delivered:0,dropped:0,sinkFailures:0};
57
+ let scheduled=false;
58
+ const output=typeof sink==='function'?sink:record=>{
59
+ // Trace's own public factory is called before the Tools observer can
60
+ // subscribe. Retain only bounded metadata until its first subscriber.
61
+ if(bufferUntilSubscribe&&!listeners.size){
62
+ if(bootstrap.length>=MAX_PENDING){stats.dropped++;return false}
63
+ bootstrap.push(record);
64
+ return;
65
+ }
66
+ if(listeners.size){
67
+ const pending=[];
68
+ for(const listener of [...listeners]){
69
+ try{
70
+ const result=listener(record);
71
+ if(result&&typeof result.then==='function')
72
+ pending.push(Promise.resolve(result).then(
73
+ value=>{if(value===false)stats.sinkFailures++},
74
+ ()=>{stats.sinkFailures++}
75
+ ));
76
+ else if(result===false)stats.sinkFailures++;
77
+ }catch{stats.sinkFailures++}
78
+ }
79
+ // The drain boundary must also wait for async subscribers, not merely
80
+ // the event queue. A listener failure stays soft but is diagnosed.
81
+ return pending.length?Promise.all(pending):undefined;
82
+ }
83
+ if(typeof process==='undefined'||!process.stderr?.write||
84
+ process.env.CHAT_LOOP_API_LOG_STDERR==='0'){
85
+ stats.dropped++;
86
+ return false;
87
+ }
88
+ process.stderr.write('CHAT_LOOP_API_LOG '+JSON.stringify(record)+'\n');
89
+ };
90
+ const flush=()=>{
91
+ scheduled=false;
92
+ for(let i=0;i<MAX_BATCH&&queue.length;i++){
93
+ const item=queue.shift();
94
+ try{
95
+ const result=output(item);
96
+ stats.delivered++;
97
+ // A synchronous explicit rejection must never count as successful
98
+ // delivery merely because the queue is empty.
99
+ if(result===false)stats.sinkFailures++;
100
+ if(result&&typeof result.then==='function'){
101
+ const pending=Promise.resolve(result);
102
+ inFlight.add(pending);
103
+ pending.then(value=>{if(value===false)stats.sinkFailures++},
104
+ ()=>{stats.sinkFailures++}).finally(()=>{inFlight.delete(pending)})
105
+ .catch(()=>{stats.sinkFailures++});
106
+ }
107
+ }catch{stats.sinkFailures++}
108
+ }
109
+ if(queue.length){scheduled=true;schedule(flush)}
110
+ };
111
+ const emit=event=>{
112
+ try{
113
+ if(queue.length>=MAX_PENDING){stats.dropped++;return}
114
+ queue.push(Object.freeze(event));stats.emitted++;
115
+ if(!scheduled){scheduled=true;schedule(flush)}
116
+ }catch{stats.dropped++}
117
+ };
118
+ function observe(name,fn,surface='sdk',options={}){
119
+ if(typeof fn!=='function')throw TypeError('API_ASPECT_TARGET_REQUIRED');
120
+ const api=safe(name),layer=safe(surface,'sdk');
121
+ return new Proxy(fn,{
122
+ get(target,key,receiver){
123
+ if(key===Symbol.for('chat-loop.api-observed.v1'))return true;
124
+ return Reflect.get(target,key,receiver);
125
+ },
126
+ apply(target,thisArg,args){
127
+ let started,base;
128
+ try{
129
+ // MCP requests are fresh user operations, not children of a
130
+ // long-lived CLI/server bootstrap event listener registration.
131
+ // Browser callbacks lack Node AsyncLocalStorage; a narrowly scoped
132
+ // explicit parent links the async reply to its actual dispatch span.
133
+ const explicit=validParent(options?.parent)?options.parent:null;
134
+ const callId=uid(),parent=explicit||(layer==='mcp'?null:currentApiTrace());
135
+ started=clock();
136
+ base={contract:'chat-loop.api-call.v1',package:packageId,
137
+ api,surface:layer,callId,
138
+ traceId:parent?.traceId||callId,spanId:callId,
139
+ parentSpanId:parent?.spanId||null};
140
+ }catch{/* Never fail a target due to tracing. */}
141
+ const mark=(phase,error)=>{
142
+ if(!base)return;
143
+ try{
144
+ emit({...base,phase,time:new Date().toISOString(),
145
+ durationMs:phase==='BEGIN'?null:Math.max(0,Math.round(clock()-started)),
146
+ errorCode:phase==='FAILED'?code(error):null});
147
+ }catch{/* Non-authoritative telemetry. */}
148
+ };
149
+ mark('BEGIN');
150
+ // Only sanitized correlation IDs may cross from the AOP boundary into
151
+ // the hosting callback. A faulty observer must never affect the call.
152
+ if(base&&typeof options?.onBegin==='function'){
153
+ try{options.onBegin(Object.freeze({traceId:base.traceId,spanId:base.spanId}));}
154
+ catch{stats.sinkFailures++}
155
+ }
156
+ const execute=()=>Reflect.apply(target,thisArg,args);
157
+ let result;
158
+ try{
159
+ const storage=base?contextStore():null;
160
+ // A context-inspection API must see its caller's span, not the
161
+ // observation span created to record the inspection itself.
162
+ result=storage&&!options?.preserveCallerContext
163
+ ?storage.run({traceId:base.traceId,spanId:base.spanId},execute)
164
+ :execute();
165
+ }catch(e){mark('FAILED',e);throw e}
166
+ const failed=value=>{
167
+ try{return (layer==='mcp'&&value?.isError===true)
168
+ ||(layer==='browser'&&api.startsWith('browser.dispatch.')&&value===false)}
169
+ catch{stats.sinkFailures++;return false}
170
+ };
171
+ const failureCode=()=>({code:layer==='browser'
172
+ ?'BROWSER_MESSAGE_UNHANDLED':'MCP_TOOL_ERROR'});
173
+ // Do not assimilate arbitrary user thenables for telemetry: invoking
174
+ // their then() could cause a second business side effect. Observe native
175
+ // Promises only, otherwise record the synchronous return boundary.
176
+ let nativePromise=false;
177
+ try{nativePromise=result instanceof Promise}catch{stats.sinkFailures++}
178
+ if(nativePromise){
179
+ // Preserve the exact native Promise object and rejection semantics.
180
+ try{Promise.resolve(result).then(
181
+ value=>{
182
+ const isError=failed(value);
183
+ mark(isError?'FAILED':'OK',
184
+ isError?failureCode():undefined);
185
+ },
186
+ error=>mark('FAILED',error)
187
+ ).catch(()=>{stats.sinkFailures++});}
188
+ catch{stats.sinkFailures++}
189
+ return result;
190
+ }
191
+ const isError=failed(result);
192
+ mark(isError?'FAILED':'OK',
193
+ isError?failureCode():undefined);
194
+ return result;
195
+ }});
196
+ }
197
+ // A contract-driven facade for APIs whose safe name/ACL references
198
+ // depend on their arguments (Context). Domain code stays unaware of AOP.
199
+ function described(target,describe,onBegin){
200
+ if(typeof target!=='function'||typeof describe!=='function')
201
+ throw TypeError('API_ASPECT_TARGET_REQUIRED');
202
+ return new Proxy(target,{
203
+ get(fn,key,receiver){
204
+ if(key===Symbol.for('chat-loop.api-observed.v1'))return true;
205
+ return Reflect.get(fn,key,receiver);
206
+ },
207
+ apply(fn,thisArg,args){
208
+ let detail;
209
+ try{detail=describe(args)??{}}catch{detail={api:'api.invalid',mode:'unknown'}}
210
+ const wrapped=observe(detail.api,()=>Reflect.apply(fn,thisArg,args),
211
+ detail.surface??'sdk',{
212
+ onBegin:ids=>{if(typeof onBegin==='function')onBegin(detail,ids)}
213
+ });
214
+ return wrapped();
215
+ }
216
+ });
217
+ }
218
+ // One public method facade for both fixed-name SDK APIs and Context's
219
+ // descriptor-driven APIs. Neither case duplicates Proxy/cache mechanics.
220
+ function mapMethods(instance,wrap,descriptors=null){
221
+ if(!instance||typeof instance!=='object')return instance;
222
+ if(descriptors)
223
+ for(const [key,item] of Object.entries(Object.getOwnPropertyDescriptors(instance)))
224
+ if(typeof item.value==='function'&&!Object.hasOwn(descriptors,key))
225
+ throw TypeError('API_AUDIT_DESCRIPTOR_MISSING:'+key);
226
+ const facade={...instance},cache=new Map();
227
+ return new Proxy(facade,{
228
+ get(object,key,receiver){
229
+ const value=Reflect.get(object,key,receiver);
230
+ if(typeof value!=='function'||typeof key!=='string'
231
+ ||(descriptors&&!Object.hasOwn(descriptors,key)))return value;
232
+ // Existing public proxies already own a complete BEGIN/terminal pair.
233
+ if(value[Symbol.for('chat-loop.api-observed.v1')]===true)return value;
234
+ if(!cache.has(key))cache.set(key,wrap(key,value));
235
+ return cache.get(key);
236
+ },
237
+ set(){return false},defineProperty(){return false},deleteProperty(){return false}
238
+ });
239
+ }
240
+ const describedMethods=(instance,descriptors,onBegin)=>mapMethods(
241
+ instance,(key,value)=>described(value,descriptors[key],onBegin),descriptors);
242
+ const methods=(instance,prefix,surface='sdk')=>mapMethods(
243
+ instance,(key,value)=>observe(prefix+'.'+key,value,surface));
244
+ // Short-lived CLI/Native entrypoints may wait for telemetry *after* replying.
245
+ // No call to drain is made from a business execution path.
246
+ async function drain(timeoutMs=300){
247
+ const budget=Number.isSafeInteger(timeoutMs)?Math.max(0,Math.min(timeoutMs,750)):300;
248
+ const deadline=Date.now()+budget;
249
+ while(queue.length||bootstrap.length||scheduled||inFlight.size){
250
+ if(Date.now()>=deadline)return false;
251
+ await new Promise(resolve=>setTimeout(resolve,Math.min(10,deadline-Date.now())));
252
+ }
253
+ // Clearing a queue is not evidence of successful transport. A failed
254
+ // sink or overflow remains an explicit incomplete audit outcome.
255
+ return stats.dropped===0&&stats.sinkFailures===0;
256
+ }
257
+ const subscribe=observe('subscribeApiLog',listener=>{
258
+ if(typeof listener!=='function')throw TypeError('API_LOG_LISTENER_REQUIRED');
259
+ listeners.add(listener);
260
+ if(bootstrap.length){
261
+ const capacity=Math.max(0,MAX_PENDING-queue.length);
262
+ const replay=bootstrap.splice(0,capacity);
263
+ if(bootstrap.length){stats.dropped+=bootstrap.length;bootstrap.length=0}
264
+ queue.unshift(...replay);
265
+ if(queue.length&&!scheduled){scheduled=true;schedule(flush)}
266
+ }
267
+ return ()=>listeners.delete(listener);
268
+ },'internal');
269
+ return Object.freeze({observe,methods,described,describedMethods,subscribe,drain,
270
+ health:()=>Object.freeze({...stats,pending:queue.length+bootstrap.length,
271
+ bootstrap:bootstrap.length,inFlight:inFlight.size}),
272
+ current:currentApiTrace,withParent:withApiTraceParent});
273
+ }
@@ -0,0 +1,265 @@
1
+ // Trace Reader: bounded, scoped, read-only diagnostic and API usage views.
2
+ import {constants as FS,createReadStream,closeSync,fstatSync,openSync} from 'node:fs';
3
+ import {createInterface} from 'node:readline';
4
+
5
+ export function makeTraceReader(options,deps){
6
+ const {TRACE_SCHEMA_VERSION,fail,validStoredFamily,object,isId,safeScope,
7
+ safeRef,natural,keys,secureFile,eventRule,EVENT,CODE,COMPONENTS,STATUSES}=deps;
8
+ const OUTPUT=['time','schemaVersion','eventId','traceId','spanId','parentSpanId',
9
+ 'writerEpoch','writerSeq','component','event','projectRef','taskRef','sessionRef',
10
+ 'generation','requestId','actionId','status','errorCode','durationMs','api','apiName','evidenceRef'];
11
+ const publicEvent=v=>Object.fromEntries(OUTPUT.flatMap(k=>{
12
+ const value=k==='status'
13
+ ?(v.schemaVersion===1?v.traceStatus??v.status:v.status):v[k];
14
+ return value===undefined||value===null?[]:[[k,value]];
15
+ }));
16
+ // The on-disk log is evidence, not executable truth. Reject forged/malformed
17
+ // fields at the read boundary too; do not trust a matching projectRef alone.
18
+ const STORED_FIELDS=new Set(['time','schemaVersion','eventId','traceId',
19
+ 'spanId','parentSpanId','writerEpoch','writerSeq','component','event',
20
+ 'projectRef','taskRef','sessionRef','generation','requestId','actionId',
21
+ 'status','errorCode','durationMs','api','apiName','evidenceRef']);
22
+ const validStored=v=>object(v)
23
+ &&(v.schemaVersion===1||v.schemaVersion===TRACE_SCHEMA_VERSION)
24
+ &&(v.schemaVersion===1||Object.keys(v).every(k=>STORED_FIELDS.has(k)))
25
+ &&isId(v.eventId)&&isId(v.traceId)
26
+ &&isId(v.spanId)&&isId(v.writerEpoch)&&natural(v.writerSeq)
27
+ &&EVENT.test(v.event||'')&&COMPONENTS.has(v.component)
28
+ &&STATUSES.has(v.schemaVersion===1?v.traceStatus??v.status:v.status)
29
+ &&typeof v.time==='string'&&v.time.length<=40&&Number.isFinite(Date.parse(v.time))
30
+ &&safeScope(v.projectRef)
31
+ &&['parentSpanId','taskRef','sessionRef','requestId','actionId','evidenceRef']
32
+ .every(k=>v[k]==null||(k==='parentSpanId'?isId(v[k]):safeRef(v[k])))
33
+ &&(v.errorCode==null||typeof v.errorCode==='string'&&CODE.test(v.errorCode))
34
+ &&(v.generation==null||natural(v.generation))
35
+ &&(v.durationMs==null||natural(v.durationMs))
36
+ &&(v.event==='typed.api.call'||!Object.hasOwn(v,'apiName'))
37
+ &&validStoredFamily(v);
38
+ function filterInput(v,allowed){
39
+ keys(v,new Set(['traceId','sessionRef','projectRef','maxEvents']));
40
+ if(!safeScope(v.projectRef)||!allowed.includes(v.projectRef))
41
+ throw fail('TRACE_PROJECT_ACCESS_DENIED');
42
+ if(v.traceId!==undefined&&!isId(v.traceId))throw fail('TRACE_INVALID_ID');
43
+ if(v.sessionRef!==undefined&&!safeRef(v.sessionRef))
44
+ throw fail('TRACE_INVALID_REFERENCE');
45
+ if(!v.traceId&&!v.sessionRef)throw fail('TRACE_FILTER_REQUIRED');
46
+ const maxEvents=v.maxEvents??100;
47
+ if(!Number.isSafeInteger(maxEvents)||maxEvents<1||maxEvents>200)
48
+ throw fail('TRACE_INVALID_LIMIT');
49
+ return {...v,maxEvents};
50
+ }
51
+ function createTraceReader({filePath,allowedProjects,maxSegments=5}){
52
+ if(!Array.isArray(allowedProjects)||!allowedProjects.length||
53
+ allowedProjects.some(x=>!safeScope(x)))
54
+ throw fail('TRACE_PROJECT_SCOPE_REQUIRED');
55
+ if(!Number.isSafeInteger(maxSegments)||maxSegments<1||maxSegments>5)
56
+ throw fail('TRACE_ROTATION_INVALID');
57
+ async function query(opts){
58
+ const filter=filterInput(opts,allowedProjects);
59
+ const files=[...Array.from({length:maxSegments},(_,i)=>filePath+'.'+(maxSegments-i)),
60
+ filePath].map(path=>({path,stat:secureFile(path)})).filter(x=>x.stat);
61
+ if(!files.length)return {events:[],matched:0,legacyUncorrelated:true,gapped:true,
62
+ errors:['TRACE_LOG_MISSING'],truncated:false};
63
+ if(files.reduce((sum,x)=>sum+x.stat.size,0)>64*1024*1024)
64
+ throw fail('TRACE_FILE_TOO_LARGE');
65
+ const seen=new Set(),events=[],errors=[],writerEpochs=new Set();
66
+ let matched=0,corrupt=0,legacy=0;
67
+ for(const item of files){
68
+ const fd=openSync(item.path,FS.O_RDONLY|FS.O_NOFOLLOW);
69
+ const opened=fstatSync(fd);
70
+ if(!opened.isFile()||(opened.mode&0o077)||process.getuid&&opened.uid!==process.getuid()){
71
+ closeSync(fd);throw fail('TRACE_FILE_UNTRUSTED');
72
+ }
73
+ const stream=createReadStream(item.path,{fd,autoClose:true,encoding:'utf8'});
74
+ const lines=createInterface({input:stream,crlfDelay:Infinity});
75
+ try{
76
+ for await(const line of lines){
77
+ if(!line.trim())continue;
78
+ if(Buffer.byteLength(line)>8192){corrupt++;continue}
79
+ let entry;try{entry=JSON.parse(line)}catch{corrupt++;continue}
80
+ // v1 is retained read-only evidence, never rewritten or promoted to
81
+ // the new typed API contract; unknown schemas stay untrusted.
82
+ if(entry.schemaVersion!==TRACE_SCHEMA_VERSION&&entry.schemaVersion!==1){
83
+ legacy++;continue;
84
+ }
85
+ if(entry.projectRef!==filter.projectRef||
86
+ filter.traceId&&entry.traceId!==filter.traceId||
87
+ filter.sessionRef&&entry.sessionRef!==filter.sessionRef)continue;
88
+ if(!validStored(entry)){corrupt++;continue}
89
+ if(seen.has(entry.eventId))continue;
90
+ seen.add(entry.eventId);matched++;
91
+ writerEpochs.add(entry.writerEpoch);
92
+ events.push(publicEvent(entry));
93
+ if(events.length>filter.maxEvents)events.shift();
94
+ }
95
+ }finally{lines.close();stream.destroy()}
96
+ }
97
+ if(corrupt)errors.push('TRACE_MALFORMED_LINES');
98
+ return {events,matched,legacyUncorrelated:legacy>0,gapped:corrupt>0,
99
+ // A restart is not proof of loss, but evidence continuity across epochs
100
+ // cannot be asserted by a log reader alone, even with later ACKs.
101
+ writerRestartUnverified:writerEpochs.size>1,
102
+ errors,truncated:matched>filter.maxEvents};
103
+ }
104
+ async function diagnose(opts){
105
+ const result=await query(opts);
106
+ const pending=new Map(),gaps=[...result.errors],unmatchedApiTerminals=[];
107
+ let lastConfirmed=null,unknown=false;
108
+ for(const e of result.events){
109
+ if(e.status==='CONFIRMED')lastConfirmed={
110
+ eventId:e.eventId,event:e.event,time:e.time,component:e.component
111
+ };
112
+ if(e.status==='UNKNOWN'||e.status==='BLOCKED')unknown=true;
113
+ // V2 API BEGIN and terminal always share one spanId, even when
114
+ // several sibling APIs share the same traceId. V1 used traceId.
115
+ const apiCall=e.event==='context.api'||e.event==='typed.api.call';
116
+ const id=apiCall?(e.schemaVersion===1?e.traceId:e.spanId):
117
+ e.actionId||e.requestId;
118
+ if(!id)continue;
119
+ if(e.status==='BEGIN'){
120
+ if(pending.has(id)&&apiCall)gaps.push('DUPLICATE_API_BEGIN');
121
+ pending.set(id,{event:e.event,apiCall,apiName:e.apiName||
122
+ e.api?.name||null,spanId:e.spanId,beginTime:e.time});
123
+ }else if(['CONFIRMED','FAILED','UNKNOWN','BLOCKED'].includes(e.status)){
124
+ if(apiCall&&!pending.has(id)&&!result.truncated)
125
+ unmatchedApiTerminals.push({event:e.event,spanId:e.spanId});
126
+ pending.delete(id);
127
+ }
128
+ }
129
+ const incompleteApiSpans=[...pending.values()].filter(x=>x.apiCall)
130
+ .slice(0,30);
131
+ if(incompleteApiSpans.length)gaps.push('MISSING_API_TERMINAL');
132
+ if(unmatchedApiTerminals.length)gaps.push('ORPHAN_API_TERMINAL');
133
+ if(result.truncated)gaps.push('TRACE_WINDOW_TRUNCATED');
134
+ if(result.writerRestartUnverified)gaps.push('TRACE_WRITER_RESTART_UNVERIFIED');
135
+ if(result.legacyUncorrelated)gaps.push('LEGACY_EVENTS_UNCORRELATED');
136
+ if(pending.size)gaps.push('MISSING_ACTION_RECEIPT');
137
+ if(!result.events.length)gaps.push('NO_MATCHING_EVENTS');
138
+ return {traceId:opts.traceId??null,projectRef:opts.projectRef,
139
+ inspected:result.events.length,totalMatched:result.matched,lastConfirmed,
140
+ incompleteApiSpans,unmatchedApiTerminals:unmatchedApiTerminals.slice(0,30),
141
+ lastEvent:result.events.at(-1)??null,unknown,gaps:[...new Set(gaps)],
142
+ confidence:gaps.length?'INCOMPLETE':'TRACE_ONLY',
143
+ retryDisposition:unknown||pending.size||gaps.length?
144
+ 'VERIFY_AUTHORITATIVE_RECEIPT_FIRST':'NO_AUTOMATIC_RETRY',
145
+ timeline:result.events};
146
+ }
147
+ // Operational API usage is a sanitized system-local observation view.
148
+ // It cannot read business projects, arguments, results or raw chat data.
149
+ async function apiUsage({windowMinutes=60,limit=100}={}){
150
+ if(!allowedProjects.includes('api_system'))
151
+ throw fail('TRACE_PROJECT_ACCESS_DENIED');
152
+ if(!Number.isSafeInteger(windowMinutes)||windowMinutes<1||windowMinutes>1440
153
+ ||!Number.isSafeInteger(limit)||limit<1||limit>200)
154
+ throw fail('TRACE_INVALID_LIMIT');
155
+ const now=Date.now(),since=now-windowMinutes*60000;
156
+ const calls=new Map(),seenEvents=new Set();
157
+ const files=[...Array.from({length:maxSegments},(_,i)=>
158
+ filePath+'.'+(maxSegments-i)),filePath]
159
+ .map(path=>({path,stat:secureFile(path)})).filter(x=>x.stat);
160
+ if(files.reduce((n,x)=>n+x.stat.size,0)>64*1024*1024)
161
+ throw fail('TRACE_FILE_TOO_LARGE');
162
+ let malformed=0;
163
+ for(const item of files){
164
+ const fd=openSync(item.path,FS.O_RDONLY|FS.O_NOFOLLOW);
165
+ const opened=fstatSync(fd);
166
+ if(!opened.isFile()||(opened.mode&0o077)
167
+ ||process.getuid&&opened.uid!==process.getuid()){
168
+ closeSync(fd);throw fail('TRACE_FILE_UNTRUSTED');
169
+ }
170
+ const stream=createReadStream(item.path,{fd,autoClose:true,encoding:'utf8'});
171
+ const lines=createInterface({input:stream,crlfDelay:Infinity});
172
+ try{
173
+ for await(const line of lines){
174
+ if(!line.trim())continue;
175
+ if(Buffer.byteLength(line)>8192){malformed++;continue}
176
+ let v;try{v=JSON.parse(line)}catch{malformed++;continue}
177
+ // New event families provide their own safe usage projection.
178
+ // A Provider never acquires access to a Project by being registered.
179
+ if(!allowedProjects.includes(v?.projectRef))continue;
180
+ const rule=eventRule(v);
181
+ if(typeof rule?.usageName!=='function')continue;
182
+ if(!['BEGIN','CONFIRMED','FAILED'].includes(v.status))continue;
183
+ if(!validStored(v)){malformed++;continue}
184
+ if(seenEvents.has(v.eventId))continue;
185
+ seenEvents.add(v.eventId);
186
+ const time=Date.parse(v.time);
187
+ if(!Number.isFinite(time)||time<since||time>now+60000)continue;
188
+ let name;
189
+ try{
190
+ const view={...v};
191
+ if(object(view.api))view.api=Object.freeze({...view.api});
192
+ name=rule.usageName(Object.freeze(view));
193
+ }catch{malformed++;continue}
194
+ if(typeof name!=='string'||
195
+ !/^[a-zA-Z][a-zA-Z0-9_.:-]{1,126}$/.test(name)||
196
+ // New typed families cannot impersonate an existing MCP, Context,
197
+ // Extension, Trace or Tunnel API in a usage report.
198
+ !['context.api','typed.api.call'].includes(rule.id)
199
+ &&!name.startsWith(rule.id+'.')){
200
+ malformed++;continue
201
+ }
202
+ // V2 root and child API calls both use their own stable spanId.
203
+ // Grouping V2 roots by shared traceId can silently hide an orphan
204
+ // BEGIN when another sibling succeeds. V1 used traceId.
205
+ const callKey=v.schemaVersion===1?v.traceId:v.spanId;
206
+ const key=v.projectRef+':'+v.event+':'+callKey;
207
+ const call=calls.get(key)||{api:name,begin:false,end:null,durationMs:null};
208
+ if(call.api!==name){malformed++;continue}
209
+ if(v.status==='BEGIN')call.begin=true;
210
+ if(v.status==='CONFIRMED'||v.status==='FAILED'){
211
+ if(call.end&&call.end!==v.status)call.end='UNKNOWN';
212
+ else if(!call.end)call.end=v.status;
213
+ if(Number.isSafeInteger(v.durationMs))
214
+ call.durationMs=v.durationMs;
215
+ }
216
+ calls.set(key,call);
217
+ }
218
+ }finally{lines.close();stream.destroy()}
219
+ }
220
+ // Count calls by their BEGIN inside the time window, never by the
221
+ // number of log records. An unmatched completion is not a new API call.
222
+ const counts=new Map();
223
+ let orphanCompletions=0;
224
+ for(const call of calls.values()){
225
+ if(!call.begin){if(call.end)orphanCompletions++;continue}
226
+ const entry=counts.get(call.api)||{api:call.api,calls:0,
227
+ success:0,failures:0,incomplete:0,totalDurationMs:0,durationSamples:0,
228
+ maxDurationMs:0};
229
+ entry.calls++;
230
+ if(call.end==='CONFIRMED')entry.success++;
231
+ else if(call.end==='FAILED')entry.failures++;
232
+ else entry.incomplete++;
233
+ if(call.end&&!['UNKNOWN'].includes(call.end)
234
+ &&Number.isSafeInteger(call.durationMs)){
235
+ entry.totalDurationMs+=call.durationMs;
236
+ entry.durationSamples++;
237
+ entry.maxDurationMs=Math.max(entry.maxDurationMs,call.durationMs);
238
+ }
239
+ counts.set(call.api,entry);
240
+ }
241
+ const all=[...counts.values()].map(({totalDurationMs,durationSamples,...entry})=>({
242
+ ...entry,avgDurationMs:durationSamples
243
+ ?Number((totalDurationMs/durationSamples).toFixed(2)):null,
244
+ maxDurationMs:durationSamples?entry.maxDurationMs:null
245
+ }));
246
+ all.sort((a,b)=>b.calls-a.calls||a.api.localeCompare(b.api));
247
+ const api=all.slice(0,limit).map(entry=>({
248
+ ...entry,callsPerMinute:Number((entry.calls/windowMinutes).toFixed(3))
249
+ }));
250
+ return {scope:'api_system',windowMinutes,
251
+ calls:all.reduce((n,x)=>n+x.calls,0),
252
+ success:all.reduce((n,x)=>n+x.success,0),
253
+ failures:all.reduce((n,x)=>n+x.failures,0),
254
+ incomplete:all.reduce((n,x)=>n+x.incomplete,0),
255
+ orphanCompletions,api,malformed,limited:all.length>limit,
256
+ source:files.length?'TRACE_ONLY':'TRACE_LOG_MISSING'};
257
+ }
258
+ return {query,diagnose,apiUsage,health:()=>{
259
+ const st=secureFile(filePath);
260
+ return {status:st?'READABLE':'TRACE_LOG_MISSING',
261
+ bytes:st?.size??0,projectScopes:allowedProjects.length};
262
+ }};
263
+ }
264
+ return createTraceReader(options);
265
+ }