@probnaya/057-cli 1.0.0 → 1.1.0

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/NOTICE.md CHANGED
@@ -29,12 +29,13 @@ falls through to the system monospace when it is not installed locally, so no fo
29
29
  and no font licence applies.
30
30
 
31
31
  **057 Desktop** (`057.app`, built by `desktop/app/bundle.sh`; not part of the npm package)
32
- redistributes two further components, each with its licence inside the app bundle:
32
+ redistributes three further components, each with its licence inside the app bundle:
33
33
 
34
34
  | Component | Version | License | Copyright | In the bundle |
35
35
  | --- | --- | --- | --- | --- |
36
36
  | IBM Plex Mono, Regular and Medium (WOFF2, unmodified) | 2.5.0 | SIL Open Font License 1.1 | © 2017 IBM Corp., Reserved Font Name "Plex" | `Contents/Resources/Fonts/IBMPlexMono-LICENSE.txt` |
37
37
  | Node.js (official darwin-arm64 build, re-signed as the Core helper) | 24.14.0 | MIT, with the third-party licences Node lists | Node.js contributors and others | `Contents/Resources/Licenses/Node-LICENSE.txt` |
38
+ | Sparkle (the update framework; arm64 slices only, without its XPC services, re-signed) | 2.10.0 | MIT, with the external licences Sparkle lists | © 2006–2013 Andy Matuschak and the Sparkle contributors | `Contents/Resources/Licenses/Sparkle-LICENSE.txt` |
38
39
 
39
40
  ---
40
41
 
package/README.md CHANGED
@@ -9,16 +9,20 @@ A spatial interface for observing the shape of a computational workday.
9
9
 
10
10
  **Infrastructure is permanent. Activity is temporary. The field remembers.**
11
11
 
12
- ```bash
13
- npx @probnaya/057-cli
14
- ```
12
+ One instrument, two ways in:
15
13
 
16
- Then open the URL it prints. Nothing else is needed — no account, no configuration, no network.
14
+ - **Download for macOS** — 057.app, at <https://057.probnaya.work/download/macos>. Apple silicon,
15
+ macOS 14 or later.
16
+ - **Install with npm** — the web / CLI surface:
17
17
 
18
- > **Public experiment — v0.1.2.** 057 is being released early and narrowly, to find out
19
- > whether the idea holds up on machines that are not the one it was built on. It supports **macOS
20
- > and a WebGPU browser**, and nothing else honestly. The store format may change between 0.x
21
- > releases. Read *Experimental limitations* before you rely on it.
18
+ ```bash
19
+ npx @probnaya/057-cli
20
+ ```
21
+
22
+ Then open the URL it prints.
23
+
24
+ Nothing else is needed — no account, no configuration, no network. Both run the same Core, read the
25
+ same store and mean the same things; 057 runs on **macOS only**, and honestly nothing else.
22
26
 
23
27
  ## What it is
24
28
 
@@ -38,6 +42,20 @@ anywhere, because token counts are reported and money mostly is not.
38
42
 
39
43
  ## Run it
40
44
 
45
+ ### 057 for macOS
46
+
47
+ Download the disk image from <https://057.probnaya.work/download/macos>, drag 057 to Applications
48
+ and open it. The app carries its own Core — no Node, npm or terminal — and starts observing when it
49
+ opens. Closing the window leaves it observing from the menu bar; quitting the app stops it. It is
50
+ signed with Developer ID and notarized by Apple.
51
+
52
+ **Open in Browser** (the menu-bar menu, or View) opens the browser surface its Core serves. At its
53
+ first launch 057 asks, the way Mac apps do, whether it may send notifications: allowed, it tells you
54
+ only when its Core fails or a source has failed for ten minutes, silently. **Notifications** in the
55
+ **057** menu switches them afterwards.
56
+
57
+ ### The web / CLI surface
58
+
41
59
  ```bash
42
60
  npx @probnaya/057-cli
43
61
  ```
@@ -57,18 +75,22 @@ npm install -g @probnaya/057-cli
57
75
  057 --help
58
76
  ```
59
77
 
60
- 057 runs in the foreground and stops when you stop it. There is no daemon, no background service,
61
- and nothing is installed into your login items. If `5057` is busy it takes the next free port and
62
- prints it.
78
+ The command runs in the foreground and stops when you stop it. There is no daemon, no background
79
+ service, and nothing is installed into your login items. If `5057` is busy it takes the next free
80
+ port and prints it.
81
+
82
+ One store has one observer. If 057.app is already running, `057` says so and names the URL its Core
83
+ serves, and `057 --open` opens it; the history is the same either way.
63
84
 
64
85
  ## Requirements
65
86
 
66
87
  | | |
67
88
  | --- | --- |
89
+ | **macOS app** | Apple silicon, macOS 14 or later. Nothing else to install. |
68
90
  | **OS** | **macOS only.** The package declares `"os": ["darwin"]` and npm will refuse to install elsewhere — the process sampler reads a BSD process table and the Cursor reader looks in a macOS path. A 057 that silently mis-parsed your process table would be worse than one that will not start. |
69
91
  | **Node** | 24.x. The package declares `>=22.5.0`, where the built-in SQLite the store needs first exists, but only 24 has been exercised. |
70
92
  | **Browser** | A WebGPU browser: Chrome 113+, Edge 113+, or Safari 26+. Without WebGPU the interface says so plainly rather than falling back to something that is not FIELD. |
71
- | **Network** | Only to download the package. Running 057 needs none. |
93
+ | **Network** | Only to download the app or the package. Running 057 needs none. |
72
94
 
73
95
  ## What it reads, and what it keeps
74
96
 
@@ -77,7 +99,7 @@ coding runtimes on your machine have already written for their own purposes. 057
77
99
  processes, does not read process memory, and does not watch your keyboard, screen, network or
78
100
  filesystem at large.
79
101
 
80
- **Stored:** hostname and machine name; working-directory and workspace paths; process and command
102
+ **Stored:** the machine's name; working-directory and workspace paths; process and command
81
103
  names; session and execution labels as the runtime recorded them; models, tools, token counts,
82
104
  statuses and timings; and a timeline of when your machine was working.
83
105
 
@@ -88,10 +110,17 @@ pointer to the record it read a fact from, never a copy of it.
88
110
  **Where:** one SQLite database at `~/.057/events.db`, created owner-only (`0700`/`0600`). Nowhere
89
111
  else. `O57_STORE` overrides it; `057 status` prints the path, size and permissions.
90
112
 
91
- **Sent:** nothing. No account, no cloud, no synchronisation, no product analytics, no crash
92
- reporting, no update check. The interface fetches nothing but its own local API — not even a web
93
- font. The only connection is the loopback socket between your browser and the local server. This is
94
- 057's own behaviour; the runtimes it observes talk to their providers on their own terms.
113
+ **Sent:** by the web / CLI surface, nothing. No account, no cloud, no synchronisation, no product
114
+ analytics, no crash reporting, no update check. The interface fetches nothing but its own local API —
115
+ not even a web font. The only connection is the loopback socket between your browser and the local
116
+ server. This is 057's own behaviour; the runtimes it observes talk to their providers on their own
117
+ terms.
118
+
119
+ The macOS app adds exactly one request: **an update check**, to
120
+ `https://057.probnaya.work/appcast.xml`, about once a day — on by default, and off with *Check for
121
+ Updates Automatically* in the 057 menu (*Check for Updates…* beside it checks at once). The request
122
+ carries the app's version and nothing else — no system profile, none of your telemetry. An update is
123
+ installed only when you choose to, and only if it carries 057's signature.
95
124
 
96
125
  **Kept:** process observations 7 days, sessions and executions 90 days, machine identity forever.
97
126
  Both windows are configurable. Deleting rows lets SQLite reuse the pages, so the store plateaus
@@ -152,13 +181,14 @@ how to delete it, and what it is licensed under. The full manual is at
152
181
  | [Reading FIELD](https://057.probnaya.work/docs/field) | How to read the interface. |
153
182
  | [Troubleshooting](https://057.probnaya.work/docs/troubleshooting) | Failure modes, and which ones are safe to act on. |
154
183
 
155
- ## Experimental limitations
184
+ ## Limitations
156
185
 
157
- Stated plainly, because this is a 0.1.0 and you are the experiment.
186
+ Stated plainly.
158
187
 
159
- - **macOS only, and WebGPU is required.** Neither is a "coming soon"; both are refusals to pretend.
160
- - **The store format may change.** It is versioned and upgrades in place, and a store from a newer
161
- 057 is refused rather than downgraded — but a 0.x release may still ask you to reset.
188
+ - **macOS only.** The browser surface needs WebGPU; the app needs Apple silicon. Neither is a
189
+ "coming soon"; both are refusals to pretend.
190
+ - **The store format is versioned** and upgrades in place, and a store from a newer 057 is refused
191
+ rather than downgraded.
162
192
  - **Exits are inferred.** The process sampler is a five-second snapshot, not a kernel hook: it
163
193
  cannot see an exit, only stop seeing a process, and everything derived from that says so. A
164
194
  process that starts and exits within one interval is never observed at all.
@@ -180,7 +210,7 @@ by design, because adding accounts to a local instrument would be adding the exa
180
210
  product does not have.
181
211
 
182
212
  **Do not put 057 behind a reverse proxy, and do not set `O57_HOST` on a network you do not control.**
183
- Either publishes an unauthenticated read of your hostname, your project paths, your session labels,
213
+ Either publishes an unauthenticated read of your machine's name, your project paths, your session labels,
184
214
  your models and a record of when you were at your machine, to anything that can reach that address.
185
215
  057 warns you at startup if you do it. There is no auth to turn on.
186
216
 
@@ -189,7 +219,7 @@ metadata rather than opening it publicly.
189
219
 
190
220
  ## Licence
191
221
 
192
- 057 is publicly installable, but v0.1.2 is not an open-source release. It is distributed under the
222
+ 057 is publicly installable, but it is not an open-source release. It is distributed under the
193
223
  PolyForm Internal Use License 1.0.0: personal use and internal business or workplace use are
194
224
  permitted, redistribution is not, and private modifications for permitted purposes remain governed
195
225
  by the licence. See `LICENSE.md` for the terms. Third-party components retain their own licences as
@@ -1,10 +1,12 @@
1
- import{existsSync as F,writeFileSync as fn,renameSync as mn,rmSync as Ss,readFileSync as hn,statSync as Ge,mkdirSync as gn,chmodSync as bn,createReadStream as vn}from"node:fs";import{createInterface as yn}from"node:readline";import{createServer as wn}from"node:http";import{join as C,isAbsolute as An,resolve as Re,dirname as Sn,normalize as En,sep as kn,extname as In}from"node:path";import{fileURLToPath as Tn}from"node:url";import{stat as fe,readdir as W,readFile as re}from"node:fs/promises";import{hostname as Es,homedir as me}from"node:os";import Mn from"node:zlib";import{createHash as On}from"node:crypto";import{DatabaseSync as pt}from"node:sqlite";import{execFile as $n}from"node:child_process";import{promisify as Rn}from"node:util";const Rt=["machine","session","execution","process","artifact"];function xn(e){return`${e.ns}|${e.parts.join("|")}`}const R={interactions:"interactions",steps:"steps",errors:"errors",retries:"retries",cpuMs:"cpu.ms",tokensInput:"tokens.input",tokensOutput:"tokens.output",tokensCacheRead:"tokens.cacheRead",tokensReasoning:"tokens.reasoning"},Nn=[{a:"execution",b:"process",kind:"ran-as"},{a:"session",b:"process",kind:"ran-as"},{a:"execution",b:"session",kind:"ran-as"},{a:"session",b:"session",kind:"same-as"},{a:"execution",b:"execution",kind:"same-as"},{a:"machine",b:"machine",kind:"same-as"},{a:"process",b:"process",kind:"same-as"}];function xt(e,t){for(const s of Nn){if(e.subjectType===s.a&&t.subjectType===s.b)return{kind:s.kind,from:e,to:t};if(t.subjectType===s.a&&e.subjectType===s.b)return{kind:s.kind,from:t,to:e}}return null}const _n=(e,t)=>e.validFrom<=t.validTo&&t.validFrom<=e.validTo;function Cn(e,t){const s=Math.max(e.validFrom,t.validFrom),n=Math.min(e.validTo,t.validTo);if(n<s)return 0;const o=Math.max(e.validTo,t.validTo)-Math.min(e.validFrom,t.validFrom);return o<=0?1:(n-s)/o}const jn=.5;function Dn(e,t){return _n(e,t)?Cn(e,t)>=jn?2:1:0}const V=e=>`${e.subjectType}:${e.subjectId}`,Fn="inferred",Ln="Two observers asserted the same identity claim over overlapping validity windows, and each was the other's only candidate at the strongest available evidence tier (two lifetimes that substantially coincide beat a bare overlap). The claims themselves are measured; the identification is inferred.";function Un(e){const t=new Map;for(const r of e){const a=t.get(r.key);a?a.push(r):t.set(r.key,[r])}const s=[],n=[];let o=0;for(const[r,a]of[...t.entries()].sort(([i],[c])=>i<c?-1:1)){const i=new Map;for(const b of a){const S=V(b),h=i.get(S);if(!h){i.set(S,{...b});continue}h.validFrom=Math.min(h.validFrom,b.validFrom),h.validTo=Math.max(h.validTo,b.validTo)}const c=[...i.values()].sort((b,S)=>V(b)<V(S)?-1:1);if(c.length<2){o++;continue}const d=[];let u=!1;for(let b=0;b<c.length;b++)for(let S=b+1;S<c.length;S++){const h=c[b],f=c[S];if(h.sourceId===f.sourceId)continue;const v=Dn(h,f);if(v!==0){if(!xt(h,f)){u=!0;continue}d.push({x:h,y:f,tier:v})}}const m=new Map;for(const b of d)for(const S of[b.x,b.y]){const h=V(S);m.set(h,Math.max(m.get(h)??0,b.tier))}const E=new Map;for(const b of d)for(const S of[b.x,b.y]){const h=V(S);m.get(h)===b.tier&&E.set(h,(E.get(h)??0)+1)}if(d.length===0){n.push({key:r,reason:u?"no-pairing-defined":"no-window-overlap",subjects:[...i.keys()].sort()});continue}for(const{x:b,y:S,tier:h}of d){if(m.get(V(b))!==h||m.get(V(S))!==h)continue;if(E.get(V(b))!==1||E.get(V(S))!==1){n.push({key:r,reason:"multiple-candidates",subjects:[V(b),V(S)].sort()});continue}const f=xt(b,S);s.push({from:{type:f.from.subjectType,id:f.from.subjectId},to:{type:f.to.subjectType,id:f.to.subjectId},kind:f.kind,basis:Fn,assumption:Ln,via:r})}}return{relationships:s,ambiguous:n,unmatched:o,considered:t.size}}async function Pn(e,t,s,n,o){const r=[];let a=0,i=0;for(const c of t){const d=Date.now();try{const u=await c.collect(s,n),m=e.append(u);a+=m.inserted,i+=m.duplicate,r.push({id:c.id,ok:!0,collected:u.length,inserted:m.inserted,duplicate:m.duplicate,ms:Date.now()-d})}catch(u){r.push({id:c.id,ok:!1,collected:0,inserted:0,duplicate:0,error:u instanceof Error?u.message:String(u),ms:Date.now()-d})}o?.(r[r.length-1])}return{sources:r,inserted:a,duplicate:i}}function Bn(e,t,s){return Un(e.claims(t,s))}const ks="deepseek-harness",P=e=>typeof e=="number"&&Number.isFinite(e)?e:0,G=e=>typeof e=="string"?e:void 0;function Hn(e){const t=e.split("/").filter(Boolean);return(t[t.length-1]??e).toUpperCase()}function Wn(e,t){const s=[],n=e[0];if(!n||n.type!=="session"||!n.id)return s;const o=n.id,r=n.cwd??"",a=P(n.createdAt),i=P(n.delegationDepth),c=Hn(r);let d="deepseek",u,m;for(const y of e)if(y.type==="request/context"&&y.data?(d=G(y.data.provider)??d,u=G(y.data.model)??u):y.type==="session/title"&&y.data&&(m=G(y.data.title)??m),u&&m)break;const b={source:{id:ks,instance:t.instance},observedAt:t.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"};let S=a;for(const y of e){const M=P(y.time);M>S&&(S=M)}const h={ns:"fs.cwd",parts:[t.host,r],validFrom:a,validTo:Math.max(a,S)};s.push({...b,occurredAt:a,seq:"session",kind:"began",subject:{type:"session",id:o},claims:r?[h]:void 0,core:{machineId:t.machine.id,label:m,executor:d,model:u,depth:i},attrs:{context:r,"dsh.delegationDepth":i}});const f=y=>`${o}:turn:${y}`;let v=null;const l=new Map,w=new Map;let g=a;for(const y of e){const M=P(y.time)||g;if(M<a)continue;g=M;const p=y.data??{},A=y.seq??`t${M}`,I=k=>({type:"execution",id:f(k)});switch(y.type){case"turn/start":{const k=P(p.turn);v=k,s.push({...b,occurredAt:M,seq:A,kind:"began",subject:I(k),core:{machineId:t.machine.id,sessionId:o,label:m?`${c} · ${m}`:c,executor:d,model:u,depth:i},attrs:{"dsh.turn":k}});break}case"turn/end":{const k=P(p.turn),T=p.reason,O=T?.kind;if(O==="error"){const $=T?.error??{};s.push({...b,occurredAt:M,seq:A,kind:"ended",subject:I(k),core:{outcome:"error",failureCode:G($.code)??"ERROR",failureMessage:G($.message)??"Run failed"},attrs:{"dsh.endReason":O}})}else s.push({...b,occurredAt:M,seq:A,kind:"ended",subject:I(k),core:{outcome:O==="aborted"?"interrupted":"completed"},attrs:{"dsh.endReason":O??"completed"}});v===k&&(v=null);break}case"assistant/message":{const k=P(p.turn),T=p.usage;if(!T)break;const O={[R.tokensInput]:P(T.inputTokens),[R.tokensOutput]:P(T.outputTokens),[R.tokensCacheRead]:P(T.cacheReadTokens),[R.tokensReasoning]:P(T.reasoningTokens),[R.steps]:1};s.push({...b,occurredAt:M,seq:A,kind:"progressed",subject:I(k),core:{measures:O},attrs:{"dsh.inputTokens":P(T.inputTokens),"dsh.outputTokens":P(T.outputTokens),"dsh.cacheReadTokens":P(T.cacheReadTokens),"dsh.reasoningTokens":P(T.reasoningTokens)}});break}case"tool/call":{s.push({...b,occurredAt:M,seq:A,kind:"progressed",subject:I(P(p.turn)),core:{measures:{[R.interactions]:1}},attrs:{"dsh.tool":G(p.name)}});break}case"tool/result":{const k=p.message;let T=!1;for(const O of k?.content??[])O.isError===!0&&(T=!0);T&&s.push({...b,occurredAt:M,seq:A,kind:"progressed",subject:I(P(p.turn)),core:{measures:{[R.errors]:1}}});break}case"llm/retry":{s.push({...b,occurredAt:M,seq:A,kind:"progressed",subject:I(P(p.turn)),core:{measures:{[R.retries]:1}}});break}case"approval/asked":{const k=G(p.id);if(v===null)break;k&&l.set(k,v),s.push({...b,occurredAt:M,seq:A,kind:"blocked",subject:I(v),core:{blockedOn:"approval"},attrs:{"dsh.approvalId":k}});break}case"approval/decided":{const k=G(p.id),T=k?l.get(k):v;if(T==null)break;l.delete(k??""),s.push({...b,occurredAt:M,seq:A,kind:"resumed",subject:I(T),attrs:{"dsh.approvalId":k}});break}case"tool-workflow/agent-start":{if(v===null)break;const k=G(p.childId);if(!k)break;const T=`${o}:agent:${k}`;w.set(`${G(p.runId)}:${P(p.seq)}`,T),s.push({...b,occurredAt:M,seq:A,kind:"began",subject:{type:"execution",id:T},core:{machineId:t.machine.id,sessionId:o,label:G(p.label)??`${c} · SUB`,executor:d,model:u,parentId:f(v),depth:i+1},attrs:{"dsh.childId":k}});break}case"tool-workflow/agent-end":{const k=`${G(p.runId)}:${P(p.seq)}`,T=w.get(k);if(!T)break;w.delete(k);const O=G(p.outcome);s.push({...b,occurredAt:M,seq:A,kind:"ended",subject:{type:"execution",id:T},core:O==="completed"?{outcome:"completed"}:{outcome:"error",failureCode:"SUBAGENT",failureMessage:O??"Sub-agent did not complete"},attrs:{"dsh.subagentOutcome":O}});break}}}if(t.closeOpenTurns){const y="The session log has not been written to for longer than the live window, so the process that owned it is gone and any turn left open was cut off rather than still running.";v!==null&&s.push({...b,occurredAt:g,seq:"close:turn",kind:"ended",subject:{type:"execution",id:f(v)},core:{outcome:"interrupted"},basis:"inferred",assumption:y});for(const M of w.values())s.push({...b,occurredAt:g,seq:`close:${M}`,kind:"ended",subject:{type:"execution",id:M},core:{outcome:"interrupted"},basis:"inferred",assumption:y});s.push({...b,occurredAt:g,seq:"close:session",kind:"ended",subject:{type:"session",id:o},basis:"inferred",assumption:y})}return t.since!==void 0?s.filter(y=>y.occurredAt>=t.since):s}function Xn(e){const t=[];let s=0;for(;s<e.length;){let n=e.indexOf(`
2
- `,s);n===-1&&(n=e.length);const o=e.slice(s,n);if(s=n+1,o.length!==0&&!(o.startsWith('{"type":"reasoning-chunks"')||o.startsWith('{"type":"text-chunks"')||o.startsWith('{"type":"tool-call-chunks"')||o.startsWith('{"type":"assistant/chunk"')))try{t.push(JSON.parse(o))}catch{}}return t}function Gn(e){const t=JSON.stringify([e.source.id,e.source.instance,e.occurredAt,e.clock,e.kind,e.subject.type,e.subject.id,e.basis,e.seq??null,Be(e.core),Be(e.attrs)]);return On("sha256").update(t).digest("hex").slice(0,32)}function Be(e){if(e==null)return null;if(Array.isArray(e))return e.map(Be);if(typeof e!="object")return e;const t={};for(const s of Object.keys(e).sort())t[s]=Be(e[s]);return t}function ee(e){const{seq:t,...s}=e;return{id:Gn(e),...s}}const qn=4247762216,Yn=407710288,Vn=407710303;function zn(e){const t=[];for(let o=0;o+4<=e.length;o++){const r=e.readUInt32LE(o);(r===qn||r>=Yn&&r<=Vn)&&t.push(o)}if(t.length===0)return Buffer.alloc(0);const s=[];let n=0;for(;n<t.length;){let o=n+1,r=null;for(;;){const a=o<t.length?t[o]:e.length;try{r=Mn.zstdDecompressSync(e.subarray(t[n],a));break}catch{if(o>=t.length)break;o++}}r?(s.push(r),n=o):n++}return Buffer.concat(s)}function ft(){return process.env.DSH_HOME||C(me(),".dsh")}function ue(){return Es().replace(/\.local$/i,"")}function he(){const e=ue();return{id:`host:${e}`,name:e.toUpperCase(),kind:"laptop",firstSeenAt:0}}const Nt=new Map;async function Is(){const e=C(ft(),"sessions");if(!F(e))return[];const t=[];for(const s of await W(e)){const n=C(e,s);let o;try{o=await W(n)}catch{continue}for(const r of o){const a=C(n,r,"session.jsonl.zstd");F(a)&&t.push({path:a,workspace:s,sessionId:r})}}return t}const Kn=10*6e4;async function Jn(e,t){const s=await fe(e.path),n=Nt.get(e.path);if(n&&n.mtimeMs===s.mtimeMs&&n.size===s.size)return n.envelopes;const o=await re(e.path),r=zn(o).toString("utf8"),a=Xn(r),i=Date.now()-s.mtimeMs>Kn,d=Wn(a,{machine:t,host:ue(),instance:ft(),observedAt:Date.now(),closeOpenTurns:i}).map(ee);return Nt.set(e.path,{mtimeMs:s.mtimeMs,size:s.size,envelopes:d}),d}async function Qn(e,t){const s=he(),n=await Is(),o=[];for(const r of n){let a;try{a=await fe(r.path)}catch{continue}if(!(a.mtimeMs<e))for(const i of await Jn(r,s))i.occurredAt>=e&&i.occurredAt<=t&&o.push(i)}return o}async function _t(){const e=await Is(),t=ft();return{available:e.length>0,present:F(t),home:t,sessions:e.length}}const Ts=1e3,Ct=60*Ts;function H(e){if(!Number.isFinite(e)||e<=0)return"0m";if(e<Ct)return`${Math.max(1,Math.round(e/Ts))}s`;const t=Math.round(e/Ct),s=Math.floor(t/60),n=t%60;return s===0?`${n}m`:n===0?`${s}h`:`${s}h ${n}m`}function X(e){if(!Number.isFinite(e))return"—";const t=Math.abs(e);return t>=1e9?`${(e/1e9).toFixed(t>=1e10?0:2)}B`:t>=1e6?`${(e/1e6).toFixed(t>=1e7?0:2)}M`:t>=1e3?`${(e/1e3).toFixed(t>=1e4?0:1)}k`:String(Math.round(e))}function Zn(e,t="NOT OBSERVED"){return e===void 0?t:X(e)}function eo(e){return e===void 0||!Number.isFinite(e)?"—":e>=1e9?`${(e/1e9).toFixed(1)} GB`:e>=1e6?`${(e/1e6).toFixed(0)} MB`:e>=1e3?`${(e/1e3).toFixed(0)} KB`:`${e} B`}function xe(e){const t=new Date(e);return`${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}`}function z(e){const t=e.split("/").filter(Boolean);return t[t.length-1]??e}const ot="0x2f",se=e=>{if(typeof e!="string")return;const t=Date.parse(e);return Number.isFinite(t)?t:void 0},Ms=(e,t)=>`2f:${e}#${t}`,to=(e,t,s)=>`${Ms(e,t)}:run:${s}`;function jt(e){return e?.type==="permission"?"approval":"input"}function so(e){const t=new Map;for(const s of e){const n=typeof s.run=="number"?s.run:1,o=t.get(n);o?o.push(s):t.set(n,[s])}return t}function no(e,t){const s=t.find(r=>r.type==="run.started");let n;for(let r=t.length-1;r>=0;r--){const a=t[r];if(a.type==="run.completed"||a.type==="run.failed"||a.type==="needs_user"&&a.blockedOn){n=a;break}}let o;return n?.type==="run.completed"?o="ready":n?.type==="run.failed"?o="failed":n?o="needs_you":e.status==="needs_you"||e.status==="ready"||e.status==="failed"?o=e.status:e.status==="working"?o="working":o=e.error?"failed":"ready",{run:1,provider:e.execution?.provider??null,node:e.execution?.node??null,model:e.execution?.model,externalSessionId:e.execution?.externalSessionId,attempts:e.execution?.attempts??1,startedAt:s?.at,completedAt:n?.at,outcome:o,error:e.error??(n?.type==="run.failed"?n.error:void 0),blockedOn:n?.type==="needs_user"?n.blockedOn:void 0,failure:e.failure}}function oo(e,t){return Array.isArray(e.runs)&&e.runs.length?e.runs:[no(e,t)]}function ro(e,t,s){if(typeof e.id!="number")return[];const n=Ms(s.base,e.id),o=oo(e,t),r=z(s.base).toUpperCase(),a=e.title,i=e.execution?.provider??o.at(-1)?.provider??ot,c=se(e.createdAt)??o.map(f=>se(f.startedAt)).find(f=>f!==void 0);if(c===void 0)return[];const u={source:{id:ot,instance:s.base},observedAt:s.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"},m=[{...u,occurredAt:c,kind:"began",subject:{type:"session",id:n},core:{machineId:s.machine.id,label:a,executor:i,model:e.execution?.model},attrs:{context:s.base,"0x2f.taskId":e.id,"0x2f.status":e.status}}],E=so(t),b=t.filter(f=>f.type==="task.answered"),S=t.find(f=>f.type==="task.closed"),h=o.at(-1);for(let f=0;f<o.length;f++){const v=o[f],l=se(v.startedAt);if(l===void 0)continue;const w=to(s.base,e.id,v.run),g=v.provider??i,y=se(v.completedAt),M=y??s.now,p=[{ns:"fs.cwd",parts:[s.host,s.base],validFrom:l,validTo:M}];typeof v.externalSessionId=="string"&&v.externalSessionId&&p.push({ns:"agent.session",parts:[g,v.externalSessionId],validFrom:l,validTo:M}),v===h&&typeof e.pid=="number"&&p.push({ns:"os.process",parts:[s.host,e.pid],validFrom:l,validTo:M}),m.push({...u,occurredAt:l,seq:`run:${v.run}`,kind:"began",subject:{type:"execution",id:w},claims:p,core:{machineId:s.machine.id,sessionId:n,label:a?`${r} · ${a} · RUN ${v.run}`:`${r} · RUN ${v.run}`,executor:g,model:v.model??e.execution?.model,depth:0},attrs:{"0x2f.run":v.run,"0x2f.provider":g,"0x2f.workspace":s.base,...v.requestedProvider?{"0x2f.requestedProvider":v.requestedProvider}:{},...e.pid!==void 0&&v===h?{"0x2f.workerPid":e.pid}:{}}});let A=!1,I=0;for(const T of E.get(v.run)??[]){I++;const O=se(T.at);if(O===void 0||O<l)continue;const $=`run:${v.run}:${I}`;if(T.type==="tool.started")m.push({...u,occurredAt:O,seq:$,kind:"progressed",subject:{type:"execution",id:w},core:{measures:{[R.interactions]:1}},attrs:{"0x2f.tool":T.name}});else if(T.type==="progress")m.push({...u,occurredAt:O,seq:$,kind:"progressed",subject:{type:"execution",id:w}});else if(T.type==="needs_user"&&T.blockedOn){if(A)continue;A=!0,m.push({...u,occurredAt:O,seq:$,kind:"blocked",subject:{type:"execution",id:w},core:{blockedOn:jt(T.blockedOn)},attrs:{"0x2f.blockedOn":T.blockedOn.type}})}else if(T.type==="permission.resolved"||T.type==="task.updated"&&typeof T.grant=="string"){if(!A)continue;A=!1,m.push({...u,occurredAt:O,seq:$,kind:"resumed",subject:{type:"execution",id:w},attrs:{"0x2f.grant":T.grant}})}}const k=(T,O,$)=>m.push({...u,occurredAt:T,seq:$,kind:"ended",subject:{type:"execution",id:w},core:O});if(v.outcome==="ready"&&y!==void 0)k(y,{outcome:"completed"},`run:${v.run}:end`);else if(v.outcome==="failed"&&y!==void 0)k(y,{outcome:"error",failureCode:(v.failure?.kind??e.failure?.kind??"unclassified").toUpperCase(),failureMessage:v.error??e.error??"Run failed"},`run:${v.run}:end`);else if(v.outcome==="needs_you"&&y!==void 0){A||(A=!0,m.push({...u,occurredAt:y,seq:`run:${v.run}:block`,kind:"blocked",subject:{type:"execution",id:w},core:{blockedOn:jt(v.blockedOn)}}));const T=io(y,b,o[f+1],S);T!==void 0&&k(T,{outcome:"interrupted"},`run:${v.run}:end`)}}if(S){const f=se(S.at);f!==void 0&&m.push({...u,occurredAt:f,seq:"task:closed",kind:"ended",subject:{type:"session",id:n}})}return m}function io(e,t,s,n){const o=[...t.map(a=>se(a.at)),se(s?.startedAt),se(n?.at)];let r;for(const a of o)a===void 0||a<e||(r===void 0||a<r)&&(r=a);return r}function ao(e){const t=[];for(const s of e.split(`
3
- `))if(s.trim())try{const n=JSON.parse(s);n&&typeof n.type=="string"&&t.push(n)}catch{}return t}const Os=".work";function $s(){const e=process.env.WORK_ROOTS;return e?e.split(/[:,]/).map(t=>t.trim()).filter(Boolean):[me()]}const Dt=e=>F(C(e,Os,"tasks")),co=new Set(["Desktop","Documents","Downloads"]);async function Rs(){const e=new Set,t=!process.env.WORK_ROOTS;for(const s of $s()){if(Dt(s)){e.add(s);continue}let n;try{n=await W(s,{withFileTypes:!0})}catch{continue}for(const o of n){if(!o.isDirectory()||o.name.startsWith(".")||t&&co.has(o.name))continue;const r=C(s,o.name);Dt(r)&&e.add(r)}}return[...e].sort()}async function uo(){const e=[];for(const t of await Rs()){const s=C(t,Os,"tasks");let n;try{n=await W(s,{withFileTypes:!0})}catch{continue}for(const o of n){if(!o.isDirectory())continue;const r=C(s,o.name,"task.json");F(r)&&e.push({base:t,slug:o.name,taskPath:r,eventsPath:C(s,o.name,"events.jsonl")})}}return e}const Ft=new Map;async function lo(e,t,s){let n;try{n=await fe(e.taskPath)}catch{return null}const o=await fe(e.eventsPath).catch(()=>null),r=Math.max(n.mtimeMs,o?.mtimeMs??0),a=`${n.mtimeMs}:${n.size}:${o?.mtimeMs??0}:${o?.size??0}`,i=Ft.get(e.taskPath);if(i&&i.stamp===a)return{envelopes:i.envelopes,touchedAt:r};let c;try{c=JSON.parse(await re(e.taskPath,"utf8"))}catch{return null}let d=[];try{d=ao(await re(e.eventsPath,"utf8"))}catch{}const u=ro(c,d,{machine:t,base:e.base,host:ue(),observedAt:Date.now(),now:s}).map(ee);return Ft.set(e.taskPath,{stamp:a,envelopes:u}),{envelopes:u,touchedAt:r}}async function po(e,t){const s=he(),n=await uo(),o=[];for(const r of n){const a=await lo(r,s,t);if(a&&!(a.touchedAt<e))for(const i of a.envelopes)i.occurredAt>=e&&i.occurredAt<=t&&o.push(i)}return o}async function Lt(){const e=$s(),t=await Rs();return{available:t.length>0,present:e.some(s=>F(s)),roots:e,workspaces:t}}const Ae="claude-code",xs="claude-code";class oe extends Error{constructor(t,s,n){super(t),this.path=s,this.sourceVersion=n,this.name="ClaudeFormatError"}path;sourceVersion}const Ns=e=>`claude:${e}`;function fo(e,t){const s=e,n=typeof s?.version=="string"?s.version:void 0;if(!s||typeof s!="object")throw new oe("registry entry is not an object",t,n);if(typeof s.sessionId!="string"||!s.sessionId)throw new oe("registry entry has no sessionId",t,n);if(typeof s.pid!="number"||!Number.isFinite(s.pid))throw new oe("registry entry has no numeric pid",t,n);if(typeof s.startedAt!="number"||!Number.isFinite(s.startedAt))throw new oe("registry entry has no numeric startedAt",t,n);return s}function mo(e,t,s){const n=[{ns:"agent.session",parts:[xs,e.sessionId],validFrom:e.startedAt,validTo:s.now},{ns:"os.process",parts:[s.host,e.pid],validFrom:e.startedAt,validTo:s.now}];return{source:{id:Ae,instance:s.host},occurredAt:e.startedAt,observedAt:s.observedAt,clock:"wall",stratum:"identity",kind:"began",subject:{type:"session",id:Ns(e.sessionId)},claims:n,basis:"measured",core:{machineId:s.machine.id,label:e.name??z(e.cwd??"").toUpperCase(),executor:Ae},attrs:{context:e.cwd,"claude.sessionId":e.sessionId,"claude.pid":e.pid,"claude.procStart":e.procStart,"claude.version":e.version,"claude.kind":e.kind,"claude.entrypoint":e.entrypoint,"claude.status":e.status,"claude.waitingFor":e.waitingFor},provenance:{path:t,recordId:e.sessionId,sourceVersion:e.version},seq:"registry"}}const ne=e=>typeof e=="number"&&Number.isFinite(e)?e:0,be=e=>{if(typeof e!="string")return;const t=Date.parse(e);return Number.isFinite(t)?t:void 0};function ho(e){const t=[];for(const s of e.split(`
4
- `))if(s.trim())try{const n=JSON.parse(s);n&&typeof n=="object"&&t.push(n)}catch{}return t}function go(e){if(!e)return{};const t=e.output_tokens_details;return{[R.tokensInput]:ne(e.input_tokens)+ne(e.cache_creation_input_tokens),[R.tokensOutput]:ne(e.output_tokens),[R.tokensCacheRead]:ne(e.cache_read_input_tokens),[R.tokensReasoning]:ne(t?.thinking_tokens),[R.steps]:1}}function bo(e,t){const s=e.filter(l=>be(l.timestamp)!==void 0);if(s.length===0)throw new oe("transcript has no timestamped records",t.path);const n=e.find(l=>typeof l.sessionId=="string")?.sessionId;if(n&&n!==t.sessionId)throw new oe(`transcript names session ${n} but is filed under ${t.sessionId}`,t.path);const o=e.find(l=>typeof l.version=="string")?.version,r=e.find(l=>typeof l.cwd=="string")?.cwd??"",a=e.find(l=>typeof l.gitBranch=="string")?.gitBranch,i=e.find(l=>typeof l.entrypoint=="string")?.entrypoint,c=z(r).toUpperCase(),d=t.sessionId,u=Ns(d),m=be(s[0].timestamp),E=be(s[s.length-1].timestamp),S={source:{id:Ae,instance:t.host},observedAt:t.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"},h=(l,w)=>({path:t.path,...l?{recordId:l}:{},...w!==void 0?{index:w}:{},...o?{sourceVersion:o}:{}}),f=[{...S,occurredAt:m,kind:"began",subject:{type:"session",id:u},claims:[{ns:"agent.session",parts:[xs,d],validFrom:m,validTo:E}],core:{machineId:t.machine.id,label:c,executor:Ae},attrs:{context:r,"claude.sessionId":d,"claude.gitBranch":a,"claude.entrypoint":i,"claude.version":o},provenance:h(d),seq:"session"}],v=[];for(let l=0;l<e.length;l++){const w=e[l];w.type==="user"&&typeof w.promptSource=="string"&&be(w.timestamp)!==void 0&&v.push(l)}if(v.length===0)throw new oe(`transcript has ${e.length} records but no prompt-bearing user record (expected \`type:"user"\` with \`promptSource\`)`,t.path,o);for(let l=0;l<v.length;l++){const w=v[l],g=l+1<v.length?v[l+1]:e.length,y=l+1,M=`${u}:turn:${y}`,p=be(e[w].timestamp),A=e.slice(w,g).some(O=>O.isSidechain===!0);let I,k=p;const T=[];for(let O=w;O<g;O++){const $=e[O],x=be($.timestamp);if(x===void 0)continue;if(($.type==="assistant"||$.type==="user"&&Array.isArray($.message?.content))&&x>k&&(k=x),$.type==="assistant"&&$.message){I??=$.message.model;const U=(Array.isArray($.message.content)?$.message.content:[]).filter(N=>!!N&&typeof N=="object"&&N.type==="tool_use"),K={...go($.message.usage)};U.length&&(K[R.interactions]=U.length),T.push({...S,occurredAt:x,kind:"progressed",subject:{type:"execution",id:M},core:{measures:K},attrs:{...U.length?{"claude.tools":U.map(N=>N.name??"unknown")}:{},...$.message.model?{"claude.model":$.message.model}:{},...$.requestId?{"claude.requestId":$.requestId}:{},...$.message.stop_reason?{"claude.stopReason":$.message.stop_reason}:{},...$.message.usage?{"claude.usage.inputTokens":ne($.message.usage.input_tokens),"claude.usage.outputTokens":ne($.message.usage.output_tokens),"claude.usage.cacheReadTokens":ne($.message.usage.cache_read_input_tokens),"claude.usage.cacheCreationTokens":ne($.message.usage.cache_creation_input_tokens),"claude.usage.serviceTier":$.message.usage.service_tier}:{}},provenance:h($.uuid,O),seq:$.uuid??`a${O}`})}else if($.type==="user"&&$.message&&Array.isArray($.message.content)){const D=$.message.content.filter(U=>!!U&&typeof U=="object"&&U.is_error===!0).length;D&&T.push({...S,occurredAt:x,kind:"progressed",subject:{type:"execution",id:M},core:{measures:{[R.errors]:D}},provenance:h($.uuid,O),seq:$.uuid??`e${O}`})}}f.push({...S,occurredAt:p,kind:"began",subject:{type:"execution",id:M},core:{machineId:t.machine.id,sessionId:u,label:`${c} · TURN ${y}`,executor:Ae,model:I,depth:A?1:0},attrs:{"claude.turn":y,"claude.promptSource":e[w].promptSource,"claude.promptId":e[w].promptId,...A?{"claude.isSidechain":!0}:{}},provenance:h(e[w].uuid,w),seq:`turn:${y}`}),f.push(...T),f.push({...S,occurredAt:k,kind:"ended",subject:{type:"execution",id:M},core:{outcome:"completed"},provenance:h(e[w].uuid,w),seq:`turn:${y}:end`})}return f}function mt(){return process.env.CLAUDE_HOME||C(me(),".claude")}const rt=()=>C(mt(),"sessions"),vo=()=>C(mt(),"projects"),Ut=new Map;async function yo(e,t,s){const n=rt();if(!F(n))return;s.identityAvailable=!0;let o;try{o=await W(n)}catch(r){s.problems.push({path:n,message:String(r)});return}for(const r of o){if(!r.endsWith(".json"))continue;const a=C(n,r);try{const i=fo(JSON.parse(await re(a,"utf8")),a);s.envelopes.push(ee(mo(i,a,{machine:e,host:ue(),observedAt:t,now:t}))),s.registryEntries++}catch(i){s.problems.push({path:a,message:i instanceof Error?i.message:String(i),sourceVersion:i instanceof oe?i.sourceVersion:void 0})}}}async function _s(){const e=vo();if(!F(e))return[];const t=[];let s;try{s=await W(e)}catch{return t}for(const n of s){let o;try{o=await W(C(e,n))}catch{continue}for(const r of o)r.endsWith(".jsonl")&&t.push({path:C(e,n,r),sessionId:r.slice(0,-6),project:n})}return t}async function wo(e,t,s,n){const o=await _s();if(o.length!==0){n.storedAvailable=!0;for(const r of o){let a;try{a=await fe(r.path)}catch{continue}if(a.mtimeMs<t)continue;const i=`${a.mtimeMs}:${a.size}`,c=Ut.get(r.path);let d;if(c&&c.stamp===i)d=c.envelopes;else try{const u=ho(await re(r.path,"utf8"));d=bo(u,{machine:e,host:ue(),observedAt:Date.now(),path:r.path,sessionId:r.sessionId}).map(ee),Ut.set(r.path,{stamp:i,envelopes:d})}catch(u){n.transcriptsFailed++,n.problems.push({path:r.path,message:u instanceof Error?u.message:String(u),sourceVersion:u instanceof oe?u.sourceVersion:void 0});continue}n.transcriptsRead++;for(const u of d)u.occurredAt>=t&&u.occurredAt<=s&&n.envelopes.push(u)}}}async function Cs(e,t){const s=he(),n=Date.now(),o={envelopes:[],registryEntries:0,transcriptsRead:0,transcriptsFailed:0,problems:[],identityAvailable:!1,storedAvailable:!1};return await yo(s,n,o),await wo(s,e,t,o),o}async function Ao(e,t){return(await Cs(e,t)).envelopes}async function Pt(){const e=mt(),t=F(rt())?(await W(rt()).catch(()=>[])).filter(n=>n.endsWith(".json")).length:0,s=(await _s()).length;return{available:t>0||s>0,present:F(e),home:e,registry:t,transcripts:s}}const De="codex",So="codex",Eo=10*6e4;class ye extends Error{constructor(t,s,n){super(t),this.path=s,this.sourceVersion=n,this.name="CodexFormatError"}path;sourceVersion}const ko=e=>`codex:${e}`,J=e=>typeof e=="number"&&Number.isFinite(e)?e:0,j=e=>typeof e=="string"&&e?e:void 0,Ke=e=>{if(typeof e!="string")return;const t=Date.parse(e);return Number.isFinite(t)?t:void 0};function Io(e){const t=[];for(const s of e.split(`
5
- `))if(s.trim())try{const n=JSON.parse(s);n&&typeof n=="object"&&t.push(n)}catch{}return t}function To(e){const t=J(e.input_tokens),s=J(e.cached_input_tokens);return{[R.tokensInput]:Math.max(0,t-s),[R.tokensOutput]:J(e.output_tokens),[R.tokensCacheRead]:s,[R.tokensReasoning]:J(e.reasoning_output_tokens),[R.steps]:1}}function Mo(e,t){const s=e.find(l=>l.type==="session_meta");if(!s||!s.payload)throw new ye("rollout has no session_meta record",t.path);const n=s.payload,o=j(n.cli_version),r=j(n.session_id)??j(n.id);if(r&&r!==t.sessionId)throw new ye(`rollout names session ${r} but is filed under ${t.sessionId}`,t.path,o);const a=j(n.cwd)??"",i=Ke(n.timestamp)??Ke(s.timestamp);if(i===void 0)throw new ye("session_meta has no parseable timestamp",t.path,o);const c=z(a).toUpperCase(),d=ko(t.sessionId),m={source:{id:De,instance:t.host},observedAt:t.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"},E=(l,w)=>({path:t.path,...l?{recordId:l}:{},...w!==void 0?{index:w}:{},...o?{sourceVersion:o}:{}}),b=[];let S=null,h=i,f=0;for(let l=0;l<e.length;l++){const w=e[l],g=Ke(w.timestamp);g!==void 0&&g>h&&(h=g);const y=w.payload;if(!y)continue;if(w.type==="turn_context"){S&&j(y.turn_id)===S.turnId&&(S.model??=j(y.model),S.effort??=j(y.effort));continue}if(w.type!=="event_msg")continue;const M=j(y.type);if(M==="task_started"){const A=j(y.turn_id);if(!A||g===void 0)throw new ye(`task_started at ordinal ${w.ordinal} is missing turn_id or timestamp`,t.path,o);S={turnId:A,startedAt:g,interior:[],lastAt:g},b.push(S);continue}if(M==="task_complete"){const A=j(y.turn_id),I=b.find(k=>k.turnId===A)??S;if(I&&g!==void 0){I.completedAt=g;const k=y.error;I.outcome=k?"error":"completed",I.failureMessage=k?j(k.message):void 0,I.lastAt=Math.max(I.lastAt,g)}I===S&&(S=null);continue}if(M==="token_count"||M==="item_completed"){if(!S){f++;continue}if(g===void 0)continue}else continue;const p=`${d}:turn:${S.turnId}`;if(M==="token_count"){const I=y.info?.last_token_usage;if(!I)continue;S.lastAt=Math.max(S.lastAt,g),S.interior.push({...m,occurredAt:g,kind:"progressed",subject:{type:"execution",id:p},core:{measures:To(I)},attrs:{"codex.usage.inputTokens":J(I.input_tokens),"codex.usage.cachedInputTokens":J(I.cached_input_tokens),"codex.usage.cacheWriteInputTokens":J(I.cache_write_input_tokens),"codex.usage.outputTokens":J(I.output_tokens),"codex.usage.reasoningOutputTokens":J(I.reasoning_output_tokens)},provenance:E(void 0,w.ordinal),seq:`o${w.ordinal??l}`});continue}if(M==="item_completed"){const A=y.item,I=j(A?.type);if(!A||!I)continue;S.lastAt=Math.max(S.lastAt,g);let k,T;if(I==="CommandExecution"){const O=J(A.exit_code);k={[R.interactions]:1,...O!==0?{[R.errors]:1}:{}},T={"codex.itemType":I,"codex.exitCode":O,...A.process_id!==void 0?{"codex.processId":A.process_id}:{},...j(A.status)?{"codex.status":A.status}:{}}}else if(I==="McpToolCall"){const O=j(A.status)==="failed"||j(A.status)==="error";k={[R.interactions]:1,...O?{[R.errors]:1}:{}},T={"codex.itemType":I,"codex.tool":[j(A.server),j(A.tool)].filter(Boolean).join("."),...j(A.status)?{"codex.status":A.status}:{}}}else if(I==="WebSearch")k={[R.interactions]:1},T={"codex.itemType":I};else if(I==="FileChange"){const O=A.changes;k={[R.interactions]:1},T={"codex.itemType":I,...O&&typeof O=="object"?{"codex.fileChanges":Object.entries(O).map(([$,x])=>({path:$,kind:j(x?.type)}))}:{}}}else continue;S.interior.push({...m,occurredAt:g,kind:"progressed",subject:{type:"execution",id:p},core:{measures:k},attrs:T,provenance:E(j(A.id),w.ordinal),seq:`o${w.ordinal??l}`})}}if(b.length===0&&f>0)throw new ye(`rollout has ${f} work records but no task_started marker`,t.path,o);const v=[{...m,occurredAt:i,kind:"began",subject:{type:"session",id:d},claims:[{ns:"agent.session",parts:[So,t.sessionId],validFrom:i,validTo:h}],core:{machineId:t.machine.id,label:c,executor:De},attrs:{context:a,"codex.sessionId":t.sessionId,"codex.cliVersion":o,"codex.originator":j(n.originator),"codex.source":j(n.source),"codex.modelProvider":j(n.model_provider),...Oo(n.git)},provenance:E(t.sessionId,s.ordinal),seq:"session"}];for(let l=0;l<b.length;l++){const w=b[l],g=`${d}:turn:${w.turnId}`;v.push({...m,occurredAt:w.startedAt,kind:"began",subject:{type:"execution",id:g},core:{machineId:t.machine.id,sessionId:d,label:`${c} · TURN ${l+1}`,executor:De,model:w.model,depth:0},attrs:{"codex.turnId":w.turnId,...w.effort?{"codex.effort":w.effort}:{}},provenance:E(w.turnId),seq:`turn:${w.turnId}`}),v.push(...w.interior),w.completedAt!==void 0?v.push({...m,occurredAt:w.completedAt,kind:"ended",subject:{type:"execution",id:g},core:{outcome:w.outcome??"completed",...w.outcome==="error"?{failureCode:"CODEX_TURN_ERROR",failureMessage:w.failureMessage??"turn failed"}:{}},provenance:E(w.turnId),seq:`turn:${w.turnId}:end`}):t.now-h>Eo&&v.push({...m,basis:"inferred",assumption:"A rollout untouched for 10 minutes belongs to a dead process, so a turn left open in it was interrupted, not still running. Its end is the last instant the rollout moved.",occurredAt:w.lastAt,kind:"ended",subject:{type:"execution",id:g},core:{outcome:"interrupted"},provenance:E(w.turnId),seq:`turn:${w.turnId}:end`})}return v}function Oo(e){if(!e||typeof e!="object")return{};const t=e;return{...j(t.branch)?{"codex.gitBranch":t.branch}:{},...j(t.commit_hash)?{"codex.gitCommit":t.commit_hash}:{},...j(t.repository_url)?{"codex.gitOriginUrl":t.repository_url}:{}}}function js(){return process.env.CODEX_HOME||C(me(),".codex")}const Ds=()=>C(js(),"sessions"),$o=/^rollout-.*-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/,Bt=new Map;async function Fs(){const e=Ds();if(!F(e))return[];const t=[];let s;try{s=await W(e)}catch{return t}for(const n of s){let o;try{o=await W(C(e,n))}catch{continue}for(const r of o){let a;try{a=await W(C(e,n,r))}catch{continue}for(const i of a){let c;try{c=await W(C(e,n,r,i))}catch{continue}for(const d of c){const u=$o.exec(d);u&&t.push({path:C(e,n,r,i,d),sessionId:u[1]})}}}}return t}async function Ls(e,t){const s=he(),n=Date.now(),o={envelopes:[],rolloutsRead:0,rolloutsFailed:0,problems:[],storedAvailable:!1},r=await Fs();if(r.length===0)return o.storedAvailable=F(Ds()),o;o.storedAvailable=!0;for(const a of r){let i;try{i=await fe(a.path)}catch{continue}if(i.mtimeMs<e)continue;const c=`${i.mtimeMs}:${i.size}`,d=Bt.get(a.path);let u;if(d&&d.stamp===c)u=d.envelopes;else try{const m=Io(await re(a.path,"utf8"));u=Mo(m,{machine:s,host:ue(),observedAt:n,path:a.path,sessionId:a.sessionId,now:n}).map(ee),Bt.set(a.path,{stamp:c,envelopes:u})}catch(m){o.rolloutsFailed++,o.problems.push({path:a.path,message:m instanceof Error?m.message:String(m),sourceVersion:m instanceof ye?m.sourceVersion:void 0});continue}o.rolloutsRead++;for(const m of u)m.occurredAt>=e&&m.occurredAt<=t&&o.envelopes.push(m)}return o}async function Ro(e,t){return(await Ls(e,t)).envelopes}async function Ht(){const e=js(),t=(await Fs()).length;return{available:t>0,present:F(e),home:e,rollouts:t}}const Oe="cursor",xo="cursor";class Fe extends Error{constructor(t,s,n){super(t),this.path=s,this.sourceVersion=n,this.name="CursorFormatError"}path;sourceVersion}const it=e=>`cursor:${e}`,we=e=>typeof e=="string"&&e?e:void 0,Ne=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Wt=e=>{if(typeof e!="string")return;const t=Date.parse(e);return Number.isFinite(t)?t:void 0};function Us(e,t){if(typeof e.composerId!="string"||!e.composerId)throw new Fe("composer header has no composerId",t);if(typeof e.createdAt!="number"||!Number.isFinite(e.createdAt))throw new Fe("composer header has no numeric createdAt",t);if(typeof e.lastUpdatedAt!="number"||!Number.isFinite(e.lastUpdatedAt))throw new Fe("composer header has no numeric lastUpdatedAt",t)}function No(e,t){Us(e,t.path);const s=e.value??{},n=s.subagentInfo,o=n?we(n.parentComposerId):void 0,r=t.workspacePath??"",a=we(s.name)?.toUpperCase()??(r?z(r).toUpperCase():"CURSOR");return{source:{id:Oe,instance:t.host},occurredAt:e.createdAt,observedAt:t.observedAt,clock:"wall",stratum:"stored-semantics",kind:"began",subject:{type:"session",id:it(e.composerId)},claims:[{ns:"agent.session",parts:[xo,e.composerId],validFrom:e.createdAt,validTo:e.lastUpdatedAt}],basis:"measured",core:{machineId:t.machine.id,label:a,executor:Oe,...o?{parentId:it(o)}:{}},attrs:{context:r,"cursor.composerId":e.composerId,"cursor.workspaceId":e.workspaceId,"cursor.isSubagent":e.isSubagent,...n?{"cursor.parentComposerId":we(n.parentComposerId),"cursor.subagentType":we(n.subagentTypeName)}:{},...Ne(s.totalLinesAdded)!==void 0?{"cursor.linesAdded":s.totalLinesAdded}:{},...Ne(s.totalLinesRemoved)!==void 0?{"cursor.linesRemoved":s.totalLinesRemoved}:{},...Ne(s.filesChangedCount)!==void 0?{"cursor.filesChanged":s.filesChangedCount}:{},...we(s.unifiedMode)?{"cursor.mode":s.unifiedMode}:{},...Ne(s._v)!==void 0?{"cursor.schemaVersion":s._v}:{}},provenance:{path:t.path,recordId:e.composerId},seq:"composer"}}const Xt="Cursor persists no turn timing: the bounds are the first and last timestamped records inside the turn, untimestamped activity may extend beyond them, and the turn is taken as completed because Cursor records no turn outcome.";function _o(e,t,s){Us(e,s.path);const n=it(e.composerId),r={source:{id:Oe,instance:s.host},observedAt:s.observedAt,clock:"wall",stratum:"stored-semantics"},a=u=>({path:s.path,...u?{recordId:u}:{}}),i=[];for(let u=0;u<t.length;u++)t[u].type===1&&i.push(u);const c=[];let d=0;for(let u=0;u<i.length;u++){const m=i[u],E=u+1<i.length?i[u+1]:t.length,b=u+1,S=t.slice(m,E),h=S.map(y=>({bubble:y,at:Wt(y.createdAt)})).filter(y=>y.at!==void 0);if(h.length<2){d++;continue}const f=Math.min(...h.map(y=>y.at)),v=Math.max(...h.map(y=>y.at)),l=`${n}:turn:${b}`,w=S.filter(y=>y.toolName&&Wt(y.createdAt)===void 0),g=w.filter(y=>y.toolStatus==="error").length;c.push({...r,occurredAt:f,kind:"began",subject:{type:"execution",id:l},basis:"inferred",assumption:Xt,core:{machineId:s.machine.id,sessionId:n,label:`${we(e.value?.name)?.toUpperCase()??"CURSOR"} · TURN ${b}`,executor:Oe,depth:e.isSubagent?1:0,...w.length?{measures:{[R.interactions]:w.length,...g?{[R.errors]:g}:{}}}:{}},attrs:{"cursor.turn":b},provenance:a(t[m].bubbleId),seq:`turn:${b}`});for(const{bubble:y,at:M}of h){if(!y.toolName)continue;const p=y.toolStatus==="error",A={[R.interactions]:1,...p?{[R.errors]:1}:{}};c.push({...r,occurredAt:M,kind:"progressed",subject:{type:"execution",id:l},basis:"measured",core:{measures:A},attrs:{"cursor.tool":y.toolName,...y.toolStatus?{"cursor.toolStatus":y.toolStatus}:{}},provenance:a(y.bubbleId),seq:y.bubbleId})}c.push({...r,occurredAt:v,kind:"ended",subject:{type:"execution",id:l},basis:"inferred",assumption:Xt,core:{outcome:"completed"},provenance:a(t[m].bubbleId),seq:`turn:${b}:end`})}return{drafts:c,turns:i.length,untimedTurns:d}}function Te(){return process.env.CURSOR_GLOBAL_STORAGE||C(me(),"Library","Application Support","Cursor","User","globalStorage")}function Co(){return process.env.CURSOR_WORKSPACE_STORAGE||C(Te(),"..","workspaceStorage")}const Ps=()=>C(Te(),"state.vscdb"),Gt=new Map;async function jo(){const e=new Map,t=Co();if(!F(t))return e;let s;try{s=await W(t)}catch{return e}for(const n of s)try{const o=JSON.parse(await re(C(t,n,"workspace.json"),"utf8"));typeof o.folder=="string"&&o.folder.startsWith("file://")&&e.set(n,decodeURIComponent(o.folder.slice(7)))}catch{continue}return e}function Do(e,t){let s;if(e.value)try{s=JSON.parse(e.value)}catch{s=void 0}const n=a=>typeof a=="number"&&Number.isFinite(a)?a:void 0,o=e.lastUpdatedAt??n(s?.lastUpdatedAt)??n(s?.conversationCheckpointLastUpdatedAt)??e.createdAt??NaN,r={composerId:e.composerId,workspaceId:e.workspaceId??void 0,createdAt:e.createdAt??NaN,lastUpdatedAt:o,isSubagent:e.isSubagent===1,value:s};if(!Number.isFinite(r.createdAt)||!Number.isFinite(r.lastUpdatedAt))throw new Fe(`composer ${e.composerId} has no numeric createdAt/lastUpdatedAt`,t);return r}function Fo(e,t){const s=e.prepare("SELECT value FROM cursorDiskKV WHERE key = ?").get(`composerData:${t}`);if(!s?.value)return[];const n=typeof s.value=="string"?s.value:Buffer.from(s.value).toString("utf8"),r=JSON.parse(n).fullConversationHeadersOnly??[],a=e.prepare("SELECT key, value FROM cursorDiskKV WHERE key >= ? AND key < ?").all(`bubbleId:${t}:`,`bubbleId:${t};`),i=new Map;for(const c of a){const d=c.key.slice(`bubbleId:${t}:`.length);try{const u=typeof c.value=="string"?c.value:Buffer.from(c.value).toString("utf8"),m=JSON.parse(u);i.set(d,{bubbleId:d,type:m.type,createdAt:typeof m.createdAt=="string"&&m.createdAt?m.createdAt:void 0,toolName:m.toolFormerData?.name,toolStatus:m.toolFormerData?.status})}catch{continue}}return r.filter(c=>typeof c.bubbleId=="string").map(c=>i.get(c.bubbleId)??{bubbleId:c.bubbleId,type:c.type})}async function Bs(e,t){const s=he(),n=Date.now(),o=Ps(),r={envelopes:[],composersRead:0,composersFailed:0,problems:[],storedAvailable:!1};if(!F(o))return r;r.storedAvailable=!0;const a=await jo();let i;try{i=new pt(o,{readOnly:!0})}catch(c){return r.problems.push({path:o,message:`cannot open read-only: ${String(c)}`}),r}try{let c;try{c=i.prepare("SELECT composerId, workspaceId, createdAt, lastUpdatedAt, isSubagent, value FROM composerHeaders WHERE (lastUpdatedAt >= ? OR lastUpdatedAt IS NULL) AND createdAt <= ?").all(e,t)}catch(d){return r.problems.push({path:o,message:`composerHeaders unreadable: ${String(d)}`}),r}for(const d of c)try{const u=Do(d,o);if(u.lastUpdatedAt<e)continue;const m={machine:s,host:ue(),observedAt:n,path:o,workspacePath:u.workspaceId?a.get(u.workspaceId):void 0};r.envelopes.push(ee(No(u,m)));const E=`${u.lastUpdatedAt}`,b=Gt.get(u.composerId);let S;if(b&&b.stamp===E)S=b.envelopes;else{const h=Fo(i,u.composerId),{drafts:f}=_o(u,h,m);S=f.map(ee),Gt.set(u.composerId,{stamp:E,envelopes:S})}for(const h of S)h.occurredAt>=e&&h.occurredAt<=t&&r.envelopes.push(h);r.composersRead++}catch(u){r.composersFailed++,r.problems.push({path:o,message:`${d.composerId}: ${u instanceof Error?u.message:String(u)}`})}}finally{i.close()}return r}async function Lo(e,t){return(await Bs(e,t)).envelopes}async function qt(){const e=Ps();if(!F(e))return{available:!1,present:!1,globalStorage:Te()};try{const t=new pt(e,{readOnly:!0});try{const s=t.prepare("SELECT count(*) AS n FROM composerHeaders").get();return{available:s.n>0,present:!0,globalStorage:Te(),composers:s.n}}finally{t.close()}}catch{return{available:!1,present:!0,globalStorage:Te()}}}const Le="gemini",Uo="gemini";class He extends Error{constructor(t,s){super(t),this.path=s,this.name="GeminiFormatError"}path}const Po=e=>`gemini:${e}`,Q=e=>typeof e=="number"&&Number.isFinite(e)?e:0,_e=e=>typeof e=="string"&&e?e:void 0,ve=e=>{if(typeof e!="string")return;const t=Date.parse(e);return Number.isFinite(t)?t:void 0};function Bo(e,t){const s=e.split(`
6
- `).filter(i=>i.trim());if(s.length===0)throw new He("session file is empty",t);let n=null;const o=[],r=new Map,a=i=>{const c=i;!c||typeof c!="object"||typeof c.id!="string"||(r.has(c.id)||o.push(c.id),r.set(c.id,c))};for(const i of s){let c;try{c=JSON.parse(i)}catch{continue}if(!c||typeof c!="object")continue;const d=c;if(!n&&typeof d.sessionId=="string"){n=d;continue}const u=d.$set;if(u){const m=u.messages;if(Array.isArray(m))for(const E of m)a(E);continue}typeof d.id=="string"&&a(d)}if(!n||!n.sessionId)throw new He("session file has no header with a sessionId",t);return{header:n,messages:o.map(i=>r.get(i))}}const Hs=e=>Array.isArray(e.content)&&e.content.some(t=>!!t&&typeof t=="object"&&"functionResponse"in t);function Ho(e){if(e.type!=="user"||Hs(e))return!1;const t=Array.isArray(e.content)?e.content.map(s=>s?.text).filter(s=>typeof s=="string"):[];return t.length===0?!1:!t[0].startsWith("<session_context>")}function Wo(e){const t=Q(e.input),s=Q(e.cached);return{[R.tokensInput]:Math.max(0,t-s),[R.tokensOutput]:Q(e.output)+Q(e.thoughts),[R.tokensCacheRead]:s,[R.tokensReasoning]:Q(e.thoughts),[R.steps]:1}}function Xo(e,t){const{header:s,messages:n}=e,o=s.sessionId,r=ve(s.startTime);if(r===void 0)throw new He("session header has no parseable startTime",t.path);const a=n.filter(f=>ve(f.timestamp)!==void 0),i=a.length?Math.max(...a.map(f=>ve(f.timestamp))):r,c=t.workspacePath??"",d=c?z(c).toUpperCase():"GEMINI",u=Po(o),E={source:{id:Le,instance:t.host},observedAt:t.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"},b=f=>({path:t.path,...f?{recordId:f}:{}}),S=[{...E,occurredAt:r,kind:"began",subject:{type:"session",id:u},claims:[{ns:"agent.session",parts:[Uo,o],validFrom:r,validTo:i}],core:{machineId:t.machine.id,label:d,executor:Le},attrs:{context:c,"gemini.sessionId":o,"gemini.projectHash":s.projectHash,..._e(s.kind)?{"gemini.kind":s.kind}:{}},provenance:b(o),seq:"session"}],h=[];for(let f=0;f<n.length;f++)Ho(n[f])&&ve(n[f].timestamp)!==void 0&&h.push(f);if(h.length===0){if(n.some(f=>f.type==="gemini"))throw new He(`session has ${n.length} messages including model output but no recognisable user prompt`,t.path);return S}for(let f=0;f<h.length;f++){const v=h[f],l=f+1<h.length?h[f+1]:n.length,w=f+1,g=`${u}:turn:${w}`,y=ve(n[v].timestamp);let M=y,p;const A=[];for(let I=v;I<l;I++){const k=n[I],T=ve(k.timestamp);if(T===void 0||k.type!=="gemini"&&!(k.type==="user"&&Hs(k))||(T>M&&(M=T),k.type!=="gemini"))continue;p??=_e(k.model);const O=Array.isArray(k.toolCalls)?k.toolCalls:[],$=k.tokens?Wo(k.tokens):{};O.length&&($[R.interactions]=O.length),Object.keys($).length!==0&&A.push({...E,occurredAt:T,kind:"progressed",subject:{type:"execution",id:g},core:{measures:$},attrs:{...O.length?{"gemini.tools":O.map(x=>_e(x.name)??"unknown")}:{},..._e(k.model)?{"gemini.model":k.model}:{},...k.tokens?{"gemini.usage.input":Q(k.tokens.input),"gemini.usage.output":Q(k.tokens.output),"gemini.usage.cached":Q(k.tokens.cached),"gemini.usage.thoughts":Q(k.tokens.thoughts),"gemini.usage.tool":Q(k.tokens.tool)}:{}},provenance:b(k.id),seq:k.id})}S.push({...E,occurredAt:y,kind:"began",subject:{type:"execution",id:g},core:{machineId:t.machine.id,sessionId:u,label:`${d} · TURN ${w}`,executor:Le,model:p,depth:0},attrs:{"gemini.turn":w},provenance:b(n[v].id),seq:`turn:${w}`}),S.push(...A),S.push({...E,occurredAt:M,kind:"ended",subject:{type:"execution",id:g},core:{outcome:"completed"},provenance:b(n[v].id),seq:`turn:${w}:end`})}return S}function ht(){return process.env.GEMINI_HOME||C(me(),".gemini")}const Ws=()=>C(ht(),"tmp"),Yt=new Map;async function Go(){const e=new Map;try{const t=JSON.parse(await re(C(ht(),"projects.json"),"utf8"));for(const[s,n]of Object.entries(t.projects??{}))typeof n=="string"&&e.set(n,s)}catch{}return e}async function Xs(){const e=Ws();if(!F(e))return[];const t=[];let s;try{s=await W(e)}catch{return t}for(const n of s){let o;try{o=await W(C(e,n,"chats"))}catch{continue}for(const r of o)r.startsWith("session-")&&r.endsWith(".jsonl")&&t.push({path:C(e,n,"chats",r),slug:n})}return t}async function Gs(e,t){const s=he(),n=Date.now(),o={envelopes:[],sessionsRead:0,sessionsFailed:0,problems:[],storedAvailable:!1},r=await Xs();if(r.length===0)return o.storedAvailable=F(Ws()),o;o.storedAvailable=!0;const a=await Go();for(const i of r){let c;try{c=await fe(i.path)}catch{continue}if(c.mtimeMs<e)continue;const d=`${c.mtimeMs}:${c.size}`,u=Yt.get(i.path);let m;if(u&&u.stamp===d)m=u.envelopes;else try{const E=Bo(await re(i.path,"utf8"),i.path);m=Xo(E,{machine:s,host:ue(),observedAt:n,path:i.path,workspacePath:a.get(i.slug)}).map(ee),Yt.set(i.path,{stamp:d,envelopes:m})}catch(E){o.sessionsFailed++,o.problems.push({path:i.path,message:E instanceof Error?E.message:String(E)});continue}o.sessionsRead++;for(const E of m)E.occurredAt>=e&&E.occurredAt<=t&&o.envelopes.push(E)}return o}async function qo(e,t){return(await Gs(e,t)).envelopes}async function Vt(){const e=ht(),t=(await Xs()).length;return{available:t>0,present:F(e),home:e,sessions:t}}function Z(e,t){const s=e[t];return typeof s=="number"&&Number.isFinite(s)?s:void 0}function We(e,t){for(const[s,n]of Object.entries(t)){if(typeof n!="number"||!Number.isFinite(n))continue;const o=s;e[o]=(e[o]??0)+n}}const Yo=[R.tokensInput,R.tokensOutput,R.tokensCacheRead];function ce(e){let t=0,s=!1;for(const n of Yo){const o=Z(e,n);o!==void 0&&(s=!0,t+=o)}return s?t:void 0}function qs(e){return{input:Z(e,R.tokensInput)??0,output:Z(e,R.tokensOutput)??0,cacheRead:Z(e,R.tokensCacheRead)??0,reasoning:Z(e,R.tokensReasoning)??0}}function Ys(e){const t=ce(e.measures);if(t!==void 0)return zt(t/1e3,200);const s=Z(e.measures,R.cpuMs);if(s!==void 0)return zt(s/1e3,200)}function Se(e){return Z(e.measures,R.interactions)}function Vs(e){return Z(e.measures,R.steps)??0}function at(e){return Z(e.measures,R.errors)??0}function ct(e){return Z(e.measures,R.retries)??0}function zt(e,t){return Math.min(1,Math.log1p(Math.max(0,e))/Math.log1p(t))}const Vo=new Set(["running","waiting"]);function zs(e){return Vo.has(e)}function Ks(e,t){return{now:e,dayStart:e,dayEnd:t,machines:new Map,sources:new Map,sessions:new Map,executions:new Map,processes:new Map,artifacts:new Map,transfers:new Map,relationships:[],active:new Set,seen:new Set}}const zo=9e4;function Kt(e,t){if(e.waitingSince===void 0)return;const s=e.waitingSince,n=Math.max(s,t);e.waitingMs+=n-s,e.waits.push({start:s,end:n})}function Ko(e,t){const s=`${t.source.id}:${t.source.instance}`;let n=e.sources.get(s);n||(n={id:t.source.id,instance:t.source.instance,origin:t.source.instance,firstSeenAt:t.occurredAt,lastSeenAt:t.occurredAt,events:0,strata:{}},e.sources.set(s,n)),n.events++,t.occurredAt<n.firstSeenAt&&(n.firstSeenAt=t.occurredAt),t.occurredAt>n.lastSeenAt&&(n.lastSeenAt=t.occurredAt),t.stratum&&(n.strata[t.stratum]=(n.strata[t.stratum]??0)+1);const o=t.provenance?.sourceVersion;o&&(n.sourceVersions?n.sourceVersions.includes(o)||n.sourceVersions.push(o):n.sourceVersions=[o])}function Jo(e,t){if(e.seen.has(t.id))return;e.seen.add(t.id),t.occurredAt>e.now&&(e.now=t.occurredAt),Ko(e,t);const s=t.core??{},n=t.occurredAt;switch(t.subject.type){case"machine":{if(e.machines.has(t.subject.id))break;const o={id:t.subject.id,name:s.machineName??t.subject.id,kind:s.machineKind??"laptop",parentId:s.parentId,firstSeenAt:n};e.machines.set(o.id,o);break}case"session":{if(t.kind==="began"){const o=e.sessions.get(t.subject.id);if(o){o.parentId===void 0&&s.parentId&&(o.parentId=s.parentId);break}const r={id:t.subject.id,machineId:s.machineId??"",label:s.label,context:t.attrs?.context??s.label??"",executor:s.executor,model:s.model,startedAt:n,executionIds:[],parentId:s.parentId};e.sessions.set(r.id,r)}else if(t.kind==="ended"){const o=e.sessions.get(t.subject.id);o&&(o.endedAt=n)}break}case"execution":Qo(e,t,n);break;case"process":Zo(e,t,n);break;case"artifact":{if(e.artifacts.has(t.subject.id))break;e.artifacts.set(t.subject.id,{id:t.subject.id,kind:"file",path:s.label??t.subject.id,firstSeenAt:n});break}}}function Qo(e,t,s){const n=t.core??{},o=t.subject.id;if(t.kind==="began"){if(e.executions.has(o))return;const a={id:o,sessionId:n.sessionId??n.parentId??"",machineId:n.machineId??"",label:n.label??o,executor:n.executor??"unknown",model:n.model,status:"running",startedAt:s,lastActivityAt:s,measures:{},waitingMs:0,waits:[],parentId:n.parentId,depth:n.depth??0,startBasis:t.basis,boundsAssumption:t.assumption};n.measures&&We(a.measures,n.measures),e.executions.set(o,a),e.active.add(o),e.sessions.get(a.sessionId)?.executionIds.push(o);return}const r=e.executions.get(o);if(r)switch(t.kind){case"progressed":{n.measures&&We(r.measures,n.measures),r.lastActivityAt=s,r.status==="idle"&&(r.status="running",e.active.add(o));break}case"blocked":{if(!zs(r.status))break;r.status="waiting",r.waitingSince=s,r.waitReason=n.blockedOn??"input",r.lastActivityAt=s;break}case"resumed":{Kt(r,s),r.status="running",r.waitingSince=void 0,r.waitReason=void 0,r.lastActivityAt=s,e.active.add(o);break}case"ended":{const a=n.outcome==="error";r.status=a?"failed":"completed",r.endedAt=s,r.endBasis=t.basis,t.assumption&&!r.boundsAssumption&&(r.boundsAssumption=t.assumption),r.lastActivityAt=s,r.outcome=n.outcome??"completed",a&&(r.failure={code:n.failureCode??"ERROR",message:n.failureMessage??"Execution failed"}),Kt(r,s),r.waitingSince=void 0,r.waitReason=void 0,e.active.delete(o);break}case"observed":r.lastActivityAt=Math.max(r.lastActivityAt,s);break}}function Zo(e,t,s){const n=t.core??{},o=t.subject.id,r=Number(t.attrs?.["os.pid"]??0);if(t.kind==="began"){if(e.processes.has(o))return;const i={id:o,machineId:n.machineId??"",pid:r,ppid:typeof t.attrs?.["os.ppid"]=="number"?t.attrs["os.ppid"]:void 0,command:n.label??n.executor??String(r),startedAt:s,lastSeenAt:s,status:"running",measures:{}};n.measures&&We(i.measures,n.measures),e.processes.set(o,i);return}const a=e.processes.get(o);if(a)if(t.kind==="observed"||t.kind==="progressed"){if(a.lastSeenAt=Math.max(a.lastSeenAt,s),n.measures){const i=n.measures[R.cpuMs];typeof i=="number"&&(a.measures[R.cpuMs]=i);const{[R.cpuMs]:c,...d}=n.measures;We(a.measures,d)}}else t.kind==="ended"&&(a.endedAt=s,a.lastSeenAt=Math.max(a.lastSeenAt,s),a.status="exited",a.endInferred=t.basis==="inferred")}function er(e,t){for(let s=0;s<t.length;s++)Jo(e,t[s])}function tr(e,t){if(!(t<=e.now)){e.now=t;for(const s of e.active){const n=e.executions.get(s);if(!n){e.active.delete(s);continue}n.status==="running"&&t-n.lastActivityAt>zo&&(n.status="idle")}}}const sr=5*6e4;function nr(e){const t=[];for(const s of e)s.parentId&&t.push({from:{type:"session",id:s.parentId},to:{type:"session",id:s.id},kind:"spawned",basis:"measured",via:"recorded by the child session's own runtime"});return t}function or(e,t){const s=e.now-sr,n=new Set;for(const i of t)i.from.type==="process"&&n.add(i.from.id),i.to.type==="process"&&n.add(i.to.id);const o=[];let r=0,a=0;for(const i of e.processes.values())i.lastSeenAt>=s&&r++,i.endInferred&&a++,n.has(i.id)&&o.push(i);return{now:e.now,dayStart:e.dayStart,dayEnd:e.dayEnd,machines:[...e.machines.values()],sources:[...e.sources.values()],sessions:[...e.sessions.values()],executions:[...e.executions.values()],processes:o,processTotals:{observed:e.processes.size,recentlySeen:r,exitsInferred:a},relationships:[...t,...nr(e.sessions.values())]}}function Jt(e){const t=Ks(e.dayStart,e.dayEnd);t.now=e.now;for(const s of e.machines)t.machines.set(s.id,s);for(const s of e.sources)t.sources.set(`${s.id}:${s.instance}`,s);for(const s of e.sessions)t.sessions.set(s.id,s);for(const s of e.executions)t.executions.set(s.id,s),zs(s.status)&&t.active.add(s.id);for(const s of e.processes)t.processes.set(s.id,s);return t.processTotals=e.processTotals,t.relationships=e.relationships,t}function rr(e){let t=2166136261;for(let s=0;s<e.length;s++)t^=e.charCodeAt(s),t=Math.imul(t,16777619);return t>>>0}function Xe(e,t=0){return rr(e+"#"+t)%1e5/1e5}const Je=[{x:430,y:508,extentX:300,extentY:186},{x:838,y:322,extentX:186,extentY:116}];function ir(e){if(e<Je.length)return Je[e];const s=-.9+(e-Je.length)*1.15;return{x:620+Math.cos(s)*520,y:300+Math.sin(s)*250,extentX:150,extentY:94}}function ar(e){const t=s=>s==="laptop"?0:s==="desktop"?1:2;return[...e].sort((s,n)=>t(s.kind)-t(n.kind)||s.firstSeenAt-n.firstSeenAt||(s.id<n.id?-1:s.id>n.id?1:0))}function Qt(e,t){const s=Xe(t,1),n=Xe(t,2),o=s*Math.PI*2+n*2.399963,r=.34+.46*Math.sqrt(n);return{x:e.x+Math.cos(o)*e.extentX*r,y:e.y+Math.sin(o)*e.extentY*r}}const Zt=30,cr=74;function ur(e){return Zt+e*(cr-Zt)}const es=64,dr=8,lr=8,ts=16,ss=.45;function pr(e,t){switch(e.status){case"running":{const s=t-e.lastActivityAt;return .55+.45*Math.exp(-s/45e3)}case"waiting":return .08;case"failed":return .9;case"completed":return 0;case"idle":return .03}}const ns=.32;function fr(e){const t=Ys(e),s=e.depth>0?.62:1;return t===void 0?ns*s:Math.min(1,(ns+.68*t)*s)}function mr(e,t){const s=Math.max(1,(e.endedAt??t)-e.startedAt),n=(Se(e)??0)/(s/6e4);return Math.min(1,.25+n/24)}function os(e){return(e.status==="failed"?3:e.status==="waiting"?2:e.status==="running"?1:0)*1e15+e.lastActivityAt}function hr(e){const t=new Set,s=new Set,n=new Map,o=new Map,r=(a,i,c)=>{const d=a.get(i);d?d.push(c):a.set(i,[c])};for(const a of e.relationships){const{from:i,to:c,kind:d}=a;d==="ran-as"?(i.type==="execution"&&t.add(i.id),c.type==="execution"&&t.add(c.id),i.type==="session"&&c.type==="process"&&s.add(i.id),c.type==="session"&&i.type==="process"&&s.add(c.id),i.type==="execution"&&c.type==="session"?n.set(i.id,c.id):i.type==="session"&&c.type==="execution"&&n.set(c.id,i.id)):d==="same-as"&&i.type==="execution"&&c.type==="execution"&&(t.add(i.id),t.add(c.id),r(o,i.id,c.id),r(o,c.id,i.id))}return{resolvedExecutions:t,sessionsWithProcess:s,runObservesSession:n,sameExecution:o}}function gr(e,t){const n=e.startBasis===void 0?.5:e.startBasis==="measured"?1:0,o=e.endBasis===void 0?.5:e.endBasis==="measured"?1:0,r=e.endedAt===void 0?n:(n+o)/2,a=Ys(e)===void 0?0:1,i=t.resolvedExecutions.has(e.id)||t.sessionsWithProcess.has(e.sessionId)?1:0;return(1+r+a+i)/4}function rs(e){let t=1;for(const s of e)t*=1-Math.min(1,Math.max(0,s));return 1-t}function is(e,t,s,n){const o=Math.max(e,s),r=Math.min(t,n);if(r<o)return 0;const a=Math.max(t,n)-Math.min(e,s);return a<=0?1:(r-o)/a}function as(e){const t=e.now,s=ar(e.machines.values()).slice(0,dr),n=new Map,o=[];let r=1;const a=new Map;for(const p of e.executions.values()){const A=(a.get(p.machineId)??0)+1;a.set(p.machineId,A),A>r&&(r=A)}s.forEach((p,A)=>{const I=ir(A);n.set(p.id,I),o.push({id:p.id,name:p.name,kind:p.kind,x:I.x,y:I.y,extentX:I.extentX,extentY:I.extentY,prominence:(a.get(p.id)??0)/r,seed:Xe(p.id,7)})});const i=45e3,c=[];for(const p of e.executions.values())(p.status==="completed"||p.status==="failed")&&t-(p.endedAt??t)>i||p.status==="idle"&&t-p.lastActivityAt>i*4||n.has(p.machineId)&&c.push(p);c.length>es&&(c.sort((p,A)=>os(A)-os(p)),c.length=es);const d=hr(e),u=p=>{const A=n.get(p.machineId),{x:I,y:k}=Qt(A,p.id);return{id:p.id,massId:p.machineId,sessionId:p.sessionId,x:I,y:k,extent:fr(p),energy:pr(p,t),rate:mr(p,t),phase:Xe(p.id,3)*Math.PI*2,status:p.status,label:p.label,statusSince:p.waitingSince??p.endedAt??p.startedAt,articulation:gr(p,d),shoulder:0,observers:1}},m=new Set(c.map(p=>p.id)),E=new Set,b=[],S=p=>[p.startedAt,p.endedAt??t];for(const p of[...c].sort((A,I)=>A.id<I.id?-1:1)){if(E.has(p.id))continue;const A=[p];E.add(p.id);for(let x=0;x<A.length;x++)for(const L of d.sameExecution.get(A[x].id)??[])!m.has(L)||E.has(L)||(E.add(L),A.push(e.executions.get(L)));if(A.length===1){b.push(u(p));continue}const I=A.map(u),k=I.reduce((x,L)=>L.articulation>x.articulation||L.articulation===x.articulation&&L.id<x.id?L:x);let T=1;const[O,$]=S(e.executions.get(k.id));for(const x of A){const[L,D]=S(x);T=Math.min(T,is(O,$,L,D))}b.push({...k,extent:Math.max(...I.map(x=>x.extent)),energy:Math.max(...I.map(x=>x.energy)),articulation:rs(I.map(x=>x.articulation)),shoulder:Math.min(ss,1-T),observers:A.length})}const h=new Map;for(const p of b){if(d.runObservesSession.has(p.id))continue;const A=h.get(p.sessionId);A?A.push(p):h.set(p.sessionId,[p])}const f=new Map,v=[];for(const p of b){const A=d.runObservesSession.get(p.id),I=A?h.get(A):void 0;if(!A||!I||I.length===0){if(v.push(p),A){const D=h.get(p.sessionId);D?D.push(p):h.set(p.sessionId,[p])}continue}const k=e.executions.get(p.id);let T=1/0,O=-1/0;for(const D of I){const[U,K]=S(e.executions.get(D.id));T=Math.min(T,U),O=Math.max(O,K)}const[$,x]=S(k),L=f.get(A)??{articulations:[],coincidence:1};L.articulations.push(p.articulation),L.coincidence=Math.min(L.coincidence,is($,x,T,O)),f.set(A,L)}const l=[];for(const p of[...h.keys()].sort()){const A=h.get(p),I=e.sessions.get(p);if(!I||A.length===0)continue;let k=0,T=0;for(const D of A)k+=D.x,T+=D.y;k/=A.length,T/=A.length;let O=0,$=0;for(const D of A){const U=ur(D.extent);O=Math.max(O,Math.abs(D.x-k)+U*1.5),$=Math.max($,Math.abs(D.y-T)+U)}const x=f.get(p),L=Math.max(...A.map(D=>D.articulation));l.push({id:p,massId:A[0].massId,x:k,y:T,extentX:Math.max(O,52),extentY:Math.max($,36),presence:1,articulation:x?rs([L,...x.articulations]):L,parentId:I.parentId,empty:!1,shoulder:x?Math.min(ss,1-x.coincidence):0,observers:1+(x?.articulations.length??0),label:I.label??I.executor??p})}for(const p of[...e.sessions.values()].sort((A,I)=>A.id<I.id?-1:1)){if(p.executionIds.length>0||p.endedAt!==void 0&&t-p.endedAt>i)continue;const A=n.get(p.machineId);if(!A)continue;const{x:I,y:k}=Qt(A,`session-presence:${p.id}`);l.push({id:p.id,massId:p.machineId,x:I,y:k,extentX:64,extentY:42,presence:1,articulation:d.sessionsWithProcess.has(p.id)?.5:.25,parentId:p.parentId,empty:!0,shoulder:0,observers:1,label:p.label??p.executor??p.id})}if(l.length>ts){const p=A=>A.empty?0:h.get(A.id)?.length??0;l.sort((A,I)=>p(I)-p(A)||(A.id<I.id?-1:1)),l.length=ts}const w=[];for(const p of e.transfers.values())if(p.endedAt===void 0&&!(!n.has(p.fromMachineId)||!n.has(p.toMachineId))){if(w.length>=lr)break;w.push({id:p.id,fromMassId:p.fromMachineId,toMassId:p.toMachineId,energy:1,label:p.label})}const g=new Map;s.forEach((p,A)=>g.set(p.id,A));const y=Math.max(1,e.dayEnd-e.dayStart),M=[];for(const p of e.executions.values()){const A=g.get(p.machineId);if(A===void 0)continue;const I=(p.startedAt-e.dayStart)/y,k=((p.endedAt??t)-e.dayStart)/y;M.push({id:p.id,massId:p.machineId,lane:A,startFraction:Math.max(0,Math.min(1,I)),endFraction:Math.max(0,Math.min(1,k)),status:p.status,label:p.label})}return{time:t,masses:o,disturbances:v,plinths:l,couplings:w,strata:M}}const Js="057.landscape",Qs=1;function br(e){return{contract:Js,version:Qs,landscape:e}}const gt="SHAPES FIELD",bt="METADATA — DOES NOT SHAPE FIELD";function Zs(e){const t=new Date(e),s=n=>String(n).padStart(2,"0");return`${s(t.getHours())}:${s(t.getMinutes())}:${s(t.getSeconds())}`}function vr(e){return H(e).toUpperCase().replace(/(\d)([HMS])/g,"$1 $2").replace(/\bM\b/g,"MIN")}function yr(e,t,s,n,o=()=>{}){if(s==="mass")return Sr(e,t,n);if(s==="coupling")return Er(e,n);const r=e.executions.get(n);return r?wr(e,t,r,s,o("execution",n)):null}function wr(e,t,s,n,o){const r=e.sessions.get(s.sessionId),a=e.machines.get(s.machineId),c=t.disturbances.find(f=>f.id===s.id)?.statusSince??s.endedAt??s.startedAt,d=s.startBasis==="inferred"||s.endBasis==="inferred",u=ce(s.measures),m=[{key:"MACHINE",value:(a?.name??s.machineId).toUpperCase()},{key:"STATE",value:s.status.toUpperCase(),tone:s.status},{key:"SINCE",value:Zs(c)},u===void 0?{key:"TOKENS",value:"NOT OBSERVED",tone:"absent",note:"This source does not persist token accounting."}:{key:"TOKENS",value:X(u)}];if(r){const f=r.executionIds.indexOf(s.id),v=t.plinths.some(w=>w.id===r.id),l=f>=0?`${f+1} OF ${r.executionIds.length}`:`OF ${r.executionIds.length}`;m.push({key:"SESSION",value:v?`${l} · PLINTH`:l})}const E=Ar(e,s.id),b=[s.model??r?.model?{key:"MODEL",value:s.model??r?.model}:{key:"MODEL",value:"not observed",tone:"absent",note:"This source does not record the model."}];r?.context&&b.push({key:"PROJECT",value:z(r.context),note:r.context}),b.push({key:"SOURCE",value:[s.executor,E===void 0?void 0:`pid ${E}`].filter(Boolean).join(" · "),note:o}),b.push({key:"REQUESTS",value:String(Vs(s))});const S=Se(s);if(b.push(S===void 0?{key:"TOOL CALLS",value:"not observed",tone:"absent",note:"This source does not count discrete operations."}:{key:"TOOL CALLS",value:Zn(S)}),b.push({key:"ELAPSED",value:`${H((s.endedAt??e.now)-s.startedAt)}${d?" · inferred":""}`,note:d?s.boundsAssumption:void 0}),u!==void 0){const f=qs(s.measures);b.push({key:"INPUT",value:X(f.input)},{key:"OUTPUT",value:X(f.output)}),b.push({key:"CACHE READ",value:X(f.cacheRead)},{key:"REASONING",value:X(f.reasoning)})}at(s)>0&&b.push({key:"TOOL ERRORS",value:String(at(s)),tone:"failed"}),ct(s)>0&&b.push({key:"RETRIES",value:String(ct(s)),tone:"waiting",note:"Provider retries."}),(s.waits.length>0||s.waitingMs>0)&&b.push({key:"BLOCKED",value:`${H(s.waitingMs)} on you · ${s.waits.length||1}×`,tone:"waiting"}),s.depth>0&&b.push({key:"SUB-AGENT",value:`depth ${s.depth}`});const h=s.status==="running"||s.status==="waiting";return{id:s.id,eyebrow:n==="stratum"||!h?"SELECTED · RUN":"SELECTED · PROCESS",title:s.label.toUpperCase(),state:{text:h?`${s.status.toUpperCase()} · ${vr(e.now-c)}`:s.status.toUpperCase(),status:s.status},groups:[{title:gt,metadata:!1,rows:m},{title:bt,metadata:!0,rows:b}],failure:s.failure?`${s.failure.code}: ${s.failure.message}`:void 0,reveal:o}}function Ar(e,t){for(const s of e.relationships){if(s.kind!=="ran-as")continue;const n=s.from.type==="execution"&&s.from.id===t&&s.to.type==="process"?s.to.id:s.to.type==="execution"&&s.to.id===t&&s.from.type==="process"?s.from.id:void 0;if(n)return e.processes.get(n)?.pid}}function Sr(e,t,s){const n=e.machines.get(s);if(!n)return null;let o=0,r=0,a=0,i;for(const b of e.executions.values()){if(b.machineId!==n.id)continue;const S=ce(b.measures);S!==void 0&&(i=(i??0)+S),b.status==="running"?o++:b.status==="waiting"?r++:a++}const d=[{key:"KIND",value:(t.masses.find(b=>b.id===s)?.kind??n.kind).toUpperCase()},{key:"RUNNING",value:String(o),tone:o>0?"running":void 0}];r>0&&d.push({key:"WAITING",value:String(r),tone:"waiting"}),d.push({key:"RAN TODAY",value:String(a)});const u=[i===void 0?{key:"TOKENS",value:"not observed",tone:"absent",note:"No execution in this window reported token accounting."}:{key:"TOKENS",value:X(i)}],m=e.processTotals;if(m){const b=new Set;for(const S of e.relationships)S.kind==="ran-as"&&(S.from.type==="process"&&b.add(S.from.id),S.to.type==="process"&&b.add(S.to.id));u.push({key:"PROCESSES",value:`${m.observed} observed`}),u.push({key:"LAST 5 MIN",value:`${m.recentlySeen} seen`,note:"Processes with a liveness observation in the last five minutes. The sampler never witnesses an exit, so recency is the honest liveness signal."}),u.push({key:"ATTRIBUTED",value:`${b.size} of ${m.observed}`,note:"Processes tied to a session or execution by resolved identity. The rest are observed, not explained."})}const E=o+r;return{id:s,eyebrow:"SELECTED · MACHINE",title:n.name.toUpperCase(),state:E>0?{text:`${E} ACTIVE`,status:o>0?"running":"waiting"}:{text:"QUIET"},groups:[{title:gt,metadata:!1,rows:d},{title:bt,metadata:!0,rows:u}]}}function Er(e,t){const s=e.transfers.get(t);if(!s)return null;const n=e.machines.get(s.fromMachineId)?.name??s.fromMachineId,o=e.machines.get(s.toMachineId)?.name??s.toMachineId;return{id:t,eyebrow:"SELECTED · TRANSFER",title:`${n} → ${o}`.toUpperCase(),state:{text:"TRANSFERRING",status:"running"},groups:[{title:gt,metadata:!1,rows:[{key:"FROM",value:n.toUpperCase()},{key:"TO",value:o.toUpperCase()},{key:"SINCE",value:Zs(s.startedAt)}]},{title:bt,metadata:!0,rows:[{key:"WHAT",value:s.label},{key:"SIZE",value:eo(s.bytes)}]}]}}const q=e=>({value:e,basis:"measured"}),Ce=(e,t)=>({value:e,basis:"inferred",assumption:t});function vt(e){if(e.length===0)return[];e.sort((s,n)=>s.start-n.start);const t=[{start:e[0].start,end:e[0].end}];for(let s=1;s<e.length;s++){const n=e[s],o=t[t.length-1];n.start<=o.end?n.end>o.end&&(o.end=n.end):t.push({start:n.start,end:n.end})}return t}function cs(e){let t=0;for(const s of e)t+=s.end-s.start;return t}function kr(e,t){const s=[];let n=0,o=0;for(;n<e.length&&o<t.length;){const r=Math.max(e[n].start,t[o].start),a=Math.min(e[n].end,t[o].end);r<a&&s.push({start:r,end:a}),e[n].end<t[o].end?n++:o++}return s}function en(e){if(e.length===0)return{peak:0,at:0};const t=[];for(const r of e)t.push({t:r.start,d:1}),t.push({t:r.end,d:-1});t.sort((r,a)=>r.t-a.t||r.d-a.d);let s=0,n=0,o=t[0].t;for(const r of t)s+=r.d,s>n&&(n=s,o=r.t);return{peak:n,at:o}}function Ir(e){if(e.length===0)return;const t=[...e].sort((n,o)=>n-o),s=t.length>>1;return t.length%2?t[s]:(t[s-1]+t[s])/2}const tn=6e4;function Tr(e,t){return{start:e.startedAt,end:e.endedAt??t}}function Mr(e){const t=[];for(const s of e.executions.values()){s.depth===0&&t.push({start:s.startedAt-tn,end:s.startedAt});for(const n of s.waits)t.push({start:n.start,end:n.end});s.waitingSince!==void 0&&t.push({start:s.waitingSince,end:e.now})}return vt(t)}function Or(e){const t=e.now,s=[...e.executions.values()];let n=0,o=0,r=0,a=0,i=0,c=0,d=0,u=0;const m=[],E=new Map;for(const y of s){n+=Vs(y),o+=ce(y.measures)??0,r+=Se(y)??0,y.status==="completed"?a++:y.status==="failed"?i++:y.status==="waiting"?c++:y.status==="idle"&&d++;const M=Tr(y,t);m.push(M),u+=y.waitingMs,y.waitingSince!==void 0&&(u+=Math.max(0,t-y.waitingSince));let p=E.get(y.machineId);p||(p={machineId:y.machineId,executions:0,tokens:0,computeTime:0},E.set(y.machineId,p)),p.executions++,p.tokens+=ce(y.measures)??0,p.computeTime+=M.end-M.start}const b=vt(m.map(y=>({...y}))),S=Mr(e),h=cs(kr(b,S)),{peak:f,at:v}=en(m),l=$r(e),w=Math.max(0,l.length-1);let g=null;for(const y of l)(!g||y.end-y.start>g.end-g.start)&&(g=y);return{requests:q(n),sessions:q(e.sessions.size),executions:q(s.length),tokens:q(o),toolCalls:q(r),autonomousCompute:Ce(cs(b),"Wall-clock time during which at least one run was in flight, merged so parallel runs are not double-counted."),humanAgentOverlap:Ce(h,`Compute time intersecting a window when you were plausibly present: the ${tn/1e3}s before you sent a message, and any approval from ask to answer.`),peakConcurrency:q(f),peakConcurrencyAt:q(v),contextSwitches:Ce(w,"Transitions between working directories, ordered by time. A directory is the closest thing the source has to a project."),longestFocus:Ce(g,"Longest unbroken stretch spent in one working directory."),waitingOnYou:q(u),completed:q(a),failed:q(i),waiting:q(c),idle:q(d),byMachine:E,contextSpans:l,transfers:q(e.transfers.size)}}function $r(e){const t=[];for(const n of e.executions.values()){const o=e.sessions.get(n.sessionId);o&&t.push({context:o.context,start:n.startedAt,end:n.endedAt??e.now})}t.sort((n,o)=>n.start-o.start);const s=[];for(const n of t){const o=s[s.length-1];o&&o.context===n.context&&n.start<=o.end?n.end>o.end&&(o.end=n.end):o&&o.context===n.context?n.start-o.end<=Rr?o.end=Math.max(o.end,n.end):s.push({context:n.context,start:n.start,end:n.end}):s.push({context:n.context,start:n.start,end:n.end})}return s}const Rr=15*6e4;function xr(e){return{key:e,runs:0,tokens:0,tokenRuns:0,medianRuns:0,computeMs:0,failed:0,waitingMs:0,toolCalls:0}}function Qe(e,t){const s=new Map,n=new Map;for(const o of e.executions.values()){const r=t(o,e.sessions.get(o.sessionId));if(r===void 0)continue;let a=s.get(r);a||(a=xr(r),s.set(r,a)),a.runs++;const i=ce(o.measures);if(i!==void 0&&(a.tokens+=i,a.tokenRuns++,o.endedAt!==void 0)){let c=n.get(r);c||(c=[],n.set(r,c)),c.push(i)}a.computeMs+=(o.endedAt??e.now)-o.startedAt,a.waitingMs+=o.waitingMs,a.toolCalls+=Se(o)??0,o.status==="failed"&&a.failed++}for(const[o,r]of n){const a=s.get(o);a&&(a.medianTokens=Ir(r),a.medianRuns=r.length)}return[...s.values()].sort((o,r)=>r.computeMs-o.computeMs)}function Nr(e){const t={input:0,output:0,cacheRead:0,reasoning:0,total:0};for(const s of e.executions.values()){const n=qs(s.measures);t.input+=n.input,t.output+=n.output,t.cacheRead+=n.cacheRead,t.reasoning+=n.reasoning}return t.total=t.input+t.output+t.cacheRead+t.reasoning,t}function _r(e){const t={count:0,totalMs:0,longestMs:0,openNow:0};for(const s of e.executions.values()){for(const n of s.waits){t.count++;const o=n.end-n.start;t.totalMs+=o,o>t.longestMs&&(t.longestMs=o)}if(s.waitingSince!==void 0){t.openNow++;const n=e.now-s.waitingSince;t.totalMs+=n,n>t.longestMs&&(t.longestMs=n)}}return t}function Cr(e){const t={toolCalls:0,toolErrors:0,retries:0,failed:0,interrupted:0,completed:0};for(const s of e.executions.values())t.toolCalls+=Se(s)??0,t.toolErrors+=at(s),t.retries+=ct(s),s.status==="failed"?t.failed++:s.outcome==="interrupted"?t.interrupted++:s.outcome==="completed"&&t.completed++;return t}function jr(e){const t=[];for(const r of e.executions.values())t.push({start:r.startedAt,end:r.endedAt??e.now});if(t.length===0)return[];const s=vt(t.map(r=>({...r}))),n=new Date(e.dayStart);n.setMinutes(0,0,0);const o=[];for(let r=n.getTime();r<e.now;r+=36e5){const a=r+36e5;let i=0;for(const u of s){const m=Math.max(u.start,r),E=Math.min(u.end,a);E>m&&(i+=E-m)}let c=0;const d=[];for(const u of t)u.start<a&&u.end>r&&(c++,d.push({start:Math.max(u.start,r),end:Math.min(u.end,a)}));o.push({hour:new Date(r).getHours(),runs:c,computeMs:i,peak:en(d).peak})}return o}const Ue=6e4,Dr=60*Ue;function Fr(e,t){const s=[],n=t.contextSpans,o=t.longestFocus.value,r=Math.max(1,e.now-e.dayStart),a=t.autonomousCompute.value/r;let i;if(t.executions.value===0)return{headline:"QUIET",clauses:["No computation observed in this window."]};if(t.peakConcurrency.value>=3?i="PARALLEL":n.length>=6?i="FRAGMENTED":o&&o.end-o.start>2*Dr?i="SUSTAINED":a<.15?i="SPARSE":i="SERIAL",t.peakConcurrency.value>=2?s.push(`Up to ${t.peakConcurrency.value} runs in flight at once; ${H(t.autonomousCompute.value)} of wall-clock time had computation running.`):s.push(`Runs happened one at a time, across ${H(t.autonomousCompute.value)} of wall-clock time.`),o&&s.push(`The longest unbroken stretch was ${H(o.end-o.start)} in ${z(o.context)}.`),n.length>1){const c=new Set(n.map(d=>d.context)).size;s.push(`Attention moved ${t.contextSwitches.value} ${t.contextSwitches.value===1?"time":"times"} across ${c} ${c===1?"context":"contexts"}.`)}if(t.waitingOnYou.value>Ue&&s.push(`${H(t.waitingOnYou.value)} was spent with a run waiting on your answer.`),t.humanAgentOverlap.value>Ue){const c=Math.round(t.humanAgentOverlap.value/Math.max(1,t.autonomousCompute.value)*100);s.push(`About ${c}% of that computation overlapped a window when you were present; the rest ran without you.`)}else t.autonomousCompute.value>5*Ue&&s.push("Computation ran almost entirely outside the moments you were present.");if(t.failed.value>0&&s.push(`${t.failed.value} of ${t.executions.value} runs ended in failure; ${t.completed.value} completed.`),t.byMachine.size>1){const c=[...t.byMachine.values()].sort((d,u)=>u.computeTime-d.computeTime).map(d=>`${e.machines.get(d.machineId)?.name??d.machineId} ${H(d.computeTime)}`);s.push(`Compute was split across ${c.join(", ")}.`)}return{headline:i,clauses:s}}const us="(no model)";function Lr(e){if(e.medianTokens===void 0)return{text:"no token accounting",title:"No run in this group reports token accounting, so there is no figure — not a figure of zero.",absent:!0};if(e.medianRuns===1)return{text:`single run ${X(e.medianTokens)}`,title:"One eligible run, so this is that run's figure, not a median. Same window as the rest of TODAY.",absent:!1};const t=e.medianRuns===e.runs?`${e.runs}`:`${e.medianRuns} of ${e.runs}`;return{text:`median ${X(e.medianTokens)} over ${t} runs`,title:`Median billed tokens per run, over the runs in this group that have ended and whose source reports token accounting — ${e.medianRuns} of ${e.runs} here. Runs still in flight are excluded: their totals are partial. Runs whose source persists no accounting are excluded: absence is not zero. Same window as the rest of TODAY.`,absent:!1}}function Y(e,t,s,n={}){const o=s?.basis==="inferred";return{key:e,value:t,inferred:o,assumption:o?s?.assumption:void 0,...n}}function Ze(e,t,s){const n=e[0]?.computeMs??0;return e.map(o=>({key:o.key,label:t(o.key),detail:`${o.runs} ${o.runs===1?"run":"runs"}${o.tokenRuns>0?` · ${X(o.tokens)} tok`:""} · ${H(o.computeMs)}`,failed:o.failed,fraction:n>0?o.computeMs/n:0,median:s?Lr(o):void 0}))}function Ur(e){const t=Or(e),s=Fr(e,t),n=Nr(e),o=_r(e),r=Cr(e),a=jr(e),i=Qe(e,(g,y)=>y?.context),c=Qe(e,g=>g.model??us),d=Qe(e,g=>g.machineId),u=[...e.executions.values()],m=u.filter(g=>ce(g.measures)===void 0).length,E=u.filter(g=>g.depth>0).length,b=t.longestFocus.value,S=Math.round(t.humanAgentOverlap.value/Math.max(1,t.autonomousCompute.value)*100),h=[Y("REQUESTS",X(t.requests.value),t.requests),Y("RUNS",String(t.executions.value),t.executions,{note:E>0?`${E} of them sub-agents`:void 0}),Y("SESSIONS",String(t.sessions.value),t.sessions),Y("TOKENS",X(t.tokens.value),t.tokens,{note:`${Math.round(n.cacheRead/Math.max(1,n.total)*100)}% cache reads`+(m>0?` · ${m} ${m===1?"run reports":"runs report"} no accounting`:"")}),Y("TOOL CALLS",X(r.toolCalls),t.toolCalls,{note:r.toolErrors>0?`${r.toolErrors} failed`:void 0}),Y("AUTONOMOUS COMPUTE",H(t.autonomousCompute.value),t.autonomousCompute),Y("HUMAN + AGENT OVERLAP",H(t.humanAgentOverlap.value),t.humanAgentOverlap,{note:`${S}% of compute`}),Y("PEAK CONCURRENCY",t.peakConcurrency.value>0?`${t.peakConcurrency.value} · ${xe(t.peakConcurrencyAt.value)}`:"0",t.peakConcurrency),Y("CONTEXT SWITCHES",String(t.contextSwitches.value),t.contextSwitches,{note:`across ${i.length} ${i.length===1?"context":"contexts"}`}),Y("LONGEST FOCUS",b?H(b.end-b.start):"—",t.longestFocus,{note:b?`${z(b.context)} · ${xe(b.start)}–${xe(b.end)}`:void 0}),Y("WAITING ON YOU",H(t.waitingOnYou.value),t.waitingOnYou,{tone:t.waitingOnYou.value>0?"waiting":void 0,note:o.count>0?`${o.count} ${o.count===1?"block":"blocks"} · longest ${H(o.longestMs)}`:void 0}),Y("FAILED",String(r.failed),void 0,{tone:r.failed>0?"failed":void 0,note:r.interrupted>0||r.retries>0?`${r.interrupted} stopped · ${r.retries} retries`:void 0})],f=a.length>0?a.reduce((g,y)=>y.computeMs>g.computeMs?y:g,a[0]):void 0,v=g=>`${String(g).padStart(2,"0")}:00`,l=[{title:"WHERE THE TIME WENT",rows:Ze(i,z,!1)}];d.length>0&&l.push({title:"BY MACHINE",rows:Ze(d,g=>e.machines.get(g)?.name??g,!1)}),c.length>0&&l.push({title:"BY MODEL",rows:Ze(c,g=>g===us?"model not observed":g,!0)});const w=g=>g/Math.max(1,n.total);return{headline:s.headline,clauses:[...s.clauses],measures:h,hours:a.map(g=>({hour:g.hour,computeMs:g.computeMs,runs:g.runs,peak:g.peak})),busiest:f?`busiest ${v(f.hour)} · ${H(f.computeMs)} of that hour`:void 0,groups:l,tokens:[["CACHE READS",n.cacheRead],["INPUT",n.input],["OUTPUT",n.output],["REASONING",n.reasoning]].map(([g,y])=>({key:g,value:X(y),percent:Math.round(w(y)*100),fraction:w(y)})),tokensNote:"Cache reads are context replayed into each request, not work generated. They dominate the total, which is why the headline token figure is much larger than it feels.",failures:u.filter(g=>g.status==="failed").sort((g,y)=>y.startedAt-g.startedAt).slice(0,12).map(g=>({id:g.id,at:xe(g.startedAt),label:g.label,reason:g.failure?`${g.failure.code}: ${g.failure.message}`:"failed"})),notAvailable:[{key:"COST",text:"Every source here reports tokens or CPU time; none reports money. Converting one to the other needs a price table 057 does not have, so no cost figure is shown anywhere."},{key:"TOKENS, FROM SOME SOURCES",text:"Cursor persists no usage and 0x2F records none; their runs read NOT OBSERVED rather than 0, and the token totals sum only the runs that report."},{key:"MACHINE-TO-MACHINE TRANSFER",text:"Every observed source is single-host. Transfers are modelled and the field renders them, but no real adapter emits one; only the synthetic source does."},{key:"PROCESS EXITS",text:"The OS collector samples; an exit is inferred from disappearance between samples, never witnessed."},{key:"OUTCOME QUALITY",text:"The log records that a run completed, not whether the work was any good."}]}}function Pr(e,t){const s=new Set(t.disturbances.map(r=>r.id)),n=new Set(t.strata.map(r=>r.id)),o=[...e.executions.values()].sort((r,a)=>a.startedAt-r.startedAt).map(r=>{const a=e.sessions.get(r.sessionId);return{id:r.id,startedAt:r.startedAt,label:r.label,depth:r.depth,context:a?.context?z(a.context):null,model:r.model??null,status:r.status,stopped:r.outcome==="interrupted",durationMs:(r.endedAt??e.now)-r.startedAt,inferred:r.startBasis==="inferred"||r.endBasis==="inferred",tokens:ce(r.measures)??null,tools:Se(r)??null,waitedMs:r.waitingMs,inField:s.has(r.id)?"disturbance":n.has(r.id)?"stratum":null}});return{now:e.now,rows:o}}const yt={[Js]:Qs};function wt(e){return`${e}.core.json`}function sn(e){const t=wt(e);if(!F(t))return null;try{const s=JSON.parse(hn(t,"utf8"));return typeof s.pid!="number"||typeof s.url!="string"?null:s}catch{return null}}function Br(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}async function Hr(e,t=1500){const s=sn(e);if(!s||s.pid===process.pid||!Br(s.pid))return null;try{const n=await fetch(`${s.url}/api/health`,{signal:AbortSignal.timeout(t)});return n.ok&&(await n.json()).pid===s.pid?s:null}catch{return null}}function Wr(e,t){if(e===":memory:")return;const s=wt(e),n=`${s}.${process.pid}.tmp`;fn(n,`${JSON.stringify(t,null,1)}
7
- `,{mode:384}),mn(n,s)}function Xr(e,t=process.pid){if(e===":memory:")return;const s=sn(e);s&&s.pid===t&&Ss(wt(e),{force:!0})}class At extends Error{constructor(t){super(`057 is already observing ${t.store} at ${t.url} (pid ${t.pid})`),this.record=t}record}const ut={processDays:7,eventDays:90},Gr=["machine"],ds=["process"],et={processEvents:0,otherEvents:0,claims:0,subjects:0,retainedByDependents:0,processBefore:null,otherBefore:null},qr=["execution","session","artifact"];function nn(e=process.env){return{processDays:ls(e.O57_RETAIN_PROCESS_DAYS,ut.processDays),eventDays:ls(e.O57_RETAIN_DAYS,ut.eventDays)}}function ls(e,t){if(e===void 0||e.trim()==="")return t;const s=Number(e);return Number.isFinite(s)&&s>=0?s:t}function qe(e){const t=(s,n)=>s===0?`${n} kept indefinitely`:`${n} ${s}d`;return`${t(e.processDays,"processes")}, ${t(e.eventDays,"sessions/executions")}, machines never expire`}const ps=448,Yr=384;function Vr(){return C(me(),".057")}function Ye(){const e=process.env.O57_STORE;return e&&e.length>0?e===":memory:"||An(e)?e:Re(process.cwd(),e):C(Vr(),"events.db")}function on(){const e=process.env.O57_STORE;return typeof e=="string"&&e.length>0}function Ve(e){return[e,`${e}-wal`,`${e}-shm`]}function zr(e){if(e===":memory:")return;const t=Sn(e);gn(t,{recursive:!0,mode:ps}),rn(t,ps)}function dt(e){if(e===":memory:")return[];const t=[];for(const s of Ve(e))if(F(s)&&!rn(s,Yr)){const n=St(s);n!==null&&(n&63)!==0&&t.push({path:s,mode:n})}return t}function St(e){try{return Ge(e).mode&511}catch{return null}}function rn(e,t){if(process.platform==="win32")return!1;const s=St(e);if(s===null)return!1;if((s&~t)===0)return!0;try{return bn(e,t),!0}catch{return!1}}function an(){if(on())return null;const e=Re(process.cwd(),".057","events.db");return F(e)&&e!==Ye()?e:null}const Kr=`-- 057 local store.
1
+ import{existsSync as F,writeFileSync as Vn,renameSync as Yn,rmSync as Qs,readFileSync as Gn,statSync as at,mkdirSync as zn,chmodSync as Kn,createReadStream as Jn}from"node:fs";import{createInterface as Qn}from"node:readline";import{createServer as Zn}from"node:http";import{join as D,isAbsolute as eo,resolve as qe,dirname as to,normalize as so,sep as no,extname as oo}from"node:path";import{fileURLToPath as ro}from"node:url";import{stat as we,readdir as W,readFile as ue}from"node:fs/promises";import{hostname as io,homedir as Ee}from"node:os";import ao from"node:zlib";import{createHash as Zs}from"node:crypto";import{execFileSync as co,execFile as uo}from"node:child_process";import{DatabaseSync as Ct}from"node:sqlite";import{promisify as lo}from"node:util";const es=["machine","session","execution","process","artifact"];function po(e){return`${e.ns}|${e.parts.join("|")}`}const M={interactions:"interactions",steps:"steps",errors:"errors",retries:"retries",cpuMs:"cpu.ms",tokensInput:"tokens.input",tokensOutput:"tokens.output",tokensCacheRead:"tokens.cacheRead",tokensReasoning:"tokens.reasoning"},fo=[{a:"execution",b:"process",kind:"ran-as"},{a:"session",b:"process",kind:"ran-as"},{a:"execution",b:"session",kind:"ran-as"},{a:"session",b:"session",kind:"same-as"},{a:"execution",b:"execution",kind:"same-as"},{a:"machine",b:"machine",kind:"same-as"},{a:"process",b:"process",kind:"same-as"}];function ts(e,t){for(const s of fo){if(e.subjectType===s.a&&t.subjectType===s.b)return{kind:s.kind,from:e,to:t};if(t.subjectType===s.a&&e.subjectType===s.b)return{kind:s.kind,from:t,to:e}}return null}const mo=(e,t)=>e.validFrom<=t.validTo&&t.validFrom<=e.validTo;function ho(e,t){const s=Math.max(e.validFrom,t.validFrom),n=Math.min(e.validTo,t.validTo);if(n<s)return 0;const o=Math.max(e.validTo,t.validTo)-Math.min(e.validFrom,t.validFrom);return o<=0?1:(n-s)/o}const go=.5;function bo(e,t){return mo(e,t)?ho(e,t)>=go?2:1:0}const J=e=>`${e.subjectType}:${e.subjectId}`,vo="inferred",yo="Two observers asserted the same identity claim over overlapping validity windows, and each was the other's only candidate at the strongest available evidence tier (two lifetimes that substantially coincide beat a bare overlap). The claims themselves are measured; the identification is inferred.";function wo(e){const t=new Map;for(const r of e){const a=t.get(r.key);a?a.push(r):t.set(r.key,[r])}const s=[],n=[];let o=0;for(const[r,a]of[...t.entries()].sort(([i],[c])=>i<c?-1:1)){const i=new Map;for(const b of a){const g=J(b),f=i.get(g);if(!f){i.set(g,{...b});continue}f.validFrom=Math.min(f.validFrom,b.validFrom),f.validTo=Math.max(f.validTo,b.validTo)}const c=[...i.values()].sort((b,g)=>J(b)<J(g)?-1:1);if(c.length<2){o++;continue}const u=[];let h=!1;for(let b=0;b<c.length;b++)for(let g=b+1;g<c.length;g++){const f=c[b],p=c[g];if(f.sourceId===p.sourceId)continue;const y=bo(f,p);if(y!==0){if(!ts(f,p)){h=!0;continue}u.push({x:f,y:p,tier:y})}}const m=new Map;for(const b of u)for(const g of[b.x,b.y]){const f=J(g);m.set(f,Math.max(m.get(f)??0,b.tier))}const k=new Map;for(const b of u)for(const g of[b.x,b.y]){const f=J(g);m.get(f)===b.tier&&k.set(f,(k.get(f)??0)+1)}if(u.length===0){n.push({key:r,reason:h?"no-pairing-defined":"no-window-overlap",subjects:[...i.keys()].sort()});continue}for(const{x:b,y:g,tier:f}of u){if(m.get(J(b))!==f||m.get(J(g))!==f)continue;if(k.get(J(b))!==1||k.get(J(g))!==1){n.push({key:r,reason:"multiple-candidates",subjects:[J(b),J(g)].sort()});continue}const p=ts(b,g);s.push({from:{type:p.from.subjectType,id:p.from.subjectId},to:{type:p.to.subjectType,id:p.to.subjectId},kind:p.kind,basis:vo,assumption:yo,via:r})}}return{relationships:s,ambiguous:n,unmatched:o,considered:t.size}}async function Ao(e,t,s,n,o){const r=[];let a=0,i=0;for(const c of t){const u=Date.now();try{const h=await c.collect(s,n),m=e.append(h);a+=m.inserted,i+=m.duplicate,r.push({id:c.id,ok:!0,collected:h.length,inserted:m.inserted,duplicate:m.duplicate,ms:Date.now()-u})}catch(h){r.push({id:c.id,ok:!1,collected:0,inserted:0,duplicate:0,error:h instanceof Error?h.message:String(h),ms:Date.now()-u})}o?.(r[r.length-1])}return{sources:r,inserted:a,duplicate:i}}const jt="deepseek-harness",So={tokens:"supported",requests:"supported",toolInteractions:"supported",toolErrors:"supported",retries:"supported",waits:"supported",model:"supported",context:"supported",outcome:"supported"},P=e=>typeof e=="number"&&Number.isFinite(e)?e:0,V=e=>typeof e=="string"?e:void 0;function ko(e){const t=e.split("/").filter(Boolean);return(t[t.length-1]??e).toUpperCase()}function Eo(e,t){const s=[],n=e[0];if(!n||n.type!=="session"||!n.id)return s;const o=n.id,r=n.cwd??"",a=P(n.createdAt),i=P(n.delegationDepth),c=ko(r);let u="deepseek",h,m;for(const w of e)if(w.type==="request/context"&&w.data?(u=V(w.data.provider)??u,h=V(w.data.model)??h):w.type==="session/title"&&w.data&&(m=V(w.data.title)??m),h&&m)break;const b={source:{id:jt,instance:t.instance},observedAt:t.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"};let g=a;for(const w of e){const $=P(w.time);$>g&&(g=$)}const f={ns:"fs.cwd",parts:[t.host,r],validFrom:a,validTo:Math.max(a,g)};s.push({...b,occurredAt:a,seq:"session",kind:"began",subject:{type:"session",id:o},claims:r?[f]:void 0,core:{machineId:t.machine.id,label:m,executor:u,model:h,depth:i},attrs:{context:r,"dsh.delegationDepth":i}});const p=w=>`${o}:turn:${w}`;let y=null;const d=new Map,A=new Map;let v=a;for(const w of e){const $=P(w.time)||v;if($<a)continue;v=$;const l=w.data??{},S=w.seq??`t${$}`,E=T=>({type:"execution",id:p(T)});switch(w.type){case"turn/start":{const T=P(l.turn);y=T,s.push({...b,occurredAt:$,seq:S,kind:"began",subject:E(T),core:{machineId:t.machine.id,sessionId:o,label:m?`${c} · ${m}`:c,executor:u,model:h,depth:i},attrs:{"dsh.turn":T}});break}case"turn/end":{const T=P(l.turn),I=l.reason,N=I?.kind;if(N==="error"){const C=I?.error??{};s.push({...b,occurredAt:$,seq:S,kind:"ended",subject:E(T),core:{outcome:"error",failureCode:V(C.code)??"ERROR",failureMessage:V(C.message)??"Run failed"},attrs:{"dsh.endReason":N}})}else s.push({...b,occurredAt:$,seq:S,kind:"ended",subject:E(T),core:{outcome:N==="aborted"?"interrupted":"completed"},attrs:{"dsh.endReason":N??"completed"}});y===T&&(y=null);break}case"assistant/message":{const T=P(l.turn),I=l.usage;if(!I)break;const N={[M.tokensInput]:P(I.inputTokens),[M.tokensOutput]:P(I.outputTokens),[M.tokensCacheRead]:P(I.cacheReadTokens),[M.tokensReasoning]:P(I.reasoningTokens),[M.steps]:1};s.push({...b,occurredAt:$,seq:S,kind:"progressed",subject:E(T),core:{measures:N},attrs:{"dsh.inputTokens":P(I.inputTokens),"dsh.outputTokens":P(I.outputTokens),"dsh.cacheReadTokens":P(I.cacheReadTokens),"dsh.reasoningTokens":P(I.reasoningTokens)}});break}case"tool/call":{s.push({...b,occurredAt:$,seq:S,kind:"progressed",subject:E(P(l.turn)),core:{measures:{[M.interactions]:1}},attrs:{"dsh.tool":V(l.name)}});break}case"tool/result":{const T=l.message;let I=!1;for(const N of T?.content??[])N.isError===!0&&(I=!0);I&&s.push({...b,occurredAt:$,seq:S,kind:"progressed",subject:E(P(l.turn)),core:{measures:{[M.errors]:1}}});break}case"llm/retry":{s.push({...b,occurredAt:$,seq:S,kind:"progressed",subject:E(P(l.turn)),core:{measures:{[M.retries]:1}}});break}case"approval/asked":{const T=V(l.id);if(y===null)break;T&&d.set(T,y),s.push({...b,occurredAt:$,seq:S,kind:"blocked",subject:E(y),core:{blockedOn:"approval"},attrs:{"dsh.approvalId":T}});break}case"approval/decided":{const T=V(l.id),I=T?d.get(T):y;if(I==null)break;d.delete(T??""),s.push({...b,occurredAt:$,seq:S,kind:"resumed",subject:E(I),attrs:{"dsh.approvalId":T}});break}case"tool-workflow/agent-start":{if(y===null)break;const T=V(l.childId);if(!T)break;const I=`${o}:agent:${T}`;A.set(`${V(l.runId)}:${P(l.seq)}`,I),s.push({...b,occurredAt:$,seq:S,kind:"began",subject:{type:"execution",id:I},core:{machineId:t.machine.id,sessionId:o,label:V(l.label)??`${c} · SUB`,executor:u,model:h,parentId:p(y),depth:i+1},attrs:{"dsh.childId":T}});break}case"tool-workflow/agent-end":{const T=`${V(l.runId)}:${P(l.seq)}`,I=A.get(T);if(!I)break;A.delete(T);const N=V(l.outcome);s.push({...b,occurredAt:$,seq:S,kind:"ended",subject:{type:"execution",id:I},core:N==="completed"?{outcome:"completed"}:{outcome:"error",failureCode:"SUBAGENT",failureMessage:N??"Sub-agent did not complete"},attrs:{"dsh.subagentOutcome":N}});break}}}if(t.closeOpenTurns){const w="The session log has not been written to for longer than the live window, so the process that owned it is gone and any turn left open was cut off rather than still running.";y!==null&&s.push({...b,occurredAt:v,seq:"close:turn",kind:"ended",subject:{type:"execution",id:p(y)},core:{outcome:"interrupted"},basis:"inferred",assumption:w});for(const $ of A.values())s.push({...b,occurredAt:v,seq:`close:${$}`,kind:"ended",subject:{type:"execution",id:$},core:{outcome:"interrupted"},basis:"inferred",assumption:w});s.push({...b,occurredAt:v,seq:"close:session",kind:"ended",subject:{type:"session",id:o},basis:"inferred",assumption:w})}return t.since!==void 0?s.filter(w=>w.occurredAt>=t.since):s}function Io(e){const t=[];let s=0;for(;s<e.length;){let n=e.indexOf(`
2
+ `,s);n===-1&&(n=e.length);const o=e.slice(s,n);if(s=n+1,o.length!==0&&!(o.startsWith('{"type":"reasoning-chunks"')||o.startsWith('{"type":"text-chunks"')||o.startsWith('{"type":"tool-call-chunks"')||o.startsWith('{"type":"assistant/chunk"')))try{t.push(JSON.parse(o))}catch{}}return t}function To(e){const t=JSON.stringify([e.source.id,e.source.instance,e.occurredAt,e.clock,e.kind,e.subject.type,e.subject.id,e.basis,e.seq??null,tt(e.core),tt(e.attrs)]);return Zs("sha256").update(t).digest("hex").slice(0,32)}function tt(e){if(e==null)return null;if(Array.isArray(e))return e.map(tt);if(typeof e!="object")return e;const t={};for(const s of Object.keys(e).sort())t[s]=tt(e[s]);return t}function oe(e){const{seq:t,...s}=e;return{id:To(e),...s}}let ss;function $o(){try{const e=co("/usr/sbin/scutil",["--get","LocalHostName"],{encoding:"utf8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim();return/^[A-Za-z0-9-]{1,63}$/.test(e)?e:void 0}catch{return}}function en(){return ss??=$o()??io().replace(/\.local$/i,""),ss}const st="host:";function Mo(e){return`${st}${e}`}function Oo(e){return e.startsWith(st)?e.slice(st.length):void 0}function ns(e){return e.startsWith(st)}const Ro=4247762216,No=407710288,xo=407710303;function _o(e){const t=[];for(let o=0;o+4<=e.length;o++){const r=e.readUInt32LE(o);(r===Ro||r>=No&&r<=xo)&&t.push(o)}if(t.length===0)return Buffer.alloc(0);const s=[];let n=0;for(;n<t.length;){let o=n+1,r=null;for(;;){const a=o<t.length?t[o]:e.length;try{r=ao.zstdDecompressSync(e.subarray(t[n],a));break}catch{if(o>=t.length)break;o++}}r?(s.push(r),n=o):n++}return Buffer.concat(s)}function Dt(){return process.env.DSH_HOME||D(Ee(),".dsh")}function he(){return en()}function Ie(){const e=he();return{id:Mo(e),name:e.toUpperCase(),kind:"laptop",firstSeenAt:0}}const os=new Map;async function tn(){const e=D(Dt(),"sessions");if(!F(e))return[];const t=[];for(const s of await W(e)){const n=D(e,s);let o;try{o=await W(n)}catch{continue}for(const r of o){const a=D(n,r,"session.jsonl.zstd");F(a)&&t.push({path:a,workspace:s,sessionId:r})}}return t}const Lt=10*6e4;async function Co(e,t){const s=await we(e.path),n=os.get(e.path);if(n&&n.mtimeMs===s.mtimeMs&&n.size===s.size)return n.envelopes;const o=await ue(e.path),r=_o(o).toString("utf8"),a=Io(r),i=Date.now()-s.mtimeMs>Lt,u=Eo(a,{machine:t,host:he(),instance:Dt(),observedAt:Date.now(),closeOpenTurns:i}).map(oe);return os.set(e.path,{mtimeMs:s.mtimeMs,size:s.size,envelopes:u}),u}async function jo(e,t){const s=Ie(),n=await tn(),o=[];for(const r of n){let a;try{a=await we(r.path)}catch{continue}if(!(a.mtimeMs<e))for(const i of await Co(r,s))i.occurredAt>=e&&i.occurredAt<=t&&o.push(i)}return o}async function rs(){const e=await tn(),t=Dt();return{available:e.length>0,present:F(t),home:t,sessions:e.length}}const sn=1e3,is=60*sn;function H(e){if(!Number.isFinite(e)||e<=0)return"0m";if(e<is)return`${Math.max(1,Math.round(e/sn))}s`;const t=Math.round(e/is),s=Math.floor(t/60),n=t%60;return s===0?`${n}m`:n===0?`${s}h`:`${s}h ${n}m`}function X(e){if(!Number.isFinite(e))return"—";const t=Math.abs(e);return t>=1e9?`${(e/1e9).toFixed(t>=1e10?0:2)}B`:t>=1e6?`${(e/1e6).toFixed(t>=1e7?0:2)}M`:t>=1e3?`${(e/1e3).toFixed(t>=1e4?0:1)}k`:String(Math.round(e))}function Do(e,t="NOT OBSERVED"){return e===void 0?t:X(e)}function Lo(e){return e===void 0||!Number.isFinite(e)?"—":e>=1e9?`${(e/1e9).toFixed(1)} GB`:e>=1e6?`${(e/1e6).toFixed(0)} MB`:e>=1e3?`${(e/1e3).toFixed(0)} KB`:`${e} B`}function Xe(e){const t=new Date(e);return`${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}`}function te(e){const t=e.split("/").filter(Boolean);return t[t.length-1]??e}const nt="0x2f",Fo={tokens:"unsupported",requests:"unsupported",toolInteractions:"supported",toolErrors:"unsupported",retries:"unsupported",waits:"supported",model:"partial",context:"supported",outcome:"supported"},ie=e=>{if(typeof e!="string")return;const t=Date.parse(e);return Number.isFinite(t)?t:void 0},nn=(e,t)=>`2f:${e}#${t}`,Uo=(e,t,s)=>`${nn(e,t)}:run:${s}`;function as(e){return e?.type==="permission"?"approval":"input"}function Po(e){const t=new Map;for(const s of e){const n=typeof s.run=="number"?s.run:1,o=t.get(n);o?o.push(s):t.set(n,[s])}return t}function Bo(e,t){const s=t.find(r=>r.type==="run.started");let n;for(let r=t.length-1;r>=0;r--){const a=t[r];if(a.type==="run.completed"||a.type==="run.failed"||a.type==="needs_user"&&a.blockedOn){n=a;break}}let o;return n?.type==="run.completed"?o="ready":n?.type==="run.failed"?o="failed":n?o="needs_you":e.status==="needs_you"||e.status==="ready"||e.status==="failed"?o=e.status:e.status==="working"?o="working":o=e.error?"failed":"ready",{run:1,provider:e.execution?.provider??null,node:e.execution?.node??null,model:e.execution?.model,externalSessionId:e.execution?.externalSessionId,attempts:e.execution?.attempts??1,startedAt:s?.at,completedAt:n?.at,outcome:o,error:e.error??(n?.type==="run.failed"?n.error:void 0),blockedOn:n?.type==="needs_user"?n.blockedOn:void 0,failure:e.failure}}function Ho(e,t){return Array.isArray(e.runs)&&e.runs.length?e.runs:[Bo(e,t)]}function Wo(e,t,s){if(typeof e.id!="number")return[];const n=nn(s.base,e.id),o=Ho(e,t),r=te(s.base).toUpperCase(),a=e.title,i=e.execution?.provider??o.at(-1)?.provider??nt,c=ie(e.createdAt)??o.map(p=>ie(p.startedAt)).find(p=>p!==void 0);if(c===void 0)return[];const h={source:{id:nt,instance:s.base},observedAt:s.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"},m=[{...h,occurredAt:c,kind:"began",subject:{type:"session",id:n},core:{machineId:s.machine.id,label:a,executor:i,model:e.execution?.model},attrs:{context:s.base,"0x2f.taskId":e.id,"0x2f.status":e.status}}],k=Po(t),b=t.filter(p=>p.type==="task.answered"),g=t.find(p=>p.type==="task.closed"),f=o.at(-1);for(let p=0;p<o.length;p++){const y=o[p],d=ie(y.startedAt);if(d===void 0)continue;const A=Uo(s.base,e.id,y.run),v=y.provider??i,w=ie(y.completedAt),$=w??s.now,l=[{ns:"fs.cwd",parts:[s.host,s.base],validFrom:d,validTo:$}];typeof y.externalSessionId=="string"&&y.externalSessionId&&l.push({ns:"agent.session",parts:[v,y.externalSessionId],validFrom:d,validTo:$}),y===f&&typeof e.pid=="number"&&l.push({ns:"os.process",parts:[s.host,e.pid],validFrom:d,validTo:$}),m.push({...h,occurredAt:d,seq:`run:${y.run}`,kind:"began",subject:{type:"execution",id:A},claims:l,core:{machineId:s.machine.id,sessionId:n,label:a?`${r} · ${a} · RUN ${y.run}`:`${r} · RUN ${y.run}`,executor:v,model:y.model??e.execution?.model,depth:0},attrs:{"0x2f.run":y.run,"0x2f.provider":v,"0x2f.workspace":s.base,...y.requestedProvider?{"0x2f.requestedProvider":y.requestedProvider}:{},...e.pid!==void 0&&y===f?{"0x2f.workerPid":e.pid}:{}}});let S=!1,E=0;for(const I of k.get(y.run)??[]){E++;const N=ie(I.at);if(N===void 0||N<d)continue;const C=`run:${y.run}:${E}`;if(I.type==="tool.started")m.push({...h,occurredAt:N,seq:C,kind:"progressed",subject:{type:"execution",id:A},core:{measures:{[M.interactions]:1}},attrs:{"0x2f.tool":I.name}});else if(I.type==="progress")m.push({...h,occurredAt:N,seq:C,kind:"progressed",subject:{type:"execution",id:A}});else if(I.type==="needs_user"&&I.blockedOn){if(S)continue;S=!0,m.push({...h,occurredAt:N,seq:C,kind:"blocked",subject:{type:"execution",id:A},core:{blockedOn:as(I.blockedOn)},attrs:{"0x2f.blockedOn":I.blockedOn.type}})}else if(I.type==="permission.resolved"||I.type==="task.updated"&&typeof I.grant=="string"){if(!S)continue;S=!1,m.push({...h,occurredAt:N,seq:C,kind:"resumed",subject:{type:"execution",id:A},attrs:{"0x2f.grant":I.grant}})}}const T=(I,N,C)=>m.push({...h,occurredAt:I,seq:C,kind:"ended",subject:{type:"execution",id:A},core:N});if(y.outcome==="ready"&&w!==void 0)T(w,{outcome:"completed"},`run:${y.run}:end`);else if(y.outcome==="failed"&&w!==void 0)T(w,{outcome:"error",failureCode:(y.failure?.kind??e.failure?.kind??"unclassified").toUpperCase(),failureMessage:y.error??e.error??"Run failed"},`run:${y.run}:end`);else if(y.outcome==="needs_you"&&w!==void 0){S||(S=!0,m.push({...h,occurredAt:w,seq:`run:${y.run}:block`,kind:"blocked",subject:{type:"execution",id:A},core:{blockedOn:as(y.blockedOn)}}));const I=qo(w,b,o[p+1],g);I!==void 0&&T(I,{outcome:"interrupted"},`run:${y.run}:end`)}}if(g){const p=ie(g.at);p!==void 0&&m.push({...h,occurredAt:p,seq:"task:closed",kind:"ended",subject:{type:"session",id:n}})}return m}function qo(e,t,s,n){const o=[...t.map(a=>ie(a.at)),ie(s?.startedAt),ie(n?.at)];let r;for(const a of o)a===void 0||a<e||(r===void 0||a<r)&&(r=a);return r}function Xo(e){const t=[];for(const s of e.split(`
3
+ `))if(s.trim())try{const n=JSON.parse(s);n&&typeof n.type=="string"&&t.push(n)}catch{}return t}const on=".work";function rn(){const e=process.env.WORK_ROOTS;return e?e.split(/[:,]/).map(t=>t.trim()).filter(Boolean):[Ee()]}const cs=e=>F(D(e,on,"tasks")),Vo=new Set(["Desktop","Documents","Downloads"]);async function an(){const e=new Set,t=!process.env.WORK_ROOTS;for(const s of rn()){if(cs(s)){e.add(s);continue}let n;try{n=await W(s,{withFileTypes:!0})}catch{continue}for(const o of n){if(!o.isDirectory()||o.name.startsWith(".")||t&&Vo.has(o.name))continue;const r=D(s,o.name);cs(r)&&e.add(r)}}return[...e].sort()}async function Yo(){const e=[];for(const t of await an()){const s=D(t,on,"tasks");let n;try{n=await W(s,{withFileTypes:!0})}catch{continue}for(const o of n){if(!o.isDirectory())continue;const r=D(s,o.name,"task.json");F(r)&&e.push({base:t,slug:o.name,taskPath:r,eventsPath:D(s,o.name,"events.jsonl")})}}return e}const us=new Map;async function Go(e,t,s){let n;try{n=await we(e.taskPath)}catch{return null}const o=await we(e.eventsPath).catch(()=>null),r=Math.max(n.mtimeMs,o?.mtimeMs??0),a=`${n.mtimeMs}:${n.size}:${o?.mtimeMs??0}:${o?.size??0}`,i=us.get(e.taskPath);if(i&&i.stamp===a)return{envelopes:i.envelopes,touchedAt:r};let c;try{c=JSON.parse(await ue(e.taskPath,"utf8"))}catch{return null}let u=[];try{u=Xo(await ue(e.eventsPath,"utf8"))}catch{}const h=Wo(c,u,{machine:t,base:e.base,host:he(),observedAt:Date.now(),now:s}).map(oe);return us.set(e.taskPath,{stamp:a,envelopes:h}),{envelopes:h,touchedAt:r}}async function zo(e,t){const s=Ie(),n=await Yo(),o=[];for(const r of n){const a=await Go(r,s,t);if(a&&!(a.touchedAt<e))for(const i of a.envelopes)i.occurredAt>=e&&i.occurredAt<=t&&o.push(i)}return o}async function ds(){const e=rn(),t=await an();return{available:t.length>0,present:e.some(s=>F(s)),roots:e,workspaces:t}}const ye="claude-code",Ko={tokens:"supported",requests:"supported",toolInteractions:"supported",toolErrors:"supported",retries:"unsupported",waits:"unsupported",model:"supported",context:"supported",outcome:"partial"},cn="claude-code";class ce extends Error{constructor(t,s,n){super(t),this.path=s,this.sourceVersion=n,this.name="ClaudeFormatError"}path;sourceVersion}const un=e=>`claude:${e}`;function Jo(e,t){const s=e,n=typeof s?.version=="string"?s.version:void 0;if(!s||typeof s!="object")throw new ce("registry entry is not an object",t,n);if(typeof s.sessionId!="string"||!s.sessionId)throw new ce("registry entry has no sessionId",t,n);if(typeof s.pid!="number"||!Number.isFinite(s.pid))throw new ce("registry entry has no numeric pid",t,n);if(typeof s.startedAt!="number"||!Number.isFinite(s.startedAt))throw new ce("registry entry has no numeric startedAt",t,n);return s}function Qo(e,t,s){const n=[{ns:"agent.session",parts:[cn,e.sessionId],validFrom:e.startedAt,validTo:s.now},{ns:"os.process",parts:[s.host,e.pid],validFrom:e.startedAt,validTo:s.now}];return{source:{id:ye,instance:s.host},occurredAt:e.startedAt,observedAt:s.observedAt,clock:"wall",stratum:"identity",kind:"began",subject:{type:"session",id:un(e.sessionId)},claims:n,basis:"measured",core:{machineId:s.machine.id,label:e.name??te(e.cwd??"").toUpperCase(),executor:ye},attrs:{context:e.cwd,"claude.sessionId":e.sessionId,"claude.pid":e.pid,"claude.procStart":e.procStart,"claude.version":e.version,"claude.kind":e.kind,"claude.entrypoint":e.entrypoint,"claude.status":e.status,"claude.waitingFor":e.waitingFor},provenance:{path:t,recordId:e.sessionId,sourceVersion:e.version},seq:"registry"}}const Zo=new Set(["stop_hook_summary","turn_duration"]),er="The transcript has not been written to for longer than the live window, so the process that owned it is gone and the turn ended at its last record.",ae=e=>typeof e=="number"&&Number.isFinite(e)?e:0,Me=e=>{if(typeof e!="string")return;const t=Date.parse(e);return Number.isFinite(t)?t:void 0};function tr(e){const t=[];for(const s of e.split(`
4
+ `))if(s.trim())try{const n=JSON.parse(s);n&&typeof n=="object"&&t.push(n)}catch{}return t}function sr(e){if(!e)return{};const t=e.output_tokens_details;return{[M.tokensInput]:ae(e.input_tokens)+ae(e.cache_creation_input_tokens),[M.tokensOutput]:ae(e.output_tokens),[M.tokensCacheRead]:ae(e.cache_read_input_tokens),[M.tokensReasoning]:ae(t?.thinking_tokens),[M.steps]:1}}function nr(e,t){const s=e.filter(d=>Me(d.timestamp)!==void 0);if(s.length===0)throw new ce("transcript has no timestamped records",t.path);const n=e.find(d=>typeof d.sessionId=="string")?.sessionId;if(n&&n!==t.sessionId)throw new ce(`transcript names session ${n} but is filed under ${t.sessionId}`,t.path);const o=e.find(d=>typeof d.version=="string")?.version,r=e.find(d=>typeof d.cwd=="string")?.cwd??"",a=e.find(d=>typeof d.gitBranch=="string")?.gitBranch,i=e.find(d=>typeof d.entrypoint=="string")?.entrypoint,c=te(r).toUpperCase(),u=t.sessionId,h=un(u),m=Me(s[0].timestamp),k=Me(s[s.length-1].timestamp),g={source:{id:ye,instance:t.host},observedAt:t.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"},f=(d,A)=>({path:t.path,...d?{recordId:d}:{},...A!==void 0?{index:A}:{},...o?{sourceVersion:o}:{}}),p=[{...g,occurredAt:m,kind:"began",subject:{type:"session",id:h},claims:[{ns:"agent.session",parts:[cn,u],validFrom:m,validTo:k}],core:{machineId:t.machine.id,label:c,executor:ye},attrs:{context:r,"claude.sessionId":u,"claude.gitBranch":a,"claude.entrypoint":i,"claude.version":o},provenance:f(u),seq:"session"}],y=[];for(let d=0;d<e.length;d++){const A=e[d];A.type==="user"&&typeof A.promptSource=="string"&&Me(A.timestamp)!==void 0&&y.push(d)}if(y.length===0)throw new ce(`transcript has ${e.length} records but no prompt-bearing user record (expected \`type:"user"\` with \`promptSource\`)`,t.path,o);for(let d=0;d<y.length;d++){const A=y[d],v=d+1<y.length?y[d+1]:e.length,w=d+1,$=`${h}:turn:${w}`,l=Me(e[A].timestamp),S=e.slice(A,v).some(R=>R.isSidechain===!0);let E,T=l,I,N=!1;const C=[];for(let R=A;R<v;R++){const O=e[R],U=Me(O.timestamp);if(U===void 0)continue;const q=O.type==="assistant"||O.type==="user"&&Array.isArray(O.message?.content);if(q&&U>T&&(T=U),q?(I=O,N=!1):O.type==="system"&&Zo.has(O.subtype??"")&&(N=!0),O.type==="assistant"&&O.message){E??=O.message.model;const x=(Array.isArray(O.message.content)?O.message.content:[]).filter(K=>!!K&&typeof K=="object"&&K.type==="tool_use"),G={...sr(O.message.usage)};x.length&&(G[M.interactions]=x.length),C.push({...g,occurredAt:U,kind:"progressed",subject:{type:"execution",id:$},core:{measures:G},attrs:{...x.length?{"claude.tools":x.map(K=>K.name??"unknown")}:{},...O.message.model?{"claude.model":O.message.model}:{},...O.requestId?{"claude.requestId":O.requestId}:{},...O.message.stop_reason?{"claude.stopReason":O.message.stop_reason}:{},...O.message.usage?{"claude.usage.inputTokens":ae(O.message.usage.input_tokens),"claude.usage.outputTokens":ae(O.message.usage.output_tokens),"claude.usage.cacheReadTokens":ae(O.message.usage.cache_read_input_tokens),"claude.usage.cacheCreationTokens":ae(O.message.usage.cache_creation_input_tokens),"claude.usage.serviceTier":O.message.usage.service_tier}:{}},provenance:f(O.uuid,R),seq:O.uuid??`a${R}`})}else if(O.type==="user"&&O.message&&Array.isArray(O.message.content)){const j=O.message.content.filter(x=>!!x&&typeof x=="object"&&x.is_error===!0).length;j&&C.push({...g,occurredAt:U,kind:"progressed",subject:{type:"execution",id:$},core:{measures:{[M.errors]:j}},provenance:f(O.uuid,R),seq:O.uuid??`e${R}`})}}if(p.push({...g,occurredAt:l,kind:"began",subject:{type:"execution",id:$},core:{machineId:t.machine.id,sessionId:h,label:`${c} · TURN ${w}`,executor:ye,model:E,depth:S?1:0},attrs:{"claude.turn":w,"claude.promptSource":e[A].promptSource,"claude.promptId":e[A].promptId,...S?{"claude.isSidechain":!0}:{}},provenance:f(e[A].uuid,A),seq:`turn:${w}`}),p.push(...C),d+1<y.length||N)p.push({...g,occurredAt:T,kind:"ended",subject:{type:"execution",id:$},core:{outcome:"completed"},provenance:f(e[A].uuid,A),seq:`turn:${w}:end`});else if(t.closeOpenTurns){const R=I?.type==="assistant"&&(I.message?.stop_reason==="end_turn"||I.message?.stop_reason==="stop_sequence");p.push({...g,occurredAt:T,kind:"ended",subject:{type:"execution",id:$},core:{outcome:R?"completed":"interrupted"},basis:"inferred",assumption:er,provenance:f(e[A].uuid,A),seq:`turn:${w}:end`})}}return p}function Ft(){return process.env.CLAUDE_HOME||D(Ee(),".claude")}const It=()=>D(Ft(),"sessions"),or=()=>D(Ft(),"projects"),ls=new Map;async function rr(e,t,s){const n=It();if(!F(n))return;s.identityAvailable=!0;let o;try{o=await W(n)}catch(r){s.problems.push({path:n,message:String(r)});return}for(const r of o){if(!r.endsWith(".json"))continue;const a=D(n,r);try{const i=Jo(JSON.parse(await ue(a,"utf8")),a);s.envelopes.push(oe(Qo(i,a,{machine:e,host:he(),observedAt:t,now:t}))),s.registryEntries++}catch(i){s.problems.push({path:a,message:i instanceof Error?i.message:String(i),sourceVersion:i instanceof ce?i.sourceVersion:void 0})}}}async function dn(){const e=or();if(!F(e))return[];const t=[];let s;try{s=await W(e)}catch{return t}for(const n of s){let o;try{o=await W(D(e,n))}catch{continue}for(const r of o)r.endsWith(".jsonl")&&t.push({path:D(e,n,r),sessionId:r.slice(0,-6),project:n})}return t}async function ir(e,t,s,n){const o=await dn();if(o.length!==0){n.storedAvailable=!0;for(const r of o){let a;try{a=await we(r.path)}catch{continue}if(a.mtimeMs<t)continue;const i=Date.now()-a.mtimeMs>Lt,c=`${a.mtimeMs}:${a.size}:${i}`,u=ls.get(r.path);let h;if(u&&u.stamp===c)h=u.envelopes;else try{const m=tr(await ue(r.path,"utf8"));h=nr(m,{machine:e,host:he(),observedAt:Date.now(),path:r.path,sessionId:r.sessionId,closeOpenTurns:i}).map(oe),ls.set(r.path,{stamp:c,envelopes:h})}catch(m){n.transcriptsFailed++,n.problems.push({path:r.path,message:m instanceof Error?m.message:String(m),sourceVersion:m instanceof ce?m.sourceVersion:void 0});continue}n.transcriptsRead++;for(const m of h)m.occurredAt>=t&&m.occurredAt<=s&&n.envelopes.push(m)}}}async function ln(e,t){const s=Ie(),n=Date.now(),o={envelopes:[],registryEntries:0,transcriptsRead:0,transcriptsFailed:0,problems:[],identityAvailable:!1,storedAvailable:!1};return await rr(s,n,o),await ir(s,e,t,o),o}async function ar(e,t){return(await ln(e,t)).envelopes}async function ps(){const e=Ft(),t=F(It())?(await W(It()).catch(()=>[])).filter(n=>n.endsWith(".json")).length:0,s=(await dn()).length;return{available:t>0||s>0,present:F(e),home:e,registry:t,transcripts:s}}const Fe="codex",cr={tokens:"supported",requests:"supported",toolInteractions:"supported",toolErrors:"supported",retries:"unsupported",waits:"unsupported",model:"supported",context:"supported",outcome:"supported"},ur="codex",dr=10*6e4;class Re extends Error{constructor(t,s,n){super(t),this.path=s,this.sourceVersion=n,this.name="CodexFormatError"}path;sourceVersion}const lr=e=>`codex:${e}`,se=e=>typeof e=="number"&&Number.isFinite(e)?e:0,L=e=>typeof e=="string"&&e?e:void 0,ht=e=>{if(typeof e!="string")return;const t=Date.parse(e);return Number.isFinite(t)?t:void 0};function pr(e){const t=[];for(const s of e.split(`
5
+ `))if(s.trim())try{const n=JSON.parse(s);n&&typeof n=="object"&&t.push(n)}catch{}return t}function fr(e){const t=se(e.input_tokens),s=se(e.cached_input_tokens);return{[M.tokensInput]:Math.max(0,t-s),[M.tokensOutput]:se(e.output_tokens),[M.tokensCacheRead]:s,[M.tokensReasoning]:se(e.reasoning_output_tokens),[M.steps]:1}}function mr(e,t){const s=e.find(d=>d.type==="session_meta");if(!s||!s.payload)throw new Re("rollout has no session_meta record",t.path);const n=s.payload,o=L(n.cli_version),r=L(n.session_id)??L(n.id);if(r&&r!==t.sessionId)throw new Re(`rollout names session ${r} but is filed under ${t.sessionId}`,t.path,o);const a=L(n.cwd)??"",i=ht(n.timestamp)??ht(s.timestamp);if(i===void 0)throw new Re("session_meta has no parseable timestamp",t.path,o);const c=te(a).toUpperCase(),u=lr(t.sessionId),m={source:{id:Fe,instance:t.host},observedAt:t.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"},k=(d,A)=>({path:t.path,...d?{recordId:d}:{},...A!==void 0?{index:A}:{},...o?{sourceVersion:o}:{}}),b=[];let g=null,f=i,p=0;for(let d=0;d<e.length;d++){const A=e[d],v=ht(A.timestamp);v!==void 0&&v>f&&(f=v);const w=A.payload;if(!w)continue;if(A.type==="turn_context"){g&&L(w.turn_id)===g.turnId&&(g.model??=L(w.model),g.effort??=L(w.effort));continue}if(A.type!=="event_msg")continue;const $=L(w.type);if($==="task_started"){const S=L(w.turn_id);if(!S||v===void 0)throw new Re(`task_started at ordinal ${A.ordinal} is missing turn_id or timestamp`,t.path,o);g={turnId:S,startedAt:v,interior:[],lastAt:v},b.push(g);continue}if($==="task_complete"){const S=L(w.turn_id),E=b.find(T=>T.turnId===S)??g;if(E&&v!==void 0){E.completedAt=v;const T=w.error;E.outcome=T?"error":"completed",E.failureMessage=T?L(T.message):void 0,E.lastAt=Math.max(E.lastAt,v)}E===g&&(g=null);continue}if($==="token_count"||$==="item_completed"){if(!g){p++;continue}if(v===void 0)continue}else continue;const l=`${u}:turn:${g.turnId}`;if($==="token_count"){const E=w.info?.last_token_usage;if(!E)continue;g.lastAt=Math.max(g.lastAt,v),g.interior.push({...m,occurredAt:v,kind:"progressed",subject:{type:"execution",id:l},core:{measures:fr(E)},attrs:{"codex.usage.inputTokens":se(E.input_tokens),"codex.usage.cachedInputTokens":se(E.cached_input_tokens),"codex.usage.cacheWriteInputTokens":se(E.cache_write_input_tokens),"codex.usage.outputTokens":se(E.output_tokens),"codex.usage.reasoningOutputTokens":se(E.reasoning_output_tokens)},provenance:k(void 0,A.ordinal),seq:`o${A.ordinal??d}`});continue}if($==="item_completed"){const S=w.item,E=L(S?.type);if(!S||!E)continue;g.lastAt=Math.max(g.lastAt,v);let T,I;if(E==="CommandExecution"){const N=se(S.exit_code);T={[M.interactions]:1,...N!==0?{[M.errors]:1}:{}},I={"codex.itemType":E,"codex.exitCode":N,...S.process_id!==void 0?{"codex.processId":S.process_id}:{},...L(S.status)?{"codex.status":S.status}:{}}}else if(E==="McpToolCall"){const N=L(S.status)==="failed"||L(S.status)==="error";T={[M.interactions]:1,...N?{[M.errors]:1}:{}},I={"codex.itemType":E,"codex.tool":[L(S.server),L(S.tool)].filter(Boolean).join("."),...L(S.status)?{"codex.status":S.status}:{}}}else if(E==="WebSearch")T={[M.interactions]:1},I={"codex.itemType":E};else if(E==="FileChange"){const N=S.changes;T={[M.interactions]:1},I={"codex.itemType":E,...N&&typeof N=="object"?{"codex.fileChanges":Object.entries(N).map(([C,_])=>({path:C,kind:L(_?.type)}))}:{}}}else continue;g.interior.push({...m,occurredAt:v,kind:"progressed",subject:{type:"execution",id:l},core:{measures:T},attrs:I,provenance:k(L(S.id),A.ordinal),seq:`o${A.ordinal??d}`})}}if(b.length===0&&p>0)throw new Re(`rollout has ${p} work records but no task_started marker`,t.path,o);const y=[{...m,occurredAt:i,kind:"began",subject:{type:"session",id:u},claims:[{ns:"agent.session",parts:[ur,t.sessionId],validFrom:i,validTo:f}],core:{machineId:t.machine.id,label:c,executor:Fe},attrs:{context:a,"codex.sessionId":t.sessionId,"codex.cliVersion":o,"codex.originator":L(n.originator),"codex.source":L(n.source),"codex.modelProvider":L(n.model_provider),...hr(n.git)},provenance:k(t.sessionId,s.ordinal),seq:"session"}];for(let d=0;d<b.length;d++){const A=b[d],v=`${u}:turn:${A.turnId}`;y.push({...m,occurredAt:A.startedAt,kind:"began",subject:{type:"execution",id:v},core:{machineId:t.machine.id,sessionId:u,label:`${c} · TURN ${d+1}`,executor:Fe,model:A.model,depth:0},attrs:{"codex.turnId":A.turnId,...A.effort?{"codex.effort":A.effort}:{}},provenance:k(A.turnId),seq:`turn:${A.turnId}`}),y.push(...A.interior),A.completedAt!==void 0?y.push({...m,occurredAt:A.completedAt,kind:"ended",subject:{type:"execution",id:v},core:{outcome:A.outcome??"completed",...A.outcome==="error"?{failureCode:"CODEX_TURN_ERROR",failureMessage:A.failureMessage??"turn failed"}:{}},provenance:k(A.turnId),seq:`turn:${A.turnId}:end`}):t.now-f>dr&&y.push({...m,basis:"inferred",assumption:"A rollout untouched for 10 minutes belongs to a dead process, so a turn left open in it was interrupted, not still running. Its end is the last instant the rollout moved.",occurredAt:A.lastAt,kind:"ended",subject:{type:"execution",id:v},core:{outcome:"interrupted"},provenance:k(A.turnId),seq:`turn:${A.turnId}:end`})}return y}function hr(e){if(!e||typeof e!="object")return{};const t=e;return{...L(t.branch)?{"codex.gitBranch":t.branch}:{},...L(t.commit_hash)?{"codex.gitCommit":t.commit_hash}:{},...L(t.repository_url)?{"codex.gitOriginUrl":t.repository_url}:{}}}function pn(){return process.env.CODEX_HOME||D(Ee(),".codex")}const fn=()=>D(pn(),"sessions"),gr=/^rollout-.*-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/,fs=new Map;async function mn(){const e=fn();if(!F(e))return[];const t=[];let s;try{s=await W(e)}catch{return t}for(const n of s){let o;try{o=await W(D(e,n))}catch{continue}for(const r of o){let a;try{a=await W(D(e,n,r))}catch{continue}for(const i of a){let c;try{c=await W(D(e,n,r,i))}catch{continue}for(const u of c){const h=gr.exec(u);h&&t.push({path:D(e,n,r,i,u),sessionId:h[1]})}}}}return t}async function hn(e,t){const s=Ie(),n=Date.now(),o={envelopes:[],rolloutsRead:0,rolloutsFailed:0,problems:[],storedAvailable:!1},r=await mn();if(r.length===0)return o.storedAvailable=F(fn()),o;o.storedAvailable=!0;for(const a of r){let i;try{i=await we(a.path)}catch{continue}if(i.mtimeMs<e)continue;const c=`${i.mtimeMs}:${i.size}`,u=fs.get(a.path);let h;if(u&&u.stamp===c)h=u.envelopes;else try{const m=pr(await ue(a.path,"utf8"));h=mr(m,{machine:s,host:he(),observedAt:n,path:a.path,sessionId:a.sessionId,now:n}).map(oe),fs.set(a.path,{stamp:c,envelopes:h})}catch(m){o.rolloutsFailed++,o.problems.push({path:a.path,message:m instanceof Error?m.message:String(m),sourceVersion:m instanceof Re?m.sourceVersion:void 0});continue}o.rolloutsRead++;for(const m of h)m.occurredAt>=e&&m.occurredAt<=t&&o.envelopes.push(m)}return o}async function br(e,t){return(await hn(e,t)).envelopes}async function ms(){const e=pn(),t=(await mn()).length;return{available:t>0,present:F(e),home:e,rollouts:t}}const _e="cursor",vr={tokens:"unsupported",requests:"unsupported",toolInteractions:"supported",toolErrors:"supported",retries:"unsupported",waits:"unsupported",model:"unsupported",context:"partial",outcome:"partial"},yr="cursor";class Je extends Error{constructor(t,s,n){super(t),this.path=s,this.sourceVersion=n,this.name="CursorFormatError"}path;sourceVersion}const Tt=e=>`cursor:${e}`,Ne=e=>typeof e=="string"&&e?e:void 0,Ve=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,hs=e=>{if(typeof e!="string")return;const t=Date.parse(e);return Number.isFinite(t)?t:void 0};function gn(e,t){if(typeof e.composerId!="string"||!e.composerId)throw new Je("composer header has no composerId",t);if(typeof e.createdAt!="number"||!Number.isFinite(e.createdAt))throw new Je("composer header has no numeric createdAt",t);if(typeof e.lastUpdatedAt!="number"||!Number.isFinite(e.lastUpdatedAt))throw new Je("composer header has no numeric lastUpdatedAt",t)}function wr(e,t){gn(e,t.path);const s=e.value??{},n=s.subagentInfo,o=n?Ne(n.parentComposerId):void 0,r=t.workspacePath??"",a=Ne(s.name)?.toUpperCase()??(r?te(r).toUpperCase():"CURSOR");return{source:{id:_e,instance:t.host},occurredAt:e.createdAt,observedAt:t.observedAt,clock:"wall",stratum:"stored-semantics",kind:"began",subject:{type:"session",id:Tt(e.composerId)},claims:[{ns:"agent.session",parts:[yr,e.composerId],validFrom:e.createdAt,validTo:e.lastUpdatedAt}],basis:"measured",core:{machineId:t.machine.id,label:a,executor:_e,...o?{parentId:Tt(o)}:{}},attrs:{context:r,"cursor.composerId":e.composerId,"cursor.workspaceId":e.workspaceId,"cursor.isSubagent":e.isSubagent,...n?{"cursor.parentComposerId":Ne(n.parentComposerId),"cursor.subagentType":Ne(n.subagentTypeName)}:{},...Ve(s.totalLinesAdded)!==void 0?{"cursor.linesAdded":s.totalLinesAdded}:{},...Ve(s.totalLinesRemoved)!==void 0?{"cursor.linesRemoved":s.totalLinesRemoved}:{},...Ve(s.filesChangedCount)!==void 0?{"cursor.filesChanged":s.filesChangedCount}:{},...Ne(s.unifiedMode)?{"cursor.mode":s.unifiedMode}:{},...Ve(s._v)!==void 0?{"cursor.schemaVersion":s._v}:{}},provenance:{path:t.path,recordId:e.composerId},seq:"composer"}}const gs="Cursor persists no turn timing: the bounds are the first and last timestamped records inside the turn, untimestamped activity may extend beyond them, and the turn is taken as completed because Cursor records no turn outcome.";function Ar(e,t,s){gn(e,s.path);const n=Tt(e.composerId),r={source:{id:_e,instance:s.host},observedAt:s.observedAt,clock:"wall",stratum:"stored-semantics"},a=h=>({path:s.path,...h?{recordId:h}:{}}),i=[];for(let h=0;h<t.length;h++)t[h].type===1&&i.push(h);const c=[];let u=0;for(let h=0;h<i.length;h++){const m=i[h],k=h+1<i.length?i[h+1]:t.length,b=h+1,g=t.slice(m,k),f=g.map(w=>({bubble:w,at:hs(w.createdAt)})).filter(w=>w.at!==void 0);if(f.length<2){u++;continue}const p=Math.min(...f.map(w=>w.at)),y=Math.max(...f.map(w=>w.at)),d=`${n}:turn:${b}`,A=g.filter(w=>w.toolName&&hs(w.createdAt)===void 0),v=A.filter(w=>w.toolStatus==="error").length;c.push({...r,occurredAt:p,kind:"began",subject:{type:"execution",id:d},basis:"inferred",assumption:gs,core:{machineId:s.machine.id,sessionId:n,label:`${Ne(e.value?.name)?.toUpperCase()??"CURSOR"} · TURN ${b}`,executor:_e,depth:e.isSubagent?1:0,...A.length?{measures:{[M.interactions]:A.length,...v?{[M.errors]:v}:{}}}:{}},attrs:{"cursor.turn":b},provenance:a(t[m].bubbleId),seq:`turn:${b}`});for(const{bubble:w,at:$}of f){if(!w.toolName)continue;const l=w.toolStatus==="error",S={[M.interactions]:1,...l?{[M.errors]:1}:{}};c.push({...r,occurredAt:$,kind:"progressed",subject:{type:"execution",id:d},basis:"measured",core:{measures:S},attrs:{"cursor.tool":w.toolName,...w.toolStatus?{"cursor.toolStatus":w.toolStatus}:{}},provenance:a(w.bubbleId),seq:w.bubbleId})}c.push({...r,occurredAt:y,kind:"ended",subject:{type:"execution",id:d},basis:"inferred",assumption:gs,core:{outcome:"completed"},provenance:a(t[m].bubbleId),seq:`turn:${b}:end`})}return{drafts:c,turns:i.length,untimedTurns:u}}function Ue(){return process.env.CURSOR_GLOBAL_STORAGE||D(Ee(),"Library","Application Support","Cursor","User","globalStorage")}function Sr(){return process.env.CURSOR_WORKSPACE_STORAGE||D(Ue(),"..","workspaceStorage")}const bn=()=>D(Ue(),"state.vscdb"),bs=new Map;async function kr(){const e=new Map,t=Sr();if(!F(t))return e;let s;try{s=await W(t)}catch{return e}for(const n of s)try{const o=JSON.parse(await ue(D(t,n,"workspace.json"),"utf8"));typeof o.folder=="string"&&o.folder.startsWith("file://")&&e.set(n,decodeURIComponent(o.folder.slice(7)))}catch{continue}return e}function Er(e,t){let s;if(e.value)try{s=JSON.parse(e.value)}catch{s=void 0}const n=a=>typeof a=="number"&&Number.isFinite(a)?a:void 0,o=e.lastUpdatedAt??n(s?.lastUpdatedAt)??n(s?.conversationCheckpointLastUpdatedAt)??e.createdAt??NaN,r={composerId:e.composerId,workspaceId:e.workspaceId??void 0,createdAt:e.createdAt??NaN,lastUpdatedAt:o,isSubagent:e.isSubagent===1,value:s};if(!Number.isFinite(r.createdAt)||!Number.isFinite(r.lastUpdatedAt))throw new Je(`composer ${e.composerId} has no numeric createdAt/lastUpdatedAt`,t);return r}function Ir(e,t){const s=e.prepare("SELECT value FROM cursorDiskKV WHERE key = ?").get(`composerData:${t}`);if(!s?.value)return[];const n=typeof s.value=="string"?s.value:Buffer.from(s.value).toString("utf8"),r=JSON.parse(n).fullConversationHeadersOnly??[],a=e.prepare("SELECT key, value FROM cursorDiskKV WHERE key >= ? AND key < ?").all(`bubbleId:${t}:`,`bubbleId:${t};`),i=new Map;for(const c of a){const u=c.key.slice(`bubbleId:${t}:`.length);try{const h=typeof c.value=="string"?c.value:Buffer.from(c.value).toString("utf8"),m=JSON.parse(h);i.set(u,{bubbleId:u,type:m.type,createdAt:typeof m.createdAt=="string"&&m.createdAt?m.createdAt:void 0,toolName:m.toolFormerData?.name,toolStatus:m.toolFormerData?.status})}catch{continue}}return r.filter(c=>typeof c.bubbleId=="string").map(c=>i.get(c.bubbleId)??{bubbleId:c.bubbleId,type:c.type})}async function vn(e,t){const s=Ie(),n=Date.now(),o=bn(),r={envelopes:[],composersRead:0,composersFailed:0,problems:[],storedAvailable:!1};if(!F(o))return r;r.storedAvailable=!0;const a=await kr();let i;try{i=new Ct(o,{readOnly:!0})}catch(c){return r.problems.push({path:o,message:`cannot open read-only: ${String(c)}`}),r}try{let c;try{c=i.prepare("SELECT composerId, workspaceId, createdAt, lastUpdatedAt, isSubagent, value FROM composerHeaders WHERE (lastUpdatedAt >= ? OR lastUpdatedAt IS NULL) AND createdAt <= ?").all(e,t)}catch(u){return r.problems.push({path:o,message:`composerHeaders unreadable: ${String(u)}`}),r}for(const u of c)try{const h=Er(u,o);if(h.lastUpdatedAt<e)continue;const m={machine:s,host:he(),observedAt:n,path:o,workspacePath:h.workspaceId?a.get(h.workspaceId):void 0};r.envelopes.push(oe(wr(h,m)));const k=`${h.lastUpdatedAt}`,b=bs.get(h.composerId);let g;if(b&&b.stamp===k)g=b.envelopes;else{const f=Ir(i,h.composerId),{drafts:p}=Ar(h,f,m);g=p.map(oe),bs.set(h.composerId,{stamp:k,envelopes:g})}for(const f of g)f.occurredAt>=e&&f.occurredAt<=t&&r.envelopes.push(f);r.composersRead++}catch(h){r.composersFailed++,r.problems.push({path:o,message:`${u.composerId}: ${h instanceof Error?h.message:String(h)}`})}}finally{i.close()}return r}async function Tr(e,t){return(await vn(e,t)).envelopes}async function vs(){const e=bn();if(!F(e))return{available:!1,present:!1,globalStorage:Ue()};try{const t=new Ct(e,{readOnly:!0});try{const s=t.prepare("SELECT count(*) AS n FROM composerHeaders").get();return{available:s.n>0,present:!0,globalStorage:Ue(),composers:s.n}}finally{t.close()}}catch{return{available:!1,present:!0,globalStorage:Ue()}}}const Pe="gemini",$r={tokens:"supported",requests:"supported",toolInteractions:"supported",toolErrors:"unsupported",retries:"unsupported",waits:"unsupported",model:"supported",context:"partial",outcome:"partial"},Mr="gemini";class ot extends Error{constructor(t,s){super(t),this.path=s,this.name="GeminiFormatError"}path}const Or="The session file has not been written to for longer than the live window, so the runtime that owned it is gone and the turn ended at its last message.";function Rr(e){return(typeof e.content=="string"?e.content:Array.isArray(e.content)?e.content.map(s=>s?.text).filter(s=>typeof s=="string").join(`
6
+ `):"").split(`
7
+ `)[0].trim().slice(0,200)||"Gemini reported an error"}const Nr=e=>`gemini:${e}`,ne=e=>typeof e=="number"&&Number.isFinite(e)?e:0,Ye=e=>typeof e=="string"&&e?e:void 0,Oe=e=>{if(typeof e!="string")return;const t=Date.parse(e);return Number.isFinite(t)?t:void 0};function xr(e,t){const s=e.split(`
8
+ `).filter(i=>i.trim());if(s.length===0)throw new ot("session file is empty",t);let n=null;const o=[],r=new Map,a=i=>{const c=i;!c||typeof c!="object"||typeof c.id!="string"||(r.has(c.id)||o.push(c.id),r.set(c.id,c))};for(const i of s){let c;try{c=JSON.parse(i)}catch{continue}if(!c||typeof c!="object")continue;const u=c;if(!n&&typeof u.sessionId=="string"){n=u;continue}const h=u.$set;if(h){const m=h.messages;if(Array.isArray(m))for(const k of m)a(k);continue}typeof u.id=="string"&&a(u)}if(!n||!n.sessionId)throw new ot("session file has no header with a sessionId",t);return{header:n,messages:o.map(i=>r.get(i))}}const yn=e=>Array.isArray(e.content)&&e.content.some(t=>!!t&&typeof t=="object"&&"functionResponse"in t);function _r(e){if(e.type!=="user"||yn(e))return!1;const t=Array.isArray(e.content)?e.content.map(n=>n?.text).filter(n=>typeof n=="string"):[];if(t.length===0)return!1;const s=t[0];return!s.startsWith("<session_context>")&&!s.startsWith("[System:")}function Cr(e){const t=ne(e.input),s=ne(e.cached);return{[M.tokensInput]:Math.max(0,t-s),[M.tokensOutput]:ne(e.output)+ne(e.thoughts),[M.tokensCacheRead]:s,[M.tokensReasoning]:ne(e.thoughts),[M.steps]:1}}function jr(e,t){const{header:s,messages:n}=e,o=s.sessionId,r=Oe(s.startTime);if(r===void 0)throw new ot("session header has no parseable startTime",t.path);const a=n.filter(p=>Oe(p.timestamp)!==void 0),i=a.length?Math.max(...a.map(p=>Oe(p.timestamp))):r,c=t.workspacePath??"",u=c?te(c).toUpperCase():"GEMINI",h=Nr(o),k={source:{id:Pe,instance:t.host},observedAt:t.observedAt,clock:"wall",basis:"measured",stratum:"stored-semantics"},b=p=>({path:t.path,...p?{recordId:p}:{}}),g=[{...k,occurredAt:r,kind:"began",subject:{type:"session",id:h},claims:[{ns:"agent.session",parts:[Mr,o],validFrom:r,validTo:i}],core:{machineId:t.machine.id,label:u,executor:Pe},attrs:{context:c,"gemini.sessionId":o,"gemini.projectHash":s.projectHash,...Ye(s.kind)?{"gemini.kind":s.kind}:{}},provenance:b(o),seq:"session"}],f=[];for(let p=0;p<n.length;p++)_r(n[p])&&Oe(n[p].timestamp)!==void 0&&f.push(p);if(f.length===0){if(n.some(p=>p.type==="gemini"))throw new ot(`session has ${n.length} messages including model output but no recognisable user prompt`,t.path);return g}for(let p=0;p<f.length;p++){const y=f[p],d=p+1<f.length?f[p+1]:n.length,A=p+1,v=`${h}:turn:${A}`,w=Oe(n[y].timestamp);let $=w,l,S;const E=[];for(let _=y;_<d;_++){const R=n[_],O=Oe(R.timestamp);if(O===void 0||R.type!=="gemini"&&R.type!=="error"&&!(R.type==="user"&&yn(R))||(O>$&&($=O),S=R,R.type!=="gemini"))continue;l??=Ye(R.model);const U=Array.isArray(R.toolCalls)?R.toolCalls:[],q=R.tokens?Cr(R.tokens):{};U.length&&(q[M.interactions]=U.length),Object.keys(q).length!==0&&E.push({...k,occurredAt:O,kind:"progressed",subject:{type:"execution",id:v},core:{measures:q},attrs:{...U.length?{"gemini.tools":U.map(j=>Ye(j.name)??"unknown")}:{},...Ye(R.model)?{"gemini.model":R.model}:{},...R.tokens?{"gemini.usage.input":ne(R.tokens.input),"gemini.usage.output":ne(R.tokens.output),"gemini.usage.cached":ne(R.tokens.cached),"gemini.usage.thoughts":ne(R.tokens.thoughts),"gemini.usage.tool":ne(R.tokens.tool)}:{}},provenance:b(R.id),seq:R.id})}g.push({...k,occurredAt:w,kind:"began",subject:{type:"execution",id:v},core:{machineId:t.machine.id,sessionId:h,label:`${u} · TURN ${A}`,executor:Pe,model:l,depth:0},attrs:{"gemini.turn":A},provenance:b(n[y].id),seq:`turn:${A}`}),g.push(...E);const T=S?.type==="error",I=S?.type==="gemini"&&!(Array.isArray(S.toolCalls)&&S.toolCalls.length),N=p+1<f.length,C=(_,R)=>({...k,occurredAt:$,kind:"ended",subject:{type:"execution",id:v},core:_,...R?{basis:"inferred",assumption:Or}:{},provenance:b(n[y].id),seq:`turn:${A}:end`});T?g.push(C({outcome:"error",failureMessage:Rr(S)},!1)):N||I&&t.settled?g.push(C({outcome:"completed"},!1)):t.closeOpenTurns&&g.push(C({outcome:I?"completed":"interrupted"},!0))}return g}const Dr=3e3;function Ut(){return process.env.GEMINI_HOME||D(Ee(),".gemini")}const wn=()=>D(Ut(),"tmp"),ys=new Map;async function Lr(){const e=new Map;try{const t=JSON.parse(await ue(D(Ut(),"projects.json"),"utf8"));for(const[s,n]of Object.entries(t.projects??{}))typeof n=="string"&&e.set(n,s)}catch{}return e}async function An(){const e=wn();if(!F(e))return[];const t=[];let s;try{s=await W(e)}catch{return t}for(const n of s){let o;try{o=await W(D(e,n,"chats"))}catch{continue}for(const r of o)r.startsWith("session-")&&r.endsWith(".jsonl")&&t.push({path:D(e,n,"chats",r),slug:n})}return t}async function Sn(e,t){const s=Ie(),n=Date.now(),o={envelopes:[],sessionsRead:0,sessionsFailed:0,problems:[],storedAvailable:!1},r=await An();if(r.length===0)return o.storedAvailable=F(wn()),o;o.storedAvailable=!0;const a=await Lr();for(const i of r){let c;try{c=await we(i.path)}catch{continue}if(c.mtimeMs<e)continue;const u=Date.now()-c.mtimeMs,h=u>Dr,m=u>Lt,k=`${c.mtimeMs}:${c.size}:${h}:${m}`,b=ys.get(i.path);let g;if(b&&b.stamp===k)g=b.envelopes;else try{const f=xr(await ue(i.path,"utf8"),i.path);g=jr(f,{machine:s,host:he(),observedAt:n,path:i.path,workspacePath:a.get(i.slug),settled:h,closeOpenTurns:m}).map(oe),ys.set(i.path,{stamp:k,envelopes:g})}catch(f){o.sessionsFailed++,o.problems.push({path:i.path,message:f instanceof Error?f.message:String(f)});continue}o.sessionsRead++;for(const f of g)f.occurredAt>=e&&f.occurredAt<=t&&o.envelopes.push(f)}return o}async function Fr(e,t){return(await Sn(e,t)).envelopes}async function ws(){const e=Ut(),t=(await An()).length;return{available:t>0,present:F(e),home:e,sessions:t}}const Ur=new Set(["running","waiting"]);function kn(e){return Ur.has(e)}function En(e,t){return{now:e,dayStart:e,dayEnd:t,machines:new Map,sources:new Map,sessions:new Map,executions:new Map,processes:new Map,artifacts:new Map,transfers:new Map,relationships:[],active:new Set,seen:new Set}}const Pr=5*6e4;function Br(e){const t=[];for(const s of e)s.parentId&&t.push({from:{type:"session",id:s.parentId},to:{type:"session",id:s.id},kind:"spawned",basis:"measured",via:"recorded by the child session's own runtime"});return t}function Hr(e,t){const s=e.now-Pr,n=new Set;for(const i of t)i.from.type==="process"&&n.add(i.from.id),i.to.type==="process"&&n.add(i.to.id);const o=[];let r=0,a=0;for(const i of e.processes.values())i.lastSeenAt>=s&&r++,i.endInferred&&a++,n.has(i.id)&&o.push(i);return{now:e.now,dayStart:e.dayStart,dayEnd:e.dayEnd,machines:[...e.machines.values()],sources:[...e.sources.values()],sessions:[...e.sessions.values()],executions:[...e.executions.values()],processes:o,processTotals:{observed:e.processes.size,recentlySeen:r,exitsInferred:a},relationships:[...t,...Br(e.sessions.values())]}}function As(e){const t=En(e.dayStart,e.dayEnd);t.now=e.now;for(const s of e.machines)t.machines.set(s.id,s);for(const s of e.sources)t.sources.set(`${s.id}:${s.instance}`,s);for(const s of e.sessions)t.sessions.set(s.id,s);for(const s of e.executions)t.executions.set(s.id,s),kn(s.status)&&t.active.add(s.id);for(const s of e.processes)t.processes.set(s.id,s);return t.processTotals=e.processTotals,t.relationships=e.relationships,t}function ee(e,t){const s=e[t];return typeof s=="number"&&Number.isFinite(s)?s:void 0}function rt(e,t){for(const[s,n]of Object.entries(t)){if(typeof n!="number"||!Number.isFinite(n))continue;const o=s;e[o]=(e[o]??0)+n}}const Wr=[M.tokensInput,M.tokensOutput,M.tokensCacheRead];function de(e){let t=0,s=!1;for(const n of Wr){const o=ee(e,n);o!==void 0&&(s=!0,t+=o)}return s?t:void 0}function In(e){return{input:ee(e,M.tokensInput)??0,output:ee(e,M.tokensOutput)??0,cacheRead:ee(e,M.tokensCacheRead)??0,reasoning:ee(e,M.tokensReasoning)??0}}function Tn(e){const t=de(e.measures);if(t!==void 0)return Ss(t/1e3,200);const s=ee(e.measures,M.cpuMs);if(s!==void 0)return Ss(s/1e3,200)}function Ce(e){return ee(e.measures,M.interactions)}function $n(e){return ee(e.measures,M.steps)??0}function $t(e){return ee(e.measures,M.errors)??0}function Mt(e){return ee(e.measures,M.retries)??0}function Ss(e,t){return Math.min(1,Math.log1p(Math.max(0,e))/Math.log1p(t))}function qr(e){let t=2166136261;for(let s=0;s<e.length;s++)t^=e.charCodeAt(s),t=Math.imul(t,16777619);return t>>>0}function it(e,t=0){return qr(e+"#"+t)%1e5/1e5}const gt=[{x:430,y:508,extentX:300,extentY:186},{x:838,y:322,extentX:186,extentY:116}];function Xr(e){if(e<gt.length)return gt[e];const s=-.9+(e-gt.length)*1.15;return{x:620+Math.cos(s)*520,y:300+Math.sin(s)*250,extentX:150,extentY:94}}function Vr(e){const t=s=>s==="laptop"?0:s==="desktop"?1:2;return[...e].sort((s,n)=>t(s.kind)-t(n.kind)||s.firstSeenAt-n.firstSeenAt||(s.id<n.id?-1:s.id>n.id?1:0))}function ks(e,t){const s=it(t,1),n=it(t,2),o=s*Math.PI*2+n*2.399963,r=.34+.46*Math.sqrt(n);return{x:e.x+Math.cos(o)*e.extentX*r,y:e.y+Math.sin(o)*e.extentY*r}}const Es=30,Yr=74;function Gr(e){return Es+e*(Yr-Es)}const Is=64,zr=8,Kr=8,Ts=16,$s=.45;function Jr(e,t){switch(e.status){case"running":{const s=t-e.lastActivityAt;return .55+.45*Math.exp(-s/45e3)}case"waiting":return .08;case"failed":return .9;case"completed":return 0;case"idle":return .03}}const Ms=.32;function Qr(e){const t=Tn(e),s=e.depth>0?.62:1;return t===void 0?Ms*s:Math.min(1,(Ms+.68*t)*s)}function Zr(e,t){const s=Math.max(1,(e.endedAt??t)-e.startedAt),n=(Ce(e)??0)/(s/6e4);return Math.min(1,.25+n/24)}function Os(e){return(e.status==="failed"?3:e.status==="waiting"?2:e.status==="running"?1:0)*1e15+e.lastActivityAt}function ei(e){const t=new Set,s=new Set,n=new Map,o=new Map,r=(a,i,c)=>{const u=a.get(i);u?u.push(c):a.set(i,[c])};for(const a of e.relationships){const{from:i,to:c,kind:u}=a;u==="ran-as"?(i.type==="execution"&&t.add(i.id),c.type==="execution"&&t.add(c.id),i.type==="session"&&c.type==="process"&&s.add(i.id),c.type==="session"&&i.type==="process"&&s.add(c.id),i.type==="execution"&&c.type==="session"?n.set(i.id,c.id):i.type==="session"&&c.type==="execution"&&n.set(c.id,i.id)):u==="same-as"&&i.type==="execution"&&c.type==="execution"&&(t.add(i.id),t.add(c.id),r(o,i.id,c.id),r(o,c.id,i.id))}return{resolvedExecutions:t,sessionsWithProcess:s,runObservesSession:n,sameExecution:o}}function ti(e,t){const n=e.startBasis===void 0?.5:e.startBasis==="measured"?1:0,o=e.endBasis===void 0?.5:e.endBasis==="measured"?1:0,r=e.endedAt===void 0?n:(n+o)/2,a=Tn(e)===void 0?0:1,i=t.resolvedExecutions.has(e.id)||t.sessionsWithProcess.has(e.sessionId)?1:0;return(1+r+a+i)/4}function Rs(e){let t=1;for(const s of e)t*=1-Math.min(1,Math.max(0,s));return 1-t}function Ns(e,t,s,n){const o=Math.max(e,s),r=Math.min(t,n);if(r<o)return 0;const a=Math.max(t,n)-Math.min(e,s);return a<=0?1:(r-o)/a}function xs(e){const t=e.now,s=Vr(e.machines.values()).slice(0,zr),n=new Map,o=[];let r=1;const a=new Map;for(const l of e.executions.values()){const S=(a.get(l.machineId)??0)+1;a.set(l.machineId,S),S>r&&(r=S)}s.forEach((l,S)=>{const E=Xr(S);n.set(l.id,E),o.push({id:l.id,name:l.name,kind:l.kind,x:E.x,y:E.y,extentX:E.extentX,extentY:E.extentY,prominence:(a.get(l.id)??0)/r,seed:it(l.id,7)})});const i=45e3,c=[];for(const l of e.executions.values())(l.status==="completed"||l.status==="failed")&&t-(l.endedAt??t)>i||l.status==="idle"&&t-l.lastActivityAt>i*4||n.has(l.machineId)&&c.push(l);c.length>Is&&(c.sort((l,S)=>Os(S)-Os(l)),c.length=Is);const u=ei(e),h=l=>{const S=n.get(l.machineId),{x:E,y:T}=ks(S,l.id);return{id:l.id,massId:l.machineId,sessionId:l.sessionId,x:E,y:T,extent:Qr(l),energy:Jr(l,t),rate:Zr(l,t),phase:it(l.id,3)*Math.PI*2,status:l.status,label:l.label,statusSince:l.waitingSince??l.endedAt??l.startedAt,articulation:ti(l,u),shoulder:0,observers:1}},m=new Set(c.map(l=>l.id)),k=new Set,b=[],g=l=>[l.startedAt,l.endedAt??t];for(const l of[...c].sort((S,E)=>S.id<E.id?-1:1)){if(k.has(l.id))continue;const S=[l];k.add(l.id);for(let _=0;_<S.length;_++)for(const R of u.sameExecution.get(S[_].id)??[])!m.has(R)||k.has(R)||(k.add(R),S.push(e.executions.get(R)));if(S.length===1){b.push(h(l));continue}const E=S.map(h),T=E.reduce((_,R)=>R.articulation>_.articulation||R.articulation===_.articulation&&R.id<_.id?R:_);let I=1;const[N,C]=g(e.executions.get(T.id));for(const _ of S){const[R,O]=g(_);I=Math.min(I,Ns(N,C,R,O))}b.push({...T,extent:Math.max(...E.map(_=>_.extent)),energy:Math.max(...E.map(_=>_.energy)),articulation:Rs(E.map(_=>_.articulation)),shoulder:Math.min($s,1-I),observers:S.length})}const f=new Map;for(const l of b){if(u.runObservesSession.has(l.id))continue;const S=f.get(l.sessionId);S?S.push(l):f.set(l.sessionId,[l])}const p=new Map,y=[];for(const l of b){const S=u.runObservesSession.get(l.id),E=S?f.get(S):void 0;if(!S||!E||E.length===0){if(y.push(l),S){const O=f.get(l.sessionId);O?O.push(l):f.set(l.sessionId,[l])}continue}const T=e.executions.get(l.id);let I=1/0,N=-1/0;for(const O of E){const[U,q]=g(e.executions.get(O.id));I=Math.min(I,U),N=Math.max(N,q)}const[C,_]=g(T),R=p.get(S)??{articulations:[],coincidence:1};R.articulations.push(l.articulation),R.coincidence=Math.min(R.coincidence,Ns(C,_,I,N)),p.set(S,R)}const d=[];for(const l of[...f.keys()].sort()){const S=f.get(l),E=e.sessions.get(l);if(!E||S.length===0)continue;let T=0,I=0;for(const O of S)T+=O.x,I+=O.y;T/=S.length,I/=S.length;let N=0,C=0;for(const O of S){const U=Gr(O.extent);N=Math.max(N,Math.abs(O.x-T)+U*1.5),C=Math.max(C,Math.abs(O.y-I)+U)}const _=p.get(l),R=Math.max(...S.map(O=>O.articulation));d.push({id:l,massId:S[0].massId,x:T,y:I,extentX:Math.max(N,52),extentY:Math.max(C,36),presence:1,articulation:_?Rs([R,..._.articulations]):R,parentId:E.parentId,empty:!1,shoulder:_?Math.min($s,1-_.coincidence):0,observers:1+(_?.articulations.length??0),label:E.label??E.executor??l})}for(const l of[...e.sessions.values()].sort((S,E)=>S.id<E.id?-1:1)){if(l.executionIds.length>0||l.endedAt!==void 0&&t-l.endedAt>i)continue;const S=n.get(l.machineId);if(!S)continue;const{x:E,y:T}=ks(S,`session-presence:${l.id}`);d.push({id:l.id,massId:l.machineId,x:E,y:T,extentX:64,extentY:42,presence:1,articulation:u.sessionsWithProcess.has(l.id)?.5:.25,parentId:l.parentId,empty:!0,shoulder:0,observers:1,label:l.label??l.executor??l.id})}if(d.length>Ts){const l=S=>S.empty?0:f.get(S.id)?.length??0;d.sort((S,E)=>l(E)-l(S)||(S.id<E.id?-1:1)),d.length=Ts}const A=[];for(const l of e.transfers.values())if(l.endedAt===void 0&&!(!n.has(l.fromMachineId)||!n.has(l.toMachineId))){if(A.length>=Kr)break;A.push({id:l.id,fromMassId:l.fromMachineId,toMassId:l.toMachineId,energy:1,label:l.label})}const v=new Map;s.forEach((l,S)=>v.set(l.id,S));const w=Math.max(1,e.dayEnd-e.dayStart),$=[];for(const l of e.executions.values()){const S=v.get(l.machineId);if(S===void 0)continue;const E=(l.startedAt-e.dayStart)/w,T=((l.endedAt??t)-e.dayStart)/w;$.push({id:l.id,massId:l.machineId,lane:S,startFraction:Math.max(0,Math.min(1,E)),endFraction:Math.max(0,Math.min(1,T)),status:l.status,label:l.label})}return{time:t,masses:o,disturbances:y,plinths:d,couplings:A,strata:$}}const Mn="057.landscape",On=1;function si(e){return{contract:Mn,version:On,landscape:e}}const Pt="SHAPES FIELD",Bt="METADATA — DOES NOT SHAPE FIELD";function Rn(e){const t=new Date(e),s=n=>String(n).padStart(2,"0");return`${s(t.getHours())}:${s(t.getMinutes())}:${s(t.getSeconds())}`}function ni(e){return H(e).toUpperCase().replace(/(\d)([HMS])/g,"$1 $2").replace(/\bM\b/g,"MIN")}function oi(e,t,s,n,o=()=>{}){if(s==="mass")return ai(e,t,n);if(s==="coupling")return ci(e,n);const r=e.executions.get(n);return r?ri(e,t,r,s,o("execution",n)):null}function ri(e,t,s,n,o){const r=e.sessions.get(s.sessionId),a=e.machines.get(s.machineId),c=t.disturbances.find(p=>p.id===s.id)?.statusSince??s.endedAt??s.startedAt,u=s.startBasis==="inferred"||s.endBasis==="inferred",h=de(s.measures),m=[{key:"MACHINE",value:(a?.name??s.machineId).toUpperCase()},{key:"STATE",value:s.status.toUpperCase(),tone:s.status},{key:"SINCE",value:Rn(c)},h===void 0?{key:"TOKENS",value:"NOT OBSERVED",tone:"absent",note:"This source does not persist token accounting."}:{key:"TOKENS",value:X(h)}];if(r){const p=r.executionIds.indexOf(s.id),y=t.plinths.some(A=>A.id===r.id),d=p>=0?`${p+1} OF ${r.executionIds.length}`:`OF ${r.executionIds.length}`;m.push({key:"SESSION",value:y?`${d} · PLINTH`:d})}const k=ii(e,s.id),b=[s.model??r?.model?{key:"MODEL",value:s.model??r?.model}:{key:"MODEL",value:"not observed",tone:"absent",note:"This source does not record the model."}];r?.context&&b.push({key:"PROJECT",value:te(r.context),note:r.context}),b.push({key:"SOURCE",value:[s.executor,k===void 0?void 0:`pid ${k}`].filter(Boolean).join(" · "),note:o}),b.push({key:"REQUESTS",value:String($n(s))});const g=Ce(s);if(b.push(g===void 0?{key:"TOOL CALLS",value:"not observed",tone:"absent",note:"This source does not count discrete operations."}:{key:"TOOL CALLS",value:Do(g)}),b.push({key:"ELAPSED",value:`${H((s.endedAt??e.now)-s.startedAt)}${u?" · inferred":""}`,note:u?s.boundsAssumption:void 0}),h!==void 0){const p=In(s.measures);b.push({key:"INPUT",value:X(p.input)},{key:"OUTPUT",value:X(p.output)}),b.push({key:"CACHE READ",value:X(p.cacheRead)},{key:"REASONING",value:X(p.reasoning)})}$t(s)>0&&b.push({key:"TOOL ERRORS",value:String($t(s)),tone:"failed"}),Mt(s)>0&&b.push({key:"RETRIES",value:String(Mt(s)),tone:"waiting",note:"Provider retries."}),(s.waits.length>0||s.waitingMs>0)&&b.push({key:"BLOCKED",value:`${H(s.waitingMs)} on you · ${s.waits.length||1}×`,tone:"waiting"}),s.depth>0&&b.push({key:"SUB-AGENT",value:`depth ${s.depth}`});const f=s.status==="running"||s.status==="waiting";return{id:s.id,eyebrow:n==="stratum"||!f?"SELECTED · RUN":"SELECTED · PROCESS",title:s.label.toUpperCase(),state:{text:f?`${s.status.toUpperCase()} · ${ni(e.now-c)}`:s.status.toUpperCase(),status:s.status},groups:[{title:Pt,metadata:!1,rows:m},{title:Bt,metadata:!0,rows:b}],failure:s.failure?`${s.failure.code}: ${s.failure.message}`:void 0,reveal:o}}function ii(e,t){for(const s of e.relationships){if(s.kind!=="ran-as")continue;const n=s.from.type==="execution"&&s.from.id===t&&s.to.type==="process"?s.to.id:s.to.type==="execution"&&s.to.id===t&&s.from.type==="process"?s.from.id:void 0;if(n)return e.processes.get(n)?.pid}}function ai(e,t,s){const n=e.machines.get(s);if(!n)return null;let o=0,r=0,a=0,i;for(const b of e.executions.values()){if(b.machineId!==n.id)continue;const g=de(b.measures);g!==void 0&&(i=(i??0)+g),b.status==="running"?o++:b.status==="waiting"?r++:a++}const u=[{key:"KIND",value:(t.masses.find(b=>b.id===s)?.kind??n.kind).toUpperCase()},{key:"RUNNING",value:String(o),tone:o>0?"running":void 0}];r>0&&u.push({key:"WAITING",value:String(r),tone:"waiting"}),u.push({key:"RAN TODAY",value:String(a)});const h=[i===void 0?{key:"TOKENS",value:"not observed",tone:"absent",note:"No execution in this window reported token accounting."}:{key:"TOKENS",value:X(i)}],m=e.processTotals;if(m){const b=new Set;for(const g of e.relationships)g.kind==="ran-as"&&(g.from.type==="process"&&b.add(g.from.id),g.to.type==="process"&&b.add(g.to.id));h.push({key:"PROCESSES",value:`${m.observed} observed`}),h.push({key:"LAST 5 MIN",value:`${m.recentlySeen} seen`,note:"Processes with a liveness observation in the last five minutes. The sampler never witnesses an exit, so recency is the honest liveness signal."}),h.push({key:"ATTRIBUTED",value:`${b.size} of ${m.observed}`,note:"Processes tied to a session or execution by resolved identity. The rest are observed, not explained."})}const k=o+r;return{id:s,eyebrow:"SELECTED · MACHINE",title:n.name.toUpperCase(),state:k>0?{text:`${k} ACTIVE`,status:o>0?"running":"waiting"}:{text:"QUIET"},groups:[{title:Pt,metadata:!1,rows:u},{title:Bt,metadata:!0,rows:h}]}}function ci(e,t){const s=e.transfers.get(t);if(!s)return null;const n=e.machines.get(s.fromMachineId)?.name??s.fromMachineId,o=e.machines.get(s.toMachineId)?.name??s.toMachineId;return{id:t,eyebrow:"SELECTED · TRANSFER",title:`${n} → ${o}`.toUpperCase(),state:{text:"TRANSFERRING",status:"running"},groups:[{title:Pt,metadata:!1,rows:[{key:"FROM",value:n.toUpperCase()},{key:"TO",value:o.toUpperCase()},{key:"SINCE",value:Rn(s.startedAt)}]},{title:Bt,metadata:!0,rows:[{key:"WHAT",value:s.label},{key:"SIZE",value:Lo(s.bytes)}]}]}}const Y=e=>({value:e,basis:"measured"}),Ge=(e,t)=>({value:e,basis:"inferred",assumption:t});function Ht(e){if(e.length===0)return[];e.sort((s,n)=>s.start-n.start);const t=[{start:e[0].start,end:e[0].end}];for(let s=1;s<e.length;s++){const n=e[s],o=t[t.length-1];n.start<=o.end?n.end>o.end&&(o.end=n.end):t.push({start:n.start,end:n.end})}return t}function _s(e){let t=0;for(const s of e)t+=s.end-s.start;return t}function ui(e,t){const s=[];let n=0,o=0;for(;n<e.length&&o<t.length;){const r=Math.max(e[n].start,t[o].start),a=Math.min(e[n].end,t[o].end);r<a&&s.push({start:r,end:a}),e[n].end<t[o].end?n++:o++}return s}function Nn(e){if(e.length===0)return{peak:0,at:0};const t=[];for(const r of e)t.push({t:r.start,d:1}),t.push({t:r.end,d:-1});t.sort((r,a)=>r.t-a.t||r.d-a.d);let s=0,n=0,o=t[0].t;for(const r of t)s+=r.d,s>n&&(n=s,o=r.t);return{peak:n,at:o}}function di(e){if(e.length===0)return;const t=[...e].sort((n,o)=>n-o),s=t.length>>1;return t.length%2?t[s]:(t[s-1]+t[s])/2}const xn=6e4;function li(e,t){return{start:e.startedAt,end:e.endedAt??t}}function pi(e){const t=[];for(const s of e.executions.values()){s.depth===0&&t.push({start:s.startedAt-xn,end:s.startedAt});for(const n of s.waits)t.push({start:n.start,end:n.end});s.waitingSince!==void 0&&t.push({start:s.waitingSince,end:e.now})}return Ht(t)}function fi(e){const t=e.now,s=[...e.executions.values()];let n=0,o=0,r=0,a=0,i=0,c=0,u=0,h=0;const m=[],k=new Map;for(const w of s){n+=$n(w),o+=de(w.measures)??0,r+=Ce(w)??0,w.status==="completed"?a++:w.status==="failed"?i++:w.status==="waiting"?c++:w.status==="idle"&&u++;const $=li(w,t);m.push($),h+=w.waitingMs,w.waitingSince!==void 0&&(h+=Math.max(0,t-w.waitingSince));let l=k.get(w.machineId);l||(l={machineId:w.machineId,executions:0,tokens:0,computeTime:0},k.set(w.machineId,l)),l.executions++,l.tokens+=de(w.measures)??0,l.computeTime+=$.end-$.start}const b=Ht(m.map(w=>({...w}))),g=pi(e),f=_s(ui(b,g)),{peak:p,at:y}=Nn(m),d=mi(e),A=Math.max(0,d.length-1);let v=null;for(const w of d)(!v||w.end-w.start>v.end-v.start)&&(v=w);return{requests:Y(n),sessions:Y(e.sessions.size),executions:Y(s.length),tokens:Y(o),toolCalls:Y(r),autonomousCompute:Ge(_s(b),"Wall-clock time during which at least one run was in flight, merged so parallel runs are not double-counted."),humanAgentOverlap:Ge(f,`Compute time intersecting a window when you were plausibly present: the ${xn/1e3}s before you sent a message, and any approval from ask to answer.`),peakConcurrency:Y(p),peakConcurrencyAt:Y(y),contextSwitches:Ge(A,"Transitions between working directories, ordered by time. A directory is the closest thing the source has to a project."),longestFocus:Ge(v,"Longest unbroken stretch spent in one working directory."),waitingOnYou:Y(h),completed:Y(a),failed:Y(i),waiting:Y(c),idle:Y(u),byMachine:k,contextSpans:d,transfers:Y(e.transfers.size)}}function mi(e){const t=[];for(const n of e.executions.values()){const o=e.sessions.get(n.sessionId);o&&t.push({context:o.context,start:n.startedAt,end:n.endedAt??e.now})}t.sort((n,o)=>n.start-o.start);const s=[];for(const n of t){const o=s[s.length-1];o&&o.context===n.context&&n.start<=o.end?n.end>o.end&&(o.end=n.end):o&&o.context===n.context?n.start-o.end<=hi?o.end=Math.max(o.end,n.end):s.push({context:n.context,start:n.start,end:n.end}):s.push({context:n.context,start:n.start,end:n.end})}return s}const hi=15*6e4;function gi(e){return{key:e,runs:0,tokens:0,tokenRuns:0,medianRuns:0,computeMs:0,failed:0,waitingMs:0,toolCalls:0}}function bt(e,t){const s=new Map,n=new Map;for(const o of e.executions.values()){const r=t(o,e.sessions.get(o.sessionId));if(r===void 0)continue;let a=s.get(r);a||(a=gi(r),s.set(r,a)),a.runs++;const i=de(o.measures);if(i!==void 0&&(a.tokens+=i,a.tokenRuns++,o.endedAt!==void 0)){let c=n.get(r);c||(c=[],n.set(r,c)),c.push(i)}a.computeMs+=(o.endedAt??e.now)-o.startedAt,a.waitingMs+=o.waitingMs,a.toolCalls+=Ce(o)??0,o.status==="failed"&&a.failed++}for(const[o,r]of n){const a=s.get(o);a&&(a.medianTokens=di(r),a.medianRuns=r.length)}return[...s.values()].sort((o,r)=>r.computeMs-o.computeMs)}function bi(e){const t={input:0,output:0,cacheRead:0,reasoning:0,total:0};for(const s of e.executions.values()){const n=In(s.measures);t.input+=n.input,t.output+=n.output,t.cacheRead+=n.cacheRead,t.reasoning+=n.reasoning}return t.total=t.input+t.output+t.cacheRead+t.reasoning,t}function vi(e){const t={count:0,totalMs:0,longestMs:0,openNow:0};for(const s of e.executions.values()){for(const n of s.waits){t.count++;const o=n.end-n.start;t.totalMs+=o,o>t.longestMs&&(t.longestMs=o)}if(s.waitingSince!==void 0){t.openNow++;const n=e.now-s.waitingSince;t.totalMs+=n,n>t.longestMs&&(t.longestMs=n)}}return t}function yi(e){const t={toolCalls:0,toolErrors:0,retries:0,failed:0,interrupted:0,completed:0};for(const s of e.executions.values())t.toolCalls+=Ce(s)??0,t.toolErrors+=$t(s),t.retries+=Mt(s),s.status==="failed"?t.failed++:s.outcome==="interrupted"?t.interrupted++:s.outcome==="completed"&&t.completed++;return t}function wi(e){const t=[];for(const r of e.executions.values())t.push({start:r.startedAt,end:r.endedAt??e.now});if(t.length===0)return[];const s=Ht(t.map(r=>({...r}))),n=new Date(e.dayStart);n.setMinutes(0,0,0);const o=[];for(let r=n.getTime();r<e.now;r+=36e5){const a=r+36e5;let i=0;for(const h of s){const m=Math.max(h.start,r),k=Math.min(h.end,a);k>m&&(i+=k-m)}let c=0;const u=[];for(const h of t)h.start<a&&h.end>r&&(c++,u.push({start:Math.max(h.start,r),end:Math.min(h.end,a)}));o.push({hour:new Date(r).getHours(),runs:c,computeMs:i,peak:Nn(u).peak})}return o}const Qe=6e4,Ai=60*Qe;function Si(e,t){const s=[],n=t.contextSpans,o=t.longestFocus.value,r=Math.max(1,e.now-e.dayStart),a=t.autonomousCompute.value/r;let i;if(t.executions.value===0)return{headline:"QUIET",clauses:["No computation observed in this window."]};if(t.peakConcurrency.value>=3?i="PARALLEL":n.length>=6?i="FRAGMENTED":o&&o.end-o.start>2*Ai?i="SUSTAINED":a<.15?i="SPARSE":i="SERIAL",t.peakConcurrency.value>=2?s.push(`Up to ${t.peakConcurrency.value} runs in flight at once; ${H(t.autonomousCompute.value)} of wall-clock time had computation running.`):s.push(`Runs happened one at a time, across ${H(t.autonomousCompute.value)} of wall-clock time.`),o&&s.push(`The longest unbroken stretch was ${H(o.end-o.start)} in ${te(o.context)}.`),n.length>1){const c=new Set(n.map(u=>u.context)).size;s.push(`Attention moved ${t.contextSwitches.value} ${t.contextSwitches.value===1?"time":"times"} across ${c} ${c===1?"context":"contexts"}.`)}if(t.waitingOnYou.value>Qe&&s.push(`${H(t.waitingOnYou.value)} was spent with a run waiting on your answer.`),t.humanAgentOverlap.value>Qe){const c=Math.round(t.humanAgentOverlap.value/Math.max(1,t.autonomousCompute.value)*100);s.push(`About ${c}% of that computation overlapped a window when you were present; the rest ran without you.`)}else t.autonomousCompute.value>5*Qe&&s.push("Computation ran almost entirely outside the moments you were present.");if(t.failed.value>0&&s.push(`${t.failed.value} of ${t.executions.value} runs ended in failure; ${t.completed.value} completed.`),t.byMachine.size>1){const c=[...t.byMachine.values()].sort((u,h)=>h.computeTime-u.computeTime).map(u=>`${e.machines.get(u.machineId)?.name??u.machineId} ${H(u.computeTime)}`);s.push(`Compute was split across ${c.join(", ")}.`)}return{headline:i,clauses:s}}const Cs="(no model)";function ki(e){if(e.medianTokens===void 0)return{text:"no token accounting",title:"No run in this group reports token accounting, so there is no figure — not a figure of zero.",absent:!0};if(e.medianRuns===1)return{text:`single run ${X(e.medianTokens)}`,title:"One eligible run, so this is that run's figure, not a median. Same window as the rest of TODAY.",absent:!1};const t=e.medianRuns===e.runs?`${e.runs}`:`${e.medianRuns} of ${e.runs}`;return{text:`median ${X(e.medianTokens)} over ${t} runs`,title:`Median billed tokens per run, over the runs in this group that have ended and whose source reports token accounting — ${e.medianRuns} of ${e.runs} here. Runs still in flight are excluded: their totals are partial. Runs whose source persists no accounting are excluded: absence is not zero. Same window as the rest of TODAY.`,absent:!1}}function z(e,t,s,n={}){const o=s?.basis==="inferred";return{key:e,value:t,inferred:o,assumption:o?s?.assumption:void 0,...n}}function vt(e,t,s){const n=e[0]?.computeMs??0;return e.map(o=>({key:o.key,label:t(o.key),detail:`${o.runs} ${o.runs===1?"run":"runs"}${o.tokenRuns>0?` · ${X(o.tokens)} tok`:""} · ${H(o.computeMs)}`,failed:o.failed,fraction:n>0?o.computeMs/n:0,median:s?ki(o):void 0}))}function Ei(e){const t=fi(e),s=Si(e,t),n=bi(e),o=vi(e),r=yi(e),a=wi(e),i=bt(e,(v,w)=>w?.context),c=bt(e,v=>v.model??Cs),u=bt(e,v=>v.machineId),h=[...e.executions.values()],m=h.filter(v=>de(v.measures)===void 0).length,k=h.filter(v=>v.depth>0).length,b=t.longestFocus.value,g=Math.round(t.humanAgentOverlap.value/Math.max(1,t.autonomousCompute.value)*100),f=[z("REQUESTS",X(t.requests.value),t.requests),z("RUNS",String(t.executions.value),t.executions,{note:k>0?`${k} of them sub-agents`:void 0}),z("SESSIONS",String(t.sessions.value),t.sessions),z("TOKENS",X(t.tokens.value),t.tokens,{note:`${Math.round(n.cacheRead/Math.max(1,n.total)*100)}% cache reads`+(m>0?` · ${m} ${m===1?"run reports":"runs report"} no accounting`:"")}),z("TOOL CALLS",X(r.toolCalls),t.toolCalls,{note:r.toolErrors>0?`${r.toolErrors} failed`:void 0}),z("AUTONOMOUS COMPUTE",H(t.autonomousCompute.value),t.autonomousCompute),z("HUMAN + AGENT OVERLAP",H(t.humanAgentOverlap.value),t.humanAgentOverlap,{note:`${g}% of compute`}),z("PEAK CONCURRENCY",t.peakConcurrency.value>0?`${t.peakConcurrency.value} · ${Xe(t.peakConcurrencyAt.value)}`:"0",t.peakConcurrency),z("CONTEXT SWITCHES",String(t.contextSwitches.value),t.contextSwitches,{note:`across ${i.length} ${i.length===1?"context":"contexts"}`}),z("LONGEST FOCUS",b?H(b.end-b.start):"—",t.longestFocus,{note:b?`${te(b.context)} · ${Xe(b.start)}–${Xe(b.end)}`:void 0}),z("WAITING ON YOU",H(t.waitingOnYou.value),t.waitingOnYou,{tone:t.waitingOnYou.value>0?"waiting":void 0,note:o.count>0?`${o.count} ${o.count===1?"block":"blocks"} · longest ${H(o.longestMs)}`:void 0}),z("FAILED",String(r.failed),void 0,{tone:r.failed>0?"failed":void 0,note:r.interrupted>0||r.retries>0?`${r.interrupted} stopped · ${r.retries} retries`:void 0})],p=a.length>0?a.reduce((v,w)=>w.computeMs>v.computeMs?w:v,a[0]):void 0,y=v=>`${String(v).padStart(2,"0")}:00`,d=[{title:"WHERE THE TIME WENT",rows:vt(i,te,!1)}];u.length>0&&d.push({title:"BY MACHINE",rows:vt(u,v=>e.machines.get(v)?.name??v,!1)}),c.length>0&&d.push({title:"BY MODEL",rows:vt(c,v=>v===Cs?"model not observed":v,!0)});const A=v=>v/Math.max(1,n.total);return{headline:s.headline,clauses:[...s.clauses],measures:f,hours:a.map(v=>({hour:v.hour,computeMs:v.computeMs,runs:v.runs,peak:v.peak})),busiest:p?`busiest ${y(p.hour)} · ${H(p.computeMs)} of that hour`:void 0,groups:d,tokens:[["CACHE READS",n.cacheRead],["INPUT",n.input],["OUTPUT",n.output],["REASONING",n.reasoning]].map(([v,w])=>({key:v,value:X(w),percent:Math.round(A(w)*100),fraction:A(w)})),tokensNote:"Cache reads are context replayed into each request, not work generated. They dominate the total, which is why the headline token figure is much larger than it feels.",failures:h.filter(v=>v.status==="failed").sort((v,w)=>w.startedAt-v.startedAt).slice(0,12).map(v=>({id:v.id,at:Xe(v.startedAt),label:v.label,reason:v.failure?`${v.failure.code}: ${v.failure.message}`:"failed"})),notAvailable:[{key:"COST",text:"Every source here reports tokens or CPU time; none reports money. Converting one to the other needs a price table 057 does not have, so no cost figure is shown anywhere."},{key:"TOKENS, FROM SOME SOURCES",text:"Cursor persists no usage and 0x2F records none; their runs read NOT OBSERVED rather than 0, and the token totals sum only the runs that report."},{key:"MACHINE-TO-MACHINE TRANSFER",text:"Every observed source is single-host. Transfers are modelled and the field renders them, but no real adapter emits one; only the synthetic source does."},{key:"PROCESS EXITS",text:"The OS collector samples; an exit is inferred from disappearance between samples, never witnessed."},{key:"OUTCOME QUALITY",text:"The log records that a run completed, not whether the work was any good."}]}}function Ii(e,t){const s=new Set(t.disturbances.map(r=>r.id)),n=new Set(t.strata.map(r=>r.id)),o=[...e.executions.values()].sort((r,a)=>a.startedAt-r.startedAt).map(r=>{const a=e.sessions.get(r.sessionId);return{id:r.id,startedAt:r.startedAt,label:r.label,depth:r.depth,context:a?.context?te(a.context):null,model:r.model??null,status:r.status,stopped:r.outcome==="interrupted",durationMs:(r.endedAt??e.now)-r.startedAt,inferred:r.startBasis==="inferred"||r.endBasis==="inferred",tokens:de(r.measures)??null,tools:Ce(r)??null,waitedMs:r.waitingMs,inField:s.has(r.id)?"disturbance":n.has(r.id)?"stratum":null}});return{now:e.now,rows:o}}const Wt={[Mn]:On};function qt(e){return`${e}.core.json`}function _n(e){const t=qt(e);if(!F(t))return null;try{const s=JSON.parse(Gn(t,"utf8"));return typeof s.pid!="number"||typeof s.url!="string"?null:s}catch{return null}}function Ti(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}async function $i(e,t=1500){const s=_n(e);if(!s||s.pid===process.pid||!Ti(s.pid))return null;try{const n=await fetch(`${s.url}/api/health`,{signal:AbortSignal.timeout(t)});return n.ok&&(await n.json()).pid===s.pid?s:null}catch{return null}}function Mi(e,t){if(e===":memory:")return;const s=qt(e),n=`${s}.${process.pid}.tmp`;Vn(n,`${JSON.stringify(t,null,1)}
9
+ `,{mode:384}),Yn(n,s)}function Oi(e,t=process.pid){if(e===":memory:")return;const s=_n(e);s&&s.pid===t&&Qs(qt(e),{force:!0})}class Xt extends Error{constructor(t){super(`057 is already observing ${t.store} at ${t.url} (pid ${t.pid})`),this.record=t}record}const Ot={processDays:7,eventDays:90},Ri=["machine"],js=["process"],yt={processEvents:0,otherEvents:0,claims:0,subjects:0,retainedByDependents:0,processBefore:null,otherBefore:null},Ni=["execution","session","artifact"];function Cn(e=process.env){return{processDays:Ds(e.O57_RETAIN_PROCESS_DAYS,Ot.processDays),eventDays:Ds(e.O57_RETAIN_DAYS,Ot.eventDays)}}function Ds(e,t){if(e===void 0||e.trim()==="")return t;const s=Number(e);return Number.isFinite(s)&&s>=0?s:t}function ct(e){const t=(s,n)=>s===0?`${n} kept indefinitely`:`${n} ${s}d`;return`${t(e.processDays,"processes")}, ${t(e.eventDays,"sessions/executions")}, machines never expire`}const Ls=448,xi=384;function _i(){return D(Ee(),".057")}function ut(){const e=process.env.O57_STORE;return e&&e.length>0?e===":memory:"||eo(e)?e:qe(process.cwd(),e):D(_i(),"events.db")}function jn(){const e=process.env.O57_STORE;return typeof e=="string"&&e.length>0}function dt(e){return[e,`${e}-wal`,`${e}-shm`]}function Ci(e){if(e===":memory:")return;const t=to(e);zn(t,{recursive:!0,mode:Ls}),Dn(t,Ls)}function Rt(e){if(e===":memory:")return[];const t=[];for(const s of dt(e))if(F(s)&&!Dn(s,xi)){const n=Vt(s);n!==null&&(n&63)!==0&&t.push({path:s,mode:n})}return t}function Vt(e){try{return at(e).mode&511}catch{return null}}function Dn(e,t){if(process.platform==="win32")return!1;const s=Vt(e);if(s===null)return!1;if((s&~t)===0)return!0;try{return Kn(e,t),!0}catch{return!1}}function Ln(){if(jn())return null;const e=qe(process.cwd(),".057","events.db");return F(e)&&e!==ut()?e:null}const ji=`-- 057 local store.
8
10
  --
9
11
  -- \`events\` is the only durable truth. \`claims\` is denormalized out of events so identity
10
12
  -- resolution is one indexed read rather than a scan; it is rebuildable from events at any time.
@@ -55,33 +57,49 @@ CREATE TABLE IF NOT EXISTS claims (
55
57
  CREATE INDEX IF NOT EXISTS claims_key ON claims(key, valid_from, valid_to);
56
58
  CREATE INDEX IF NOT EXISTS claims_window ON claims(valid_to, valid_from);
57
59
  CREATE INDEX IF NOT EXISTS claims_event ON claims(event_id);
58
- `,ke=1;class pe extends Error{constructor(t,s,n){super(t),this.kind=s,this.remedy=n,this.name="StoreError"}kind;remedy}function tt(e){const t=e?.code;if(t==="EACCES"||t==="EPERM"||t==="EROFS")return!0;const s=e instanceof Error?e.message:String(e);return/readonly|read-only|attempt to write a readonly database|unable to open database file|permission denied|SQLITE_(READONLY|PERM|CANTOPEN)/i.test(s)}function st(e,t){const s=t instanceof Error?t.message:String(t);return new pe(`store ${e} cannot be written: ${s}`,"permission","The store itself looks intact — this is a permissions problem, not a corrupt file. Do NOT delete it. Check that you own the file and its directory and that both are writable (057 needs 0600 on the store and 0700 on its directory), or point O57_STORE at a writable path.")}function Jr(e){zr(e);let t;try{t=new pt(e)}catch(h){throw tt(h)?st(e,h):new pe(`cannot open the store at ${e}: ${h instanceof Error?h.message:String(h)}`,"unreadable","Check that the path exists and names a file 057 can open, or point O57_STORE elsewhere.")}let s;try{s=Number(t.prepare("PRAGMA user_version").get().user_version)}catch(h){throw t.close(),tt(h)?st(e,h):new pe(`store ${e} is not a readable database: ${h instanceof Error?h.message:String(h)}`,"unreadable","The file exists but is not a 057 store. Move it aside and 057 will start a new one; `057 reset` does that for you. Back it up first if it might be data you want.")}if(s>ke)throw t.close(),new pe(`store ${e} was written by a newer 057 (schema ${s}, this build understands ${ke})`,"future-schema","Upgrade 057, or point O57_STORE at a different file. The store was not modified.");try{t.exec(Kr);const h=new Set(t.prepare("PRAGMA table_info(events)").all().map(f=>String(f.name)));h.has("stratum")||t.exec("ALTER TABLE events ADD COLUMN stratum TEXT"),h.has("provenance")||t.exec("ALTER TABLE events ADD COLUMN provenance TEXT"),s!==ke&&t.exec(`PRAGMA user_version = ${ke}`)}catch(h){t.close();const f=h instanceof Error?h.message:String(h);throw tt(h)?st(e,h):new pe(`store ${e} could not be prepared: ${f}`,"unreadable","The file may be corrupt. Back it up, then move it aside and 057 will start a new store; `057 reset` does that for you.")}dt(e);const n=1e3,o=new Set,r=new Set;let a=null;const i=(h,f)=>{r.add(h),a??=Date.now(),o.size<n&&o.add(f)},c=h=>Zr(h,i),d=t.prepare(`INSERT OR IGNORE INTO events
60
+ `,je=1;class ve extends Error{constructor(t,s,n){super(t),this.kind=s,this.remedy=n,this.name="StoreError"}kind;remedy}function wt(e){const t=e?.code;if(t==="EACCES"||t==="EPERM"||t==="EROFS")return!0;const s=e instanceof Error?e.message:String(e);return/readonly|read-only|attempt to write a readonly database|unable to open database file|permission denied|SQLITE_(READONLY|PERM|CANTOPEN)/i.test(s)}function At(e,t){const s=t instanceof Error?t.message:String(t);return new ve(`store ${e} cannot be written: ${s}`,"permission","The store itself looks intact — this is a permissions problem, not a corrupt file. Do NOT delete it. Check that you own the file and its directory and that both are writable (057 needs 0600 on the store and 0700 on its directory), or point O57_STORE at a writable path.")}function Di(e){Ci(e);let t;try{t=new Ct(e)}catch(f){throw wt(f)?At(e,f):new ve(`cannot open the store at ${e}: ${f instanceof Error?f.message:String(f)}`,"unreadable","Check that the path exists and names a file 057 can open, or point O57_STORE elsewhere.")}let s;try{s=Number(t.prepare("PRAGMA user_version").get().user_version)}catch(f){throw t.close(),wt(f)?At(e,f):new ve(`store ${e} is not a readable database: ${f instanceof Error?f.message:String(f)}`,"unreadable","The file exists but is not a 057 store. Move it aside and 057 will start a new one; `057 reset` does that for you. Back it up first if it might be data you want.")}if(s>je)throw t.close(),new ve(`store ${e} was written by a newer 057 (schema ${s}, this build understands ${je})`,"future-schema","Upgrade 057, or point O57_STORE at a different file. The store was not modified.");try{t.exec(ji);const f=new Set(t.prepare("PRAGMA table_info(events)").all().map(p=>String(p.name)));f.has("stratum")||t.exec("ALTER TABLE events ADD COLUMN stratum TEXT"),f.has("provenance")||t.exec("ALTER TABLE events ADD COLUMN provenance TEXT"),s!==je&&t.exec(`PRAGMA user_version = ${je}`)}catch(f){t.close();const p=f instanceof Error?f.message:String(f);throw wt(f)?At(e,f):new ve(`store ${e} could not be prepared: ${p}`,"unreadable","The file may be corrupt. Back it up, then move it aside and 057 will start a new store; `057 reset` does that for you.")}Rt(e);const n=1e3,o=new Set,r=new Set;let a=null;const i=(f,p)=>{r.add(f),a??=Date.now(),o.size<n&&o.add(p)},c=f=>Fi(f,i),u=t.prepare(`INSERT OR IGNORE INTO events
59
61
  (id, source_id, source_instance, occurred_at, observed_at, clock, kind,
60
62
  subject_type, subject_id, core, attrs, basis, assumption, stratum, provenance)
61
- VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`),u=t.prepare(`INSERT INTO claims
63
+ VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`),h=t.prepare(`INSERT INTO claims
62
64
  (event_id, key, ns, subject_type, subject_id, source_id, valid_from, valid_to)
63
- VALUES (?,?,?,?,?,?,?,?)`),m=t.prepare("SELECT * FROM events WHERE occurred_at >= ? AND occurred_at <= ? ORDER BY occurred_at, id"),E=new Map,b=t.prepare(`SELECT key, ns, subject_type, subject_id, source_id, valid_from, valid_to
64
- FROM claims WHERE valid_from <= ? AND valid_to >= ?`),S={path:e,schemaVersion:ke,append(h){let f=0,v=0;t.exec("BEGIN");try{for(const l of h){if(d.run(l.id,l.source.id,l.source.instance,l.occurredAt,l.observedAt,l.clock,l.kind,l.subject.type,l.subject.id,l.core?JSON.stringify(l.core):null,l.attrs?JSON.stringify(l.attrs):null,l.basis,l.assumption??null,l.stratum??null,l.provenance?JSON.stringify(l.provenance):null).changes===0){v++;continue}f++;for(const g of l.claims??[])u.run(l.id,xn(g),g.ns,l.subject.type,l.subject.id,l.source.id,g.validFrom,g.validTo)}t.exec("COMMIT")}catch(l){throw t.exec("ROLLBACK"),l}return{inserted:f,duplicate:v}},query(h,f,v){if(!v||v.length===0)return m.all(h,f).map(c);const l=[...v].sort().join(",");let w=E.get(l);if(!w){const g=v.map(()=>"?").join(",");w=t.prepare(`SELECT * FROM events
65
- WHERE occurred_at >= ? AND occurred_at <= ? AND subject_type IN (${g})
66
- ORDER BY occurred_at, id`),E.set(l,w)}return w.all(h,f,...v).map(c)},claims(h,f){return b.all(f,h).map(v=>{const l=v;return{key:String(l.key),subjectType:l.subject_type,subjectId:String(l.subject_id),sourceId:String(l.source_id),validFrom:Number(l.valid_from),validTo:Number(l.valid_to)}})},stats(){const h=Number(t.prepare("SELECT COUNT(*) c FROM events").get().c),f=Number(t.prepare("SELECT COUNT(*) c FROM claims").get().c),v=t.prepare("SELECT MIN(occurred_at) lo, MAX(occurred_at) hi FROM events").get(),l=t.prepare(`SELECT source_id s, COUNT(*) c, MIN(occurred_at) lo, MAX(occurred_at) hi
67
- FROM events GROUP BY source_id ORDER BY s`).all().map(w=>{const g=w;return{source:String(g.s),events:Number(g.c),first:Number(g.lo),last:Number(g.hi)}});return{events:h,claims:f,bySource:l,earliest:v.lo,latest:v.hi}},begansFor(h){const f=[],v=t.prepare(`SELECT * FROM events
65
+ VALUES (?,?,?,?,?,?,?,?)`),m=t.prepare("SELECT * FROM events WHERE occurred_at >= ? AND occurred_at <= ? ORDER BY occurred_at, id"),k=new Map,b=t.prepare(`SELECT key, ns, subject_type, subject_id, source_id, valid_from, valid_to
66
+ FROM claims WHERE valid_from <= ? AND valid_to >= ?`),g={path:e,schemaVersion:je,append(f){let p=0,y=0;t.exec("BEGIN");try{for(const d of f){if(u.run(d.id,d.source.id,d.source.instance,d.occurredAt,d.observedAt,d.clock,d.kind,d.subject.type,d.subject.id,d.core?JSON.stringify(d.core):null,d.attrs?JSON.stringify(d.attrs):null,d.basis,d.assumption??null,d.stratum??null,d.provenance?JSON.stringify(d.provenance):null).changes===0){y++;continue}p++;for(const v of d.claims??[])h.run(d.id,po(v),v.ns,d.subject.type,d.subject.id,d.source.id,v.validFrom,v.validTo)}t.exec("COMMIT")}catch(d){throw t.exec("ROLLBACK"),d}return{inserted:p,duplicate:y}},query(f,p,y){if(!y||y.length===0)return m.all(f,p).map(c);const d=[...y].sort().join(",");let A=k.get(d);if(!A){const v=y.map(()=>"?").join(",");A=t.prepare(`SELECT * FROM events
67
+ WHERE occurred_at >= ? AND occurred_at <= ? AND subject_type IN (${v})
68
+ ORDER BY occurred_at, id`),k.set(d,A)}return A.all(f,p,...y).map(c)},claims(f,p){return b.all(p,f).map(y=>{const d=y;return{key:String(d.key),subjectType:d.subject_type,subjectId:String(d.subject_id),sourceId:String(d.source_id),validFrom:Number(d.valid_from),validTo:Number(d.valid_to)}})},stats(){const f=Number(t.prepare("SELECT COUNT(*) c FROM events").get().c),p=Number(t.prepare("SELECT COUNT(*) c FROM claims").get().c),y=t.prepare("SELECT MIN(occurred_at) lo, MAX(occurred_at) hi FROM events").get(),d=t.prepare(`SELECT source_id s, COUNT(*) c, MIN(occurred_at) lo, MAX(occurred_at) hi
69
+ FROM events GROUP BY source_id ORDER BY s`).all().map(A=>{const v=A;return{source:String(v.s),events:Number(v.c),first:Number(v.lo),last:Number(v.hi)}});return{events:f,claims:p,bySource:d,earliest:y.lo,latest:y.hi}},begansFor(f){const p=[],y=t.prepare(`SELECT * FROM events
68
70
  WHERE kind = 'began' AND subject_type = ? AND subject_id = ?
69
- ORDER BY occurred_at LIMIT 1`);for(const l of h){const w=l.indexOf(":");if(w<0)continue;const g=v.get(l.slice(0,w),l.slice(w+1));g&&f.push(c(g))}return f},subjectEvents(h,f){return t.prepare("SELECT * FROM events WHERE subject_type = ? AND subject_id = ? ORDER BY occurred_at, id").all(h,f).map(c)},latestFor(h){return t.prepare("SELECT MAX(occurred_at) hi FROM events WHERE source_id = ?").get(h)?.hi??null},sweep(h=ut,f=Date.now()){const v=h.processDays>0?f-h.processDays*864e5:null,l=h.eventDays>0?f-h.eventDays*864e5:null;if(v===null&&l===null)return{...et};const w=N=>Gr.includes(N)?null:ds.includes(N)?v:l,g=t.prepare(`SELECT subject_type t, subject_id i, MAX(occurred_at) last
70
- FROM events GROUP BY subject_type, subject_id`).all().map(N=>{const _=N;return{type:String(_.t),id:String(_.i),last:Number(_.last)}}),y=(N,_)=>`${N}:${_}`,M=new Set,p=new Map;for(const N of g){const _=w(N.type);_===null||N.last>=_?M.add(y(N.type,N.id)):p.set(y(N.type,N.id),{type:N.type,id:N.id})}if(p.size===0)return{...et,processBefore:v,otherBefore:l};const A=[...qr],I=t.prepare(`SELECT DISTINCT core FROM events
71
- WHERE subject_type = ? AND subject_id = ? AND core IS NOT NULL`),k=new Set(A);let T=[...M].filter(N=>k.has(N.slice(0,N.indexOf(":"))));const O=new Set(T);let $=0;for(let N=0;N<4&&T.length>0;N++){const _=[];for(const te of T){const Ee=te.indexOf(":");for(const ln of I.all(te.slice(0,Ee),te.slice(Ee+1))){const Mt=Pe(ln.core);if(Mt)for(const[pn,Ot]of[["sessionId","session"],["parentId","session"],["parentId","execution"]]){const $t=Mt[pn];if(typeof $t!="string")continue;const ge=y(Ot,$t);p.has(ge)&&(p.delete(ge),M.add(ge),$++,!O.has(ge)&&k.has(Ot)&&(O.add(ge),_.push(ge)))}}}T=_}if(p.size===0)return{...et,retainedByDependents:$,processBefore:v,otherBefore:l};const x=t.prepare(`DELETE FROM claims WHERE event_id IN
72
- (SELECT id FROM events WHERE subject_type = ? AND subject_id = ?)`),L=t.prepare("DELETE FROM events WHERE subject_type = ? AND subject_id = ?");let D=0,U=0,K=0;t.exec("BEGIN");try{for(const{type:N,id:_}of p.values()){K+=Number(x.run(N,_).changes);const te=Number(L.run(N,_).changes);ds.includes(N)?D+=te:U+=te}t.exec("COMMIT")}catch(N){throw t.exec("ROLLBACK"),N}return D+U>0&&S.checkpoint(),{processEvents:D,otherEvents:U,claims:K,subjects:p.size,retainedByDependents:$,processBefore:v,otherBefore:l}},checkpoint(){try{t.exec("PRAGMA wal_checkpoint(TRUNCATE)")}catch{}},sizeBytes(){const[h,f,v]=Ve(e).map(Qr);return{db:h,wal:f,shm:v,total:h+f+v}},health(){const h=o.size;return h===0?{ok:!0,malformedRows:0,columns:[],since:null}:{ok:!1,malformedRows:h,columns:[...r].sort(),since:a,remedy:`${h} stored row(s) could not be read as JSON and lost their ${[...r].sort().join("/")} channel. Everything else is being used normally and nothing has been deleted. Run \`057 compact\` to rewrite the store; if the count keeps growing, back the store up and run \`057 reset\` to start a new one.`}},compact(){t.exec("VACUUM"),S.checkpoint(),dt(e)},close(){S.checkpoint(),t.close()}};return S}function Qr(e){try{return Ge(e).size}catch{return 0}}function Pe(e,t,s){if(e!=null)try{const n=JSON.parse(String(e));if(n&&typeof n=="object")return n;t&&s?.(t);return}catch{t&&s?.(t);return}}function Zr(e,t){const s=e,n=t?o=>t(o,String(s.id)):void 0;return{id:String(s.id),source:{id:String(s.source_id),instance:String(s.source_instance)},occurredAt:Number(s.occurred_at),observedAt:Number(s.observed_at),clock:s.clock,kind:s.kind,subject:{type:s.subject_type,id:String(s.subject_id)},core:Pe(s.core,"core",n),attrs:Pe(s.attrs,"attrs",n),basis:s.basis,assumption:s.assumption?String(s.assumption):void 0,stratum:s.stratum?s.stratum:void 0,provenance:Pe(s.provenance,"provenance",n)}}const le="os",ei=(e,t)=>`os:${e}:${t.pid}:${t.startedAt}`,ti=e=>`The process was present in one ${Math.round(e/1e3)}s snapshot and absent from the next, so it exited somewhere in that window. The recorded instant is the last moment it was observed alive — a lower bound on the true exit. A process that started and exited entirely within one interval is never observed at all.`,si=250,ni=8*1024*1024;function oi(e,t,s){const n={source:{id:le,instance:s.host},observedAt:s.observedAt,clock:"wall",stratum:"machine"},o=[],r=new Map;for(const a of t){const i=ei(s.host,a);r.set(i,a);const c={ns:"os.process",parts:[s.host,a.pid],validFrom:a.startedAt,validTo:s.observedAt};if(!e.has(i)){o.push({...n,occurredAt:a.startedAt,kind:"began",subject:{type:"process",id:i},claims:[c],basis:"measured",core:{machineId:s.machineId,label:ri(a.command),executor:a.command,measures:{[R.cpuMs]:a.cpuMs}},attrs:{"os.pid":a.pid,"os.ppid":a.ppid,"os.command":a.command,"os.rssBytes":a.rssBytes}});continue}const d=e.get(i),u=a.cpuMs-d.cpuMs>=si,m=Math.abs(a.rssBytes-d.rssBytes)>=ni;(u||m)&&o.push({...n,occurredAt:s.observedAt,seq:`obs:${s.observedAt}`,kind:"observed",subject:{type:"process",id:i},claims:[c],basis:"measured",core:{measures:{[R.cpuMs]:a.cpuMs}},attrs:{"os.rssBytes":a.rssBytes}})}for(const[a,i]of e)r.has(a)||o.push({...n,occurredAt:s.observedAt-s.intervalMs,kind:"ended",subject:{type:"process",id:a},basis:"inferred",assumption:ti(s.intervalMs),core:{outcome:"completed",measures:{[R.cpuMs]:i.cpuMs}},attrs:{"os.pid":i.pid}});return{envelopes:o,next:r}}function ri(e){return(e.split("/").pop()??e).toUpperCase()}const ii=Rn($n);function ai(){return Es().replace(/\.local$/i,"")}function ci(e){const t=[];for(const s of e.split(`
73
- `)){const n=s.trim();if(!n)continue;const o=n.match(/^(\d+)\s+(\d+)\s+(\w{3}\s+\w{3}\s+\d+\s+[\d:]+\s+\d{4})\s+([\d:.]+)\s+(\d+)\s+(.*)$/);if(!o)continue;const[,r,a,i,c,d,u]=o,m=Date.parse(i);Number.isFinite(m)&&t.push({pid:Number(r),ppid:Number(a),startedAt:m,cpuMs:ui(c),rssBytes:Number(d)*1024,command:u.trim()})}return t}function ui(e){const[t,s]=e.includes("-")?e.split("-"):["0",e],n=s.split(":").map(Number);let o=0;for(const r of n)o=o*60+(Number.isFinite(r)?r:0);return Math.round((o+Number(t)*86400)*1e3)}async function di(){const{stdout:e}=await ii("ps",["-Ao","pid=,ppid=,lstart=,time=,rss=,comm="],{maxBuffer:8388608});return ci(e)}const fs=5e3;function li(e,t){const s=ai();let n=new Map,o=null,r=0,a=null,i,c=!1;async function d(){if(c)return[];c=!0;try{const u=Date.now(),m=await di(),{envelopes:E,next:b}=oi(n,m,{machineId:t,host:s,observedAt:u,intervalMs:fs}),S=E.map(ee);return e.append(S),n=b,r++,a=u,i=void 0,S}catch(u){return i=u instanceof Error?u.message:String(u),[]}finally{c=!1}}return{sample:d,start(){o||(d(),o=setInterval(()=>{d()},fs),o.unref?.())},stop(){o&&clearInterval(o),o=null},get running(){return o!==null},stats(){return{samples:r,tracked:n.size,lastSampleAt:a,lastError:i}}}}const cn={info:e=>console.log(e),warn:e=>console.warn(e),error:e=>console.error(e)},pi=36e5,fi=15e3,mi=3;function Et(e={}){const t=e.log??cn,s=e.path??Ye(),n=e.retention??nn(),o=Jr(s),r=o.stats();t.info(r.events>0?`[057] store ${s}: opened with ${r.events} events`:`[057] store ${s}: NEW EMPTY STORE — if history existed before, it was lost, not carried`);const a=an();a&&t.warn(`[057] a store from a previous layout exists at ${a} and is NOT in use. Run 057 with O57_STORE=${a} to keep using it, or move it to ${s}.`);const i=he();o.append([ee({source:{id:"host",instance:i.id},occurredAt:0,observedAt:Date.now(),clock:"wall",kind:"began",stratum:"machine",subject:{type:"machine",id:i.id},basis:"measured",core:{machineName:i.name,machineKind:i.kind},seq:"host"})]);const c=li(o,i.id),d=new Map;function u(l){for(const w of l){const g=d.get(w.id)??{consecutiveFailures:0,totalFailures:0,failing:!1};w.ok?(g.consecutiveFailures=0,g.failing=!1,g.lastSuccessAt=Date.now()):(g.consecutiveFailures++,g.totalFailures++,g.lastFailureAt=Date.now(),g.lastError=w.error,g.consecutiveFailures>=mi&&!g.failing&&(g.failing=!0,t.warn(`[057] source ${w.id} has failed ${g.consecutiveFailures} collection rounds in a row: ${w.error??"unknown error"}`))),d.set(w.id,g)}}const m=ms(s);let E=null;function b(l){return E||(E=l,t.error(`[057] ${l.message} — ${l.remedy}`),c.stop()),E}function S(){if(E)return E;if(s===":memory:")return null;if(!F(s))return b({kind:"unlinked",message:`the store at ${s} no longer exists on disk; captured events are going to an orphaned file and will be lost`,remedy:"Stop 057 and start it again. It will open a new store at the same path.",since:Date.now()});const l=ms(s);return m!==null&&l!==null&&l!==m?b({kind:"replaced",message:`the store at ${s} was replaced by a different file while 057 was running; captured events are going to the old one`,remedy:"Stop 057 and start it again so it opens the file that is actually there.",since:Date.now()}):null}e.observe!==!1&&c.start();const h=o.sweep(n);h.processEvents+h.otherEvents>0&&t.info(`[057] retention: removed ${h.processEvents} process and ${h.otherEvents} semantic events (${qe(n)})`);const f=setInterval(()=>{if(!E)try{o.sweep(n),dt(s)}catch(l){t.warn(`[057] retention sweep failed: ${String(l)}`)}},pi);f.unref?.();const v=setInterval(()=>{S()},fi);return v.unref?.(),{store:o,machine:i,os:c,path:s,retention:n,fault:()=>E,sweep:l=>o.sweep(n,l),checkStore:S,recordCollection:u,collectionHealth:()=>Object.fromEntries(d),stop(){clearInterval(f),clearInterval(v),c.stop(),o.close()}}}function ms(e){try{return Ge(e).ino}catch{return null}}const lt=[{id:ks,collect:(e,t)=>Qn(e,t)},{id:ot,collect:(e,t)=>po(e,t)},{id:Ae,collect:(e,t)=>Ao(e,t)},{id:De,collect:(e,t)=>Ro(e,t)},{id:Oe,collect:(e,t)=>Lo(e,t)},{id:Le,collect:(e,t)=>qo(e,t)}],hs=[...lt.map(e=>e.id),le],gs=10*365*24*36e5,je=2e5,hi=24*36e5,gi=72*36e5;function bs(e){const t=new Date(e);return t.setHours(0,0,0,0),{from:t.getTime(),to:e}}function vs(e){const t=e.collectionHealth(),s=Object.entries(t).filter(([,i])=>i.failing).map(([i])=>i),n=e.store.health(),o=e.os.stats(),r=e.fault();let a=null;for(const i of Object.values(t))i.lastSuccessAt&&(a===null||i.lastSuccessAt>a)&&(a=i.lastSuccessAt);return{ok:s.length===0&&n.ok&&!r&&!o.lastError,fault:r??void 0,failingSources:s,errors:Object.fromEntries(Object.entries(t).filter(([,i])=>i.failing).map(([i,c])=>[i,c.lastError??"failing"])),store:{ok:n.ok,remedy:n.remedy},os:{running:e.os.running,lastSampleAt:o.lastSampleAt,lastError:o.lastError},lastCollectionAt:a,sources:{total:hs.length,reported:hs.filter(i=>t[i]!==void 0).length}}}function bi(e,t,s){const n=t.startsWith("/api/");if(s){const i=(e.headers.host??"").toLowerCase(),c=i.startsWith("[")?i.slice(0,i.indexOf("]")+1):i.split(":")[0];if(!s.includes(c))return`refusing a request for host "${i}"; 057 answers only on ${s.join(", ")}`}const o=e.headers.origin;if(typeof o=="string"&&o!=="null"){const i=(e.headers.host??"").toLowerCase();let c="";try{c=new URL(o).host.toLowerCase()}catch{return"refusing a request with an unparseable Origin"}if(c!==i)return`refusing a cross-origin request from ${o}`}const r=e.headers["sec-fetch-site"],a=String(e.headers["sec-fetch-dest"]??"");if(yi.has(a))return`refusing to be embedded as ${a}`;if(typeof r=="string"&&r!==""){if(r!=="same-origin"&&r!=="none")return`refusing a ${r} request`;if(r==="none"&&n)return"refusing a directly-navigated API request"}else if(n&&t==="/api/collect"&&!e.headers[vi])return"refusing a state-changing request that carries no fetch metadata";return null}const vi="x-057-client",yi=new Set(["iframe","frame","embed","object","fencedframe"]);function kt(e){e.setHeader("x-frame-options","DENY"),e.setHeader("content-security-policy","frame-ancestors 'none'")}function wi(e,t){const s=(r,a)=>{const i=e.get(r);if(i===null||i==="")return a;const c=Number(i);return Number.isSafeInteger(c)?c:null},n=s("from",t-864e5),o=s("to",t);return n===null||o===null?{error:"from and to must be integer epoch millis"}:o<n?{error:"to must not precede from"}:o>t+hi?{error:"to is too far in the future"}:o-n>gs?{error:`window must not exceed ${gs} ms`}:{from:n,to:o}}function B(e,t,s){e.statusCode=t,e.setHeader("content-type","application/json"),e.setHeader("cache-control","no-store"),e.setHeader("x-content-type-options","nosniff"),kt(e),e.end(JSON.stringify(s))}function un(e,t,s,n){const o=e.query(t,s,n),r=new Set,a=new Set,i=u=>{const m=`${u.subject.type}:${u.subject.id}`;u.kind==="began"?r.add(m):a.add(m),u.core?.sessionId&&a.add(`session:${u.core.sessionId}`),u.core?.machineId&&a.add(`machine:${u.core.machineId}`)};for(const u of o)i(u);const c=[];for(let u=0;u<4;u++){const m=[...a].filter(b=>!r.has(b));if(m.length===0)break;const E=e.begansFor(m);if(E.length===0)break;for(const b of E)c.push(b.occurredAt<t?{...b,occurredAt:t}:b),i(b),r.add(`${b.subject.type}:${b.subject.id}`)}return{events:[...c,...o].sort((u,m)=>u.occurredAt-m.occurredAt||ys(u)-ys(m)),relationships:Bn(e,t,s).relationships}}function Ie(e,t,s){const n=performance.now(),{events:o,relationships:r}=un(e,t,s),a=performance.now()-n,i=performance.now(),c=Ks(t,s);er(c,o),tr(c,s);const d=performance.now()-i,u=performance.now(),m=or(c,r),E=performance.now()-u;return{world:m,meta:{events:o.length,readMs:Math.round(a*10)/10,deriveMs:Math.round(d*10)/10,serializeMs:Math.round(E*10)/10}}}function ys(e){if(e.kind==="ended")return 5;switch(e.subject.type){case"machine":return 0;case"session":return 1;case"execution":case"process":return e.kind==="began"?2:3;default:return 4}}function Ai(e){const t=e.problems.filter(s=>s.path.includes("/sessions/")).length;return{identity:e.identityAvailable?t===0?"available":e.registryEntries>0?"partial":"failed":"unavailable","stored-semantics":e.storedAvailable?e.transcriptsFailed===0?"available":e.transcriptsRead>0?"partial":"failed":"unavailable","live-semantics":"unavailable"}}function nt(e){return{"stored-semantics":e.storedAvailable?e.failed===0?"available":e.read>0?"partial":"failed":"unavailable","live-semantics":"unavailable"}}function Si(e){return e.error?"failed":e.available?"observing":e.present?"installed-no-data":"not-installed"}function Ei(e){const t=e.home??e.globalStorage;if(typeof t=="string")return t;const s=e.roots;return Array.isArray(s)?s.join(", "):void 0}function de(e){return{available:e.available,present:e.present??!1,presence:Si(e),origin:Ei(e),error:e.error}}function ki(e){const{runtime:t,log:s}=e;let n=null;function o(r){if(!n||r-n.at>6e4){const a=bs(r),i=Jt(Ie(t.store,a.from,a.to).world);n={at:r,label:"TODAY",world:i,landscape:as(i)}}return n}return async function(a,i){const c=a.url??"";if(!c.startsWith("/api/"))return!1;const d=new URL(c,"http://localhost"),u=bi(a,d.pathname,e.allowedHosts);if(u)return s.warn(`[057] ${u}`),B(i,403,{error:u}),!0;const m=t.store,E=Date.now(),b=wi(d.searchParams,E);if("error"in b)return B(i,400,{error:b.error}),!0;const{from:S,to:h}=b;try{if(d.pathname==="/api/state"){const[f,v,l,w,g,y]=await Promise.all([_t().catch(_=>({available:!1,error:String(_)})),Lt().catch(_=>({available:!1,error:String(_)})),Pt().catch(_=>({available:!1,error:String(_)})),Ht().catch(_=>({available:!1,error:String(_)})),qt().catch(_=>({available:!1,error:String(_)})),Vt().catch(_=>({available:!1,error:String(_)}))]),[M,p,A,I]=await Promise.all([Cs(S,h).catch(()=>null),Ls(S,h).catch(()=>null),Bs(S,h).catch(()=>null),Gs(S,h).catch(()=>null)]),k={strata:{"stored-semantics":"failed"}},T={"claude-code":M?{strata:Ai(M),registryEntries:M.registryEntries,transcriptsRead:M.transcriptsRead,transcriptsFailed:M.transcriptsFailed,problems:M.problems.slice(0,20)}:{strata:{identity:"failed"}},codex:p?{strata:nt({storedAvailable:p.storedAvailable,read:p.rolloutsRead,failed:p.rolloutsFailed}),rolloutsRead:p.rolloutsRead,rolloutsFailed:p.rolloutsFailed,problems:p.problems.slice(0,20)}:k,cursor:A?{strata:nt({storedAvailable:A.storedAvailable,read:A.composersRead,failed:A.composersFailed}),composersRead:A.composersRead,composersFailed:A.composersFailed,problems:A.problems.slice(0,20)}:k,gemini:I?{strata:nt({storedAvailable:I.storedAvailable,read:I.sessionsRead,failed:I.sessionsFailed}),sessionsRead:I.sessionsRead,sessionsFailed:I.sessionsFailed,problems:I.problems.slice(0,20)}:k},O={deepseek:de(f),"0x2f":de(v),"claude-code":de(l),codex:de(w),cursor:de(g),gemini:de(y)},$=t.collectionHealth();for(const[_,te]of Object.entries(O)){const Ee=$[_];Ee?.failing&&(te.presence="failed",te.error??=Ee.lastError)}const x=t.os.stats(),D=Object.values(O).filter(_=>_.available).length>0?"observing":x.samples>0?"os-only":"empty",U=Object.entries($).filter(([,_])=>_.failing).map(([_])=>_),K=m.health(),N={ok:U.length===0&&K.ok&&!t.fault()&&!x.lastError,failingSources:U,collection:$,store:K,os:x.lastError?{failing:!0,lastError:x.lastError}:{failing:!1}};return B(i,200,{machine:t.machine,mode:D,fault:t.fault()??void 0,health:N,store:{...m.stats(),path:m.path,schemaVersion:m.schemaVersion,bytes:m.sizeBytes(),retention:{...t.retention,description:qe(t.retention)}},os:{...x,running:t.os.running,source:le},sources:O,observation:T}),!0}if(d.pathname==="/api/collect"){const f=t.checkStore();if(f)return B(i,503,{error:f.message,fault:f}),!0;const v=await Pn(m,lt,S,h,w=>t.recordCollection([w])),l=await t.os.sample();return t.recordCollection([{id:le,ok:!t.os.stats().lastError,error:t.os.stats().lastError}]),B(i,200,{...v,sources:[...v.sources,{id:le,ok:!t.os.stats().lastError,collected:l.length,inserted:l.length,duplicate:0,error:t.os.stats().lastError,ms:0}]}),!0}if(d.pathname==="/api/world")return B(i,200,{from:S,to:h,now:E,...Ie(m,S,h)}),!0;if(d.pathname==="/api/health")return B(i,200,{pid:process.pid,version:e.version??"dev",contract:yt,store:t.path,health:vs(t)}),!0;if(d.pathname==="/api/landscape"){let f={from:S,to:h},v="WINDOW",l;if(d.searchParams.get("window")==="live"){if(f=bs(E),v="TODAY",l=Ie(m,f.from,f.to),l.world.executions.length===0&&l.world.sessions.length===0){const y={from:E-gi,to:E},M=Ie(m,y.from,y.to);(M.world.executions.length>0||M.world.sessions.length>0)&&(f=y,v="LAST 72H",l=M)}}else l=Ie(m,S,h);const w=Jt(l.world),g=as(w);return d.searchParams.get("window")==="live"&&(n={at:E,label:v,world:w,landscape:g}),B(i,200,{...f,now:E,window:v,meta:l.meta,health:vs(t),...br(g)}),!0}if(d.pathname==="/api/today"||d.pathname==="/api/log"){const f=o(E);return B(i,200,d.pathname==="/api/today"?{window:f.label,...Ur(f.world)}:{window:f.label,...Pr(f.world,f.landscape)}),!0}if(d.pathname==="/api/inspect"){const f=d.searchParams.get("kind")??"",v=d.searchParams.get("id")??"";if(!["disturbance","stratum","mass","coupling"].includes(f)||!v||v.length>512)return B(i,400,{error:"inspect needs kind=disturbance|stratum|mass|coupling and an id"}),!0;if(o(E),!n)return!0;const l=(g,y)=>{for(const M of m.subjectEvents(g,y))if(M.provenance?.path)return M.provenance.path},w=yr(n.world,n.landscape,f,v,l);return w?(B(i,200,w),!0):(B(i,404,{error:"not in the current world"}),!0)}if(d.pathname==="/api/sources"){const f=await Promise.all([_t().catch(g=>({available:!1,error:String(g)})),Lt().catch(g=>({available:!1,error:String(g)})),Pt().catch(g=>({available:!1,error:String(g)})),Ht().catch(g=>({available:!1,error:String(g)})),qt().catch(g=>({available:!1,error:String(g)})),Vt().catch(g=>({available:!1,error:String(g)}))]),v=t.collectionHealth(),l=t.os.stats(),w=lt.map((g,y)=>{const M=de(f[y]),p=v[g.id];return{id:g.id,presence:p?.failing?"failed":M.presence,origin:M.origin,error:p?.failing?p.lastError??M.error:M.error,consecutiveFailures:p?.consecutiveFailures??0,lastSuccessAt:p?.lastSuccessAt}});return w.push({id:le,presence:l.lastError?"failed":l.samples>0?"observing":"installed-no-data",origin:void 0,error:l.lastError,consecutiveFailures:v[le]?.consecutiveFailures??0,lastSuccessAt:l.lastSampleAt??void 0}),B(i,200,{sources:w}),!0}if(d.pathname==="/api/detail"){const f=d.searchParams.get("type")??"",v=d.searchParams.get("id")??"";if(!Rt.includes(f)||!v)return B(i,400,{error:"detail needs type=<entity type> and id"}),!0;if(v.length>512)return B(i,400,{error:"id is too long"}),!0;const l=m.subjectEvents(f,v);return B(i,200,{type:f,id:v,events:l.slice(0,je),truncated:l.length>je}),!0}if(d.pathname==="/api/events"){const f=d.searchParams.get("subject"),v=f?f.split(",").filter(w=>Rt.includes(w)):void 0,l=un(m,S,h,v);return B(i,200,{from:S,to:h,now:E,events:l.events.slice(0,je),truncated:l.events.length>je,relationships:l.relationships}),!0}return B(i,404,{error:"unknown endpoint"}),!0}catch(f){return s.error(`[057] ${String(f)}`),B(i,500,{error:String(f)}),!0}}}const It=5057,ae="127.0.0.1",Ii=["localhost","127.0.0.1","[::1]","::1"],Ti=10,Mi={".html":"text/html; charset=utf-8",".js":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".json":"application/json; charset=utf-8",".svg":"image/svg+xml",".woff2":"font/woff2",".png":"image/png",".ico":"image/vnd.microsoft.icon"};function ws(e,t,s){let n;try{n=decodeURIComponent(t)}catch{return!1}if(n.includes("\0"))return!1;const o=Re(e,`.${En(n)}`);if(o!==e&&!o.startsWith(e+kn)||!F(o)||!Ge(o).isFile())return!1;const r=Mi[In(o).toLowerCase()]??"application/octet-stream";return s.statusCode=200,s.setHeader("content-type",r),s.setHeader("x-content-type-options","nosniff"),kt(s),s.setHeader("cache-control",t.startsWith("/assets/")?"public, max-age=31536000, immutable":"no-store"),vn(o).pipe(s),!0}function Oi(e,t,s,n){return new Promise((o,r)=>{let a=n,i=t;const c=d=>{if(d.code==="EADDRINUSE"&&a>1){a--,i++,e.listen(i,s);return}e.off("error",c),r(d)};e.on("error",c),e.once("listening",()=>{e.off("error",c);const d=e.address();o(typeof d=="object"&&d?d.port:i)}),e.listen(i,s)})}function $i(e,t){const s=String(e.headers["sec-fetch-dest"]??"");if(Ri.has(s))return`refusing to be embedded as ${s}`;const n=e.headers["sec-fetch-site"];return typeof n=="string"&&n!==""&&n!=="same-origin"&&n!=="none"?`refusing a ${n} request for ${t}`:null}const Ri=new Set(["iframe","frame","embed","object","fencedframe"]);async function dn(e){const t=e.log??cn,s=Re(e.root),n=e.host??ae,o=n===ae||n==="::1"||n==="localhost",r=e.runtime?.path??e.storePath??Ye();if(!e.runtime){const m=await Hr(r);if(m)throw new At(m)}const a=e.runtime??Et({path:e.storePath,log:t,retention:e.retention,observe:e.observe}),i=ki({runtime:a,log:t,version:e.version,allowedHosts:o?Ii:null}),c=wn((m,E)=>{(async()=>{try{if(await i(m,E))return;if(m.method!=="GET"&&m.method!=="HEAD"){E.statusCode=405,E.setHeader("allow","GET, HEAD"),E.end();return}const b=new URL(m.url??"/","http://localhost").pathname,S=$i(m,b);if(S){t.warn(`[057] ${S}`),E.statusCode=403,E.setHeader("content-type","text/plain; charset=utf-8"),kt(E),E.end(`${S}
74
- `);return}if(ws(s,b==="/"?"/index.html":b,E)||!b.startsWith("/assets/")&&ws(s,"/index.html",E))return;E.statusCode=404,E.setHeader("content-type","text/plain; charset=utf-8"),E.end(`not found
75
- `)}catch(b){t.error(`[057] request failed: ${String(b)}`),E.headersSent||(E.statusCode=500),E.end()}})()}),d=await Oi(c,e.port??It,n,Ti).catch(m=>{throw a.stop(),m}),u=o?"localhost":n;return Wr(a.path,{pid:process.pid,url:`http://${o?ae:n}:${d}`,version:e.version??"dev",contract:yt,store:a.path,startedAt:Date.now(),owner:e.owner??"cli"}),{url:`http://${u}:${d}`,port:d,host:n,runtime:a,server:c,close(){return new Promise(m=>{Xr(a.path),c.close(()=>{a.stop(),m()}),c.closeAllConnections?.()})}}}function xi(e){return Re(Tn(new URL(".",e)),"..","dist")}const $e="1.0.0";function Ni(e){const t={command:"serve",open:!1,yes:!1,desktop:!1},s=[...e],n=s[0];if(n&&!n.startsWith("-"))if(n==="status"||n==="compact"||n==="reset")t.command=n,s.shift();else return{...t,command:"help",error:`unknown command: ${n}`};for(;s.length;){const o=s.shift(),[r,a]=o.includes("=")?_i(o,"="):[o,void 0],i=()=>a??s.shift();switch(r){case"-h":case"--help":t.command="help";break;case"-v":case"--version":t.command="version";break;case"--open":t.open=!0;break;case"--yes":case"-y":t.yes=!0;break;case"--desktop":t.desktop=!0;break;case"--port":{const c=i(),d=Number(c);if(!Number.isInteger(d)||d<0||d>65535)return{...t,command:"help",error:`--port needs a port number, got ${c}`};t.port=d;break}case"--host":{const c=i();if(!c)return{...t,command:"help",error:"--host needs a value"};t.host=c;break}case"--store":{const c=i();if(!c)return{...t,command:"help",error:"--store needs a path"};t.store=c;break}default:return{...t,command:"help",error:`unknown option: ${r}`}}}return t}function _i(e,t){const s=e.indexOf(t);return[e.slice(0,s),e.slice(s+1)]}const Ci=`057 — a spatial interface for observing the shape of a computational workday
71
+ ORDER BY occurred_at LIMIT 1`);for(const d of f){const A=d.indexOf(":");if(A<0)continue;const v=y.get(d.slice(0,A),d.slice(A+1));v&&p.push(c(v))}return p},subjectEvents(f,p){return t.prepare("SELECT * FROM events WHERE subject_type = ? AND subject_id = ? ORDER BY occurred_at, id").all(f,p).map(c)},latestFor(f){return t.prepare("SELECT MAX(occurred_at) hi FROM events WHERE source_id = ?").get(f)?.hi??null},sweep(f=Ot,p=Date.now()){const y=f.processDays>0?p-f.processDays*864e5:null,d=f.eventDays>0?p-f.eventDays*864e5:null;if(y===null&&d===null)return{...yt};const A=j=>Ri.includes(j)?null:js.includes(j)?y:d,v=t.prepare(`SELECT subject_type t, subject_id i, MAX(occurred_at) last
72
+ FROM events GROUP BY subject_type, subject_id`).all().map(j=>{const x=j;return{type:String(x.t),id:String(x.i),last:Number(x.last)}}),w=(j,x)=>`${j}:${x}`,$=new Set,l=new Map;for(const j of v){const x=A(j.type);x===null||j.last>=x?$.add(w(j.type,j.id)):l.set(w(j.type,j.id),{type:j.type,id:j.id})}if(l.size===0)return{...yt,processBefore:y,otherBefore:d};const S=[...Ni],E=t.prepare(`SELECT DISTINCT core FROM events
73
+ WHERE subject_type = ? AND subject_id = ? AND core IS NOT NULL`),T=new Set(S);let I=[...$].filter(j=>T.has(j.slice(0,j.indexOf(":"))));const N=new Set(I);let C=0;for(let j=0;j<4&&I.length>0;j++){const x=[];for(const G of I){const K=G.indexOf(":");for(const qn of E.all(G.slice(0,K),G.slice(K+1))){const Jt=Ze(qn.core);if(Jt)for(const[Xn,Qt]of[["sessionId","session"],["parentId","session"],["parentId","execution"]]){const Zt=Jt[Xn];if(typeof Zt!="string")continue;const $e=w(Qt,Zt);l.has($e)&&(l.delete($e),$.add($e),C++,!N.has($e)&&T.has(Qt)&&(N.add($e),x.push($e)))}}}I=x}if(l.size===0)return{...yt,retainedByDependents:C,processBefore:y,otherBefore:d};const _=t.prepare(`DELETE FROM claims WHERE event_id IN
74
+ (SELECT id FROM events WHERE subject_type = ? AND subject_id = ?)`),R=t.prepare("DELETE FROM events WHERE subject_type = ? AND subject_id = ?");let O=0,U=0,q=0;t.exec("BEGIN");try{for(const{type:j,id:x}of l.values()){q+=Number(_.run(j,x).changes);const G=Number(R.run(j,x).changes);js.includes(j)?O+=G:U+=G}t.exec("COMMIT")}catch(j){throw t.exec("ROLLBACK"),j}return O+U>0&&g.checkpoint(),{processEvents:O,otherEvents:U,claims:q,subjects:l.size,retainedByDependents:C,processBefore:y,otherBefore:d}},checkpoint(){try{t.exec("PRAGMA wal_checkpoint(TRUNCATE)")}catch{}},sizeBytes(){const[f,p,y]=dt(e).map(Li);return{db:f,wal:p,shm:y,total:f+p+y}},health(){const f=o.size;return f===0?{ok:!0,malformedRows:0,columns:[],since:null}:{ok:!1,malformedRows:f,columns:[...r].sort(),since:a,remedy:`${f} stored row(s) could not be read as JSON and lost their ${[...r].sort().join("/")} channel. Everything else is being used normally and nothing has been deleted. Run \`057 compact\` to rewrite the store; if the count keeps growing, back the store up and run \`057 reset\` to start a new one.`}},compact(){t.exec("VACUUM"),g.checkpoint(),Rt(e)},close(){g.checkpoint(),t.close()}};return g}function Li(e){try{return at(e).size}catch{return 0}}function Ze(e,t,s){if(e!=null)try{const n=JSON.parse(String(e));if(n&&typeof n=="object")return n;t&&s?.(t);return}catch{t&&s?.(t);return}}function Fi(e,t){const s=e,n=t?o=>t(o,String(s.id)):void 0;return{id:String(s.id),source:{id:String(s.source_id),instance:String(s.source_instance)},occurredAt:Number(s.occurred_at),observedAt:Number(s.observed_at),clock:s.clock,kind:s.kind,subject:{type:s.subject_type,id:String(s.subject_id)},core:Ze(s.core,"core",n),attrs:Ze(s.attrs,"attrs",n),basis:s.basis,assumption:s.assumption?String(s.assumption):void 0,stratum:s.stratum?s.stratum:void 0,provenance:Ze(s.provenance,"provenance",n)}}const be="os",Ui=(e,t)=>`os:${e}:${t.pid}:${t.startedAt}`;function Pi(e,t){const s=/^os:[^:]+:(\d+):(\d+)$/.exec(e);return s?`os:${t}:${s[1]}:${s[2]}`:void 0}const Bi=e=>`The process was present in one ${Math.round(e/1e3)}s snapshot and absent from the next, so it exited somewhere in that window. The recorded instant is the last moment it was observed alive — a lower bound on the true exit. A process that started and exited entirely within one interval is never observed at all.`,Hi=250,Wi=8*1024*1024;function qi(e,t,s){const n={source:{id:be,instance:s.host},observedAt:s.observedAt,clock:"wall",stratum:"machine"},o=[],r=new Map;for(const a of t){const i=Ui(s.host,a);r.set(i,a);const c={ns:"os.process",parts:[s.host,a.pid],validFrom:a.startedAt,validTo:s.observedAt};if(!e.has(i)){o.push({...n,occurredAt:a.startedAt,kind:"began",subject:{type:"process",id:i},claims:[c],basis:"measured",core:{machineId:s.machineId,label:Xi(a.command),executor:a.command,measures:{[M.cpuMs]:a.cpuMs}},attrs:{"os.pid":a.pid,"os.ppid":a.ppid,"os.command":a.command,"os.rssBytes":a.rssBytes}});continue}const u=e.get(i),h=a.cpuMs-u.cpuMs>=Hi,m=Math.abs(a.rssBytes-u.rssBytes)>=Wi;(h||m)&&o.push({...n,occurredAt:s.observedAt,seq:`obs:${s.observedAt}`,kind:"observed",subject:{type:"process",id:i},claims:[c],basis:"measured",core:{measures:{[M.cpuMs]:a.cpuMs}},attrs:{"os.rssBytes":a.rssBytes}})}for(const[a,i]of e)r.has(a)||o.push({...n,occurredAt:s.observedAt-s.intervalMs,kind:"ended",subject:{type:"process",id:a},basis:"inferred",assumption:Bi(s.intervalMs),core:{outcome:"completed",measures:{[M.cpuMs]:i.cpuMs}},attrs:{"os.pid":i.pid}});return{envelopes:o,next:r}}function Xi(e){return(e.split("/").pop()??e).toUpperCase()}const Vi=lo(uo);function Yi(){return en()}function Gi(e){const t=[];for(const s of e.split(`
75
+ `)){const n=s.trim();if(!n)continue;const o=n.match(/^(\d+)\s+(\d+)\s+(\w{3}\s+\w{3}\s+\d+\s+[\d:]+\s+\d{4})\s+([\d:.]+)\s+(\d+)\s+(.*)$/);if(!o)continue;const[,r,a,i,c,u,h]=o,m=Date.parse(i);Number.isFinite(m)&&t.push({pid:Number(r),ppid:Number(a),startedAt:m,cpuMs:zi(c),rssBytes:Number(u)*1024,command:h.trim()})}return t}function zi(e){const[t,s]=e.includes("-")?e.split("-"):["0",e],n=s.split(":").map(Number);let o=0;for(const r of n)o=o*60+(Number.isFinite(r)?r:0);return Math.round((o+Number(t)*86400)*1e3)}async function Ki(){const{stdout:e}=await Vi("ps",["-Ao","pid=,ppid=,lstart=,time=,rss=,comm="],{maxBuffer:8388608});return Gi(e)}const Fs=5e3;function Ji(e,t){const s=Yi();let n=new Map,o=null,r=0,a=null,i,c=!1;async function u(){if(c)return[];c=!0;try{const h=await Ki(),m=Date.now(),{envelopes:k,next:b}=qi(n,h,{machineId:t,host:s,observedAt:m,intervalMs:Fs}),g=k.map(oe);return e.append(g),n=b,r++,a=m,i=void 0,g}catch(h){return i=h instanceof Error?h.message:String(h),[]}finally{c=!1}}return{sample:u,start(){o||(u(),o=setInterval(()=>{u()},Fs),o.unref?.())},stop(){o&&clearInterval(o),o=null},get running(){return o!==null},stats(){return{samples:r,tracked:n.size,lastSampleAt:a,lastError:i}}}}const Fn={info:e=>console.log(e),warn:e=>console.warn(e),error:e=>console.error(e)},Qi=36e5,Zi=15e3,ea=3;function lt(e={}){const t=e.log??Fn,s=e.path??ut(),n=e.retention??Cn(),o=Di(s),r=o.stats();t.info(r.events>0?`[057] store ${s}: opened with ${r.events} events`:`[057] store ${s}: NEW EMPTY STORE — if history existed before, it was lost, not carried`);const a=Ln();a&&t.warn(`[057] a store from a previous layout exists at ${a} and is NOT in use. Run 057 with O57_STORE=${a} to keep using it, or move it to ${s}.`);const i=Ie();o.append([oe({source:{id:"host",instance:i.id},occurredAt:0,observedAt:Date.now(),clock:"wall",kind:"began",stratum:"machine",subject:{type:"machine",id:i.id},basis:"measured",core:{machineName:i.name,machineKind:i.kind},seq:"host"})]);const c=Ji(o,i.id),u=new Map;function h(d){for(const A of d){const v=u.get(A.id)??{consecutiveFailures:0,totalFailures:0,failing:!1};A.ok?(v.consecutiveFailures=0,v.failing=!1,v.failingSince=void 0,v.lastSuccessAt=Date.now()):(v.consecutiveFailures===0&&(v.failingSince=Date.now()),v.consecutiveFailures++,v.totalFailures++,v.lastFailureAt=Date.now(),v.lastError=A.error,v.consecutiveFailures>=ea&&!v.failing&&(v.failing=!0,t.warn(`[057] source ${A.id} has failed ${v.consecutiveFailures} collection rounds in a row: ${A.error??"unknown error"}`))),u.set(A.id,v)}}const m=Us(s);let k=null;function b(d){return k||(k=d,t.error(`[057] ${d.message} — ${d.remedy}`),c.stop()),k}function g(){if(k)return k;if(s===":memory:")return null;if(!F(s))return b({kind:"unlinked",message:`the store at ${s} no longer exists on disk; captured events are going to an orphaned file and will be lost`,remedy:"Stop 057 and start it again. It will open a new store at the same path.",since:Date.now()});const d=Us(s);return m!==null&&d!==null&&d!==m?b({kind:"replaced",message:`the store at ${s} was replaced by a different file while 057 was running; captured events are going to the old one`,remedy:"Stop 057 and start it again so it opens the file that is actually there.",since:Date.now()}):null}e.observe!==!1&&c.start();const f=o.sweep(n);f.processEvents+f.otherEvents>0&&t.info(`[057] retention: removed ${f.processEvents} process and ${f.otherEvents} semantic events (${ct(n)})`);const p=setInterval(()=>{if(!k)try{o.sweep(n),Rt(s)}catch(d){t.warn(`[057] retention sweep failed: ${String(d)}`)}},Qi);p.unref?.();const y=setInterval(()=>{g()},Zi);return y.unref?.(),{store:o,machine:i,os:c,path:s,retention:n,fault:()=>k,sweep:d=>o.sweep(n,d),checkStore:g,recordCollection:h,collectionHealth:()=>Object.fromEntries(u),stop(){clearInterval(p),clearInterval(y),c.stop(),o.close()}}}function Us(e){try{return at(e).ino}catch{return null}}const ta=9e4;function Ps(e,t){if(e.waitingSince===void 0)return;const s=e.waitingSince,n=Math.max(s,t);e.waitingMs+=n-s,e.waits.push({start:s,end:n})}function sa(e,t){const s=`${t.source.id}:${t.source.instance}`;let n=e.sources.get(s);n||(n={id:t.source.id,instance:t.source.instance,origin:t.source.instance,firstSeenAt:t.occurredAt,lastSeenAt:t.occurredAt,events:0,strata:{}},e.sources.set(s,n)),n.events++,t.occurredAt<n.firstSeenAt&&(n.firstSeenAt=t.occurredAt),t.occurredAt>n.lastSeenAt&&(n.lastSeenAt=t.occurredAt),t.stratum&&(n.strata[t.stratum]=(n.strata[t.stratum]??0)+1);const o=t.provenance?.sourceVersion;o&&(n.sourceVersions?n.sourceVersions.includes(o)||n.sourceVersions.push(o):n.sourceVersions=[o])}function na(e,t){if(e.seen.has(t.id))return;e.seen.add(t.id),t.occurredAt>e.now&&(e.now=t.occurredAt),sa(e,t);const s=t.core??{},n=t.occurredAt;switch(t.subject.type){case"machine":{if(e.machines.has(t.subject.id))break;const o={id:t.subject.id,name:s.machineName??t.subject.id,kind:s.machineKind??"laptop",parentId:s.parentId,firstSeenAt:n};e.machines.set(o.id,o);break}case"session":{if(t.kind==="began"){const o=e.sessions.get(t.subject.id);if(o){o.parentId===void 0&&s.parentId&&(o.parentId=s.parentId);break}const r={id:t.subject.id,machineId:s.machineId??"",label:s.label,context:t.attrs?.context??s.label??"",executor:s.executor,model:s.model,startedAt:n,executionIds:[],parentId:s.parentId};e.sessions.set(r.id,r)}else if(t.kind==="ended"){const o=e.sessions.get(t.subject.id);o&&(o.endedAt=n)}break}case"execution":oa(e,t,n);break;case"process":ra(e,t,n);break;case"artifact":{if(e.artifacts.has(t.subject.id))break;e.artifacts.set(t.subject.id,{id:t.subject.id,kind:"file",path:s.label??t.subject.id,firstSeenAt:n});break}}}function oa(e,t,s){const n=t.core??{},o=t.subject.id;if(t.kind==="began"){if(e.executions.has(o))return;const a={id:o,sessionId:n.sessionId??n.parentId??"",machineId:n.machineId??"",label:n.label??o,executor:n.executor??"unknown",model:n.model,status:"running",startedAt:s,lastActivityAt:s,measures:{},waitingMs:0,waits:[],parentId:n.parentId,depth:n.depth??0,startBasis:t.basis,boundsAssumption:t.assumption};n.measures&&rt(a.measures,n.measures),e.executions.set(o,a),e.active.add(o),e.sessions.get(a.sessionId)?.executionIds.push(o);return}const r=e.executions.get(o);if(r)switch(t.kind){case"progressed":{n.measures&&rt(r.measures,n.measures),r.lastActivityAt=s,r.status==="idle"&&(r.status="running",e.active.add(o));break}case"blocked":{if(!kn(r.status))break;r.status="waiting",r.waitingSince=s,r.waitReason=n.blockedOn??"input",r.lastActivityAt=s;break}case"resumed":{Ps(r,s),r.status="running",r.waitingSince=void 0,r.waitReason=void 0,r.lastActivityAt=s,e.active.add(o);break}case"ended":{const a=n.outcome==="error";r.status=a?"failed":"completed",r.endedAt=s,r.endBasis=t.basis,t.assumption&&!r.boundsAssumption&&(r.boundsAssumption=t.assumption),r.lastActivityAt=s,r.outcome=n.outcome??"completed",a&&(r.failure={code:n.failureCode??"ERROR",message:n.failureMessage??"Execution failed"}),Ps(r,s),r.waitingSince=void 0,r.waitReason=void 0,e.active.delete(o);break}case"observed":r.lastActivityAt=Math.max(r.lastActivityAt,s);break}}function ra(e,t,s){const n=t.core??{},o=t.subject.id,r=Number(t.attrs?.["os.pid"]??0);if(t.kind==="began"){if(e.processes.has(o))return;const i={id:o,machineId:n.machineId??"",pid:r,ppid:typeof t.attrs?.["os.ppid"]=="number"?t.attrs["os.ppid"]:void 0,command:n.label??n.executor??String(r),startedAt:s,lastSeenAt:s,status:"running",measures:{}};n.measures&&rt(i.measures,n.measures),e.processes.set(o,i);return}const a=e.processes.get(o);if(a)if(t.kind==="observed"||t.kind==="progressed"){if(a.lastSeenAt=Math.max(a.lastSeenAt,s),n.measures){const i=n.measures[M.cpuMs];typeof i=="number"&&(a.measures[M.cpuMs]=i);const{[M.cpuMs]:c,...u}=n.measures;rt(a.measures,u)}}else t.kind==="ended"&&(a.endedAt=s,a.lastSeenAt=Math.max(a.lastSeenAt,s),a.status="exited",a.endInferred=t.basis==="inferred")}function ia(e,t){for(let s=0;s<t.length;s++)na(e,t[s])}function aa(e,t){if(!(t<=e.now)){e.now=t;for(const s of e.active){const n=e.executions.get(s);if(!n){e.active.delete(s);continue}n.status==="running"&&t-n.lastActivityAt>ta&&(n.status="idle")}}}function Un(e,t,s,n,o){const r=o?ca(o):void 0,a=r?Bs(e.query(t,s,n),r):e.query(t,s,n),i=new Set,c=new Set,u=new Map,h=b=>{const g=`${b.subject.type}:${b.subject.id}`;b.kind==="began"?(i.add(g),u.set(g,b)):c.add(g),b.core?.sessionId&&c.add(`session:${b.core.sessionId}`),b.core?.machineId&&c.add(`machine:${b.core.machineId}`)};for(const b of a)h(b);const m=[];for(let b=0;b<4;b++){const g=[...c].filter(p=>!i.has(p));if(g.length===0)break;const f=r?Bs(e.begansFor(g),r):e.begansFor(g);if(f.length===0)break;for(const p of f)u.set(`${p.subject.type}:${p.subject.id}`,p),m.push(p.occurredAt<t?{...p,occurredAt:t}:p),h(p),i.add(`${p.subject.type}:${p.subject.id}`)}return{events:[...m,...a].sort((b,g)=>b.occurredAt-g.occurredAt||Hs(b)-Hs(g)),declarations:[...u.values()],relationships:wo(e.claims(t,s)).relationships}}function Pn(e,t,s,n){const o=performance.now(),{events:r,declarations:a,relationships:i}=Un(e,t,s,void 0,n),c=performance.now()-o,u=performance.now(),h=En(t,s);ia(h,r),aa(h,s);const m=performance.now()-u;return{state:h,events:r,declarations:a,relationships:i,meta:{events:r.length,readMs:Math.round(c*10)/10,deriveMs:Math.round(m*10)/10}}}function De(e,t,s,n){const o=Pn(e,t,s,n),r=performance.now();return{world:Hr(o.state,o.relationships),meta:{...o.meta,serializeMs:Math.round((performance.now()-r)*10)/10}}}function ca(e){const t=Oo(e);return s=>{if(s.subject.type==="machine")return s.subject.id!==e&&ns(s.subject.id)?null:s;const n=s.core?.machineId;if(!n||n===e||!ns(n))return s;const o=s.subject.type==="process"&&t?Pi(s.subject.id,t):void 0;return{...s,...o?{subject:{...s.subject,id:o}}:{},core:{...s.core,machineId:e}}}}function Bs(e,t){const s=[];for(const n of e){const o=t(n);o&&s.push(o)}return s}function Hs(e){if(e.kind==="ended")return 5;switch(e.subject.type){case"machine":return 0;case"session":return 1;case"execution":case"process":return e.kind==="began"?2:3;default:return 4}}const Nt=[{id:jt,collect:(e,t)=>jo(e,t)},{id:nt,collect:(e,t)=>zo(e,t)},{id:ye,collect:(e,t)=>ar(e,t)},{id:Fe,collect:(e,t)=>br(e,t)},{id:_e,collect:(e,t)=>Tr(e,t)},{id:Pe,collect:(e,t)=>Fr(e,t)}],Ws=[...Nt.map(e=>e.id),be],qs=10*365*24*36e5,ze=2e5,ua=24*36e5,da=72*36e5;function Xs(e){const t=new Date(e);return t.setHours(0,0,0,0),{from:t.getTime(),to:e}}function Vs(e){const t=e.collectionHealth(),s=Object.entries(t).filter(([,i])=>i.failing).map(([i])=>i),n=e.store.health(),o=e.os.stats(),r=e.fault();let a=null;for(const i of Object.values(t))i.lastSuccessAt&&(a===null||i.lastSuccessAt>a)&&(a=i.lastSuccessAt);return{ok:s.length===0&&n.ok&&!r&&!o.lastError,fault:r??void 0,failingSources:s,errors:Object.fromEntries(Object.entries(t).filter(([,i])=>i.failing).map(([i,c])=>[i,c.lastError??"failing"])),failing:Object.fromEntries(Object.entries(t).filter(([,i])=>i.failing).map(([i,c])=>[i,{since:c.failingSince??null,rounds:c.consecutiveFailures}])),store:{ok:n.ok,remedy:n.remedy},os:{running:e.os.running,lastSampleAt:o.lastSampleAt,lastError:o.lastError},lastCollectionAt:a,sources:{total:Ws.length,reported:Ws.filter(i=>t[i]!==void 0).length}}}function la(e,t,s){const n=t.startsWith("/api/");if(s){const i=(e.headers.host??"").toLowerCase(),c=i.startsWith("[")?i.slice(0,i.indexOf("]")+1):i.split(":")[0];if(!s.includes(c))return`refusing a request for host "${i}"; 057 answers only on ${s.join(", ")}`}const o=e.headers.origin;if(typeof o=="string"&&o!=="null"){const i=(e.headers.host??"").toLowerCase();let c="";try{c=new URL(o).host.toLowerCase()}catch{return"refusing a request with an unparseable Origin"}if(c!==i)return`refusing a cross-origin request from ${o}`}const r=e.headers["sec-fetch-site"],a=String(e.headers["sec-fetch-dest"]??"");if(fa.has(a))return`refusing to be embedded as ${a}`;if(typeof r=="string"&&r!==""){if(r!=="same-origin"&&r!=="none")return`refusing a ${r} request`;if(r==="none"&&n)return"refusing a directly-navigated API request"}else if(n&&t==="/api/collect"&&!e.headers[pa])return"refusing a state-changing request that carries no fetch metadata";return null}const pa="x-057-client",fa=new Set(["iframe","frame","embed","object","fencedframe"]);function Yt(e){e.setHeader("x-frame-options","DENY"),e.setHeader("content-security-policy","frame-ancestors 'none'")}function ma(e,t){const s=(r,a)=>{const i=e.get(r);if(i===null||i==="")return a;const c=Number(i);return Number.isSafeInteger(c)?c:null},n=s("from",t-864e5),o=s("to",t);return n===null||o===null?{error:"from and to must be integer epoch millis"}:o<n?{error:"to must not precede from"}:o>t+ua?{error:"to is too far in the future"}:o-n>qs?{error:`window must not exceed ${qs} ms`}:{from:n,to:o}}function B(e,t,s){e.statusCode=t,e.setHeader("content-type","application/json"),e.setHeader("cache-control","no-store"),e.setHeader("x-content-type-options","nosniff"),Yt(e),e.end(JSON.stringify(s))}function ha(e){const t=e.problems.filter(s=>s.path.includes("/sessions/")).length;return{identity:e.identityAvailable?t===0?"available":e.registryEntries>0?"partial":"failed":"unavailable","stored-semantics":e.storedAvailable?e.transcriptsFailed===0?"available":e.transcriptsRead>0?"partial":"failed":"unavailable","live-semantics":"unavailable"}}function St(e){return{"stored-semantics":e.storedAvailable?e.failed===0?"available":e.read>0?"partial":"failed":"unavailable","live-semantics":"unavailable"}}function ga(e){return e.error?"failed":e.available?"observing":e.present?"installed-no-data":"not-installed"}function ba(e){const t=e.home??e.globalStorage;if(typeof t=="string")return t;const s=e.roots;return Array.isArray(s)?s.join(", "):void 0}function ge(e){return{available:e.available,present:e.present??!1,presence:ga(e),origin:ba(e),error:e.error}}function va(e){const{runtime:t,log:s}=e;let n=null;function o(r){if(!n||r-n.at>6e4){const a=Xs(r),i=As(De(t.store,a.from,a.to,t.machine.id).world);n={at:r,label:"TODAY",world:i,landscape:xs(i)}}return n}return async function(a,i){const c=a.url??"";if(!c.startsWith("/api/"))return!1;const u=new URL(c,"http://localhost"),h=la(a,u.pathname,e.allowedHosts);if(h)return s.warn(`[057] ${h}`),B(i,403,{error:h}),!0;const m=t.store,k=Date.now(),b=ma(u.searchParams,k);if("error"in b)return B(i,400,{error:b.error}),!0;const{from:g,to:f}=b;try{if(u.pathname==="/api/state"){const[p,y,d,A,v,w]=await Promise.all([rs().catch(x=>({available:!1,error:String(x)})),ds().catch(x=>({available:!1,error:String(x)})),ps().catch(x=>({available:!1,error:String(x)})),ms().catch(x=>({available:!1,error:String(x)})),vs().catch(x=>({available:!1,error:String(x)})),ws().catch(x=>({available:!1,error:String(x)}))]),[$,l,S,E]=await Promise.all([ln(g,f).catch(()=>null),hn(g,f).catch(()=>null),vn(g,f).catch(()=>null),Sn(g,f).catch(()=>null)]),T={strata:{"stored-semantics":"failed"}},I={"claude-code":$?{strata:ha($),registryEntries:$.registryEntries,transcriptsRead:$.transcriptsRead,transcriptsFailed:$.transcriptsFailed,problems:$.problems.slice(0,20)}:{strata:{identity:"failed"}},codex:l?{strata:St({storedAvailable:l.storedAvailable,read:l.rolloutsRead,failed:l.rolloutsFailed}),rolloutsRead:l.rolloutsRead,rolloutsFailed:l.rolloutsFailed,problems:l.problems.slice(0,20)}:T,cursor:S?{strata:St({storedAvailable:S.storedAvailable,read:S.composersRead,failed:S.composersFailed}),composersRead:S.composersRead,composersFailed:S.composersFailed,problems:S.problems.slice(0,20)}:T,gemini:E?{strata:St({storedAvailable:E.storedAvailable,read:E.sessionsRead,failed:E.sessionsFailed}),sessionsRead:E.sessionsRead,sessionsFailed:E.sessionsFailed,problems:E.problems.slice(0,20)}:T},N={deepseek:ge(p),"0x2f":ge(y),"claude-code":ge(d),codex:ge(A),cursor:ge(v),gemini:ge(w)},C=t.collectionHealth();for(const[x,G]of Object.entries(N)){const K=C[x];K?.failing&&(G.presence="failed",G.error??=K.lastError)}const _=t.os.stats(),O=Object.values(N).filter(x=>x.available).length>0?"observing":_.samples>0?"os-only":"empty",U=Object.entries(C).filter(([,x])=>x.failing).map(([x])=>x),q=m.health(),j={ok:U.length===0&&q.ok&&!t.fault()&&!_.lastError,failingSources:U,collection:C,store:q,os:_.lastError?{failing:!0,lastError:_.lastError}:{failing:!1}};return B(i,200,{machine:t.machine,mode:O,fault:t.fault()??void 0,health:j,store:{...m.stats(),path:m.path,schemaVersion:m.schemaVersion,bytes:m.sizeBytes(),retention:{...t.retention,description:ct(t.retention)}},os:{..._,running:t.os.running,source:be},sources:N,observation:I}),!0}if(u.pathname==="/api/collect"){const p=t.checkStore();if(p)return B(i,503,{error:p.message,fault:p}),!0;const y=await Ao(m,Nt,g,f,A=>t.recordCollection([A])),d=await t.os.sample();return t.recordCollection([{id:be,ok:!t.os.stats().lastError,error:t.os.stats().lastError}]),B(i,200,{...y,sources:[...y.sources,{id:be,ok:!t.os.stats().lastError,collected:d.length,inserted:d.length,duplicate:0,error:t.os.stats().lastError,ms:0}]}),!0}if(u.pathname==="/api/world")return B(i,200,{from:g,to:f,now:k,...De(m,g,f,t.machine.id)}),!0;if(u.pathname==="/api/health")return B(i,200,{pid:process.pid,version:e.version??"dev",contract:Wt,store:t.path,health:Vs(t)}),!0;if(u.pathname==="/api/landscape"){let p={from:g,to:f},y="WINDOW",d;if(u.searchParams.get("window")==="live"){if(p=Xs(k),y="TODAY",d=De(m,p.from,p.to,t.machine.id),d.world.executions.length===0&&d.world.sessions.length===0){const w={from:k-da,to:k},$=De(m,w.from,w.to,t.machine.id);($.world.executions.length>0||$.world.sessions.length>0)&&(p=w,y="LAST 72H",d=$)}}else d=De(m,g,f,t.machine.id);const A=As(d.world),v=xs(A);return u.searchParams.get("window")==="live"&&(n={at:k,label:y,world:A,landscape:v}),B(i,200,{...p,now:k,window:y,meta:d.meta,health:Vs(t),...si(v)}),!0}if(u.pathname==="/api/today"||u.pathname==="/api/log"){const p=o(k);return B(i,200,u.pathname==="/api/today"?{window:p.label,...Ei(p.world)}:{window:p.label,...Ii(p.world,p.landscape)}),!0}if(u.pathname==="/api/inspect"){const p=u.searchParams.get("kind")??"",y=u.searchParams.get("id")??"";if(!["disturbance","stratum","mass","coupling"].includes(p)||!y||y.length>512)return B(i,400,{error:"inspect needs kind=disturbance|stratum|mass|coupling and an id"}),!0;if(o(k),!n)return!0;const d=(v,w)=>{for(const $ of m.subjectEvents(v,w))if($.provenance?.path)return $.provenance.path},A=oi(n.world,n.landscape,p,y,d);return A?(B(i,200,A),!0):(B(i,404,{error:"not in the current world"}),!0)}if(u.pathname==="/api/sources"){const p=await Promise.all([rs().catch(v=>({available:!1,error:String(v)})),ds().catch(v=>({available:!1,error:String(v)})),ps().catch(v=>({available:!1,error:String(v)})),ms().catch(v=>({available:!1,error:String(v)})),vs().catch(v=>({available:!1,error:String(v)})),ws().catch(v=>({available:!1,error:String(v)}))]),y=t.collectionHealth(),d=t.os.stats(),A=Nt.map((v,w)=>{const $=ge(p[w]),l=y[v.id];return{id:v.id,presence:l?.failing?"failed":$.presence,origin:$.origin,error:l?.failing?l.lastError??$.error:$.error,consecutiveFailures:l?.consecutiveFailures??0,lastSuccessAt:l?.lastSuccessAt}});return A.push({id:be,presence:d.lastError?"failed":d.samples>0?"observing":"installed-no-data",origin:void 0,error:d.lastError,consecutiveFailures:y[be]?.consecutiveFailures??0,lastSuccessAt:d.lastSampleAt??void 0}),B(i,200,{sources:A}),!0}if(u.pathname==="/api/detail"){const p=u.searchParams.get("type")??"",y=u.searchParams.get("id")??"";if(!es.includes(p)||!y)return B(i,400,{error:"detail needs type=<entity type> and id"}),!0;if(y.length>512)return B(i,400,{error:"id is too long"}),!0;const d=m.subjectEvents(p,y);return B(i,200,{type:p,id:y,events:d.slice(0,ze),truncated:d.length>ze}),!0}if(u.pathname==="/api/events"){const p=u.searchParams.get("subject"),y=p?p.split(",").filter(A=>es.includes(A)):void 0,d=Un(m,g,f,y,t.machine.id);return B(i,200,{from:g,to:f,now:k,events:d.events.slice(0,ze),truncated:d.events.length>ze,relationships:d.relationships}),!0}return B(i,404,{error:"unknown endpoint"}),!0}catch(p){return s.error(`[057] ${String(p)}`),B(i,500,{error:String(p)}),!0}}}const Gt=5057,me="127.0.0.1",ya=["localhost","127.0.0.1","[::1]","::1"],wa=10,Aa={".html":"text/html; charset=utf-8",".js":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".json":"application/json; charset=utf-8",".svg":"image/svg+xml",".woff2":"font/woff2",".png":"image/png",".ico":"image/vnd.microsoft.icon"};function Ys(e,t,s){let n;try{n=decodeURIComponent(t)}catch{return!1}if(n.includes("\0"))return!1;const o=qe(e,`.${so(n)}`);if(o!==e&&!o.startsWith(e+no)||!F(o)||!at(o).isFile())return!1;const r=Aa[oo(o).toLowerCase()]??"application/octet-stream";return s.statusCode=200,s.setHeader("content-type",r),s.setHeader("x-content-type-options","nosniff"),Yt(s),s.setHeader("cache-control",t.startsWith("/assets/")?"public, max-age=31536000, immutable":"no-store"),Jn(o).pipe(s),!0}function Sa(e,t,s,n){return new Promise((o,r)=>{let a=n,i=t;const c=u=>{if(u.code==="EADDRINUSE"&&a>1){a--,i++,e.listen(i,s);return}e.off("error",c),r(u)};e.on("error",c),e.once("listening",()=>{e.off("error",c);const u=e.address();o(typeof u=="object"&&u?u.port:i)}),e.listen(i,s)})}function ka(e,t){const s=String(e.headers["sec-fetch-dest"]??"");if(Ea.has(s))return`refusing to be embedded as ${s}`;const n=e.headers["sec-fetch-site"];return typeof n=="string"&&n!==""&&n!=="same-origin"&&n!=="none"?`refusing a ${n} request for ${t}`:null}const Ea=new Set(["iframe","frame","embed","object","fencedframe"]);async function Bn(e){const t=e.log??Fn,s=qe(e.root),n=e.host??me,o=n===me||n==="::1"||n==="localhost",r=e.runtime?.path??e.storePath??ut();if(!e.runtime){const m=await $i(r);if(m)throw new Xt(m)}const a=e.runtime??lt({path:e.storePath,log:t,retention:e.retention,observe:e.observe}),i=va({runtime:a,log:t,version:e.version,allowedHosts:o?ya:null}),c=Zn((m,k)=>{(async()=>{try{if(await i(m,k))return;if(m.method!=="GET"&&m.method!=="HEAD"){k.statusCode=405,k.setHeader("allow","GET, HEAD"),k.end();return}const b=new URL(m.url??"/","http://localhost").pathname,g=ka(m,b);if(g){t.warn(`[057] ${g}`),k.statusCode=403,k.setHeader("content-type","text/plain; charset=utf-8"),Yt(k),k.end(`${g}
76
+ `);return}if(Ys(s,b==="/"?"/index.html":b,k)||!b.startsWith("/assets/")&&Ys(s,"/index.html",k))return;k.statusCode=404,k.setHeader("content-type","text/plain; charset=utf-8"),k.end(`not found
77
+ `)}catch(b){t.error(`[057] request failed: ${String(b)}`),k.headersSent||(k.statusCode=500),k.end()}})()}),u=await Sa(c,e.port??Gt,n,wa).catch(m=>{throw a.stop(),m}),h=o?"localhost":n;return Mi(a.path,{pid:process.pid,url:`http://${o?me:n}:${u}`,version:e.version??"dev",contract:Wt,store:a.path,startedAt:Date.now(),owner:e.owner??"cli"}),{url:`http://${h}:${u}`,port:u,host:n,runtime:a,server:c,close(){return new Promise(m=>{Oi(a.path),c.close(()=>{a.stop(),m()}),c.closeAllConnections?.()})}}}function Ia(e){return qe(ro(new URL(".",e)),"..","dist")}function Ta(e){const{summary:t}=e,s=[`COMPUTATIONAL ACTIVITY · ${Ma(e.window.from)}`,`${t.executions} executions across ${t.sessions} sessions`,`NOW ${t.runningNow} running · ${Q(t.waitingNow,String)} waiting · ${t.idleNow} idle`,`OUTCOMES ${Q(t.completed,String)} completed · ${Q(t.failed,String)} failed · ${Q(t.interrupted,String)} interrupted`,`ACTIVE INTERVAL ${Q(t.observedExecutionMs,Gs)}`,`PEAK CONCURRENCY ${Q(t.peakConcurrency,n=>`${n.peak}${n.at===null?"":` at ${Oa(n.at)}`}`)}`,`TOKENS ${Q(t.tokens,Ke)}`,`TOOLS ${Q(t.toolInteractions,Ke)} interactions · ${Q(t.toolErrors,Ke)} errors`,`EXPLICIT WAITS ${Q(t.waits,n=>`${n.count} / ${Gs(n.durationMs)}${n.openNow?` / ${n.openNow} open`:""}`)}`];return t.usageByModel.length>0&&s.push(`MODELS ${t.usageByModel.map(n=>`${n.model}: ${n.executions} executions, ${Q(n.tokens,Ke)}`).join(" · ")}`),t.executionsWithoutModel>0&&s.push(`MODEL COVERAGE ${t.executionsWithoutModel} executions without an observed model`),`${s.join(`
78
+ `)}
79
+ `}function $a(e){return[`tokens: ${e.tokens.state}`,`tool interactions: ${e.toolInteractions.state}`,`tool errors: ${e.toolErrors.state}`,`waits: ${e.waits.state}`]}function Q(e,t){return"value"in e&&e.value!==void 0?`${t(e.value)} (${e.state})`:e.state}function Ke(e){return e<1e3?String(Math.round(e)):e<1e6?`${(e/1e3).toFixed(e<1e4?1:0)}k`:`${(e/1e6).toFixed(e<1e7?1:0)}m`}function Gs(e){const t=Math.round(e/6e4);return t<1?`${Math.round(e/1e3)}s`:t<60?`${t}m`:`${Math.floor(t/60)}h ${t%60}m`}function Ma(e){const t=new Date(e);return`${t.getFullYear()}-${zs(t.getMonth()+1)}-${zs(t.getDate())}`}function Oa(e){return new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}function zs(e){return String(e).padStart(2,"0")}const Ra=["today","running","waiting","failed","sessions","usage","concurrency"];function Na(e,t){switch(t){case"today":return Ta(e);case"running":return kt("RUNNING",e.executions.filter(s=>s.lifecycle.state==="running"));case"waiting":return kt("WAITING",e.executions.filter(s=>s.lifecycle.state==="waiting"));case"failed":return kt("FAILED",e.executions.filter(s=>zt(s.outcome)==="failed"));case"sessions":return`${["SESSIONS",...e.sessions.map(s=>`${s.ref} ${s.executionRefs.length} executions spawned by ${xt(s.spawnedBy)}`)].join(`
80
+ `)}
81
+ `;case"usage":return`${["USAGE",`tokens ${Le(e.summary.tokens)}`,`tool interactions ${Le(e.summary.toolInteractions)}`,`tool errors ${Le(e.summary.toolErrors)}`,...e.summary.usageByModel.map(n=>`${n.model} ${n.executions} executions ${Le(n.tokens)} tokens`),"COVERAGE",...$a(e.summary)].join(`
82
+ `)}
83
+ `;case"concurrency":{const s=e.summary.peakConcurrency;return`CONCURRENCY
84
+ peak ${"value"in s&&s.value?`${s.value.peak}${s.value.at===null?"":` at ${new Date(s.value.at).toISOString()}`}`:s.state} (${s.state})
85
+ active interval ${Le(e.summary.observedExecutionMs)} ms
86
+ `}}}function kt(e,t){return t.length===0?`${e}
87
+ none observed
88
+ `:`${[e,...t.map(s=>`${s.ref} ${s.lifecycle.state} executor ${xt(s.executor)} model ${xt(s.model)} started ${new Date(s.start.at).toISOString()}`)].join(`
89
+ `)}
90
+ `}function zt(e){return"value"in e?e.value:void 0}function xt(e){const t=zt(e);return t===void 0?e.state:typeof t=="object"&&t!==null&&"ref"in t?`${String(t.ref)} (${e.state})`:`${String(t)} (${e.state})`}function Le(e){const t=zt(e);return t===void 0?e.state:`${Math.round(t).toLocaleString()} (${e.state})`}const Ks={tokens:"unknown",requests:"unknown",toolInteractions:"unknown",toolErrors:"unknown",retries:"unknown",waits:"unknown",model:"unknown",context:"unknown",outcome:"unknown"};function xa(e){const t=new Map;for(const r of e.declarations)r.kind==="began"&&t.set(`${r.subject.type}:${r.subject.id}`,r);const s=[...e.state.executions.values()].map(r=>_a(r,e,t)).sort((r,a)=>r.start.at-a.start.at||r.ref.localeCompare(a.ref)),n=new Set(s.map(r=>r.ref)),o=[...e.state.sessions.values()].map(r=>({ref:pe("session",r.id),executionRefs:r.executionIds.map(a=>pe("execution",a)).filter(a=>n.has(a)).sort(),spawnedBy:r.parentId?Z({ref:pe("session",r.parentId)}):Se("no parent session was reported")})).filter(r=>r.executionRefs.length>0).sort((r,a)=>r.ref.localeCompare(a.ref));return{experimental:!0,window:{from:e.from,to:e.to},executions:s,sessions:o,summary:Ua(s,o,e.from,e.to)}}function _a(e,t,s){const n=s.get(`execution:${e.id}`),o=n?.source.id,r=o?t.capabilities.get(o)??Ks:Ks,a=t.state.sessions.get(e.sessionId),i=t.state.machines.get(e.machineId),c=e.status==="completed"||e.status==="failed",u=ja(n?.occurredAt??e.startedAt,n?.basis??e.startBasis),h=t.relationships.filter(g=>g.kind==="ran-as"&&(g.from.type==="execution"&&g.from.id===e.id&&g.to.type==="process"||g.to.type==="execution"&&g.to.id===e.id&&g.from.type==="process")).map(g=>{const f=g.from.type==="process"?g.from:g.to;return{kind:"ran-as",target:{type:"process",ref:pe("process",f.id)},evidence:Ca(g.basis),...g.basis==="inferred"?{qualification:"resolved from overlapping identity claims"}:{}}}).sort((g,f)=>g.target.ref.localeCompare(f.target.ref)),m=a?.context,k=e.model??a?.model,b={current:e.status==="waiting",...e.waitReason?{reason:e.waitReason}:{},count:e.waits.length+(e.waitingSince===void 0?0:1),durationMs:e.waitingMs+(e.waitingSince===void 0?0:Math.max(0,t.to-e.waitingSince))};return{ref:pe("execution",e.id),sessionRef:pe("session",e.sessionId),machine:e.machineId?Z({ref:pe("machine",e.machineId),...i?{kind:i.kind}:{}}):Se("no machine was reported"),context:m?_t(r.context,{ref:pe("context",m)},"context"):et(r.context,"context"),executor:e.executor&&e.executor!=="unknown"?Z(e.executor):Se("no executor was reported"),model:k?_t(r.model,k,"model"):et(r.model,"model"),start:u,end:e.endedAt===void 0?re("the execution is not terminal in this window"):e.endBasis==="inferred"?Kt(e.endedAt,"the terminal bound was inferred by its observer"):Z(e.endedAt),lifecycle:Da(e),outcome:La(e,r.outcome),measures:{tokens:{input:le(e,M.tokensInput,r.tokens,c,!1,"token input"),output:le(e,M.tokensOutput,r.tokens,c,!1,"token output"),cacheRead:le(e,M.tokensCacheRead,r.tokens,c,!1,"cache-read tokens"),reasoning:le(e,M.tokensReasoning,r.tokens,c,!1,"reasoning tokens"),total:Hn(de(e.measures),r.tokens,c,!1,"token total")},requests:le(e,M.steps,r.requests,c,!0,"requests"),toolInteractions:le(e,M.interactions,r.toolInteractions,c,!0,"tool interactions"),toolErrors:le(e,M.errors,r.toolErrors,c,!0,"tool errors"),retries:le(e,M.retries,r.retries,c,!0,"retries")},wait:Fa(b,r.waits,c),failure:e.status==="failed"?Z("execution-failed"):c?r.outcome==="supported"?Z("none"):et(r.outcome,"failure state"):re("the execution is not terminal"),depth:e.depth,relationships:h}}function pe(e,t){const s=Zs("sha256").update(`057-activity\0${e}\0${t}`).digest("hex").slice(0,16);return`${e}_${s}`}function Ca(e){return e==="inferred"?"inferred":"observed"}function ja(e,t){return t==="inferred"?{at:e,evidence:"inferred",qualification:"the observer inferred this temporal bound"}:t===void 0?{at:e,evidence:"inferred",qualification:"a legacy record did not declare its timing basis"}:{at:e,evidence:"observed"}}function Da(e){return e.status==="waiting"?{state:"waiting",evidence:"observed"}:e.status==="running"?{state:"running",evidence:"observed"}:e.status==="idle"?{state:"idle",evidence:"inferred",qualification:"no activity was observed for the idle threshold"}:{state:"terminal",evidence:e.endBasis==="inferred"?"inferred":"observed",...e.endBasis==="inferred"?{qualification:"the observer inferred the terminal bound"}:{}}}function La(e,t){if(e.status!=="completed"&&e.status!=="failed")return re("the execution is not terminal");const s=e.outcome==="error"?"failed":e.outcome==="interrupted"?"interrupted":e.outcome==="completed"?"completed":void 0;return s?e.endBasis==="inferred"?Kt(s,"the terminal outcome follows an inferred terminal bound"):_t(t,s,"outcome"):et(t,"outcome")}function le(e,t,s,n,o,r){return Hn(ee(e.measures,t),s,n,o,r)}function Hn(e,t,s,n,o){return t==="unsupported"?Te(`this observer does not report ${o}`):t==="unknown"?re(`coverage for ${o} is not declared`):t==="partial"?Ae(e,`this observer reports ${o} only partially`):s?e!==void 0?Z(e):n?Z(0):Se(`${o} was not present in this execution`):Ae(e,`${o} may still increase while the execution is active`)}function Fa(e,t,s){return t==="unsupported"?Te("this observer does not report explicit waits"):t==="unknown"?re("wait coverage is not declared"):t==="partial"?Ae(e,"this observer reports explicit waits only partially"):!s||e.current?Ae(e,"an explicit wait may still be open"):Z(e)}function _t(e,t,s){return e==="supported"?Z(t):e==="partial"?Ae(t,`this observer reports ${s} only partially`):e==="unsupported"?Te(`this observer does not report ${s}`):re(`coverage for ${s} is not declared`)}function et(e,t){return e==="supported"?Se(`${t} was not present in this execution`):e==="partial"?Ae(void 0,`this observer reports ${t} only partially`):e==="unsupported"?Te(`this observer does not report ${t}`):re(`coverage for ${t} is not declared`)}function Z(e){return{state:"observed",value:e}}function Kt(e,t){return{state:"inferred",value:e,qualification:t}}function Ae(e,t){return e===void 0?{state:"partial",qualification:t}:{state:"partial",value:e,qualification:t}}function Te(e){return{state:"unsupported",qualification:e}}function Se(e){return{state:"not-observed",qualification:e}}function re(e){return{state:"unknown",qualification:e}}function Ua(e,t,s,n){const o=e.map(u=>({start:Math.max(s,u.start.at),end:Math.min(n,ke(u.end)??n),inferred:u.start.evidence==="inferred"||u.end.state==="inferred",partial:u.end.state!=="observed"&&u.end.state!=="inferred"})),r=pt(o.map(u=>u.partial?"partial":u.inferred?"inferred":"observed")),a=Wa(o),i=qa(o),c=e.filter(u=>u.lifecycle.state==="terminal");return{executions:e.length,sessions:t.length,runningNow:e.filter(u=>u.lifecycle.state==="running").length,waitingNow:xe(e.map(Pa)),idleNow:e.filter(u=>u.lifecycle.state==="idle").length,completed:Et(c,"completed"),failed:Et(c,"failed"),interrupted:Et(c,"interrupted"),observedExecutionMs:He(a,r),peakConcurrency:He(i,r),tokens:xe(e.map(u=>u.measures.tokens.total)),toolInteractions:xe(e.map(u=>u.measures.toolInteractions)),toolErrors:xe(e.map(u=>u.measures.toolErrors)),waits:Ba(e.map(u=>u.wait)),usageByModel:Ha(e),executionsWithoutModel:e.filter(u=>ke(u.model)===void 0).length}}function ke(e){return"value"in e?e.value:void 0}function pt(e){const t={records:e.length,observed:0,inferred:0,partial:0,unsupported:0,notObserved:0,unknown:0};for(const s of e)s==="not-observed"?t.notObserved++:t[s]++;return t}function He(e,t){return t.partial+t.unsupported+t.notObserved+t.unknown>0?{state:"partial",value:e,qualification:"coverage is incomplete",coverage:t}:t.inferred>0?{state:"inferred",value:e,qualification:"one or more bounds were inferred",coverage:t}:{state:"observed",value:e,coverage:t}}function xe(e){const t=pt(e.map(o=>o.state));let s=0,n=0;for(const o of e){const r=ke(o);r!==void 0&&(s+=r,n++)}return n>0?He(s,t):t.records>0&&t.unsupported===t.records?{...Te("no observer supports this measure"),coverage:t}:t.records>0&&t.notObserved===t.records?{...Se("no value was observed"),coverage:t}:{...re("no usable value was observed"),coverage:t}}function Pa(e){const t=ke(e.wait);return Wn(e.wait,t?.current?1:0)}function Et(e,t){return e.length===0?He(0,pt([])):xe(e.map(s=>{const n=ke(s.outcome);return Wn(s.outcome,n===t?1:0)}))}function Wn(e,t){switch(e.state){case"observed":return Z(t);case"inferred":return Kt(t,e.qualification);case"partial":return Ae("value"in e?t:void 0,e.qualification);case"unsupported":return Te(e.qualification);case"not-observed":return Se(e.qualification);case"unknown":return re(e.qualification)}}function Ba(e){const t=pt(e.map(o=>o.state));let s=0;const n={count:0,durationMs:0,openNow:0};for(const o of e){const r=ke(o);r&&(s++,n.count+=r.count,n.durationMs+=r.durationMs,r.current&&n.openNow++)}return s>0?He(n,t):t.unsupported===t.records?{...Te("no observer reports explicit waits"),coverage:t}:{...re("no usable wait value was observed"),coverage:t}}function Ha(e){const t=new Map;for(const s of e){const n=ke(s.model);if(!n)continue;const o=t.get(n)??[];o.push(s.measures.tokens.total),t.set(n,o)}return[...t.entries()].map(([s,n])=>({model:s,executions:n.length,tokens:xe(n)})).sort((s,n)=>n.executions-s.executions||s.model.localeCompare(n.model))}function Wa(e){const t=e.filter(r=>r.end>r.start).map(r=>({start:r.start,end:r.end})).sort((r,a)=>r.start-a.start||r.end-a.end);let s=0,n,o=0;for(const r of t)n===void 0?(n=r.start,o=r.end):r.start<=o?o=Math.max(o,r.end):(s+=o-n,n=r.start,o=r.end);return s+(n===void 0?0:o-n)}function qa(e){const t=[];for(const r of e)r.end<=r.start||t.push({at:r.start,delta:1},{at:r.end,delta:-1});t.sort((r,a)=>r.at-a.at||r.delta-a.delta);let s=0,n=0,o=null;for(const r of t)s+=r.delta,s>n&&(n=s,o=r.at);return{peak:n,at:o}}const Xa=[[jt,So],[nt,Fo],[ye,Ko],[Fe,cr],[_e,vr],[Pe,$r]],Va=new Map(Xa);function Ya(e,t,s,n){const o=Pn(e,t,s,n);return xa({state:o.state,declarations:o.declarations,relationships:o.relationships,capabilities:Va,from:t,to:s})}const We="1.1.0";function Ga(e){const t={command:"serve",activityQuery:"today",open:!1,yes:!1,desktop:!1},s=[...e],n=s[0];if(n&&!n.startsWith("-"))if(n==="status"||n==="compact"||n==="reset")t.command=n,s.shift();else if(n==="activity"){t.command="activity",s.shift();const o=s[0];if(o&&!o.startsWith("-")){if(!Ra.includes(o))return{...t,command:"help",error:`unknown activity query: ${o}`};t.activityQuery=o,s.shift()}}else return{...t,command:"help",error:`unknown command: ${n}`};for(;s.length;){const o=s.shift(),[r,a]=o.includes("=")?za(o,"="):[o,void 0],i=()=>a??s.shift();switch(r){case"-h":case"--help":t.command="help";break;case"-v":case"--version":t.command="version";break;case"--open":t.open=!0;break;case"--yes":case"-y":t.yes=!0;break;case"--desktop":t.desktop=!0;break;case"--port":{const c=i(),u=Number(c);if(!Number.isInteger(u)||u<0||u>65535)return{...t,command:"help",error:`--port needs a port number, got ${c}`};t.port=u;break}case"--host":{const c=i();if(!c)return{...t,command:"help",error:"--host needs a value"};t.host=c;break}case"--store":{const c=i();if(!c)return{...t,command:"help",error:"--store needs a path"};t.store=c;break}default:return{...t,command:"help",error:`unknown option: ${r}`}}}return t}function za(e,t){const s=e.indexOf(t);return[e.slice(0,s),e.slice(s+1)]}const Ka=`057 — a spatial interface for observing the shape of a computational workday
76
91
 
77
92
  057 observe this machine and serve the interface
78
93
  057 status where the store is, what it holds, what is observed
94
+ 057 activity [query] private computational activity (experimental)
95
+ queries: today, running, waiting, failed, sessions,
96
+ usage, concurrency
79
97
  057 compact reclaim disk freed by retention (rewrites the store)
80
98
  057 reset delete the local store
81
99
 
82
100
  Options
83
- --port <n> port to serve on (default ${It}; the next free one if taken)
84
- --host <addr> address to bind (default ${ae}; read the warning below first)
101
+ --port <n> port to serve on (default ${Gt}; the next free one if taken)
102
+ --host <addr> address to bind (default ${me}; read the warning below first)
85
103
  --store <path> store file to use (same as O57_STORE)
86
104
  --open open the interface in the default browser — the running
87
105
  057's, if one (or 057.app) already observes the store
@@ -105,39 +123,39 @@ anywhere. Everything it learns is in one SQLite file you can read or delete.
105
123
 
106
124
  --host binds beyond the loopback interface and serves your telemetry, unauthenticated, to
107
125
  anything that can reach that address. Do not do it on a network you do not control.
108
- `;function ie(e){return process.stdout.isTTY?`\x1B[2m${e}\x1B[0m`:e}function Me(e){return e<1024?`${e} B`:e<1024**2?`${(e/1024).toFixed(1)} KB`:e<1024**3?`${(e/1024**2).toFixed(1)} MB`:`${(e/1024**3).toFixed(2)} GB`}function ji(e,t,s,n){const o=["",` 057 ${$e}`,` ${e}`,"",ie(" observing this machine only — its process table, and any AI runtime state it finds"),ie(` storing ${t}`),ie(` keeping ${s}`),ie(" sending nothing. no account, no cloud, no analytics."),ie(" resetting 057 reset")];return n!==ae&&o.push("",` ! bound to ${n}, not loopback. Your telemetry is readable, without`," authentication, by anything that can reach this address."),o.push(""),o.join(`
109
- `)}async function Di(e){if(!process.stdin.isTTY)return!1;const t=yn({input:process.stdin,output:process.stdout});try{return(await new Promise(n=>t.question(`${e} [y/N] `,n))).trim().toLowerCase()==="y"}finally{t.close()}}async function Fi(e,t){const s=Ni(e);if(s.command==="version")return console.log($e),0;if(s.command==="help")return s.error&&console.error(`057: ${s.error}
110
- `),(s.error?console.error:console.log)(Ci),s.error?2:0;s.store&&(process.env.O57_STORE=s.store);const n=Ye(),o=nn();if(s.command==="status")return Ui(n,o);if(s.command==="compact")return Pi(n);if(s.command==="reset")return Bi(n,s.yes);if(s.desktop)return Li(t,n,o,s.port??0);const r=s.port??Hi(process.env.O57_PORT)??It,a=s.host??process.env.O57_HOST??ae;let i;try{i=await dn({root:t,port:r,host:a,storePath:n,retention:o,log:ze(),version:$e})}catch(u){if(u instanceof At){const m=u.record;return s.open?(console.log(`
111
- ${u.message}${m.owner==="desktop"?" — 057.app":""}.
126
+ `;function fe(e){return process.stdout.isTTY?`\x1B[2m${e}\x1B[0m`:e}function Be(e){return e<1024?`${e} B`:e<1024**2?`${(e/1024).toFixed(1)} KB`:e<1024**3?`${(e/1024**2).toFixed(1)} MB`:`${(e/1024**3).toFixed(2)} GB`}function Ja(e,t,s,n){const o=["",` 057 ${We}`,` ${e}`,"",fe(" observing this machine only — its process table, and any AI runtime state it finds"),fe(` storing ${t}`),fe(` keeping ${s}`),fe(" sending nothing. no account, no cloud, no analytics."),fe(" resetting 057 reset")];return n!==me&&o.push("",` ! bound to ${n}, not loopback. Your telemetry is readable, without`," authentication, by anything that can reach this address."),o.push(""),o.join(`
127
+ `)}async function Qa(e){if(!process.stdin.isTTY)return!1;const t=Qn({input:process.stdin,output:process.stdout});try{return(await new Promise(n=>t.question(`${e} [y/N] `,n))).trim().toLowerCase()==="y"}finally{t.close()}}async function Za(e,t){const s=Ga(e);if(s.command==="version")return console.log(We),0;if(s.command==="help")return s.error&&console.error(`057: ${s.error}
128
+ `),(s.error?console.error:console.log)(Ka),s.error?2:0;s.store&&(process.env.O57_STORE=s.store);const n=ut(),o=Cn();if(s.command==="status")return sc(n,o);if(s.command==="activity")return ec(n,o,s.activityQuery);if(s.command==="compact")return nc(n);if(s.command==="reset")return oc(n,s.yes);if(s.desktop)return tc(t,n,o,s.port??0);const r=s.port??ic(process.env.O57_PORT)??Gt,a=s.host??process.env.O57_HOST??me;let i;try{i=await Bn({root:t,port:r,host:a,storePath:n,retention:o,log:ft(),version:We})}catch(h){if(h instanceof Xt){const m=h.record;return s.open?(console.log(`
129
+ ${h.message}${m.owner==="desktop"?" — 057.app":""}.
112
130
  Opening ${m.url}
113
- `),await As(m.url),0):(console.error(`
114
- ${u.message}.
131
+ `),await Js(m.url),0):(console.error(`
132
+ ${h.message}.
115
133
  Open ${m.url} (\`057 --open\`), or stop that 057 before starting another.
116
- `),1)}return Tt(u)}console.log(ji(i.url,n,qe(o),a)),s.open&&await As(i.url);let c=!1;const d=()=>{c||(c=!0,console.log(`
134
+ `),1)}return mt(h)}console.log(Ja(i.url,n,ct(o),a)),s.open&&await Js(i.url);let c=!1;const u=()=>{c||(c=!0,console.log(`
117
135
  057 stopping — history is on disk
118
- `),i.close().then(()=>process.exit(0)))};return process.on("SIGINT",d),process.on("SIGTERM",d),new Promise(()=>{})}async function Li(e,t,s,n){const o=c=>{process.stdout.write(`${JSON.stringify(c)}
119
- `)};let r;try{r=await dn({root:e,port:n,host:ae,storePath:t,retention:s,log:ze(),version:$e,owner:"desktop"})}catch(c){if(c instanceof At){const d=c.record;return o({event:"running",url:d.url,pid:d.pid,version:d.version,owner:d.owner,contract:d.contract}),0}return c instanceof pe?(o({event:"error",kind:"store",message:c.message,remedy:c.remedy}),1):(o({event:"error",kind:"start",message:c instanceof Error?c.message:String(c)}),1)}let a=!1;const i=c=>{a||(a=!0,process.stderr.write(`[057] stopping (${c}) — history is on disk
120
- `),r.close().then(()=>process.exit(0)))};return process.on("SIGINT",()=>i("SIGINT")),process.on("SIGTERM",()=>i("SIGTERM")),process.stdin.on("end",()=>i("app closed its pipe")),process.stdin.on("close",()=>i("app closed its pipe")),process.stdin.resume(),o({event:"ready",url:`http://${ae}:${r.port}`,pid:process.pid,version:$e,store:t,contract:yt}),new Promise(()=>{})}function Ui(e,t){let s;try{s=Et({path:e,retention:t,observe:!1,log:ze()})}catch(n){return Tt(n)}try{const n=s.store.stats(),o=s.store.sizeBytes(),r=Ve(e).map(i=>St(i)).filter(i=>i!==null).map(i=>"0"+i.toString(8)).join(" ");if(console.log(`
121
- store ${e}${on()?" (from O57_STORE)":""}
136
+ `),i.close().then(()=>process.exit(0)))};return process.on("SIGINT",u),process.on("SIGTERM",u),new Promise(()=>{})}function ec(e,t,s){let n;try{n=lt({path:e,retention:t,observe:!1,log:rc()})}catch(o){return mt(o)}try{const o=Date.now(),r=new Date(o);r.setHours(0,0,0,0);const a=Ya(n.store,r.getTime(),o,n.machine.id);return process.stdout.write(Na(a,s)),0}finally{n.stop()}}async function tc(e,t,s,n){const o=c=>{process.stdout.write(`${JSON.stringify(c)}
137
+ `)};let r;try{r=await Bn({root:e,port:n,host:me,storePath:t,retention:s,log:ft(),version:We,owner:"desktop"})}catch(c){if(c instanceof Xt){const u=c.record;return o({event:"running",url:u.url,pid:u.pid,version:u.version,owner:u.owner,contract:u.contract}),0}return c instanceof ve?(o({event:"error",kind:"store",message:c.message,remedy:c.remedy}),1):(o({event:"error",kind:"start",message:c instanceof Error?c.message:String(c)}),1)}let a=!1;const i=c=>{a||(a=!0,process.stderr.write(`[057] stopping (${c}) — history is on disk
138
+ `),r.close().then(()=>process.exit(0)))};return process.on("SIGINT",()=>i("SIGINT")),process.on("SIGTERM",()=>i("SIGTERM")),process.stdin.on("end",()=>i("app closed its pipe")),process.stdin.on("close",()=>i("app closed its pipe")),process.stdin.resume(),o({event:"ready",url:`http://${me}:${r.port}`,pid:process.pid,version:We,store:t,contract:Wt}),new Promise(()=>{})}function sc(e,t){let s;try{s=lt({path:e,retention:t,observe:!1,log:ft()})}catch(n){return mt(n)}try{const n=s.store.stats(),o=s.store.sizeBytes(),r=dt(e).map(i=>Vt(i)).filter(i=>i!==null).map(i=>"0"+i.toString(8)).join(" ");if(console.log(`
139
+ store ${e}${jn()?" (from O57_STORE)":""}
122
140
  schema ${s.store.schemaVersion}
123
- size ${Me(o.total)} ${ie(`(db ${Me(o.db)}, wal ${Me(o.wal)})`)}
141
+ size ${Be(o.total)} ${fe(`(db ${Be(o.db)}, wal ${Be(o.wal)})`)}
124
142
  events ${n.events.toLocaleString()}
125
143
  claims ${n.claims.toLocaleString()}
126
- keeping ${qe(t)}
144
+ keeping ${ct(t)}
127
145
  permissions ${r||"none — no store yet"}
128
146
  `),n.bySource.length===0)console.log(` nothing has been captured yet
129
- `);else{for(const i of n.bySource){const c=`${new Date(i.first).toISOString().slice(0,10)} → ${new Date(i.last).toISOString().slice(0,10)}`;console.log(` ${i.source.padEnd(20)}${String(i.events).padStart(10)} events ${ie(c)}`)}console.log("")}const a=an();return a&&console.log(` a store from a previous layout is at ${a} and is not in use
130
- `),0}finally{s.stop()}}function Pi(e){let t;try{t=Et({path:e,observe:!1,log:ze()})}catch(s){return Tt(s)}try{const s=t.store.sizeBytes().total,n=t.sweep();t.store.compact();const o=t.store.sizeBytes().total;return console.log(`
147
+ `);else{for(const i of n.bySource){const c=`${new Date(i.first).toISOString().slice(0,10)} → ${new Date(i.last).toISOString().slice(0,10)}`;console.log(` ${i.source.padEnd(20)}${String(i.events).padStart(10)} events ${fe(c)}`)}console.log("")}const a=Ln();return a&&console.log(` a store from a previous layout is at ${a} and is not in use
148
+ `),0}finally{s.stop()}}function nc(e){let t;try{t=lt({path:e,observe:!1,log:ft()})}catch(s){return mt(s)}try{const s=t.store.sizeBytes().total,n=t.sweep();t.store.compact();const o=t.store.sizeBytes().total;return console.log(`
131
149
  removed ${n.processEvents+n.otherEvents} expired events
132
- ${Me(s)} → ${Me(o)}
133
- `),0}finally{t.stop()}}async function Bi(e,t){const s=Ve(e);console.log(`
150
+ ${Be(s)} → ${Be(o)}
151
+ `),0}finally{t.stop()}}async function oc(e,t){const s=dt(e);console.log(`
134
152
  this deletes, permanently:
135
- `);for(const n of s)console.log(` ${n}`);if(console.log(""),!t&&!await Di(" delete the local store?"))return console.log(` nothing was deleted
136
- `),1;for(const n of s)Ss(n,{force:!0});return console.log(` deleted. the next run starts a new store.
137
- `),0}function ze(){return{info:e=>{process.stderr.write(`${ie(e)}
153
+ `);for(const n of s)console.log(` ${n}`);if(console.log(""),!t&&!await Qa(" delete the local store?"))return console.log(` nothing was deleted
154
+ `),1;for(const n of s)Qs(n,{force:!0});return console.log(` deleted. the next run starts a new store.
155
+ `),0}function ft(){return{info:e=>{process.stderr.write(`${fe(e)}
138
156
  `)},warn:e=>{process.stderr.write(`${e}
139
157
  `)},error:e=>{process.stderr.write(`${e}
140
- `)}}}function Tt(e){if(e instanceof pe)return console.error(`
158
+ `)}}}function rc(){return{info:()=>{},warn:()=>{},error:()=>{}}}function mt(e){if(e instanceof ve)return console.error(`
141
159
  057: ${e.message}
142
160
  ${e.remedy}
143
161
  `),1;const t=e?.code;return t==="EADDRINUSE"?(console.error(`
@@ -146,4 +164,4 @@ anything that can reach that address. Do not do it on a network you do not contr
146
164
  057: cannot bind that address or port (${t}).
147
165
  `),1):(console.error(`
148
166
  057: ${e instanceof Error?e.message:String(e)}
149
- `),1)}function Hi(e){if(!e)return;const t=Number(e);return Number.isInteger(t)&&t>=0&&t<=65535?t:void 0}async function As(e){const t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open",{spawn:s}=await import("node:child_process");try{s(t,[e],{stdio:"ignore",detached:!0}).unref()}catch{}}async function ta(e){const t=await Fi(e,xi(import.meta.url));t!==0&&process.exit(t)}export{xi as defaultRoot,ta as main,Fi as run};
167
+ `),1)}function ic(e){if(!e)return;const t=Number(e);return Number.isInteger(t)&&t>=0&&t<=65535?t:void 0}async function Js(e){const t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open",{spawn:s}=await import("node:child_process");try{s(t,[e],{stdio:"ignore",detached:!0}).unref()}catch{}}async function yc(e){const t=await Za(e,Ia(import.meta.url));t!==0&&process.exit(t)}export{Ia as defaultRoot,yc as main,Za as run};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@probnaya/057-cli",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "A spatial interface for observing the shape of a computational workday. Local-first, accountless, offline.",
5
5
  "keywords": [
6
6
  "observability",