Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,9 @@ jobs:
# Coverage-instrumented run of the same suite `npm test` executes; the
# thresholds in vitest.config.ts (ratcheted to measured reality) make
# this step fail on a genuine coverage regression.
- name: Install Python test dependencies
run: python3 -m pip install --break-system-packages pyyaml

- name: Test (with coverage gate)
run: npm run test:coverage

Expand Down
1 change: 1 addition & 0 deletions .kody-trigger.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
@kody start-review
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
{
"backup": {
"backup": "created_and_verified",
"sha256": "7e7f8408962c84ca3925536a6da5f3cffe2a49615b23bc0c25592964c17792de"
},
"localAfter": {
"desiredValueSha256": {
"BOTFLEET_WORKSPACES_DIRS": "f5099a13db2d688fadbb916ae270f1b0ed6a758b8b05dc99fa8f4601550bf77e",
"OPENCODE_ADDITIONAL_DBS_JSON": "c3f9990ffa4c45c50c16fad923e748412451e4dbb0af64e835635d22b2b715f2"
},
"fileIdentity": {
"bytes": 1023,
"device": 2049,
"inode": 262355,
"mtimeNs": 1793714056530732994
},
"keys": {
"BOTFLEET_WORKSPACES_DIRS": "equal",
"OPENCODE_ADDITIONAL_DBS_JSON": "equal"
},
"mode": "0600",
"ownerGid": 1001,
"ownerUid": 1001,
"sourceSha256": "fdf864f67f7788448e6169c12ec915b7d2f78ad9ee8617c05df1152f48366188"
},
"localBefore": {
"desiredValueSha256": {
"BOTFLEET_WORKSPACES_DIRS": "f5099a13db2d688fadbb916ae270f1b0ed6a758b8b05dc99fa8f4601550bf77e",
"OPENCODE_ADDITIONAL_DBS_JSON": "c3f9990ffa4c45c50c16fad923e748412451e4dbb0af64e835635d22b2b715f2"
},
"fileIdentity": {
"bytes": 832,
"device": 2049,
"inode": 274578,
"mtimeNs": 1793403562519636205
},
"keys": {
"BOTFLEET_WORKSPACES_DIRS": "absent",
"OPENCODE_ADDITIONAL_DBS_JSON": "absent"
},
"mode": "0600",
"ownerGid": 1001,
"ownerUid": 1001,
"sourceSha256": "7e7f8408962c84ca3925536a6da5f3cffe2a49615b23bc0c25592964c17792de"
},
"localResult": {
"sha256": "fdf864f67f7788448e6169c12ec915b7d2f78ad9ee8617c05df1152f48366188",
"status": "applied_and_verified"
},
"phase": "complete",
"releaseMessageId": 637193996,
"remote": {
"claimSha256": "57ee2e4825f71ef78afd0d6a6e94897980b033161950bc7584cd9d0a8e4ae172",
"keys": {
"BOTFLEET_SERVER_WORKSPACES_DIRS": {
"attempted": true,
"confirmedCreated": true,
"plannedState": "absent",
"postHttpStatus": 200,
"readbackVerified": true,
"status": "verified_equal"
},
"OPENCODE_SERVER_ADDITIONAL_DBS_JSON": {
"attempted": true,
"confirmedCreated": true,
"plannedState": "absent",
"postHttpStatus": 200,
"readbackVerified": true,
"status": "verified_equal"
}
},
"ok": true,
"sourceOfTruthComplete": true
},
"rootPlanSha256": "ae3a6cbb3461248daad470f024b766a4b11ab189cce28af3894fc96616bb34b7",
"unrelatedBytesPreserved": true
}
130 changes: 130 additions & 0 deletions .um1646-child-pair-plan.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
{
"code": {
"controllerSha256": "0b2887e70ac5117b7d934b63a79ebc48daf0e9c6797b53bafaa0b0eceae96831",
"localModuleSha256": "bf985135a63c8f4129c1a2c0d8029a7dff074fc6d1df9d823259da8fb2fb1f2b",
"remoteSha256": "6ff4e606a01202ea6a1ec671d2b09464367e16c4f2bd18b12f7ec6f6851e62a5"
},
"installed": {
"hashes": {
"lib/collector-sentry-bridge.mjs": "c0e50eecccbf33447a0872e6f3d8acd1fe5e24170f203583abea41a131cdfb7d",
"lib/fleet-secrets.mjs": "965161f006d83325d136c1b9a0ce4295a56bf75b388a5729209cec734b7cd95c",
"lib/opencode-session-telemetry.mjs": "ee2b5c32ace959c88654a3d0b50cedcd408ab6a159ba2b6213682a9f7d1858e8",
"lib/run-session-token-collector.mjs": "adc6674e7b957fd0562212ecd9dd3bbbc24b53bdc4f40f70ddaab46293036d53",
"lib/session-token-collectors.mjs": "816829d8df98b2518164e58f0f697072d4e6bd369ec2e400a8173a2800ca6505",
"opencode-usage-collector.mjs": "78bfeaddc395d9e5a41b0c4fe0dec19a975231f5c586bfbafe7a35160ee3088c",
"telemetry-hub/allowlist.mjs": "d9020928a99d258e975b406ef152b787e9212329f753ed5179dbca75dd141be1",
"telemetry-hub/internal-event.mjs": "d061efdad89096a99e982aaeed8dff4a5ffd110fe3a1ba2a08bdcf9985fcca7d",
"telemetry-hub/journal.mjs": "da3893330b9f5f6861edab614687e4b0fa5dec4e2013c2e1e266415e42c61434",
"telemetry-hub/metadata-projection.mjs": "8b91b390859eebc729de0b4118340a7a3bff114e105121ff38ead83264c18c51",
"telemetry-hub/sentry-sender.mjs": "bf6fb45f7ef1e921aba9487d6479dbcf00f95329b6f0784ebeaaee5ce96a8a92"
},
"sourceCommit": "ca19ad6ab8e98b5ac506d75d15b72dd0b9cd9015"
},
"local": {
"desiredValueSha256": {
"BOTFLEET_WORKSPACES_DIRS": "f5099a13db2d688fadbb916ae270f1b0ed6a758b8b05dc99fa8f4601550bf77e",
"OPENCODE_ADDITIONAL_DBS_JSON": "c3f9990ffa4c45c50c16fad923e748412451e4dbb0af64e835635d22b2b715f2"
},
"fileIdentity": {
"bytes": 832,
"device": 2049,
"inode": 274578,
"mtimeNs": 1793403562519636205
},
"keys": {
"BOTFLEET_WORKSPACES_DIRS": "absent",
"OPENCODE_ADDITIONAL_DBS_JSON": "absent"
},
"mode": "0600",
"ownerGid": 1001,
"ownerUid": 1001,
"sourceSha256": "7e7f8408962c84ca3925536a6da5f3cffe2a49615b23bc0c25592964c17792de"
},
"releaseMessageId": 637193996,
"remote": {
"ok": true,
"remoteCodeSha256": "6ff4e606a01202ea6a1ec671d2b09464367e16c4f2bd18b12f7ec6f6851e62a5",
"remoteWrites": false,
"snapshot": {
"custody": {
"read": {
"bytes": 105,
"device": 16777233,
"gid": 20,
"inode": 757911686,
"mode": 384,
"mtimeNs": 1793711131926484407,
"parent": {
"device": 16777233,
"gid": 20,
"inode": 757911654,
"mode": 448,
"uid": 501
},
"sha256": "e8a0c8582f931dce2c179565f45880bc82b91dc9076eb6bacf459c3210530715",
"uid": 501
},
"write": {
"bytes": 105,
"device": 16777233,
"gid": 20,
"inode": 757911697,
"mode": 384,
"mtimeNs": 1793711132492581515,
"parent": {
"device": 16777233,
"gid": 20,
"inode": 757911654,
"mode": 448,
"uid": 501
},
"sha256": "27fc3af9abe4035163a9fa8d652d7108385c3538b5adfea29461db6e80a025fc",
"uid": 501
}
},
"keys": {
"BOTFLEET_SERVER_WORKSPACES_DIRS": {
"state": "absent",
"valueSha256": null
},
"OPENCODE_SERVER_ADDITIONAL_DBS_JSON": {
"state": "absent",
"valueSha256": null
}
},
"serviceMetadata": {
"read": {
"expiresAt": "2027-02-01T13:05:31.892Z",
"explicitIds": {
"_id": "2da57b07-1bed-4955-85ad-4db24ff60c43",
"id": "2da57b07-1bed-4955-85ad-4db24ff60c43"
},
"metadataSha256": "99cf668852d65a5dc0773b4b7a1e607c73eebed4b2130c384db6cbc2a988c547",
"nameVerified": true,
"projectVerified": true,
"role": "read",
"singletonEnvironment": "prod",
"singletonFolder": "/telemetry",
"singletonPermission": "read"
},
"write": {
"expiresAt": "2027-02-01T13:05:32.458Z",
"explicitIds": {
"_id": "81318b7a-7e2e-41f9-8788-cb0fefa12273",
"id": "81318b7a-7e2e-41f9-8788-cb0fefa12273"
},
"metadataSha256": "0c76ad22503593f306c9ebc5bf944dc1efb3a01f7fdf0982fb1b500d24519965",
"nameVerified": true,
"projectVerified": true,
"role": "write",
"singletonEnvironment": "prod",
"singletonFolder": "/telemetry",
"singletonPermission": "write"
}
}
}
},
"scope": "two-child-source-settings-only",
"version": 1,
"wireMessageId": 637192947
}
110 changes: 110 additions & 0 deletions .um1646-claude-historic24h.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import { readFile, writeFile } from 'node:fs/promises';
import { hostname } from 'node:os';
import { join } from 'node:path';
import { pathToFileURL } from 'node:url';
import childProcess from 'node:child_process';
import { syncBuiltinESMExports } from 'node:module';

