@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
package/README.md CHANGED
@@ -63,8 +63,8 @@ The six built-in Providers are:
63
63
  - `extension`: official pinned Extension CLI and nine scoped actions
64
64
  - `runtime`: exact-request receipt lookup without replay
65
65
  - `context`: independent Context SDK read/write schemas and fixed CLI
66
- - `trace`: Project-scoped diagnosis and SOFT stage observations
67
- - `form`: two ChatGPT-only fixed-card adapters, `chat_loop_form__prepare` and `chat_loop_form__submit`; optional generated `formId`, no independent approval authority, managed writes delegate to Context
66
+ - `trace`: Project-scoped diagnosis and SOFT stage observations, plus a bearer-token-scoped Form Trace lookup using the Prepare `traceRef`
67
+ - `form`: a stateless ChatGPT A/B MCP App adapter; `prepare` renders a caller-supplied card, preserves or generates `formId`, and returns a random `traceRef`; `submit` validates the choice/comment and asks the shared Supervisor to durably claim that `traceRef` once before the App may request `ui/message`. The claim is an at-most-once UI side-effect guard, not business state, user identity, message delivery or approval. Form owns no Context, approval, caller, workflow, expiry, cache or form lifecycle; Prepare/Submit observations and the claim are correlated in the existing Trace by `sessionRef=traceRef` and `evidenceRef=formId`.
68
68
 
69
69
  `npm run build:providers` generates `providers.generated.mjs`, the static
70
70
  assembly and release fingerprint manifest. Both `tools/list` and `tools/call`
@@ -107,7 +107,12 @@ to any existing Provider, the Gateway, or either npm entrypoint.
107
107
  trigger retries of unknown effects. In particular, verified Extension MCP
108
108
  results are returned **before** optional Trace transport finishes; a
109
109
  slow, rejecting or unavailable observer cannot replace the action receipt.
110
- These events are best-effort evidence, not an all-API AOP coverage claim.
110
+ Form submission claims are different: the Supervisor must durably append
111
+ the at-most-once claim before Submit returns success; if that receipt is
112
+ unknown or the Trace writer is unhealthy, the App must not request a user
113
+ message or retry. Form observations remain best-effort evidence and
114
+ dropped observations are surfaced by Trace health; they are not an
115
+ all-API AOP coverage claim.
111
116
 
112
117
  No legacy Task Registry MCP or JSON fallback is shipped. Historical
113
118
  SourceUnit files remain migration evidence, not alternate current facts.
package/index.mjs CHANGED
@@ -12,6 +12,9 @@ import {createCliCommandRouter} from './lib/cli-command-router.mjs';
12
12
  let auditPort=null;
13
13
  const auditBacklog=[];
14
14
  let auditDraining=false,auditRetryTimer=null,auditNoOwnerRetries=0,auditLost=0;
15
+ let formObservationLost=0;
16
+ const OBSERVER_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;
17
+ const localError=code=>Object.assign(Error(code),{code});
15
18
  const MAX_AUDIT_BACKLOG=1024,MAX_NO_OWNER_RETRIES=20;
16
19
  // The CLI can emit BEGIN before a cold Supervisor has opened its IPC socket.
17
20
  // Keep ordered, bounded soft observations until that exact socket exists;
