@tomflow/chatloop-tools 0.9.22 → 0.9.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -39,7 +39,9 @@ declared methods and MCP Provider
39
39
  catalog have separate capability tests. Internal Trace Writer health/record
40
40
  operations are excluded from re-submitting themselves to prevent recursive logs.
41
41
  Non-authoritative process/control logs use a bounded async queue, with drops
42
- and pending counts visible in Supervisor Trace health.
42
+ and pending counts visible in Supervisor Trace health. The Trace Writer retains
43
+ 30 days by default, prunes expired records at startup and daily, and reports
44
+ retention results/errors through its existing health receipt.
43
45
 
44
46
  ```text
45
47
  Usage: chatloop-tools <command> [target]
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tomflow/chatloop-context",
3
- "version": "0.6.11",
3
+ "version": "0.6.12",
4
4
  "type": "module",
5
5
  "description": "Independent local Context SDK and short-lived CLI for Chat Loop projects",
6
6
  "publishConfig": {
@@ -34,7 +34,7 @@
34
34
  },
35
35
  "dependencies": {
36
36
  "ps-list": "9.0.0",
37
- "@tomflow/chatloop-extension": "0.4.11",
38
- "@tomflow/chatloop-trace": "0.4.4"
37
+ "@tomflow/chatloop-extension": "0.4.12",
38
+ "@tomflow/chatloop-trace": "0.4.5"
39
39
  }
40
40
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "manifest_version": 3,
3
3
  "name": "Chat Loop Extension",
4
- "version": "0.4.11",
4
+ "version": "0.4.12",
5
5
  "description": "Chat Loop browser companion: Eye actions, Turn observer, Continue and Handoff Actions",
6
6
  "permissions": [
7
7
  "activeTab",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tomflow/chatloop-extension",
3
- "version": "0.4.11",
3
+ "version": "0.4.12",
4
4
  "type": "module",
5
5
  "description": "Chat Loop Extension package: nine formal Action pages and its own native CLI bridge",
6
6
  "bin": {
@@ -33,6 +33,6 @@
33
33
  ".": "./index.mjs"
34
34
  },
35
35
  "dependencies": {
36
- "@tomflow/chatloop-trace": "0.4.4"
36
+ "@tomflow/chatloop-trace": "0.4.5"
37
37
  }
38
38
  }
@@ -13,8 +13,13 @@ The root exposes two data APIs, a shared AOP factory and one opt-in, non-authori
13
13
  to the existing Supervisor. The writer's own `record/recordControl`
14
14
  telemetry is filtered at that boundary to prevent feedback loops. A
15
15
  standalone SDK stays installable and never creates another logging service.
16
- - `createTraceWriter({filePath})`: the Supervisor invokes
17
- `record(event)`, `recordControl(event,detail)` and `health()`.
16
+ - `createTraceWriter({filePath,retentionDays=30})`: the Supervisor invokes
17
+ `record(event)`, `recordControl(event,detail)` and `health()`. The single
18
+ Writer prunes only parseable records older than the configured retention
19
+ window at startup and daily across its active file and bounded rotation
20
+ segments. Unknown/malformed-age lines are preserved; source identity and
21
+ permissions are rechecked before atomic replacement. Retention results are
22
+ visible in `health().retention`.
18
23
  - `createTraceReader({filePath,allowedProjects})`: the Gateway invokes
19
24
  `diagnose({projectRef,traceId|sessionRef,maxEvents})`, `apiUsage({windowMinutes,limit})`
20
25
  or `health()`. `apiUsage` requires a Reader explicitly scoped to
@@ -86,7 +91,9 @@ nested result objects can enter v2 records. Existing legacy evidence is
86
91
  read-only, never migrated into a new current receipt or permission.
87
92
 
88
93
  The SDK verifies file owner, permissions, symlink safety and bounds event
89
- and query sizes. Diagnostics expose truncation, corrupted lines, writer
94
+ and query sizes. Scoped readers stream logs up to 2 GiB without loading the
95
+ full JSONL file into memory; the default 30-day Writer retention keeps normal
96
+ operational history within that read bound. Diagnostics expose truncation, corrupted lines, writer
90
97
  restarts, legacy records and pending receipts as **uncertainty**. They never
91
98
  grant approval, Context write rights, Owner transfer or automatic retry.
92
99
  A missing or interrupted Writer must be checked against the authoritative
@@ -2,6 +2,8 @@
2
2
  import {constants as FS,createReadStream,closeSync,fstatSync,openSync} from 'node:fs';
3
3
  import {createInterface} from 'node:readline';
4
4
 
5
+ const MAX_TRACE_READ_BYTES=2*1024*1024*1024;
6
+
5
7
  export function makeTraceReader(options,deps){
6
8
  const {TRACE_SCHEMA_VERSION,fail,validStoredFamily,object,isId,safeScope,
7
9
  safeRef,natural,keys,secureFile,eventRule,EVENT,CODE,COMPONENTS,STATUSES}=deps;
@@ -60,7 +62,7 @@ export function makeTraceReader(options,deps){
60
62
  filePath].map(path=>({path,stat:secureFile(path)})).filter(x=>x.stat);
61
63
  if(!files.length)return {events:[],matched:0,legacyUncorrelated:true,gapped:true,
62
64
  errors:['TRACE_LOG_MISSING'],truncated:false};
63
- if(files.reduce((sum,x)=>sum+x.stat.size,0)>64*1024*1024)
65
+ if(files.reduce((sum,x)=>sum+x.stat.size,0)>MAX_TRACE_READ_BYTES)
64
66
  throw fail('TRACE_FILE_TOO_LARGE');
65
67
  const seen=new Set(),events=[],errors=[],writerEpochs=new Set();
66
68
  let matched=0,corrupt=0,legacy=0;
@@ -157,7 +159,7 @@ export function makeTraceReader(options,deps){
157
159
  const files=[...Array.from({length:maxSegments},(_,i)=>
158
160
  filePath+'.'+(maxSegments-i)),filePath]
159
161
  .map(path=>({path,stat:secureFile(path)})).filter(x=>x.stat);
160
- if(files.reduce((n,x)=>n+x.stat.size,0)>64*1024*1024)
162
+ if(files.reduce((n,x)=>n+x.stat.size,0)>MAX_TRACE_READ_BYTES)
161
163
  throw fail('TRACE_FILE_TOO_LARGE');
162
164
  let malformed=0;
163
165
  for(const item of files){
@@ -0,0 +1,109 @@
1
+ import {randomUUID} from 'node:crypto';
2
+ import {constants as FS,closeSync,fstatSync,fsyncSync,lstatSync,openSync,readSync,writeSync,renameSync,unlinkSync} from 'node:fs';
3
+
4
+ const sameFile=(a,b)=>a.dev===b.dev&&a.ino===b.ino&&a.size===b.size
5
+ &&a.mtimeMs===b.mtimeMs;
6
+ const writeAll=(fd,buffer)=>{
7
+ let offset=0;
8
+ while(offset<buffer.length)offset+=writeSync(fd,buffer,offset,buffer.length-offset);
9
+ };
10
+ function pruneFile(filePath,cutoff,secureFile){
11
+ const before=secureFile(filePath);
12
+ if(!before)return {droppedRecords:0,droppedBytes:0,pruned:false};
13
+ const input=openSync(filePath,FS.O_RDONLY|FS.O_NOFOLLOW);
14
+ let output,temp;
15
+ try{
16
+ const opened=fstatSync(input);
17
+ if(!opened.isFile()||(opened.mode&0o077)||
18
+ process.getuid&&opened.uid!==process.getuid()||!sameFile(before,opened))
19
+ throw Object.assign(Error('TRACE_RETENTION_SOURCE_CHANGED'),
20
+ {code:'TRACE_RETENTION_SOURCE_CHANGED'});
21
+ temp=filePath+'.retention-'+randomUUID();
22
+ output=openSync(temp,FS.O_WRONLY|FS.O_CREAT|FS.O_EXCL|FS.O_NOFOLLOW,0o600);
23
+ const chunk=Buffer.allocUnsafe(64*1024),newline=Buffer.from([10]);
24
+ let position=0,pending=Buffer.alloc(0),longLine=false;
25
+ let droppedRecords=0,droppedBytes=0,keptRecords=0;
26
+ const keepLine=(line,terminated=true)=>{
27
+ let expired=false;
28
+ if(line.length<=8192){
29
+ try{
30
+ const value=JSON.parse(line.toString('utf8'));
31
+ const timestamp=Date.parse(value?.time);
32
+ expired=Number.isFinite(timestamp)&&timestamp<cutoff;
33
+ }catch{}
34
+ }
35
+ if(expired){droppedRecords++;droppedBytes+=line.length+(terminated?1:0);}
36
+ else{writeAll(output,line);writeAll(output,newline);keptRecords++;}
37
+ };
38
+ while(position<before.size){
39
+ const count=readSync(input,chunk,0,Math.min(chunk.length,before.size-position),position);
40
+ if(!count)throw Object.assign(Error('TRACE_RETENTION_READ_INCOMPLETE'),
41
+ {code:'TRACE_RETENTION_READ_INCOMPLETE'});
42
+ position+=count;
43
+ let start=0;
44
+ while(start<count){
45
+ const end=chunk.indexOf(10,start);
46
+ if(longLine){
47
+ const next=end<0?count:end+1;
48
+ writeAll(output,chunk.subarray(start,next));
49
+ if(end<0){start=count;continue;}
50
+ longLine=false;start=next;continue;
51
+ }
52
+ if(end<0){
53
+ const part=chunk.subarray(start,count);
54
+ if(pending.length+part.length>8192){
55
+ writeAll(output,pending);writeAll(output,part);
56
+ pending=Buffer.alloc(0);longLine=true;keptRecords++;
57
+ }else pending=pending.length?Buffer.concat([pending,part]):Buffer.from(part);
58
+ start=count;continue;
59
+ }
60
+ const part=chunk.subarray(start,end);
61
+ const line=pending.length?Buffer.concat([pending,part]):Buffer.from(part);
62
+ if(line.length>8192){writeAll(output,line);writeAll(output,newline);keptRecords++;}
63
+ else keepLine(line);
64
+ pending=Buffer.alloc(0);start=end+1;
65
+ }
66
+ }
67
+ if(longLine)writeAll(output,newline);
68
+ else if(pending.length)keepLine(pending,false);
69
+ const after=fstatSync(input),current=lstatSync(filePath);
70
+ if(!sameFile(before,after)||!sameFile(before,current))
71
+ throw Object.assign(Error('TRACE_RETENTION_SOURCE_CHANGED'),
72
+ {code:'TRACE_RETENTION_SOURCE_CHANGED'});
73
+ if(!droppedRecords){
74
+ closeSync(output);output=undefined;unlinkSync(temp);temp=null;
75
+ return {droppedRecords,droppedBytes,pruned:false};
76
+ }
77
+ fsyncSync(output);closeSync(output);output=undefined;
78
+ closeSync(input);
79
+ if(!keptRecords){unlinkSync(filePath);unlinkSync(temp);temp=null;}
80
+ else{renameSync(temp,filePath);temp=null;}
81
+ return {droppedRecords,droppedBytes,pruned:true};
82
+ }finally{
83
+ try{closeSync(input)}catch{}
84
+ if(output!==undefined)try{closeSync(output)}catch{}
85
+ if(temp)try{unlinkSync(temp)}catch{}
86
+ }
87
+ }
88
+ export function createTraceRetention({filePath,maxSegments,retentionDays,secureFile}){
89
+ const state={days:retentionDays,droppedRecords:0,droppedBytes:0,
90
+ prunedFiles:0,lastRunAt:null,error:null};
91
+ const prune=()=>{
92
+ const cutoff=Date.now()-retentionDays*24*60*60*1000;
93
+ const paths=[...Array.from({length:maxSegments},(_,i)=>filePath+'.'+(i+1)),filePath];
94
+ state.error=null;
95
+ for(const path of paths){
96
+ try{
97
+ const result=pruneFile(path,cutoff,secureFile);
98
+ state.droppedRecords+=result.droppedRecords;
99
+ state.droppedBytes+=result.droppedBytes;
100
+ if(result.pruned)state.prunedFiles++;
101
+ }catch(error){state.error=error.code||'TRACE_RETENTION_FAILED';}
102
+ }
103
+ state.lastRunAt=new Date().toISOString();
104
+ };
105
+ prune();
106
+ const timer=setInterval(prune,24*60*60*1000);
107
+ timer.unref?.();
108
+ return {health:()=>({...state})};
109
+ }
@@ -2,6 +2,7 @@ import {makeTraceReader} from './trace-reader.mjs';
2
2
  import {randomUUID} from 'node:crypto';
3
3
  import {constants as FS,closeSync,fstatSync,lstatSync,openSync,writeSync,renameSync,unlinkSync} from 'node:fs';
4
4
  import {dirname,isAbsolute} from 'node:path';
5
+ import {createTraceRetention} from './trace-retention.mjs';
5
6
 
6
7
  export const TRACE_SCHEMA_VERSION=2;
7
8
  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;
@@ -138,13 +139,16 @@ function secureFile(filePath){
138
139
  return st;
139
140
  }
140
141
  export function createTraceWriter({
141
- filePath,enableRotation=false,rotateBytes=10*1024*1024,maxSegments=5
142
+ filePath,enableRotation=false,rotateBytes=10*1024*1024,maxSegments=5,
143
+ retentionDays=30
142
144
  }){
143
145
  if(typeof enableRotation!=='boolean'||!Number.isSafeInteger(rotateBytes)||
144
146
  rotateBytes<512||rotateBytes>10*1024*1024||
145
- !Number.isSafeInteger(maxSegments)||maxSegments<1||maxSegments>5)
147
+ !Number.isSafeInteger(maxSegments)||maxSegments<1||maxSegments>5||
148
+ !Number.isSafeInteger(retentionDays)||retentionDays<1||retentionDays>3650)
146
149
  throw fail('TRACE_ROTATION_INVALID');
147
150
  const epoch=randomUUID();let seq=0,failures=0,lastError=null,rotations=0;
151
+ const retention=createTraceRetention({filePath,maxSegments,retentionDays,secureFile});
148
152
  const rotateIfNeeded=lineBytes=>{
149
153
  // Legacy data is never moved until an operator explicitly enables
150
154
  // rotation after preserving its historical evidence.
@@ -190,9 +194,12 @@ export function createTraceWriter({
190
194
  {errorCode:detail.errorCode}:{})
191
195
  });
192
196
  };
193
- const health=()=>({status:lastError?'TRACE_DEGRADED':'OK',
194
- errorCode:lastError,failures,writerEpoch:epoch,writerSeq:seq,
195
- rotationEnabled:enableRotation,rotations});
197
+ const health=()=>{
198
+ const retained=retention.health();
199
+ return {status:lastError||retained.error?'TRACE_DEGRADED':'OK',
200
+ errorCode:lastError||retained.error,failures,writerEpoch:epoch,writerSeq:seq,
201
+ rotationEnabled:enableRotation,rotations,retention:retained};
202
+ };
196
203
  return {record,recordControl,health};
197
204
  }
198
205
 
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tomflow/chatloop-trace",
3
- "version": "0.4.4",
3
+ "version": "0.4.5",
4
4
  "description": "Trace SDK and scoped read-only diagnostics for Chat Loop",
5
5
  "type": "module",
6
6
  "engines": {
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "0.9.22",
6
+ "version": "0.9.23",
7
7
  "type": "module",
8
8
  "description": "Chat Loop local tools: MCP gateway, isolated bundled tunnel-client and unified CLI",
9
9
  "bin": {
@@ -31,11 +31,11 @@
31
31
  "prepack": "node ./scripts/build-providers.mjs --check && node ./scripts/build-form-app.mjs --check"
32
32
  },
33
33
  "dependencies": {
34
- "@tomflow/chatloop-context": "0.6.11",
35
- "@tomflow/chatloop-trace": "0.4.4",
34
+ "@tomflow/chatloop-context": "0.6.12",
35
+ "@tomflow/chatloop-trace": "0.4.5",
36
36
  "@wonderwhy-er/desktop-commander": "0.2.44",
37
37
  "ps-list": "9.0.0",
38
- "@tomflow/chatloop-extension": "0.4.11"
38
+ "@tomflow/chatloop-extension": "0.4.12"
39
39
  },
40
40
  "bundleDependencies": [
41
41
  "@tomflow/chatloop-context",