const root='/Users/jay/apps/usage-monitor-collectors';
const planFile='/tmp/um1646-sentry-historic-20261103/claude-historic-24h-plan-v3.json';
const receiptFile='/tmp/um1646-sentry-historic-20261103/claude-historic-24h-receipt-v3.json';
const fixedLower='2026-10-29T23:32:30.055Z';
const fixedUpper='2026-10-30T23:32:30.055Z';
const commit='ca19ad6ab8e98b5ac506d75d15b72dd0b9cd9015';
assert.match(commit,/^[a-f0-9]{40}$/);
const mode=process.env.UM_CLAUDE_CATCHUP_MODE;
assert.ok(['plan','apply'].includes(mode));
assert.equal(process.argv[1],undefined);
Object.defineProperty(process,'argv',{value:Object.freeze([...process.argv,'--dry-run']),writable:false,configurable:false});
assert.ok(process.argv.includes('--dry-run'));
assert.ok(!Object.keys(process.env).some(key=>/INGEST.*TOKEN|TOKEN.*INGEST/.test(key)&&process.env[key]));
// Block the installed token resolver's absolute fleet-secrets fallback too.
const originalExecFileSync=childProcess.execFileSync;
childProcess.execFileSync=(file,args,options)=>{
if(!['ps','/bin/ps','/usr/bin/ps'].includes(file)||!Array.isArray(args)||args.length!==4||args[0]!=='-o'||args[1]!=='lstart='||args[2]!=='-p'||!/^\d+$/.test(String(args[3])))throw Error('Only read-only process birth lookup is allowed');
return originalExecFileSync(file,args,options);
};
syncBuiltinESMExports();
assert.ok(!['1','true','yes','on'].includes((process.env.USAGE_MONITOR_EXCLUDE_BOTFLEET_CHILDREN||'').toLowerCase()));
const versionMatch=(await readFile(join(root,'VERSION'),'utf8')).match(/^sha=([a-f0-9]{7,40})$/m);
assert.ok(versionMatch&&commit.startsWith(versionMatch[1]));
const hash=value=>createHash('sha256').update(value).digest('hex');
const modules=['claude-usage-collector.mjs','lib/session-token-collectors.mjs','lib/collector-sentry-bridge.mjs','telemetry-hub/metadata-projection.mjs','telemetry-hub/allowlist.mjs','telemetry-hub/sentry-sender.mjs'];
const sourceHashes=await Promise.all(modules.map(async file=>[file,hash(await readFile(join(root,'scripts',file)))]));
const originalFetch=globalThis.fetch;
globalThis.fetch=()=>{throw Error('Plan/import phase prohibits network delivery');};
const {collectClaudeEvents}=await import(pathToFileURL(join(root,'scripts/claude-usage-collector.mjs')).href);
const {collectorSentryConfig,collectorSentryEvents,enqueueCollectorSentry,drainCollectorSentry}=await import(pathToFileURL(join(root,'scripts/lib/collector-sentry-bridge.mjs')).href);
const identity={producerId:'claude-code',producerInstanceId:process.env.USAGE_MACHINE_ID?.trim()||hostname()};
assert.ok(!process.env.CLAUDE_PRODUCER_ID||process.env.CLAUDE_PRODUCER_ID===identity.producerId);
const config=collectorSentryConfig(process.env,identity.producerId);
assert.equal(config?.destination,'hub');
const deliveryConfiguration={destination:config.destination,endpoint:config.endpoint,stateRoot:config.stateRoot};
const deliveryConfigDigest=hash(JSON.stringify(deliveryConfiguration));
const validateApprovedPlan=value=>{
assert.ok(value&&typeof value==='object'&&!Array.isArray(value),'approved plan must be a JSON object');
const pick={};
for(const key of ['commit','sourceHashDigest','identityDigest','deliveryConfigDigest','lower','upper']){
assert.ok(typeof value[key]==='string','approved plan string field missing: '+key);
pick[key]=value[key];
}
assert.match(pick.commit,/^[a-f0-9]{40}$/,'approved plan commit shape');
for(const key of ['sourceHashDigest','identityDigest','deliveryConfigDigest'])assert.match(pick[key],/^[a-f0-9]{64}$/,'approved plan digest shape: '+key);
assert.ok(Number.isFinite(Date.parse(pick.lower))&&Number.isFinite(Date.parse(pick.upper)),'approved plan dates must parse');
return pick;
};
Comment on lines +46 to +57

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