@@ -153,8 +156,15 @@ async function runtime(){
153
156
  release.configureRelease({PACKAGE_VERSION:control.PACKAGE_VERSION,
154
157
  activeDesktopCommands:releasePreflight.activeDesktopCommands,
155
158
  awaitStopped:releasePreflight.awaitStopped});
159
+ const traceTalk=async request=>{
160
+ const result=await control.talk(request);
161
+ if(request?.action!=='__trace_health'||!result?.traceHealth)return result;
162
+ const health={...result.traceHealth,formObservationLost};
163
+ if(formObservationLost>0&&health.status==='OK')health.status='TRACE_DEGRADED';
164
+ return {...result,traceHealth:health};
165
+ };
156
166
  traceGateway.configureTraceGateway({paths:control.paths,
157
- talk:control.talk,CONTRACT:control.CONTRACT});
167
+ talk:traceTalk,CONTRACT:control.CONTRACT});
158
168
  contextGateway.configureContextApiLog({
159
169
  current:apiAspect.current,
160
170
  record:entry=>control.talk({
@@ -168,14 +178,44 @@ async function runtime(){
168
178
  // tools/call. Adding an independent provider never edits this Gateway.
169
179
  const coreToolRouter=createMcpToolRouter(providerDefinitions,{
170
180
  control,release,terminal:terminalPolicy,context:contextGateway,
171
- form:{current:apiAspect.current,observe:payload=>control.talk({
172
- contract:control.CONTRACT,action:'__trace_observation',
173
- requestId:randomUUID(),event:payload.event,status:'CONFIRMED',
174
- traceId:payload.traceId,spanId:payload.spanId,
175
- projectRef:payload.projectRef,
176
- ...(payload.taskRef?{taskRef:payload.taskRef}:{}),
177
- evidenceRef:payload.formId
178
- },1800)},trace:traceGateway,
181
+ form:{
182
+ current:apiAspect.current,
183
+ claimSubmission:async ({formId,traceRef})=>{
184
+ const parent=apiAspect.current();
185
+ if(!parent||!OBSERVER_UUID.test(parent.traceId||'')
186
+ ||!OBSERVER_UUID.test(parent.spanId||''))
187
+ throw localError('FORM_SUBMISSION_CLAIM_PARENT_MISSING');
188
+ let result;
189
+ try{
190
+ result=await control.talk({
191
+ contract:control.CONTRACT,action:'__form_submission_claim',
192
+ requestId:randomUUID(),formId,traceRef,
193
+ traceId:parent.traceId,spanId:parent.spanId
194
+ },1800);
195
+ }catch{
196
+ throw localError('FORM_SUBMISSION_CLAIM_UNKNOWN');
197
+ }
198
+ if(result?.status!=='FORM_SUBMISSION_CLAIMED'
199
+ ||!OBSERVER_UUID.test(result.eventId||''))
200
+ throw localError(result?.error?.code||'FORM_SUBMISSION_CLAIM_UNKNOWN');
201
+ return result;
202
+ },
203
+ observe:async payload=>{
204
+ const result=await control.talk({
205
+ contract:control.CONTRACT,action:'__trace_observation',
206
+ requestId:randomUUID(),event:payload.event,
207
+ status:payload.status||'CONFIRMED',
208
+ traceId:payload.traceId,spanId:payload.spanId,
209
+ projectRef:'api_system',sessionRef:payload.traceRef,
210
+ evidenceRef:payload.formId,
211
+ ...(payload.errorCode?{errorCode:payload.errorCode}:{})
212
+ },1800);
213
+ if(result?.status!=='OK'||!OBSERVER_UUID.test(result.eventId||''))
214
+ throw localError(result?.error?.code||'FORM_TRACE_OBSERVATION_UNCONFIRMED');
215
+ return result;
216
+ },
217
+ lost:()=>{formObservationLost++}
218
+ },trace:traceGateway,
179
219
  extension:{
180
220
  forwardExtensionAction:extensionProxy.forwardExtensionAction,
181
221
  observeExtensionResult:traceGateway.observeExtensionResult
@@ -0,0 +1,157 @@
1
+ import {createTraceWriter,createTraceReader} from '@tomflow/chatloop-trace';
2
+
3
+ const OBSERVER_ID=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
4
+ const FORM_ID=/^[A-Za-z0-9][A-Za-z0-9_-]{7,79}$/;
5
+ const OBSERVER_NAME=/^(?:mcp|extension|tools|context|trace|tunnel)\.[A-Za-z][A-Za-z0-9_.:-]{1,119}$/;
6
+ const OBSERVER_KEYS=new Set(['contract','action','requestId','callId',
7
+ 'traceId','spanId','parentSpanId','apiName','phase','durationMs','errorCode',
8
+ 'ownerNonce','managerPid']);
9
+
10
+ export function createSupervisorObservability({
11
+ filePath,rotationEnabled,contextUsageGrant,contract,nonce,processId,
12
+ createSupervisorTraceBridge,error
13
+ }){
14
+ const traceWriter=createTraceWriter({
15
+ filePath,enableRotation:rotationEnabled
16
+ });
17
+ const usageScopes=['api_system',...(
18
+ typeof contextUsageGrant==='string'&&
19
+ /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(contextUsageGrant)
20
+ ?[contextUsageGrant]:[])];
21
+ const usageReader=createTraceReader({filePath,allowedProjects:usageScopes});
22
+ const formClaimInFlight=new Set();
23
+
24
+ // Control telemetry is bounded and asynchronous; it never changes a
25
+ // confirmed or unknown business result.
26
+ const MAX_CONTROL_AUDIT=1024,CONTROL_AUDIT_BATCH=64,controlAudit=[];
27
+ let controlAuditScheduled=false,controlAuditDropped=0;
28
+ const flushControlAudit=()=>{
29
+ controlAuditScheduled=false;
30
+ for(let i=0;i<CONTROL_AUDIT_BATCH&&controlAudit.length;i++){
31
+ const {event,detail}=controlAudit.shift();
32
+ try{traceWriter.recordControl(event,detail)}catch{}
33
+ }
34
+ if(controlAudit.length){
35
+ controlAuditScheduled=true;
36
+ setImmediate(flushControlAudit);
37
+ }
38
+ };
39
+ const flushPending=()=>{while(controlAudit.length)flushControlAudit()};
40
+ const log=(event,detail={})=>{
41
+ if(controlAudit.length>=MAX_CONTROL_AUDIT){controlAuditDropped++;return}
42
+ controlAudit.push({event,detail:{
43
+ status:detail?.status,requestId:detail?.requestId,
44
+ errorCode:detail?.errorCode
45
+ }});
46
+ if(!controlAuditScheduled){
47
+ controlAuditScheduled=true;
48
+ setImmediate(flushControlAudit);
49
+ }
50
+ };
51
+ const traceHealth=()=>{
52
+ const health=traceWriter.health();
53
+ const writerAuditLost=(health.apiObservation?.dropped||0)>0||
54
+ (health.apiObservation?.sinkFailures||0)>0;
55
+ return {...health,controlAuditDropped,controlAuditPending:controlAudit.length,
56
+ ...(writerAuditLost&&health.status==='OK'
57
+ ?{status:'TRACE_DEGRADED',errorCode:'TRACE_WRITER_API_LOG_GAP'}:{}),
58
+ ...(controlAuditDropped>0&&health.status==='OK'
59
+ ?{status:'TRACE_DEGRADED',errorCode:'TRACE_AUDIT_QUEUE_SATURATED'}:{})};
60
+ };
61
+ const {handleTraceObservation,traceNativeReceipt}=createSupervisorTraceBridge({
62
+ traceWriter,contract,error
63
+ });
64
+
65
+ function recordApiObservation(req){
66
+ if(req?.ownerNonce!==undefined||req?.managerPid!==undefined){
67
+ if(req.ownerNonce!==nonce||req.managerPid!==processId)
68
+ throw Object.assign(Error('TRACE_API_OWNER_MISMATCH'),
69
+ {code:'TRACE_API_OWNER_MISMATCH'});
70
+ }
71
+ if(req?.contract!==contract||!OBSERVER_ID.test(req.requestId||'')||
72
+ !OBSERVER_ID.test(req.callId||'')||!OBSERVER_ID.test(req.traceId||'')||
73
+ req.spanId!==req.callId||
74
+ (req.parentSpanId!==undefined&&
75
+ (!OBSERVER_ID.test(req.parentSpanId)||req.parentSpanId===req.spanId))||
76
+ !OBSERVER_NAME.test(req.apiName||'')||
77
+ !['BEGIN','OK','FAILED'].includes(req.phase)||
78
+ Object.keys(req).some(k=>!OBSERVER_KEYS.has(k))||
79
+ (req.phase==='BEGIN'
80
+ ?req.durationMs!==undefined||req.errorCode!==undefined
81
+ :!Number.isSafeInteger(req.durationMs)||req.durationMs<0||
82
+ (req.phase==='FAILED'
83
+ ?req.errorCode!=='MCP_TOOL_ERROR'&&
84
+ !/^[A-Z][A-Z0-9_]{1,95}$/.test(req.errorCode||'')
85
+ :req.errorCode!==undefined)))
86
+ throw Object.assign(Error('TRACE_API_INVALID'),{code:'TRACE_API_INVALID'});
87
+ const written=traceWriter.record({
88
+ event:'typed.api.call',component:'gateway',projectRef:'api_system',
89
+ traceId:req.traceId,spanId:req.spanId,
90
+ ...(req.parentSpanId?{parentSpanId:req.parentSpanId}:{}),
91
+ apiName:req.apiName,
92
+ status:req.phase==='BEGIN'?'BEGIN':req.phase==='OK'?'CONFIRMED':'FAILED',
93
+ ...(req.phase!=='BEGIN'?{durationMs:req.durationMs}:{}),
94
+ ...(req.phase==='FAILED'?{errorCode:req.errorCode}:{})
95
+ });
96
+ return {contract,requestId:req.requestId,status:'OK',eventId:written.eventId};
97
+ }
98
+
99
+ async function apiUsage(req){
100
+ if(req?.contract!==contract||
101
+ Object.keys(req).some(k=>!['contract','action','requestId',
102
+ 'windowMinutes','limit'].includes(k))||
103
+ !OBSERVER_ID.test(req.requestId||''))
104
+ throw Object.assign(Error('TRACE_API_INVALID'),{code:'TRACE_API_INVALID'});
105
+ const summary=await usageReader.apiUsage({
106
+ windowMinutes:req.windowMinutes??60,limit:req.limit??100});
107
+ return {contract,requestId:req.requestId,status:'OK',summary};
108
+ }
109
+
110
+ async function claimFormSubmission(req){
111
+ const allowed=new Set(['contract','action','requestId','formId','traceRef',
112
+ 'traceId','spanId']);
113
+ if(req?.contract!==contract||Object.keys(req).some(key=>!allowed.has(key))||
114
+ !OBSERVER_ID.test(req.requestId||'')||
115
+ typeof req.formId!=='string'||!FORM_ID.test(req.formId)||
116
+ !OBSERVER_ID.test(req.traceRef||'')||!OBSERVER_ID.test(req.traceId||'')||
117
+ !OBSERVER_ID.test(req.spanId||''))
118
+ throw error('FORM_SUBMISSION_CLAIM_INVALID');
119
+ if(formClaimInFlight.has(req.traceRef))
120
+ throw error('FORM_ALREADY_SUBMITTED');
121
+ formClaimInFlight.add(req.traceRef);
122
+ try{
123
+ if(traceWriter.health().status!=='OK')
124
+ throw error('FORM_SUBMISSION_CLAIM_UNVERIFIED');
125
+ const prior=await usageReader.diagnose({projectRef:'api_system',
126
+ sessionRef:req.traceRef,maxEvents:200});
127
+ const preparations=prior.timeline.filter(event=>
128
+ event.event==='form.prepared.soft_observed');
129
+ if(prior.gaps.some(gap=>gap!=='NO_MATCHING_EVENTS')||!preparations.length)
130
+ throw error('FORM_SUBMISSION_CLAIM_UNVERIFIED');
131
+ if(preparations.some(event=>event.evidenceRef!==req.formId))
132
+ throw error('FORM_TRACE_REF_REUSED');
133
+ const claims=prior.timeline.filter(event=>
134
+ event.event==='form.submission.claimed');
135
+ if(claims.length){
136
+ if(claims.some(event=>event.evidenceRef!==req.formId))
137
+ throw error('FORM_TRACE_REF_REUSED');
138
+ throw error('FORM_ALREADY_SUBMITTED');
139
+ }
140
+ const written=traceWriter.record({
141
+ traceId:req.traceId,parentSpanId:req.spanId,
142
+ projectRef:'api_system',sessionRef:req.traceRef,
143
+ requestId:req.requestId,component:'gateway',
144
+ event:'form.submission.claimed',status:'CONFIRMED',
145
+ evidenceRef:req.formId
146
+ });
147
+ if(!written?.eventId)throw error('FORM_SUBMISSION_CLAIM_UNRECORDED');
148
+ return {contract,requestId:req.requestId,
149
+ status:'FORM_SUBMISSION_CLAIMED',eventId:written.eventId};
150
+ }finally{
151
+ formClaimInFlight.delete(req.traceRef);
152
+ }
153
+ }
154
+
155
+ return {log,traceHealth,handleTraceObservation,traceNativeReceipt,
156
+ recordApiObservation,apiUsage,claimFormSubmission,flushPending};
157
+ }
@@ -1,7 +1,7 @@
1
1
  import {randomUUID} from 'node:crypto';
2
- import {createTraceWriter,createTraceReader} from '@tomflow/chatloop-trace';
3
2
  import {closeSync, existsSync, openSync, readFileSync, unlinkSync, writeFileSync, chmodSync} from 'node:fs';
4
3
  import {createServer} from 'node:net';
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
7
  let CONTRACT, VERSION, PACKAGE_VERSION, registry, paths, ensurePrivateDir, ACTIONS, createAdapter, createSupervisorTraceBridge, loadContextControlSecret, handleContextControl;
@@ -36,118 +36,18 @@ function rememberRequest(id,payload,promise){
36
36
  if(seen.size>MAX_REPLAY_RESULTS)seen.delete(seen.keys().next().value);
37
37
  }
38
38
  const p=paths(), nonce=randomUUID();
39
- const traceWriter=createTraceWriter({
40
- filePath:p.log,enableRotation:process.env.CHAT_LOOP_TRACE_ROTATE_ENABLE==='1'
41
- });
42
- // One exact Context grant may contribute only sanitized method counts to
43
- // the local usage view. Never widen authorization with a multi-project string.
44
- const contextUsageGrant=process.env.CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS;
45
- const usageScopes=['api_system',...(
46
- typeof contextUsageGrant==='string'&&
47
- /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(contextUsageGrant)
48
- ?[contextUsageGrant]:[])];
49
- const usageReader=createTraceReader({
50
- filePath:p.log,allowedProjects:usageScopes
39
+ const error=(code,message=code)=>({code,message});
40
+ const observability=createSupervisorObservability({
41
+ filePath:p.log,
42
+ rotationEnabled:process.env.CHAT_LOOP_TRACE_ROTATE_ENABLE==='1',
43
+ contextUsageGrant:process.env.CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS,
44
+ contract:CONTRACT,nonce,processId:process.pid,
45
+ createSupervisorTraceBridge,error
51
46
  });
52
- const OBSERVER_ID=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
53
- // Namespaced, sanitized public entrypoints: MCP, SDK, CLI, Native and Browser.
54
- // Never accept raw UI text, arguments, URLs or other caller payloads.
55
- const OBSERVER_NAME=/^(?:mcp|extension|tools|context|trace|tunnel)\.[A-Za-z][A-Za-z0-9_.:-]{1,119}$/;
56
- const OBSERVER_KEYS=new Set(['contract','action','requestId','callId',
57
- 'traceId','spanId','parentSpanId','apiName','phase','durationMs','errorCode',
58
- 'ownerNonce','managerPid']);
59
- function recordApiObservation(req){
60
- // Native audit carries its exact Manager lock identity on the same IPC
61
- // request. The internal Tools producer uses the existing trusted channel.
62
- if(req?.ownerNonce!==undefined||req?.managerPid!==undefined){
63
- if(req.ownerNonce!==nonce||req.managerPid!==process.pid)
64
- throw Object.assign(Error('TRACE_API_OWNER_MISMATCH'),
65
- {code:'TRACE_API_OWNER_MISMATCH'});
66
- }
67
- if(req?.contract!==CONTRACT||!OBSERVER_ID.test(req.requestId||'')||
68
- !OBSERVER_ID.test(req.callId||'')||
69
- !OBSERVER_ID.test(req.traceId||'')||
70
- req.spanId!==req.callId||
71
- (req.parentSpanId!==undefined&&
72
- (!OBSERVER_ID.test(req.parentSpanId)||req.parentSpanId===req.spanId))||
73
- !OBSERVER_NAME.test(req.apiName||'')||
74
- !['BEGIN','OK','FAILED'].includes(req.phase)||
75
- Object.keys(req).some(k=>!OBSERVER_KEYS.has(k))||
76
- (req.phase==='BEGIN'
77
- ?req.durationMs!==undefined||req.errorCode!==undefined
78
- :!Number.isSafeInteger(req.durationMs)||req.durationMs<0||
79
- (req.phase==='FAILED'
80
- ?req.errorCode!=='MCP_TOOL_ERROR'&&
81
- !/^[A-Z][A-Z0-9_]{1,95}$/.test(req.errorCode||'')
82
- :req.errorCode!==undefined)))
83
- throw Object.assign(Error('TRACE_API_INVALID'),{code:'TRACE_API_INVALID'});
84
- const written=traceWriter.record({
85
- event:'typed.api.call',component:'gateway',projectRef:'api_system',
86
- traceId:req.traceId,spanId:req.spanId,
87
- ...(req.parentSpanId?{parentSpanId:req.parentSpanId}:{}),
88
- apiName:req.apiName,
89
- status:req.phase==='BEGIN'?'BEGIN':req.phase==='OK'?'CONFIRMED':'FAILED',
90
- ...(req.phase!=='BEGIN'?{durationMs:req.durationMs}:{}),
91
- ...(req.phase==='FAILED'?{errorCode:req.errorCode}:{})
92
- });
93
- return {contract:CONTRACT,requestId:req.requestId,status:'OK',
94
- eventId:written.eventId};
95
- }
96
- async function apiUsage(req){
97
- if(req?.contract!==CONTRACT||
98
- Object.keys(req).some(k=>!['contract','action','requestId',
99
- 'windowMinutes','limit'].includes(k))||
100
- !OBSERVER_ID.test(req.requestId||''))
101
- throw Object.assign(Error('TRACE_API_INVALID'),{code:'TRACE_API_INVALID'});
102
- const summary=await usageReader.apiUsage({
103
- windowMinutes:req.windowMinutes??60,limit:req.limit??100});
104
- return {contract:CONTRACT,requestId:req.requestId,status:'OK',summary};
105
- }
47
+ const {log,traceHealth,handleTraceObservation,traceNativeReceipt,
48
+ recordApiObservation,apiUsage,claimFormSubmission,flushPending}=observability;
106
49
  const desiredTunnel=new Set(), recoveryAttempts=new Map();
107
50
  let lockFd, server, idleTimer;
108
- // Internal process/control events never perform disk I/O on a business
109
- // response path. This queue is bounded, asynchronous, and drops telemetry
110
- // rather than delaying or replaying a confirmed/unknown operation.
111
- const MAX_CONTROL_AUDIT=1024,CONTROL_AUDIT_BATCH=64,controlAudit=[];
112
- let controlAuditScheduled=false,controlAuditDropped=0;
113
- const flushControlAudit=()=>{
114
- controlAuditScheduled=false;
115
- for(let i=0;i<CONTROL_AUDIT_BATCH&&controlAudit.length;i++){
116
- const {event,detail}=controlAudit.shift();
117
- try{traceWriter.recordControl(event,detail);}
118
- catch{/* Writer health carries the last error, never a business error. */}
119
- }
120
- if(controlAudit.length){
121
- controlAuditScheduled=true;setImmediate(flushControlAudit);
122
- }
123
- };
124
- const log=(event,detail={})=>{
125
- if(controlAudit.length>=MAX_CONTROL_AUDIT){controlAuditDropped++;return}
126
- // Project only the fields the existing Trace recordControl consumes.
127
- controlAudit.push({event,detail:{
128
- status:detail?.status,requestId:detail?.requestId,
129
- errorCode:detail?.errorCode
130
- }});
131
- if(!controlAuditScheduled){
132
- controlAuditScheduled=true;setImmediate(flushControlAudit);
133
- }
134
- };
135
- const traceHealth=()=>{
136
- const health=traceWriter.health();
137
- const writerAuditLost=(health.apiObservation?.dropped||0)>0||
138
- (health.apiObservation?.sinkFailures||0)>0;
139
- return {...health,controlAuditDropped,controlAuditPending:controlAudit.length,
140
- ...(writerAuditLost&&health.status==='OK'
141
- ?{status:'TRACE_DEGRADED',errorCode:'TRACE_WRITER_API_LOG_GAP'}:{}),
142
- ...(controlAuditDropped>0&&health.status==='OK'
143
- ?{status:'TRACE_DEGRADED',errorCode:'TRACE_AUDIT_QUEUE_SATURATED'}:{})};
144
- };
145
- const error=(code,message=code)=>({code,message});
146
- // One Trace owner; this module only handles native/soft event admission.
147
- const {handleTraceObservation,traceNativeReceipt}=createSupervisorTraceBridge({
148
- traceWriter,contract:CONTRACT,error
149
- });
150
-
151
51
  const after=rec=>rec ? rec.state : 'STOPPED';
152
52
  function saveReceipt(id,state,result=null,errorCode=null){
153
53
  receipts.delete(id);
@@ -298,7 +198,7 @@ async function execute(req){
298
198
  async function shutdown(){
299
199
  if([...records.values()].some(r=>!r.exited))return;
300
200
  // Closeout may flush final soft evidence, but never re-authorizes an action.
301
- while(controlAudit.length)flushControlAudit();
201
+ flushPending();
302
202
  server?.close();
303
203
  try{if(existsSync(p.socket))unlinkSync(p.socket);}catch{}
304
204
  try{if(existsSync(p.lock) && JSON.parse(readFileSync(p.lock,'utf8')).nonce===nonce)unlinkSync(p.lock);}catch{}
@@ -344,6 +244,9 @@ async function main(){
344
244
  :req?.action==='__api_usage'
345
245
  ?Promise.resolve().then(()=>apiUsage(req))
346
246
  .catch(e=>bad(req,e.code||'TRACE_USAGE_FAILED'))
247
+ :req?.action==='__form_submission_claim'
248
+ ?Promise.resolve().then(()=>claimFormSubmission(req))
249
+ .catch(e=>bad(req,e.code||'FORM_SUBMISSION_CLAIM_FAILED'))
347
250
  :req?.action==='context-control'
348
251
  ?handleContextControl(req).then(result=>{
349
252
  traceNativeReceipt(req);
@@ -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 local Trace timeline for one explicitly authorized Project and exact traceId/sessionRef. Shows gaps and unknown receipts; cannot replay actions or grant Browser Owner.',
27
+ description:'Read-only Trace timeline for an explicitly authorized Project. A separate api_system lookup is allowed only with the unguessable form traceRef returned by Form Prepare, and exposes only that form plus its parent MCP API spans.',
28
28
  inputSchema:{
29
29
  type:'object',additionalProperties:false,
30
30
  required:['projectRef'],
@@ -43,6 +43,10 @@ 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 FORM_TRACE_REF=new RegExp(UUID);
47
+ const FORM_ID=/^[A-Za-z0-9][A-Za-z0-9_-]{7,79}$/;
48
+ const FORM_EVENT=/^form\.(?:prepared|submitted)\.(?:soft_observed|failed)$|^form\.submission\.claimed$/;
49
+ const FORM_APIS=new Set(['mcp.chat_loop_form__prepare','mcp.chat_loop_form__submit']);
46
50
  export const traceStageTool={
47
51
  name:'chat_loop_trace_stage',
48
52
  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.',
@@ -94,29 +98,104 @@ const getAllowedProjects=()=>{
94
98
  // syntax; filtering entries could silently broaden a malformed config.
95
99
  return entries.length===1&&PROJECT.test(entries[0])?entries:[];
96
100
  };
101
+ async function diagnoseFormTrace(args){
102
+ const reader=createTraceReader({filePath:paths().log,allowedProjects:['api_system']});
103
+ const base=await reader.diagnose({projectRef:'api_system',
104
+ sessionRef:args.sessionRef,maxEvents:args.maxEvents});
105
+ const formEvents=base.timeline.filter(event=>
106
+ event.sessionRef===args.sessionRef&&FORM_EVENT.test(event.event||'')
107
+ &&typeof event.evidenceRef==='string'&&FORM_ID.test(event.evidenceRef));
108
+ const gaps=base.gaps.filter(gap=>gap!=='NO_MATCHING_EVENTS');
109
+ const parentKeys=new Map();
110
+ for(const event of formEvents){
111
+ const apiName=event.event==='form.prepared.soft_observed'
112
+ ||event.event==='form.prepared.failed'
113
+ ?'mcp.chat_loop_form__prepare':'mcp.chat_loop_form__submit';
114
+ if(!event.parentSpanId){gaps.push('FORM_API_PARENT_MISSING');continue}
115
+ parentKeys.set(event.traceId+':'+event.parentSpanId,apiName);
116
+ }
117
+ const apiEvents=[];
118
+ for(const traceId of new Set(formEvents.map(event=>event.traceId))){
119
+ const query=await reader.diagnose({projectRef:'api_system',traceId,maxEvents:200});
120
+ for(const gap of query.gaps)
121
+ if(['TRACE_MALFORMED_LINES','TRACE_WINDOW_TRUNCATED',
122
+ 'TRACE_WRITER_RESTART_UNVERIFIED','LEGACY_EVENTS_UNCORRELATED']
123
+ .includes(gap))gaps.push(gap);
124
+ for(const event of query.timeline){
125
+ const key=event.traceId+':'+event.spanId;
126
+ if(event.event==='typed.api.call'&&parentKeys.get(key)===event.apiName
127
+ &&FORM_APIS.has(event.apiName))apiEvents.push(event);
128
+ }
129
+ }
130
+ for(const [key,apiName] of parentKeys){
131
+ const [traceId,spanId]=key.split(':');
132
+ const linked=apiEvents.filter(event=>event.traceId===traceId
133
+ &&event.spanId===spanId&&event.apiName===apiName);
134
+ const begins=linked.filter(event=>event.status==='BEGIN');
135
+ const terminals=linked.filter(event=>
136
+ ['CONFIRMED','FAILED'].includes(event.status));
137
+ if(begins.length!==1||terminals.length!==1)
138
+ gaps.push('FORM_API_PARENT_GAP');
139
+ const terminal=terminals[0];
140
+ if(terminal&&formEvents.some(event=>event.traceId===traceId
141
+ &&event.parentSpanId===spanId&&event.status!==terminal.status))
142
+ gaps.push('FORM_API_STATUS_MISMATCH');
143
+ }
144
+ const formIds=[...new Set(formEvents.map(event=>event.evidenceRef))];
145
+ if(formIds.length>1)gaps.push('FORM_TRACE_REF_REUSED');
146
+ if(!formEvents.length)gaps.push('NO_MATCHING_EVENTS');
147
+ const timeline=[...formEvents,...apiEvents]
148
+ .sort((a,b)=>Date.parse(a.time)-Date.parse(b.time));
149
+ const last=timeline.at(-1)||null;
150
+ const unknown=formEvents.some(event=>['UNKNOWN','BLOCKED'].includes(event.status));
151
+ return {traceId:null,projectRef:'api_system',formTraceRef:args.sessionRef,
152
+ formId:formIds.length===1?formIds[0]:null,
153
+ inspected:timeline.length,totalMatched:timeline.length,
154
+ lastConfirmed:[...timeline].reverse().find(event=>event.status==='CONFIRMED')
155
+ ?{eventId:[...timeline].reverse().find(event=>event.status==='CONFIRMED').eventId,
156
+ event:[...timeline].reverse().find(event=>event.status==='CONFIRMED').event,
157
+ time:[...timeline].reverse().find(event=>event.status==='CONFIRMED').time,
158
+ component:[...timeline].reverse().find(event=>event.status==='CONFIRMED').component}
159
+ :null,
160
+ incompleteApiSpans:[],unmatchedApiTerminals:[],lastEvent:last,unknown,
161
+ gaps:[...new Set(gaps)],confidence:gaps.length?'INCOMPLETE':'TRACE_ONLY',
162
+ retryDisposition:unknown||gaps.length
163
+ ?'VERIFY_AUTHORITATIVE_RECEIPT_FIRST':'NO_AUTOMATIC_RETRY',timeline};
164
+ }
97
165
  export async function runTraceDiagnose(args){
98
- if(!traceGatewayEnabled())throw fail('TRACE_API_DISABLED');
99
166
  if(!args||typeof args!=='object'||Array.isArray(args)||
100
167
  Object.keys(args).some(k=>!Object.hasOwn(traceDiagnoseTool.inputSchema.properties,k)))
101
168
  throw fail('TRACE_INVALID_ARGUMENT');
102
- if(typeof args.projectRef!=='string'||!getAllowedProjects().includes(args.projectRef))
103
- throw fail('TRACE_PROJECT_ACCESS_DENIED');
104
- const result=await createTraceReader({
105
- filePath:paths().log,allowedProjects:getAllowedProjects()
106
- }).diagnose(args);
169
+ if(args.projectRef==='api_system'){
170
+ if(args.traceId!==undefined||typeof args.sessionRef!=='string'
171
+ ||!FORM_TRACE_REF.test(args.sessionRef))
172
+ throw fail('TRACE_FORM_LOOKUP_INVALID');
173
+ }else{
174
+ if(!traceGatewayEnabled())throw fail('TRACE_API_DISABLED');
175
+ if(typeof args.projectRef!=='string'||!getAllowedProjects().includes(args.projectRef))
176
+ throw fail('TRACE_PROJECT_ACCESS_DENIED');
177
+ }
178
+ const result=args.projectRef==='api_system'
179
+ ?await diagnoseFormTrace(args)
180
+ :await createTraceReader({filePath:paths().log,
181
+ allowedProjects:getAllowedProjects()}).diagnose(args);
107
182
  try{
108
183
  const response=await talk({contract:CONTRACT,action:'__trace_health',
109
184
  requestId:randomUUID()},1400);
110
185
  result.writerHealth=response.status==='OK'?response.traceHealth?.status||'UNKNOWN':'UNAVAILABLE';
186
+ if(args.projectRef==='api_system'&&response.traceHealth?.formObservationLost>0)
187
+ result.gaps.push('FORM_TRACE_OBSERVATION_LOSS');
111
188
  }catch{result.writerHealth='UNAVAILABLE'}
112
189
  if(result.writerHealth!=='OK'){
113
- result.gaps.push('TRACE_WRITER_UNAVAILABLE');
190
+ if(['UNKNOWN','UNAVAILABLE'].includes(result.writerHealth))
191
+ result.gaps.push('TRACE_WRITER_UNAVAILABLE');
192
+ if(result.writerHealth==='TRACE_DEGRADED')
193
+ result.gaps.push('FORM_TRACE_OBSERVATION_LOSS');
114
194
  result.confidence='INCOMPLETE';
115
- // An offline / unhealthy writer invalidates any claim that the visible
116
- // timeline is complete, even when every retained event is CONFIRMED.
117
- // Only the original authoritative receipt can settle an unknown effect.
118
195
  result.retryDisposition='VERIFY_AUTHORITATIVE_RECEIPT_FIRST';
119
196
  }
197
+ result.gaps=[...new Set(result.gaps)];
198
+ if(result.gaps.length)result.confidence='INCOMPLETE';
120
199
  return result;
121
200
  }
122
201
 
@@ -16,12 +16,17 @@ export function createSupervisorTraceBridge({traceWriter,contract,error}){
16
16
  // grant. Public Trace MCP observation/diagnosis remains opt-in and does
17
17
  // not become reachable merely because Context collection is active.
18
18
  const isContextApi=req?.event==='context.api';
19
+ const form=/^form\.(prepared|submitted)\.(soft_observed|failed)$/.test(req?.event||'');
19
20
  const contextGrant=process.env.CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS;
20
21
  const contextAuthorized=process.env.CHAT_LOOP_CONTEXT_API_ENABLE==='1'
21
22
  &&typeof contextGrant==='string'
22
23
  &&/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(contextGrant)
23
24
  &&req?.projectRef===contextGrant;
25
+ // Form IDs are system-local correlation metadata, not user Project data.
26
+ // Keep them in the existing api_system Writer without requiring a
27
+ // per-Project Trace grant or exposing Project/Chat/task identifiers.
24
28
  if(isContextApi?!contextAuthorized:
29
+ form?req?.projectRef!=='api_system':
25
30
  !traceEnabled()||!allowedTraceProjects().has(req?.projectRef))
26
31
  throw error('TRACE_PROJECT_ACCESS_DENIED');
27
32
  // Context call observation has a stable event ID and typed API fields.
@@ -67,21 +72,25 @@ export function createSupervisorTraceBridge({traceWriter,contract,error}){
67
72
  return {contract:CONTRACT,requestId:req.requestId,status:'OK',
68
73
  eventId:recorded.eventId};
69
74
  }
70
- const form=/^form\.(prepared|submitted)\.soft_observed$/.test(req?.event||'');
71
75
  if(form){
76
+ const success=req.event.endsWith('.soft_observed');
72
77
  const allowed=new Set(['contract','action','requestId','traceId','spanId',
73
- 'projectRef','taskRef','evidenceRef','event','status']);
74
- if(req.contract!==CONTRACT||req.status!=='CONFIRMED'
78
+ 'projectRef','sessionRef','evidenceRef','event','status','errorCode']);
79
+ const validError=typeof req.errorCode==='string'
80
+ &&/^[A-Z][A-Z0-9_]{1,95}$/.test(req.errorCode);
81
+ if(req.contract!==CONTRACT||req.projectRef!=='api_system'
82
+ ||req.status!==(success?'CONFIRMED':'FAILED')
75
83
  ||!UUID_RE.test(req.requestId||'')||!UUID_RE.test(req.traceId||'')
76
84
  ||!UUID_RE.test(req.spanId||'')
77
- ||!(/^[A-Za-z0-9_-]{8,80}$/).test(req.evidenceRef||'')
78
- ||req.taskRef!==undefined&&!(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/).test(req.taskRef)
85
+ ||!UUID_RE.test(req.sessionRef||'')
86
+ ||!(/^[A-Za-z0-9][A-Za-z0-9_-]{7,79}$/).test(req.evidenceRef||'')
87
+ ||(success?req.errorCode!==undefined:!validError)
79
88
  ||Object.keys(req).some(k=>!allowed.has(k)))
80
89
  throw error('TRACE_INVALID_ARGUMENT');
81
90
  const written=traceWriter.record({traceId:req.traceId,
82
- parentSpanId:req.spanId,projectRef:req.projectRef,
83
- ...(req.taskRef?{taskRef:req.taskRef}:{}),requestId:req.requestId,
84
- component:'gateway',event:req.event,status:'CONFIRMED',
91
+ parentSpanId:req.spanId,sessionRef:req.sessionRef,projectRef:'api_system',
92
+ requestId:req.requestId,component:'gateway',event:req.event,
93
+ status:req.status,...(req.errorCode?{errorCode:req.errorCode}:{}),
85
94
  evidenceRef:req.evidenceRef});
86
95
  return {contract:CONTRACT,requestId:req.requestId,status:'OK',
87
96
  eventId:written.eventId};