kody code-review Bug high

Approved plan validation drops fields required by apply

Revises an earlier Kody suggestion on .um1646-claude-historic24h.mjs:50 (2026-11-16 10:42 UTC).

validateApprovedPlan returns a pick object with only six keys, dropping selectedDigest, components and callMarkers that the plan writer emits and the apply branch asserts against, so every apply run aborts with assert.equal(selectedDigest, undefined) and the 24h catch-up never delivers. Validate those fields too — selectedDigest as a 64-character hex digest and components and callMarkers as non-negative safe integers — and copy them into pick so the approved-plan checks stay meaningful.

Prompt for LLM
File .um1646-claude-historic24h.mjs, lines 46-57:

**Revises an earlier Kody suggestion** on `.um1646-claude-historic24h.mjs:50` (2026-11-16 10:42 UTC).

Approved plan validation drops fields required by apply

The new `validateApprovedPlan` returns only a six-key `pick` object, dropping `selectedDigest`, `components` and `callMarkers` that the plan writer emits (lines 83-84) and that the apply branch asserts against (`approved.selectedDigest`, `approved.components`, `approved.callMarkers` at lines 90-92). Since those properties are now `undefined`, every `apply` run aborts with `assert.equal(selectedDigest, undefined)` and the 24h catch-up never delivers — a silent, always-failing regression introduced by this PR. Validate those fields too (e.g. require them as strings/numbers with the expected shapes and copy them into `pick`) so the approved-plan checks remain meaningful.

Suggested code:

const validateApprovedPlan=value=>{
  assert.ok(value&&typeof value==='object'&&!Array.isArray(value),'approved plan must be a JSON object');
  const pick={};
  for(const key of ['commit','sourceHashDigest','identityDigest','deliveryConfigDigest','selectedDigest','lower','upper']){
    assert.ok(typeof value[key]==='string','approved plan string field missing: '+key);
    pick[key]=value[key];
  }
  assert.match(pick.commit,/^[a-f0-9]{40}$/,'approved plan commit shape');
  for(const key of ['sourceHashDigest','identityDigest','deliveryConfigDigest','selectedDigest'])assert.match(pick[key],/^[a-f0-9]{64}$/,'approved plan digest shape: '+key);
  for(const key of ['components','callMarkers']){
    assert.ok(Number.isSafeInteger(value[key])&&value[key]>=0,'approved plan count field invalid: '+key);
    pick[key]=value[key];
  }
  assert.ok(Number.isFinite(Date.parse(pick.lower))&&Number.isFinite(Date.parse(pick.upper)),'approved plan dates must parse');
  return pick;
};

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.

​

​

let approved,planBytes;
if(mode==='apply'){
planBytes=await readFile(planFile);
assert.equal(hash(planBytes),process.env.UM_CLAUDE_CATCHUP_APPROVED_PLAN_SHA256);
approved=validateApprovedPlan(JSON.parse(planBytes));
assert.equal(approved.commit,commit);
Comment thread
swu-wise[bot] marked this conversation as resolved.
Resolved
assert.equal(approved.sourceHashDigest,hash(JSON.stringify(sourceHashes)));
assert.equal(approved.identityDigest,hash(JSON.stringify(identity)));
assert.equal(approved.deliveryConfigDigest,deliveryConfigDigest);
}
const upper=mode==='plan'?new Date(fixedUpper):new Date(approved.upper);
const lower=mode==='plan'?new Date(fixedLower):new Date(approved.lower);
assert.equal(upper.getTime()-lower.getTime(),86400000);
const scanStatus={complete:true};
const sourceEvents=await collectClaudeEvents({since:lower,scanStatus});
assert.equal(scanStatus.complete,true);
assert.ok(sourceEvents.every(event=>Number.isFinite(Date.parse(event.occurredAt))));
const events=sourceEvents.filter(event=>Date.parse(event.occurredAt)>=lower.getTime()&&Date.parse(event.occurredAt)<=upper.getTime());
assert.ok(events.length<=60000);
assert.ok(events.every(event=>event.metricType==='usage'&&event.unit==='token'));
const projected=collectorSentryEvents(events,identity);
const calls=projected.filter(event=>event.name==='chat');
assert.ok(calls.length<=15000);
const measured=calls.filter(event=>Number.isFinite(event.durationMs)&&event.durationMs>=0).length;
const selectedDigest=hash(JSON.stringify([...projected].sort((a,b)=>a.eventId.localeCompare(b.eventId))));
const summary={commit,windowHours:24,components:events.length,callMarkers:calls.length,observations:projected.length-calls.length,measuredDurations:measured,measuredCallSpans:calls.filter(event=>event.kind==='span').length,unmeasuredCallLogs:calls.filter(event=>event.kind==='log'&&!Number.isFinite(event.durationMs)).length,excludedAfterUpper:sourceEvents.length-events.length};
const plan={...summary,lower:lower.toISOString(),upper:upper.toISOString(),selectedDigest,sourceHashDigest:hash(JSON.stringify(sourceHashes)),identityDigest:hash(JSON.stringify(identity)),deliveryConfiguration,deliveryConfigDigest,maxComponents:60000,maxCallMarkers:15000,maxDrainInvocations:16,globalDrainBudgetMs:55000,perInvocationRequestLimit:32,perInvocationBudgetMs:5000};
if(mode==='plan'){
const bytes=Buffer.from(JSON.stringify(plan,null,2)+'\n');
await writeFile(planFile,bytes,{flag:'wx',mode:0o600});
console.log(JSON.stringify({mode,...summary,approvedPlanSha256:hash(bytes),durableOutboxTouched:false,networkRequests:0,umPosts:0,checkpointWrites:0}));
}else{
assert.equal(selectedDigest,approved.selectedDigest);
assert.equal(events.length,approved.components);
assert.equal(calls.length,approved.callMarkers);
const allowed=new Set(['/v1/traces','/v1/logs'].map(signal=>config.endpoint+signal));
globalThis.fetch=(url,options)=>{
if(!allowed.has(String(url))||options?.method!=='POST')throw Error('Only the reviewed hub delivery target is allowed');
return originalFetch(url,options);
};
// The installed converter projects metadata before its durable SQLite write.
const outbox=await enqueueCollectorSentry(events,identity,config);
const deadline=performance.now()+55000;
const results=[];
for(let invocation=1;invocation<=16&&performance.now()+5000<=deadline;invocation++){
const result=await drainCollectorSentry(outbox,config,{requestLimit:32,budgetMs:5000});
results.push({invocation,...result});
if(!result.pending||(!result.delivered&&!result.quarantined))break;
}
const receipt={mode,...summary,planSha256:hash(planBytes),umPosts:0,checkpointWrites:0,sourceWrites:0,results};
await writeFile(receiptFile,JSON.stringify(receipt,null,2)+'\n',{flag:'wx',mode:0o600});
console.log(JSON.stringify(receipt));
}
18 changes: 18 additions & 0 deletions .um1646-claude-historic24h.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import json, os, pathlib, plistlib, subprocess, sys
mode=sys.argv[1] if len(sys.argv)>1 else None
if mode not in ('plan','apply'):raise SystemExit('Use plan or apply')
path=pathlib.Path.home()/'Library/LaunchAgents/com.jays.claude-usage-collector.plist'
with path.open('rb') as handle:job=plistlib.load(handle)
env={**os.environ,**job.get('EnvironmentVariables',{})}
for key in list(env):
if ('INGEST' in key and 'TOKEN' in key):del env[key]
tokens=json.loads(env['COLLECTOR_TELEMETRY_HUB_TOKENS_JSON'])
env['COLLECTOR_TELEMETRY_HUB_TOKENS_JSON']=json.dumps({'claude-code':tokens['claude-code']},separators=(',',':'))
env['UM_CLAUDE_CATCHUP_MODE']=mode
if mode=='apply' and len(env.get('UM_CLAUDE_CATCHUP_APPROVED_PLAN_SHA256',''))!=64:raise SystemExit('Exact approved plan digest required')
code=pathlib.Path(__file__).with_name('.um1646-claude-historic24h.mjs').read_text()
result=subprocess.run([job['ProgramArguments'][0],'--input-type=module'],input=code,text=True,capture_output=True,env=env,timeout=180)
if result.returncode:raise SystemExit('Catch-up guard failed; no source or configuration values printed')
rows=[json.loads(line) for line in result.stdout.splitlines() if line.startswith('{')]
if len(rows)!=1:raise SystemExit('Unexpected catch-up output; no content printed')
print(json.dumps(rows[0]))
Loading
Loading