@unbrained/pm-cli 2026.9.13 → 2026.9.14
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/.claude-plugin/marketplace.json +2 -2
- package/CHANGELOG.md +22 -0
- package/dist/cli/commander-usage.js +2 -2
- package/dist/cli/error-guidance.js +1 -1
- package/dist/cli/extension-command-help.d.ts +2 -2
- package/dist/cli/extension-command-help.js +2 -2
- package/dist/cli-bundle/bundle-manifest.json +152 -152
- package/dist/cli-bundle/chunks/chunk-33PER336.js +236 -0
- package/dist/cli-bundle/chunks/{chunk-KM4XVZR7.js → chunk-5JIJAWIF.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-A2Q64TGR.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-XM7RWQLM.js → chunk-B6W5LIXK.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-YDSV4QIQ.js → chunk-BY3ID7QI.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-YQTJACN5.js → chunk-D5AJQU7F.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-ZZI7IHMM.js → chunk-DBHQIS6Z.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-LA44JECQ.js → chunk-GQMILIC5.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-3DWX3CKN.js → chunk-NYE6EREL.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-XEZOGC3P.js → chunk-O7SRS7Y3.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-GBK5MV6N.js → chunk-XEV7BHH3.js} +26 -26
- package/dist/cli-bundle/chunks/{chunk-GQQR6JAL.js → chunk-ZYRN2OG3.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-WMJTBWNW.js → register-list-query-B2U36YWL.js} +2 -2
- package/dist/cli-bundle/chunks/{register-mutation-EXGOXP3D.js → register-mutation-GX42CQYR.js} +2 -2
- package/dist/cli-bundle/chunks/{register-operations-2H4CDRGU.js → register-operations-ZV34KX5E.js} +2 -2
- package/dist/cli-bundle/chunks/{register-setup-NYBWGPOS.js → register-setup-W4OS7IZW.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-FBCLVOBE.js → chunk-6WZBO4VQ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-OENAWWP4.js → chunk-7BUJABHB.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-F66QJWI4.js → chunk-C5NQVXKE.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-CMCSUANO.js +20 -0
- package/dist/cli-bundle/focused-chunks/{chunk-FPNI4U2B.js → chunk-CPQQIVDL.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-V7PSTKHD.js → chunk-D4FQV6TY.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-TUHRUFID.js → chunk-ENJH7CBZ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-DSJYL4VP.js → chunk-FHQLQOUZ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-B6JAANOH.js → chunk-FNLAQJES.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-GGDO6VBT.js +30 -0
- package/dist/cli-bundle/focused-chunks/{chunk-SDQCJF4H.js → chunk-KWP3QTN7.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-XCCM7P7V.js → chunk-LFGTCEHX.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-KP3N6PVZ.js → chunk-N23WTRCC.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-ZAMG7HBB.js → chunk-O4EROPO3.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-UFSMYVZF.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-LQ67C7ZO.js → chunk-ZFNRD7EN.js} +2 -2
- package/dist/cli-bundle/main.js +19 -19
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +1 -1
- package/dist/cli-bundle/sdk-core.js +24 -24
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-graph.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +15 -15
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +8 -8
- package/dist/core/output/output.js +3 -3
- package/dist/core/telemetry/runtime.d.ts +35 -8
- package/dist/core/telemetry/runtime.js +5 -4
- package/dist/sdk/agent/command-suggestions.d.ts +6 -0
- package/dist/sdk/agent/command-suggestions.js +1 -1
- package/dist/sdk/cli-contracts/command-aliases.js +1 -1
- package/dist/sdk/cli-contracts/grammar-contracts.d.ts +2 -2
- package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
- package/dist/sdk/cli-contracts/runtime-contracts.d.ts +7 -3
- package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/telemetry.js +1 -1
- package/docs/AGENT_UX_CONTRACTS.md +10 -2
- package/docs/CLI_GRAMMAR.md +28 -0
- package/docs/CONFIGURATION.md +35 -1
- package/docs/generated/AGENT_CAPABILITY_ROUTING.md +1 -1
- package/docs/generated/AGENT_COMMAND_SURFACE.md +1 -0
- package/docs/generated/FLAG_LEXICON_BUDGETS.md +1 -0
- package/marketplace.json +2 -2
- package/package.json +5 -5
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/dist/cli-bundle/chunks/chunk-6KHYW3FH.js +0 -235
- package/dist/cli-bundle/chunks/chunk-AKTBOX6U.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-7JR6M2JR.js +0 -30
- package/dist/cli-bundle/focused-chunks/chunk-YUXBHIUV.js +0 -20
- package/dist/cli-bundle/focused-chunks/chunk-ZF5PXK6A.js +0 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{$d as Yt,$j as ce,Bi as Wo,Ci as Z,Cj as es,Df as Jt,Dh as rn,Di as Yo,E as hr,Ei as Xo,Ej as ts,Ff as Mo,Ge as Io,Gj as mn,He as Co,Hj as ns,Ie as So,Je as To,Jf as br,Kb as ne,Ke as Ro,Kf as Qt,Lf as Ie,Md as bo,Mf as ae,Mn as cs,N as lo,Ni as Cr,O as g,Oe as Ge,Oi as ln,Pa as Ue,Pb as zt,Pd as ye,Pf as No,Pj as rs,Q as _,Qf as ze,Rc as D,Rd as yr,Rh as kr,S as K,Sg as Zt,Tj as is,Ua as _r,Uh as $o,Va as Gt,Vh as Er,Vj as We,Wa as ho,Wh as on,Xe as xo,Xh as Ve,Yi as Jo,Zd as J,Zi as Qo,_c as Vt,_j as U,ab as L,ad as qt,ak as Se,ba as R,bb as Kt,bd as yo,bi as sn,bj as Sr,bk as os,bo as le,cb as go,cf as ve,ci as Po,ck as ss,co as ue,da as gr,df as Ke,di as jo,dk as de,ea as uo,ec as E,ef as Do,ek as pn,fa as I,ff as Xt,fi as Uo,ga as fo,gc as re,gd as vo,ha as _e,hi as an,ib as O,ii as Ho,jf as Ao,ji as Bo,ke as Q,kf as Oo,le as x,lf as Lo,me as j,mf as vr,n as pr,ne as Be,nf as Fo,nj as un,o as Bt,oa as mo,ob as He,oi as qe,oj as fn,p as je,pi as Go,q as se,qa as po,qe as wo,qi as Ko,r as ge,rd as Wt,re as ko,ri as zo,s as W,se as Eo,si as Vo,sm as as,t as co,tg as wr,ti as Ce,tj as Zo,ui as Ir,vh as en,vi as qo,wi as cn,wj as F,xc as _o,xh as tn,xi as xe,yi as dn,zh as nn}from"./chunk-6KHYW3FH.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e252abd5-9585-56f7-9fc2-7b20459a2238")}catch{}})();async function Tr(e){let t=O(process.cwd(),e);await U(t);let n=await F(t),r=L(n,D());return{pmRoot:t,settings:n,typeRegistry:r}}async function hn(e,t,n,r){He(e,Cr(t));let i=await ce(e,t,n.id_prefix,n.item_format,r);if(i)return{id:i.id,historyPath:He(e,i.id),located:i};let o=ln(t,n.id_prefix),s=Cr(t),a=o===s?[o]:[o,s];for(let c of a){let d=He(e,c);if(await Bt(d))return{id:c,historyPath:d,located:null}}throw new _(`Item ${t} not found`,g.NOT_FOUND)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b6ef0b23-e861-50ec-b7b3-751863936631")}catch{}})();function $b(e,t){let n=Ce(e),r=e.length>0?e[e.length-1].after_hash:Ho(),i=t===void 0||n.item_hash_version===void 0?void 0:an(t,n.item_hash_version,ye(e.at(-1)?.hash_algorithm)),o=t===void 0?void 0:i===void 0?Uo(t):i[Math.max(0,i.indexOf(r))],s=o===void 0?void 0:o===r,a=[...n.errors];return s===!1&&a.push("verify_failed:current_item_hash_mismatch"),{ok:a.length===0,entries:e.length,errors:a,latest_after_hash:e.length>0?e[e.length-1].after_hash:void 0,current_item_hash:o,current_matches_latest:s}}async function Pb(e,t,n={}){let r=O(n.cwd??process.cwd(),n.pmRoot);await U(r);let i=await F(r),o=L(i,D()),s=await hn(r,e,i,o.type_to_folder),a=await Xt(s.historyPath,s.id);if(a.length===0)throw new _(`No history exists for ${s.id}; point-in-time reads are unavailable.`,g.NOT_FOUND);let c=ts(t,a),d=ns(mn(a,c.historyIndex),c),l=Ko(d,{schema:i.schema});if(l.metadata.id!==s.id)throw new _(`History target resolved to item ${l.metadata.id}, expected ${s.id}.`,g.GENERIC_FAILURE);let u=a[c.historyIndex],f=es(a,!0);return{document:l,reconstructed:!0,as_of_version:f===null?null:f+c.historyIndex+1,as_of_timestamp:u.ts,target:c,history_length:a.length}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b3394526-5a20-5881-9a03-411ada32bd49")}catch{}})();function Gd(e,t,n,r,i,o){if(e.seen.has(t))return"skip";if(e.cursorFound&&e.affected.length>=o)return"truncate";e.seen.add(t),e.parents.set(t,n.id);let s=n.depth+1;return e.queue.push({id:t,depth:s}),e.cursorFound?(e.affected.push({id:t,distance:s,path:Xd(r,t,e.parents)}),"continue"):(e.cursorFound=t===i,"skip")}function ls(e,t,n,r){let i=Ie("graph impact",{root:e,direction:n,kinds:[...t.kinds??[]].sort(),max_depth:Number.isFinite(r)?r:"unbounded"});return{fingerprint:i,after:t.after===void 0?void 0:No(t.after,i)}}function Ye(e,t,n){e.get(t).add(n)}function ft(e){return new Map(e.map(t=>[t,new Set]))}function us(e){for(let t of e)t.sort();return e.sort((t,n)=>n.length-t.length||t[0].localeCompare(n[0]))}function gn(e){if(Array.isArray(e))return e.map(n=>gn(n));if(e===null||typeof e!="object")return e;let t=e.toJSON;return typeof t=="function"?gn(t.call(e)):Object.fromEntries(Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,gn(r)]))}function ds(e){return JSON.stringify(gn(e))}function Kd(e,t,n,r){let i=[{id:e,expanded:!1}];for(;i.length>0;){let o=i.pop();if(o.expanded){r.push(o.id);continue}if(n.has(o.id))continue;n.add(o.id),i.push({id:o.id,expanded:!0});let s=[...t.get(o.id)].sort().reverse();for(let a of s)n.has(a)||i.push({id:a,expanded:!1})}}function zd(e,t){let n=new Set,r=[];for(let i of e)n.has(i)||Kd(i,t,n,r);return r}function Vd(e,t){let n=new Set,r=[];for(let i of[...e].reverse()){if(n.has(i))continue;let o=[],s=[i];for(n.add(i);s.length>0;){let a=s.pop();o.push(a);for(let c of t.get(a))n.has(c)||(n.add(c),s.push(c))}r.push(o)}return us(r)}function fs(e,t){let n=ft(e);for(let[r,i]of t)for(let o of i)Ye(n,o,r);return Vd(zd(e,t),n)}function qd(e,t){let n=ft(e.nodes());for(let r of e.edges()){let i=t.require(r.kind);if(!i.ordering)continue;let o=(i.precedence??"source_before_target")==="source_before_target";Ye(n,o?r.source:r.target,o?r.target:r.source)}return n}function Wd(e,t){let n=new Map(e.map(o=>[o,0]));for(let o of t.values())for(let s of o)n.set(s,n.get(s)+1);let r=e.filter(o=>n.get(o)===0).sort(),i=[];for(;r.length>0;){i.push(r);let o=[];for(let s of r)for(let a of t.get(s)){let c=n.get(a)-1;n.set(a,c),c===0&&o.push(a)}r=o.sort()}return i}function Yd(e,t){let n=new Map(e.map(s=>[s,0])),r=new Map;for(let s of e)for(let a of t.get(s)){if(!n.has(a))continue;let c=n.get(s)+1,d=r.get(a);(c>n.get(a)||c===n.get(a)&&(d===void 0||s.localeCompare(d)<0))&&(n.set(a,c),r.set(a,s))}let i=[...e].sort((s,a)=>n.get(a)-n.get(s)||s.localeCompare(a))[0],o=i===void 0?[]:[i];for(;o[0]!==void 0&&r.has(o[0]);)o.unshift(r.get(o[0]));return{depth:Object.fromEntries(n),path:o}}function Xd(e,t,n){let r=[t],i=t;for(;i!==e;)i=n.get(i),r.push(i);return r.reverse()}function yn(e,t={}){let n=t.registry??ne(),r=[...e.nodes()],i=qd(e,n),o=Wd(r,i),s=o.flat(),a=s.length===r.length,c=a?[]:fs(r,i).filter(l=>l.length>1||i.get(l[0]).has(l[0])),d=Yd(s,i);return{exact:!0,acyclic:a,order:s,layers:o,frontier:o[0]??[],depth:d.depth,criticalPath:d.path,criticalPathLength:Math.max(0,d.path.length-1),cycles:c,provenance:{algorithm:"kahn-longest-path",edgeFamily:"ordering"}}}function Jd(e,t,n){let r=ft(e.nodes()),i=n===void 0?void 0:new Set(n.map(s=>e.registry().require(s).kind)),o=e.edges();for(let s of o){let a=e.registry().require(s.kind);i!==void 0&&!i.has(s.kind)&&(a.inverse===void 0||!i.has(a.inverse))||Ye(r,t==="incoming"?s.target:s.source,t==="incoming"?s.source:s.target)}return{adjacency:r,inspectedEdges:o.length}}function Qd(e,t,n,r,i,o){let s=_n(e,t,{...n,after:void 0,direction:"incoming",limit:void 0}),a=_n(e,t,{...n,after:void 0,direction:"outgoing",limit:void 0}),c=new Map,d=[...s.affected,...a.affected].sort((m,h)=>m.distance-h.distance||m.id.localeCompare(h.id)||m.path.join("\0").localeCompare(h.path.join("\0")));for(let m of d)c.has(m.id)||c.set(m.id,m);let l=[...c.values()].sort((m,h)=>m.distance-h.distance||m.id.localeCompare(h.id)),u=r===void 0||r===t?-1:l.findIndex(m=>m.id===r);if(r!==void 0&&r!==t&&u<0)throw new TypeError(`Unknown impact cursor item: ${r}`);let f=l.slice(u+1,u+1+i),p=u+1+f.length<l.length;return{root:t,affected:f,exact:!0,truncated:s.truncated||a.truncated||p,...p?{nextCursor:ae(o,f.at(-1)?.id??t)}:{},cost:{visitedNodes:s.cost.visitedNodes+a.cost.visitedNodes,inspectedEdges:s.cost.inspectedEdges+a.cost.inspectedEdges}}}function Zd(e,t,n){let r=n.direction,i=n.maxDepth??Number.POSITIVE_INFINITY,o=n.limit??Number.POSITIVE_INFINITY,{fingerprint:s,after:a}=ls(t,n,r,i),{adjacency:c,inspectedEdges:d}=Jd(e,r,n.kinds),l={queue:[{id:t,depth:0}],seen:new Set([t]),parents:new Map,affected:[],cursorFound:a===void 0||a===t},u=0,f=!1,p=!1;e:for(let m=0;m<l.queue.length;m+=1){n.signal?.throwIfAborted();let h=l.queue[m];u+=1;let y=[...c.get(h.id)].sort();if(h.depth>=i){y.some(b=>!l.seen.has(b))&&(f=!0);continue}for(let b of y)if(Gd(l,b,h,t,a,o)==="truncate"){f=!0,p=!0;break e}}if(!l.cursorFound)throw new TypeError(`Unknown impact cursor item: ${a}`);return{root:t,affected:l.affected,exact:!0,truncated:f,...p?{nextCursor:ae(s,l.affected.at(-1)?.id??t)}:{},cost:{visitedNodes:u,inspectedEdges:d}}}function _n(e,t,n={}){let r=n.direction??"outgoing";if(r!=="both")return Zd(e,t,{...n,direction:r});let i=n.maxDepth??Number.POSITIVE_INFINITY,o=n.limit??Number.POSITIVE_INFINITY,{fingerprint:s,after:a}=ls(t,n,r,i);return Qd(e,t,n,a,o,s)}function ms(e){let t=[...e.nodes()],n=ft(t),r=ft(t);for(let c of e.edges())Ye(n,c.source,c.target),Ye(n,c.target,c.source),Ye(r,c.source,c.target);let i=[],o=new Set;for(let c of t){if(o.has(c))continue;let d=[],l=[c];for(o.add(c);l.length>0;){let u=l.pop();d.push(u);for(let f of n.get(u))o.has(f)||(o.add(f),l.push(f))}i.push(d)}let s=t.map(c=>({id:c,degree:n.get(c).size})),a=Math.max(0,...s.map(({degree:c})=>c));return{components:us(i),stronglyConnected:fs(t,r),orphans:s.filter(({degree:c})=>c===0).map(({id:c})=>c),hubs:s.filter(({degree:c})=>c>0&&c===a),exact:!0,provenance:{algorithm:"component-degree",edgeFamily:"all"}}}function Bb(e,t){let n=new Map(e.edges.map(i=>[ds(i),i])),r=new Map(t.edges.map(i=>[ds(i),i]));return{fromVersion:e.version,toVersion:t.version,added:[...r].filter(([i])=>!n.has(i)).map(([,i])=>i),removed:[...n].filter(([i])=>!r.has(i)).map(([,i])=>i),unchangedCount:[...n.keys()].filter(i=>r.has(i)).length,exact:!0}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fdc16f69-f63f-5e17-9139-35d54db7bab5")}catch{}})();function ie(e,t="--limit"){if(e===void 0)return;let n=String(e).trim(),r=n.length===0?Number.NaN:Number(n);if(!Number.isInteger(r)||r<0)throw new _(`${t} must be a non-negative integer`,g.USAGE);return r}function vn(e,t="--priority"){if(e===void 0)return;let n=String(e).trim(),r=n.length===0?Number.NaN:Number(n);if(!Number.isInteger(r)||r<0||r>4)throw new _(`${t} filter must be 0..4`,g.USAGE);return r}function ps(e,t,n="--type"){if(e===void 0)return;let r=Kt(e,t);if(!r)throw new _(`${n} filter must be one of ${t.types.join("|")}`,g.USAGE);return r}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="94a81e04-bb02-5c2e-9362-4cf7212d66e6")}catch{}})();var bn={version:1,aliases:{}};function wn(e=[]){let t=new Set(Ge),n=r=>{/^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(r)&&t.add(r)};for(let r of e){for(let i of Object.keys(r.provenance_environment_keys??{}))n(i);for(let i of Object.keys(r.provenance_resolvers??{}))n(i);for(let i of r.provenance_unavailable_dimensions??[])n(i)}return[...t].sort()}function hs(e){if(e===void 0)return;let n=(typeof e=="string"?[e]:e).flatMap(r=>r.split(",")).map(r=>r.trim()).filter(r=>r.length>0);return n.length===0?void 0:new Set(n)}function Rr(e,t){if(e.agent_harness?.trim())return{agent_harness:e.agent_harness,harness_source:"recorded"};let n=t.aliases[e.author];return n?{agent_harness:n,harness_source:"vocabulary"}:{harness_source:"unresolved"}}function xr(e,t=Ge){let n=new Set(t),r=new Map,i=e.provenance===void 0?[]:typeof e.provenance=="string"?[e.provenance]:e.provenance;for(let o of i.flatMap(s=>s.split(","))){let s=o.indexOf("=");if(s<0)throw new _(`Provenance predicate must use dimension=value; received "${o.trim()}".`,g.USAGE,{code:"invalid_provenance_predicate"});let a=o.slice(0,s).trim().toLowerCase(),c=o.slice(s+1).trim();if(!n.has(a))throw new _(`Unknown provenance dimension "${a||o.trim()}". Declared dimensions: ${[...n].sort().join(", ")}.`,g.USAGE,{code:"unknown_provenance_dimension"});if(c.length===0)throw new _(`Provenance predicate must use dimension=value; received "${o.trim()}".`,g.USAGE,{code:"invalid_provenance_predicate"});let d=r.get(a)??new Set;d.add(c),r.set(a,d)}return r}function kn(e,t=bn,n={}){let r=Rr(e,t);return{...n.itemId===void 0?{}:{item_id:n.itemId},...n.version===void 0?{}:{version:n.version},ts:e.ts,op:e.op,author:e.author,...e.author_source===void 0?{}:{author_source:e.author_source},...r,vocabulary_version:t.version,...e.agent_instance===void 0?{}:{agent_instance:e.agent_instance},agent_provenance:e.agent_provenance??{},...e.message===void 0?{}:{message:e.message}}}function Qb(e,t,n=bn,r=Ge){return Dr(t,n,r)(e)}function Dr(e,t=bn,n=Ge){let r=hs(e.harness),i=hs(e.agentInstance),o=xr(e,n);return s=>{let c=Rr(s,t).agent_harness;if(r&&(!c||!r.has(c))||i&&!i.has(s.agent_instance??""))return!1;for(let[d,l]of o){let u=s.agent_provenance?.[d];if(!u||!l.has(u.value))return!1}return!0}}function En(e,t=bn,n=Ge){let r=new Set(n),i=new Map,o=0;for(let s of e){for(let c of Object.keys(s.agent_provenance??{}))r.add(c);Rr(s,t).agent_harness?o+=1:i.set(s.author,(i.get(s.author)??0)+1)}return{entries:e.length,vocabulary_version:t.version,harness:{resolved:o,unresolved:e.length-o,unresolved_authors:[...i].map(([s,a])=>({author:s,entries:a})).sort((s,a)=>a.entries-s.entries||s.author.localeCompare(a.author)).slice(0,20)},dimensions:[...r].sort().map(s=>{let a=0,c=0;for(let d of e){let l=d.agent_provenance?.[s];l===null?c+=1:l!==void 0&&(a+=1)}return{dimension:s,observed:a,unavailable:c,legacy_missing:e.length-a-c}})}}import el from"node:fs/promises";import ys from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="03488490-bc4a-5988-9ceb-46800c6d7833")}catch{}})();var tl=20,nl=5,rl=15,il="-24h";function dw(e){let t={...e};return t.full===!0?(t.raw=!0,t.compact=!1):t.raw===!0&&t.compact===void 0&&(t.compact=!0),delete t.full,t}var ol={digest:"activity_digest",compact:"compact_activity",provenance:"provenance_activity",full:"activity"};function Ar(e,t){if(e===void 0)return;let n=e.trim();if(n.length===0)throw new _(`${t} must not be empty`,g.USAGE);return n}function gs(e,t,n){if(e===void 0)return;let r=e.trim();if(r.length===0)throw new _("Activity time bounds must not be empty",g.USAGE);let i=n==="--from"&&/^\d+[hdwm]$/iu.test(r)?`-${r}`:r;return _e(i,new Date(t),n)}function sl(e,t,n){return!(e.ts.length===0&&(t||n)||t&&I(e.ts,t)<0||n&&I(e.ts,n)>=0)}function _s(e,t){return t===void 0?e:e.slice(0,t)}function mt(e,t=""){return typeof e=="string"?e:t}function al(e,t){return{...t,id:e,ts:mt(t.ts),author:mt(t.author,"unknown"),op:mt(t.op,"unknown"),patch:Array.isArray(t.patch)?t.patch:[],before_hash:mt(t.before_hash),after_hash:mt(t.after_hash)}}function cl(e){return[...e].sort((t,n)=>{let r=n.ts.localeCompare(t.ts);if(r!==0)return r;let i=t.id.localeCompare(n.id);return i!==0?i:t.op.localeCompare(n.op)})}async function dl(e){try{return(await el.readdir(e)).filter(t=>t.endsWith(".jsonl")).sort((t,n)=>t.localeCompare(n))}catch(t){if(se(t))return[];throw t}}function ll(e){return e.raw!==!0&&e.compact!==!0&&e.provenance!==!0?"digest":e.provenance===!0?"provenance":e.compact===!0||e.raw===!0&&e.compact!==!1?"compact":"full"}function ul(e,t,n){if(e.unbounded!==!0)return t!==void 0?t:n==="digest"?rl:n==="compact"?tl:nl}function fl(e,t){let n=R(),r=t==="digest",i=gs(e.to??(r?n:void 0),n,"--to"),o=gs(e.from??(r?il:void 0),e.from===void 0&&r?i:n,"--from");if(o&&i&&I(o,i)>=0)throw new _("Activity --from must be before --to",g.USAGE);let s=Sr(e.limit);if(e.unbounded===!0&&s!==void 0)throw new _("Activity --unbounded cannot be combined with --limit",g.USAGE);return{id:Ar(e.id,"Activity --id"),op:Ar(e.op,"Activity --op"),author:Ar(e.author,"Activity --author"),from:o,to:i,limit:ul(e,s,t),limitSource:e.unbounded===!0||s!==void 0?"explicit":"default",harness:e.harness,agentInstance:e.agentInstance,provenance:e.provenanceFilter}}async function ml(e){let t=O(process.cwd(),e.path);return await U(t),{pmRoot:t,settings:await F(t)}}async function pl(e){let t=L(e.settings,D()),n=await de(e.pmRoot,e.settings.item_format,t.type_to_folder,void 0,e.settings.schema);await Wo({pmRoot:e.pmRoot,settings:e.settings,itemIds:n.map(i=>i.id),commandLabel:"activity"});let r=ys.join(e.pmRoot,"history");return await qt({path:r,scope:"project"}),{historyDir:r,itemsById:new Map(n.map(i=>[i.id,{title:i.title,type:i.type,status:i.status}]))}}function hl(e,t,n){return n.op&&e.op!==n.op||n.author&&e.author!==n.author?!1:sl(t,n.from,n.to)}async function gl(e,t){let n=[];for(let r of await dl(e)){let i=r.slice(0,-6);if(t.id&&i!==t.id)continue;let o=await Xt(ys.join(e,r),i);for(let s of o){let a=al(i,s);hl(s,a,t)&&n.push(a)}}return n}function _l(e){return e.map(t=>({id:t.id,op:t.op,ts:t.ts,author:t.author,...t.message?{msg:t.message}:{}}))}function yl(e){let t=[...e.entries()].sort(([r,i],[o,s])=>s-i||r.localeCompare(o)),n=t.slice(0,4).map(([r,i])=>`${r}:${i}`);return t.length>n.length&&n.push(`+${t.length-n.length}`),n.join(",")}function vl(e,t){let n=new Map;for(let r of e){let i=n.get(r.id);if(i===void 0){n.set(r.id,{firstTs:r.ts,lastTs:r.ts,eventCount:1,operations:new Map([[r.op,1]])});continue}i.eventCount+=1,I(r.ts,i.firstTs)<0&&(i.firstTs=r.ts),I(r.ts,i.lastTs)>0&&(i.lastTs=r.ts),i.operations.set(r.op,(i.operations.get(r.op)??0)+1)}return[...n.entries()].map(([r,i])=>{let o=t.get(r);return{id:r,type:o?.type??"unknown",status:o?.status??"unknown",title:(o?.title??"(item metadata unavailable)").slice(0,160),event_count:i.eventCount,first_ts:i.firstTs,last_ts:i.lastTs,operations:yl(i.operations)}}).sort((r,i)=>I(i.last_ts,r.last_ts)||r.id.localeCompare(i.id))}function bl(e){let t=new Map;for(let i of e)t.set(i.op,(t.get(i.op)??0)+1);let n=[...t.entries()].sort((i,o)=>o[1]-i[1]||i[0].localeCompare(o[0])),r=n.slice(0,8);return r.length<n.length&&r.push([`+${String(n.length-r.length)}`,n.slice(r.length).reduce((i,[,o])=>i+o,0)]),Object.fromEntries(r)}function wl(e,t,n,r,i){if(e==="digest"){let s=vl(t,r),a=_s(s,n);return{rows:{activity_digest:a},compact:!1,totalRows:s.length,returnedRows:a.length}}let o=_s(t,n);return e==="compact"?{rows:{compact_activity:_l(o)},compact:!0,totalRows:t.length,returnedRows:o.length}:e==="provenance"?{rows:{provenance_activity:o.map(i)},compact:!1,totalRows:t.length,returnedRows:o.length}:{rows:{activity:o},compact:!1,totalRows:t.length,returnedRows:o.length}}async function vs(e,t){let n=await ml(t),r=ll(e),i=fl(e,r),o=await pl(n),s=wn(n.settings.agent_identity.harness_signals),a=n.settings.agent_identity.identity_vocabulary,c=Dr({harness:i.harness,agentInstance:i.agentInstance,provenance:i.provenance},a,s),d=cl(await gl(o.historyDir,i)).filter(c),l=wl(r,d,i.limit,o.itemsById,f=>kn(f,a,{itemId:f.id})),u=l.totalRows-l.returnedRows;return{...l.rows,compact:l.compact,projection:{mode:r,row_key:ol[r]},omission_receipt:Mo("activity",r),count:l.returnedRows,total_count:l.totalRows,limit:i.limit??null,omitted_count:u,has_more:u>0,...r==="digest"?{activity_summary:{window:{from:i.from,to:i.to},event_count:d.length,item_count:l.totalRows,author_count:new Set(d.map(f=>f.author)).size,operation_counts:bl(d)}}:{},...e.provenanceSummary===!0?{provenance_summary:En(d,a,s)}:{},applied_bound:{kind:i.limit===void 0?"unbounded":"limit",source:i.limitSource,value:i.limit??null}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fdd874ad-e51d-5df2-9486-a0465ad65979")}catch{}})();var kl="global",pw="external",El=["open","closed","unknown"],pt=new Map,Il=240,Cl=2048;function bs(e,t,n){return(e?.trim()||t).slice(0,n)}function Sl(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;return typeof t.status=="string"&&(t.title==null||typeof t.title=="string")&&(t.source==null||typeof t.source=="string")&&(t.checkedAt==null||typeof t.checkedAt=="string")}function hw(e){let t=e.name.trim();if(t.length===0)throw new Error("External dependency resolver name must not be empty");if(pt.has(t))throw new Error(`External dependency resolver already registered: ${t}`);let n={name:t,supports:r=>e.supports(r),resolve:r=>e.resolve(r)};return pt.set(t,n),()=>{pt.get(t)===n&&pt.delete(t)}}async function gw(e,t={}){let n=e.trim();if(!le(n))return null;let r=[...pt.values()].filter(o=>{try{return o.supports(n)}catch{return!1}}),i=await Promise.allSettled(r.map(o=>Promise.resolve().then(()=>o.resolve(n))));for(let[o,s]of i.entries()){if(s.status!=="fulfilled"||!Sl(s.value))continue;let a=r[o],c=s.value,d=El.includes(c.status)?c.status:"unknown",l=bs(c.title,"",Il),u=bs(c.source,n,Cl),f=Date.parse(c.checkedAt?.trim()??""),p=Number.isFinite(f)?new Date(f).toISOString():t.now?.()??new Date().toISOString();return{id:n,status:d,resolved:d==="closed",title:l.length>0?l:null,source:u,checked_at:p,resolver:a.name}}return null}function _w(e){let t=e?.trim();if(t)return ue(t)?kl:t}function yw(e,t,n){return Tl(e,t,n)}function Tl(e,t,n){let r=e.trim();return ue(n)||le(r)?r:ln(r,t)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0a3dd0c1-2dea-5143-a2eb-65e758a0cc71")}catch{}})();function z(){let e=ne();for(let t of D()?.relationship_kinds??[])for(let n of t.definitions)e.register(n);return e}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="83d1acab-79a1-5e9f-b6a4-97dade07d74a")}catch{}})();function ht(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function In(e){return[e.parent_id,e.child_id,e.source,e.kind,e.holder_id,e.target_id??""].join("\0")}function Rl(e,t){let n=new Set,r=[];for(let i of[...e].sort()){if(n.has(i))continue;n.add(i);let o=[{nodeId:i,children:[...t.get(i)??[]].sort(),nextChild:0}];for(;o.length>0;){let s=o.at(-1),a=s.children[s.nextChild];a===void 0?(r.push(s.nodeId),o.pop()):(s.nextChild+=1,n.has(a)||(n.add(a),o.push({nodeId:a,children:[...t.get(a)??[]].sort(),nextChild:0})))}}return r}function xl(e,t){let n=[...e].sort(),r=Rl(n,t),i=new Set,o=Dl(n,t),s=[];for(let a of r.reverse()){if(i.has(a))continue;let c=Al(a,o,i);(c.length>1||t.get(c[0])?.has(c[0]))&&s.push(c)}return s.sort((a,c)=>a.join("\0").localeCompare(c.join("\0")))}function Dl(e,t){let n=new Map(e.map(r=>[r,new Set]));for(let[r,i]of t)for(let o of i)n.get(o)?.add(r);return n}function Al(e,t,n){let r=[],i=[e];for(n.add(e);i.length>0;){let o=i.pop();r.push(o);for(let s of[...t.get(o)].sort())n.has(s)||(n.add(s),i.push(s))}return r.sort()}function ws(e){let t=new Map;for(let n of e){let r=ht(n?.id);r&&!t.has(r)&&t.set(r,n)}return t}function Ol(e,t,n){let r=ht(t.parent);if(!(!r||!n.has(r)))return{parent_id:r,child_id:e,source:"scalar_parent",kind:"parent",holder_id:e,child_cardinality:"one"}}function Ll(e,t,n,r){let i=ht(t?.id),o=r.resolve(t?.kind);if(!i||!n.has(i)||!o?.hierarchy)return;let s=o.hierarchyDirection==="source_parent";return{parent_id:s?e:i,child_id:s?i:e,source:"dependency",kind:o.kind,holder_id:e,target_id:i,child_cardinality:s?o.incoming:o.outgoing}}function ks(e,t){let n=new Map;for(let[r,i]of e){let o=Ol(r,i,e);o&&n.set(In(o),o);for(let s of i.dependencies??[]){let a=Ll(r,s,e,t);a&&n.set(In(a),a)}}return[...n.values()].sort((r,i)=>In(r).localeCompare(In(i)))}function Es(e,t=z()){return ks(ws(e),t)}function Fl(e,t,n){let r=new Set(e.filter(i=>i.child_cardinality==="one").map(i=>i.child_id));return[...t].filter(([i,o])=>o.length>1&&r.has(i)).map(([i,o])=>({child_id:i,parent_ids:[...o],legacy_terminal:n.has(i)&&o.every(s=>n.has(s))})).sort((i,o)=>i.child_id.localeCompare(o.child_id))}function Ml(e,t,n){let r=new Map;for(let o of t){if(o.source!=="dependency")continue;let s=r.get(o.child_id)??new Set;s.add(o.parent_id),r.set(o.child_id,s)}let i=[];for(let[o,s]of e){let a=ht(s.parent);if(!a||!e.has(a))continue;let c=[...r.get(o)??[]].filter(d=>d!==a).sort();c.length!==0&&i.push({child_id:o,scalar_parent_id:a,dependency_parent_ids:c,legacy_terminal:n.has(o)&&n.has(a)&&c.every(d=>n.has(d))})}return i.sort((o,s)=>o.child_id.localeCompare(s.child_id))}function Cn(e,t=r=>r==="closed"||r==="canceled",n=z()){let r=ws(e),i=ks(r,n),o=Lr(i),s=new Set([...r].filter(([,c])=>t(c.status)).map(([c])=>c)),a=xl([...r.keys()],new Map([...o.children_by_parent].map(([c,d])=>[c,new Set(d)]))).map(c=>({item_ids:c,legacy_terminal:c.every(d=>s.has(d))}));return{relations:i,cycles:a,cardinality_violations:Fl(i,o.parents_by_child,s),divergences:Ml(r,i,s)}}function Sw(e){return e.source==="scalar_parent"?`${e.parent_id} -> ${e.child_id} (scalar parent on ${e.holder_id})`:`${e.parent_id} -> ${e.child_id} (${e.kind} dependency on ${e.holder_id})`}function Lr(e){let t=new Map,n=new Map;for(let r of e){let i=t.get(r.child_id)??new Set;i.add(r.parent_id),t.set(r.child_id,i);let o=n.get(r.parent_id)??new Set;o.add(r.child_id),n.set(r.parent_id,o)}return{parents_by_child:new Map([...t].map(([r,i])=>[r,[...i].sort()])),children_by_parent:new Map([...n].map(([r,i])=>[r,[...i].sort()]))}}function Or(e,t){let n=new Set(t);return e.every(r=>n.has(r))}function Tw(e,t,n,r,i){let o=ht(n);if(!o)return;let s=Cn(e,r,i),a=Cn(t,r,i),c=a.divergences.find(u=>!s.divergences.some(f=>f.child_id===u.child_id&&f.scalar_parent_id===u.scalar_parent_id&&Or(u.dependency_parent_ids,f.dependency_parent_ids)));if(c){let u=[c.scalar_parent_id,...c.dependency_parent_ids].sort();throw new _(`Hierarchy mutation would assign ${c.child_id} to multiple parents: ${u.join(", ")}.`,g.CONFLICT,{code:"hierarchy_parent_divergence_created",source_id:o,target_id:c.child_id,verification_errors:u})}let d=a.cardinality_violations.find(u=>(u.child_id===o||u.parent_ids.includes(o))&&!s.cardinality_violations.some(f=>f.child_id===u.child_id&&Or(u.parent_ids,f.parent_ids)));if(d)throw new _(`Hierarchy mutation would assign ${d.child_id} to multiple parents: ${d.parent_ids.join(", ")}.`,g.CONFLICT,{code:"hierarchy_cardinality_created",source_id:o,target_id:d.child_id,verification_errors:d.parent_ids});let l=a.cycles.find(u=>u.item_ids.includes(o)&&!s.cycles.some(f=>Or(u.item_ids,f.item_ids)));if(l)throw new _(`Hierarchy mutation would create a cycle: ${l.item_ids.join(" -> ")}.`,g.CONFLICT,{code:"hierarchy_cycle_created",source_id:o,verification_errors:l.item_ids})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="06ecc7a4-c593-5d99-89f5-714a4590d0a5")}catch{}})();function Je(e){if(typeof e!="string")return;let t=e.trim();if(!(!t||["none","null","n/a","na"].includes(t.toLowerCase())))return t}function gt(e){let t=Je(e);return t?.toLowerCase()==="no-active-blocker"?void 0:t}function _t(e,t,n=!0){let r=Je(e);return n&&(ue(t)||r!==void 0&&le(r))}function Fr(e,t){return _t(e,t)?`external\0${e}`:`local\0${e.toLowerCase()}`}function Is(e,t,n,r){return _t(e,t)?r.get(e):n.get(e.toLowerCase())}function Xe(e,t){let n=e.toLowerCase(),r=t.toLowerCase();return n!==r?n<r?-1:1:e!==t?e<t?-1:1:0}function Nl(e){let t=new Map;for(let n of e.dependencies??[]){if(typeof n!="object"||n===null)continue;let r=n,i=Je(r.id);if(!i)continue;let o=typeof r.kind=="string"?r.kind:"related",s=`${o}\0${Fr(i,r.source_kind)}`,a=t.get(s);a?a.count+=1:t.set(s,{target_id:i,kind:o,count:1})}return t}function $l(e,t=n=>n==="closed"||n==="canceled"){let n=[];for(let r of e)if(!(typeof r?.id!="string"||r.id.trim().length===0))for(let i of Nl(r).values())i.count<2||n.push({holder_id:r.id.trim(),target_id:i.target_id,kind:i.kind,occurrences:i.count,holder_status:r.status,legacy_terminal:t(r.status)});return n.sort((r,i)=>{let o=Xe(r.holder_id,i.holder_id);if(o!==0)return o;let s=Xe(r.target_id,i.target_id);return s!==0?s:Xe(r.kind,i.kind)})}function Pl(e,t,n,r,i){if(typeof n!="object"||n===null)return;let o=Je(n.id);if(!o||Fr(o,n.source_kind)!==Fr(t))return;let s=i.resolve(typeof n.kind=="string"?n.kind:"related");if(!(s?.ordering!==!0||(s.precedence??"source_before_target")!=="source_before_target"))return{holder_id:e.id.trim(),target_id:o,dependency_kind:s.kind,holder_status:e.status,legacy_terminal:r(e.status)}}function jl(e,t=r=>r==="closed"||r==="canceled",n=z()){let r=new Map;for(let i of e){if(typeof i?.id!="string"||i.id.trim().length===0)continue;let o=Je(i.blocked_by);if(o)for(let s of i.dependencies??[]){let a=Pl(i,o,s,t,n);a&&r.set(`${a.holder_id.toLowerCase()}\0${a.target_id.toLowerCase()}\0${a.dependency_kind}`,a)}}return[...r.values()].sort((i,o)=>{let s=Xe(i.holder_id,o.holder_id);if(s!==0)return s;let a=Xe(i.target_id,o.target_id);return a!==0?a:Xe(i.dependency_kind,o.dependency_kind)})}function Mr(e,t=n=>n==="closed"||n==="canceled"){let n=e.filter(c=>typeof c?.id=="string"&&c.id.trim().length>0),r=new Set(n.map(c=>c.id.trim().toLowerCase())),i=new Map,o=(c,d,l,u,f)=>{let p=Je(d);if(!p||r.has(p.toLowerCase())||_t(p,void 0,f))return;let m={holder_id:c.id.trim(),target_id:p,kind:l,source:u,holder_status:c.status,legacy_terminal:t(c.status),no_active_blocker_sentinel:p.toLowerCase()==="no-active-blocker"};i.set(`${m.holder_id}::${m.target_id}::${m.kind}::${m.source}`,m)};for(let c of n){o(c,c.parent,"parent","parent",!1),o(c,c.blocked_by,"blocked_by","blocked_by",!0);for(let d of c.dependencies??[]){if(typeof d!="object"||d===null)continue;let l=d;ue(l.source_kind)||o(c,l.id,typeof l.kind=="string"?l.kind:"related","dependency",!0)}}let s=[...i.values()].sort((c,d)=>c.holder_id.localeCompare(d.holder_id)||c.target_id.localeCompare(d.target_id)||c.kind.localeCompare(d.kind)||c.source.localeCompare(d.source)),a=s.filter(c=>c.legacy_terminal);return{active:s.filter(c=>!c.legacy_terminal),legacy_terminal:a,no_active_blocker_sentinels:s.filter(c=>c.no_active_blocker_sentinel)}}function Ul(e){let t=new Map;for(let n of[...e.active,...e.legacy_terminal]){if(n.no_active_blocker_sentinel)continue;let r=n.target_id.trim(),i=r.toLowerCase();t.has(i)||t.set(i,r)}return[...t.values()].sort((n,r)=>n.localeCompare(r))}function Hl(e){let t=new Map;for(let n of e){let r=gt(n.blocked_by);r&&_t(r)&&!t.has(r)&&t.set(r,r);for(let i of n.dependencies??[]){if(typeof i!="object"||i===null||!_t(i.id,i.source_kind))continue;let o=gt(i.id);o&&!t.has(o)&&t.set(o,o)}}return[...t.values()].sort((n,r)=>n.localeCompare(r))}var Cs=new WeakMap;function Sn(e){return e.hierarchyIntegrity??Cs.get(e)}function Bl(e,t=z()){let n={};for(let r of e)for(let i of r.dependencies??[]){if(typeof i!="object"||i===null)continue;let o=i.kind;if(typeof o!="string")continue;let s=o.trim().toLowerCase().replaceAll("-","_"),a=t.resolve(o);a&&s!==a.kind&&(n[s]=(n[s]??0)+1)}return Object.fromEntries(Object.entries(n).sort(([r],[i])=>r.localeCompare(i)))}function Qe(e,t,n){let r=n??z(),i=e.filter(m=>typeof m?.id=="string"&&m.id.trim().length>0),o=new Map(i.map(m=>[m.id.trim().toLowerCase(),m.id.trim()])),s=Mr(i,t),a=Ul(s);for(let m of a)o.set(m.toLowerCase(),m);let c=Hl(i),d=new Set(o.keys()),l=new Map;for(let m of c){let h=m;for(;d.has(h.toLowerCase());)h=`external:${h}`;l.set(m,h),d.add(h.toLowerCase())}let u=i.map(m=>{let h=gt(m.parent),y=gt(m.blocked_by),b=(m.dependencies??[]).flatMap(v=>{if(typeof v!="object"||v===null)return[];let w=v,C=gt(w.id);return C?[{id:Is(C,w.source_kind,o,l),kind:typeof w.kind=="string"?w.kind:"related"}]:[]});return{id:m.id.trim(),...h?{parent:o.get(h.toLowerCase())}:{},...y?{blocked_by:Is(y,void 0,o,l)}:{},dependencies:b}}),f=Cn(i,t,r),p={graph:zt.fromItems([...u,...a.map(m=>({id:m})),...c.map(m=>({id:l.get(m)}))],r),details:[...i.map(m=>({id:m.id.trim(),title:m.title,status:m.status,...typeof m.type=="string"&&m.type.trim().length>0?{type:m.type.trim()}:{}})),...a.map(m=>({id:m,title:`[missing] ${m}`,status:"missing"})),...c.map(m=>({id:l.get(m),title:`[external] ${m}`,status:"external"}))],missingIdSet:new Set(a.map(m=>m.toLowerCase())),dangling:s,duplicateRows:$l(i,t),orderingContradictions:jl(i,t,r),legacyAliasCounts:Bl(i,r),hierarchyIntegrity:f};return Cs.set(p,f),p}import{createHash as Gl}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="10f534cf-ee82-54a2-9807-390eca5fb0b8")}catch{}})();var Kl=64,zl=8;function Vl(e,t){let n=(e.dependencies??[]).map(r=>{if(typeof r!="object"||r===null)return"";let i=r;return`${typeof i.kind=="string"?i.kind:"related"}:${typeof i.id=="string"?i.id:""}`}).sort().join(",");return[e.id,e.title,e.status,t(e.status)?"1":"0",typeof e.type=="string"?e.type.trim():"",e.parent??"",e.blocked_by??"",n].join("\0")}function Tn(e,t=r=>r==="closed"||r==="canceled",n=ne()){let r=e.filter(o=>typeof o?.id=="string"&&o.id.trim().length>0).map(o=>Vl(o,t)).sort(),i=n.list().map(o=>E(o)).sort();return Gl("sha256").update(r.join("")).update("").update(i.join("")).digest("hex")}function Ss(e,t,n){let r=t??n;if(!Number.isInteger(r)||r<1)throw new TypeError(`Invalid ${e} bound: ${String(t)}`);return r}var Nr=class{#e=new Map;#t;#n;constructor(t={}){this.#t=Ss("maxResultsPerWorkspace",t.maxResultsPerWorkspace,Kl),this.#n=Ss("maxWorkspaces",t.maxWorkspaces,zl)}lookup(t,n,r){let i=this.#e.get(t),o=!0;(i===void 0||i.fingerprint!==n)&&(i={fingerprint:n,assembly:r(),results:new Map},o=!1,!this.#e.has(t)&&this.#e.size>=this.#n&&this.#e.delete(this.#e.keys().next().value)),this.#e.delete(t),this.#e.set(t,i);let s=i,a=this.#t;return{assembly:s.assembly,assemblyReused:o,fingerprint:n,memoize(c,d){let l=s.results.get(c);if(l!==void 0||s.results.has(c))return s.results.delete(c),s.results.set(c,l),{value:structuredClone(l),reused:!0};let u=d();return s.results.size>=a&&s.results.delete(s.results.keys().next().value),s.results.set(c,structuredClone(u)),{value:u,reused:!1}}}}clear(){this.#e.clear()}},Ts=new Nr;function Rn(){return Ts}function Pw(){Ts.clear()}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="47b3091f-a1a8-503c-83e9-46b85adf4207")}catch{}})();var ql=["prerequisite","dependent","ancestor","descendant","provenance","related"],Wl=new TextEncoder;function $r(e,t,n){let r=e??t;if(!Number.isInteger(r)||r<1)throw new TypeError(`Relationship context ${n} must be positive`);return r}function xn(e){return Math.max(1,Math.ceil(Wl.encode(JSON.stringify(e)).byteLength/4))}function Pr(e,t,n){let r=n.resolve(e.kind);if(r?.ordering){let o=(r.precedence??"source_before_target")==="source_before_target"?e.source:e.target;return t===o?"prerequisite":"dependent"}if(r?.hierarchy){let o=r.hierarchyDirection==="source_parent"?e.source:e.target;return t===o?"ancestor":"descendant"}return e.kind==="discovered_from"||e.kind==="incident_from"?"provenance":"related"}function Yl(e,t,n,r){let i=e.filter(o=>o.source===t&&o.target===n||o.target===t&&o.source===n).map(o=>Pr(o,n,r));return[...new Set(i)].sort()}function Xl(e){return ql.find(t=>e.includes(t))}function Jl(e,t,n,r){let i=r.direction??"both",o=r.maxDepth??3;if(!Number.isInteger(o)||o<0)throw new TypeError("Relationship context maxDepth must be non-negative");let s=new Set([t]),a=[{id:t,distance:0}],c=[],d=0,l=!1;for(let u=0;u<a.length;u+=1){r.signal?.throwIfAborted();let f=a[u];if(f.distance>=o&&l)continue;let p=e.neighborEdges(f.id,{direction:i,kinds:r.kinds,signal:r.signal});if(d+=p.meta.inspectedEdges,f.distance>=o){p.value.some(m=>!s.has(m.id))&&(l=!0);continue}for(let{id:m,edge:h}of p.value){if(s.has(m))continue;s.add(m);let y={id:m,distance:f.distance+1,via:f.id,role:Pr(h,m,n)};c.push(y),a.push(y)}}return c.sort((u,f)=>u.distance-f.distance||u.id.localeCompare(f.id)),{rows:c,visitedNodes:a.length,inspectedEdges:d,depthTruncated:l}}function Ql(e,t,n,r){let i={prerequisite:0,dependent:0,ancestor:0,descendant:0,provenance:0,related:0},o=e.neighborEdges(t,{direction:r.direction??"both",kinds:r.kinds,signal:r.signal}).value;for(let{id:s,edge:a}of o)i[Pr(a,s,n)]+=1;return{directEdges:i,directTotal:o.length,rootEdges:o.map(({edge:s})=>s)}}function Zl(e){let t=[],n=e.initialTokens;for(let r of e.candidates){if(t.length>=e.nodeLimit)break;let i=r.distance===1?Yl(e.rootEdges,e.rootId,r.id,e.registry):[],o={...e.details.get(r.id)??{id:r.id},distance:r.distance,role:i.length>0?Xl(i):r.role,via:r.via,reasons:i.length>0?i:[`${r.role} via ${r.via} (depth ${r.distance})`]},s=xn(o);if(n+s>e.tokenBudget)break;t.push(o),n+=s}if(e.candidates.length>0&&t.length===0)throw new TypeError("Relationship context tokenBudget cannot fit one node");return{nodes:t,usedTokens:n}}function eu(e){let t=e.options.kinds?new Set(e.options.kinds.map(o=>e.registry.require(o).kind)):void 0,n=e.graph.edges().filter(o=>{if(!e.included.has(o.source)||!e.included.has(o.target))return!1;if(t===void 0||t.has(o.kind))return!0;let s=e.registry.resolve(o.kind)?.inverse;return s!==void 0&&t.has(s)}),r=[],i=e.initialTokens;for(let o of n){if(r.length>=e.edgeLimit)break;let s=xn(o);if(i+s>e.tokenBudget)break;r.push(o),i+=s}return{edges:r,usedTokens:i,candidateCount:n.length}}function Rs(e,t,n,r={}){if(!e.nodes().includes(t))throw new TypeError(`Relationship node not found: ${t}`);let i=$r(r.nodeLimit,20,"nodeLimit"),o=$r(r.edgeLimit,40,"edgeLimit"),s=$r(r.tokenBudget,1200,"tokenBudget"),a=r.registry??ne(),c=new Map(n.map(q=>[q.id,q])),d=c.get(t)??{id:t},{evidence:l=[],...u}=d,f=[...l],p=Jl(e,t,a,r),{rootEdges:m,...h}=Ql(e,t,a,r),y=Ie("relationship-context",{rootId:t,direction:r.direction??"both",kinds:[...r.kinds??[]].sort(),maxDepth:r.maxDepth??3}),b=ze(p.rows,r.cursor,y,({id:q})=>q),v=p.rows.slice(b),w=xn(u)+xn(f);if(w>s)throw new TypeError("Relationship context tokenBudget cannot fit root and evidence");let C=Zl({candidates:v,details:c,rootEdges:m,rootId:t,registry:a,nodeLimit:i,tokenBudget:s,initialTokens:w}),{nodes:S}=C,N=new Set([t,...S.map(({id:q})=>q)]),$=eu({graph:e,included:N,options:r,registry:a,edgeLimit:o,tokenBudget:s,initialTokens:C.usedTokens}),{edges:M,usedTokens:Ee}=$,P=b+S.length,te=P<p.rows.length,V=S.at(-1),Y=$.candidateCount-M.length,he=p.depthTruncated||te||Y>0,X={rootId:t,...u.status===void 0?{}:{rootStatus:u.status},...h,discoveredNodes:p.rows.length,returnedNodes:S.length,returnedEdges:M.length,omittedNodes:p.rows.length-P,omittedEdges:Y,evidenceCount:f.length,hasMore:te};return{root:u,summary:X,nodes:S,edges:M,evidence:f,meta:{exact:!0,truncated:he,completeness:he?"truncated":"complete",nodeLimit:i,edgeLimit:o,tokenBudget:s,usedTokens:Ee,visitedNodes:p.visitedNodes,inspectedEdges:p.inspectedEdges,omittedNodes:p.rows.length-P,omittedEdges:Y,...te&&V?{nextCursor:ae(y,V.id,P-1)}:{}}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2f2a7df8-9c95-5ed1-bd43-33dde57dd7f0")}catch{}})();var tu=["tree","graph","context"],nu=["none","repeated"],ru=["outgoing","incoming","both"],iu=32,ou=200,su=400,au=16e3;function cu(e){let t=e?.trim().toLowerCase()??"tree";if(tu.includes(t))return t;throw new _(`Invalid --format value "${e}". Use "tree", "graph", or "context".`,g.USAGE)}function fe(e,t){if(e===void 0)return;let n=typeof e=="number"?e:Number(e.trim());if(!Number.isInteger(n)||n<1)throw new _(`Invalid --${t} value "${e}". Use a positive integer.`,g.USAGE);return n}function Dn(e){if(e===void 0)return;let t=typeof e=="number"?e:Number(e.trim());if(!Number.isInteger(t)||t<0)throw new _(`Invalid --max-depth value "${e}". Use a non-negative integer.`,g.USAGE);return t}function du(e){let t=e?.trim().toLowerCase()??"none";if(nu.includes(t))return t;throw new _(`Invalid --collapse value "${e}". Use "none" or "repeated".`,g.USAGE)}function Ur(e){let t=e?.trim().toLowerCase()??"both";if(ru.includes(t))return t;throw new _(`Invalid --direction value "${e}". Use "outgoing", "incoming", or "both".`,g.USAGE)}function Hr(e,t=ne()){if(e===void 0)return;let n=(Array.isArray(e)?e:[e]).flatMap(i=>i.split(",")).map(i=>i.trim()).filter(i=>i.length>0);if(n.length===0)return;let r=new Set;for(let i of n){let o=t.resolve(i);if(!o){let s=t.list().map(a=>a.kind).join(", ");throw new _(`Invalid --kind value "${i}". Registered kinds: ${s}.`,g.USAGE)}r.add(o.kind)}return[...r].sort()}function lu(e){if(!e||e.length===0)return[];let t=e.map(({id:r,kind:i})=>({id:r.trim(),kind:i.trim().toLowerCase()})).sort((r,i)=>{let o=r.kind.localeCompare(i.kind);return o!==0?o:r.id.localeCompare(i.id)}),n=new Map;for(let r of t){let i=`${r.kind.toLowerCase()}::${r.id.toLowerCase()}`;n.has(i)||n.set(i,{id:r.id,kind:r.kind})}return[...n.values()]}function uu(e){return{id:e.id,title:e.title,type:e.type,status:e.status,dependencies:lu(e.dependencies)}}function fu(e){return Zt(new TextEncoder().encode(JSON.stringify({...e,dependencies:void 0})).byteLength)}function mu(e,t,n,r,i,o,s,a,c){for(let d of t.dependencies){let l=Math.max(1,Math.ceil(JSON.stringify({from:e.id,to:d.id,kind:d.kind}).length/3));if(a.nodes>=a.nodeLimit){e.truncated=!0,a.reasons.add("node_limit");break}if(a.edges>=a.edgeLimit){e.truncated=!0,a.reasons.add("edge_limit");break}if(a.estimatedTokens+l>=a.tokenBudget){e.truncated=!0,a.reasons.add("token_budget");break}a.edges+=1,a.estimatedTokens+=l,e.dependencies.push(Ds(d.id,n,r,i,o,s,a,c+1,d.kind))}}function pu(e,t,n,r,i,o,s,a){return s.estimatedTokens>=s.tokenBudget&&t?.dependencies.length?(e.truncated=!0,s.reasons.add("token_budget"),!0):!t||e.cycle?!0:r!==void 0&&a>=r?(t.dependencies.length>0&&(e.truncated=!0,s.reasons.add("max_depth")),!0):i==="repeated"&&o.has(n)?(e.collapsed=!0,!0):!1}function Ds(e,t,n,r,i,o,s,a=0,c){let d=e.trim().toLowerCase(),l=t.get(d),u={id:l?.id??e,title:l?.title,type:l?.type,status:l?.status,via:c,missing:!l,cycle:n.has(d),dependencies:[]};if(s.nodes+=1,s.estimatedTokens+=fu(u),pu(u,l,d,r,i,o,s,a))return u;i==="repeated"&&o.add(d);let f=new Set(n);return f.add(d),mu(u,l,t,f,r,i,o,s,a),u}function xs(e,t){return!e||e.missing&&!t.missing?t:{...e,title:e.title??t.title,type:e.type??t.type,status:e.status??t.status}}function hu(e){let t=new Map,n=new Map,r=[e];for(;r.length>0;){let a=r.pop();t.set(a.id,xs(t.get(a.id),{id:a.id,title:a.title,type:a.type,status:a.status,missing:a.missing}));for(let c of a.dependencies){t.set(c.id,xs(t.get(c.id),{id:c.id,title:c.title,type:c.type,status:c.status,missing:c.missing}));let d=c.via??"related",l=`${a.id}::${c.id}::${d}`;n.has(l)||n.set(l,{from:a.id,to:c.id,kind:d}),c.cycle||r.push(c)}}let i=[...t.values()].sort((a,c)=>a.id.localeCompare(c.id)),o=[...n.values()].sort((a,c)=>{let d=a.from.localeCompare(c.from);if(d!==0)return d;let l=a.to.localeCompare(c.to);return l!==0?l:a.kind.localeCompare(c.kind)}),s=i.filter(a=>a.missing).map(a=>a.id);return{root_id:e.id,nodes:i,edges:o,missing_ids:s}}function As(e,t,n){let r=new Set,i=new Set,o=new Set,s=new Set,a=[{id:e,depth:0}],c=0;for(;c<a.length;){let d=a[c++],l=d.id.trim().toLowerCase();r.add(l);let u=t.get(l);if(!u){o.add(l);continue}if(!(n!==void 0&&d.depth>=n)&&!s.has(l)){s.add(l);for(let f of u.dependencies)i.add(`${l}::${f.id.trim().toLowerCase()}::${f.kind}`),a.push({id:f.id,depth:d.depth+1})}}return{node_count:r.size,edge_count:i.size,edge_basis:"deduplicated_directed",missing_count:o.size}}function gu(e,t=ne()){let n=Dn(e.maxDepth),r=fe(e.nodeLimit,"node-limit"),i=fe(e.edgeLimit,"edge-limit"),o=fe(e.tokenBudget,"token-budget"),s=Hr(e.kind,t);return{direction:Ur(e.direction),...s===void 0?{}:{kinds:s},...n===void 0?{}:{maxDepth:n},...r===void 0?{}:{nodeLimit:r},...i===void 0?{}:{edgeLimit:i},...o===void 0?{}:{tokenBudget:o},...e.cursor?.trim()?{cursor:e.cursor.trim()}:{}}}function _u(e,t,n,r){return Rs(e.graph,t,e.details.map(i=>i.id===t&&r.length>0?{...i,evidence:r}:i),n)}function jr(e,t,n,r){for(let i of n.slice(0,r)){let o=i?.trim();o&&e.push(`${t}:${o}`)}}async function yu(e,t,n,r){let i=await ce(e,t,n.id_prefix,n.item_format,r);if(!i)return[];let{document:o}=await Se(i,{schema:n.schema}),s=o.metadata,a=s.files??[],c=s.tests??[],d=s.docs??[],l=[["files",a.length],["tests",c.length],["docs",d.length],["comments",(s.comments??[]).length],["notes",(s.notes??[]).length],["learnings",(s.learnings??[]).length]];if(l.every(([,f])=>f===0))return[];let u=[`linked:${l.map(([f,p])=>`${f}=${p}`).join(",")}`];return jr(u,"file",a.map(f=>f.path),3),jr(u,"test",c.map(f=>f.command??f.path),2),jr(u,"doc",d.map(f=>f.path),2),u}function vu(e){let{canonicalId:t,context:n,missingCount:r,missingReferences:i,referenceLimit:o,summaryOnly:s}=e;return{id:t,format:"context",node_count:n.nodes.length+1,edge_count:n.edges.length,edge_basis:"deduplicated_directed",missing_count:r,missing_scope:"traversal",missing_reference_count:i.length,...s?{}:{missing_references:i.slice(0,o),context:n}}}function bu(e){let{row:t,missingReachableSet:n,packetIds:r,filteredKinds:i,registry:o}=e;if(t.no_active_blocker_sentinel||!n.has(t.target_id.trim().toLowerCase())||!r.has(t.holder_id))return!1;if(i===void 0)return!0;let s=o.resolve(t.kind);return s!==void 0&&(i.has(s.kind)||s.inverse!==void 0&&i.has(s.inverse))}function Os(e,t,n){let r;for(;;){let i=Zt(new TextEncoder().encode(kr(br("deps",e),t)).byteLength);if(i===r)return i;n(i),r=i}}function wu(e){return e instanceof TypeError&&e.message.startsWith("Relationship context tokenBudget cannot fit ")}function ku(e){try{return _u(e.assembly,e.canonicalId,{...e.contextOptions,...e.internalTokenBudget===void 0?{}:{tokenBudget:e.internalTokenBudget}},e.rootEvidence)}catch(t){if(e.smallestResult!==void 0&&wu(t))return e.smallestResult;throw t}}function Eu(e){let{assembly:t,canonicalId:n,contextOptions:r,rootEvidence:i,summaryOnly:o,outputFormat:s,missingCount:a,missingReferences:c}=e,l=r.edgeLimit??40,u=r.tokenBudget,f,p;for(;;){let m=ku({assembly:t,canonicalId:n,contextOptions:r,internalTokenBudget:u,rootEvidence:i,smallestResult:p});if("format"in m)return m;let h=m;f??=h.meta.tokenBudget,u??=f;let y=vu({canonicalId:n,context:h,missingCount:a,missingReferences:c,referenceLimit:l,summaryOnly:o});if(p=y,o||(h.meta.tokenBudget=f,h.meta.usedTokens=Os(Ze(y,!1),s,w=>{h.meta.usedTokens=w}),h.meta.usedTokens<=f))return y;if(l>0){l-=1;continue}let b=u,v=b*f/h.meta.usedTokens;u=Math.min(b-1,Math.max(1,Math.floor(v*.9)))}}function Iu(e){let{assembly:t,canonicalId:n,options:r,rootEvidence:i,summaryOnly:o,outputFormat:s}=e,a=gu(r,t.graph.registry()),c=t.graph.closure(n,{direction:a.direction,...a.kinds===void 0?{}:{kinds:a.kinds},maxDepth:a.maxDepth??3}),d=c.value.filter(h=>t.missingIdSet.has(h.toLowerCase())),l=new Set(d.map(h=>h.toLowerCase())),u=t.graph.registry(),f=a.kinds?new Set(a.kinds.map(h=>u.require(h).kind)):void 0,p=new Set([n,...c.value]),m=[...t.dangling.active,...t.dangling.legacy_terminal].filter(h=>bu({row:h,missingReachableSet:l,packetIds:p,filteredKinds:f,registry:u}));return Eu({assembly:t,canonicalId:n,contextOptions:a,rootEvidence:i,summaryOnly:o,outputFormat:s,missingCount:d.length,missingReferences:m})}function Cu(e){let t=[e],n;for(;t.length>0;){let r=t.pop();r.dependencies.length>0&&(n=r,t.push(...r.dependencies))}return n?(n.dependencies.pop(),n.truncated=!0,!0):!1}function Su(e,t,n,r,i,o,s){let a=i??iu,c=fe(n.nodeLimit,"node-limit")??ou,d=fe(n.edgeLimit,"edge-limit")??su,l=fe(n.tokenBudget,"token-budget")??au,u={nodeLimit:c,edgeLimit:d,tokenBudget:l,nodes:0,edges:0,estimatedTokens:0,reasons:new Set},f=Ds(e,r,new Set,a,t==="graph"?"repeated":o,new Set,u),p=As(e,r,void 0),m;for(;;){let h=hu(f),y=u.reasons.size===0?void 0:{reasons:[...u.reasons].sort(),limits:{max_depth:a,node_limit:c,edge_limit:d,token_budget:l},estimated_tokens:0,total_node_count:p.node_count,total_edge_count:p.edge_count,omitted_node_count:Math.max(0,p.node_count-h.nodes.length),omitted_edge_count:Math.max(0,p.edge_count-h.edges.length)},b={id:e,format:t,node_count:h.nodes.length,edge_count:h.edges.length,edge_basis:"deduplicated_directed",missing_count:h.missing_ids.length,...y?{truncation:y}:{}};if(m=t==="tree"?{...b,tree:f}:{...b,graph:h},(m.truncation===void 0?Zt(new TextEncoder().encode(kr(br("deps",Ze(m,!1)),s)).byteLength):Os(Ze(m,!1),s,w=>{m.truncation.estimated_tokens=w}))<=l)return m;if(!Cu(f))return u.reasons.add("token_budget"),m;u.reasons.add("token_budget")}}function Ze(e,t,n={}){let r={name:e.format==="tree"?"dependency_tree":e.format==="graph"?"dependency_graph":"relationship_context",restore_with:"--full"};return{...e,legacy_alias_counts:n,projection:{mode:t?"summary":"full",declared_field_groups:[r],included_field_groups:t?[]:[r.name]}}}async function s0(e,t,n){let r=O(process.cwd(),n.path);await U(r);let i=cu(t.format),o=Dn(t.maxDepth),s=du(t.collapse);Jt(t.summary===!0,t.full===!0,"--summary");let a=t.summary===!0,c=await F(r),d=L(c,D()),l=await de(r,c.item_format,d.type_to_folder,void 0,c.schema),u=J(c.schema),f=new Map(l.map(m=>[m.id.trim().toLowerCase(),uu(m)])),p=Mr(l,m=>j(m,u));for(let m of[...p.active,...p.legacy_terminal]){let h=f.get(m.holder_id.trim().toLowerCase()),y=m.kind.trim().toLowerCase();h&&!h.dependencies.some(b=>b.id.trim().toLowerCase()===m.target_id.trim().toLowerCase()&&b.kind===y)&&h.dependencies.push({id:m.target_id,kind:y})}if(!f.has(e.trim().toLowerCase()))throw new _(`Item ${e} not found`,g.NOT_FOUND);if(i==="context"){let m=f.get(e.trim().toLowerCase()).id,h=a?[]:await yu(r,m,c,d.type_to_folder),y=w=>j(w,u),b=z(),v=Rn().lookup(r,Tn(l,y,b),()=>Qe(l,y,b));return Ze(Iu({assembly:v.assembly,canonicalId:m,options:t,rootEvidence:h,summaryOnly:a,outputFormat:n.json===!0?"json":"toon"}),a,v.assembly.legacyAliasCounts)}return a?Ze({id:e,format:i,...As(e,f,o)},!0,Object.fromEntries(Object.entries(Qe(l,m=>j(m,u)).legacyAliasCounts))):Ze(Su(e,i,t,f,o,s,n.json===!0?"json":"toon"),!1,Object.fromEntries(Object.entries(Qe(l,m=>j(m,u)).legacyAliasCounts)))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f01a7c5d-0cb1-5dfa-90e8-14bb66bedd94")}catch{}})();var Tu=5,Ru=1e4,xu=8;function Br(e,t){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new TypeError(`Invalid path ${e} bound: ${String(t)}`)}function An(e,t){return t.hierarchyDirection==="target_parent"?e.target:e.source}function yt(e,t){return(t.precedence??"source_before_target")==="target_before_source"?e.target:e.source}function et(e,t){let n=yt(e,t);return{predecessor:n,successor:n===e.source?e.target:e.source}}function Du(e,t,n){if(t===void 0)return;let r=e.registry(),i=new Set;for(let o of t){let s=r.require(o),a=s.traversal;if(a==="association")throw new TypeError(`Relationship kind ${s.kind} uses association traversal; use graph impact --direction both`);if(a!==n&&a!=="semantic"){let c=a==="hierarchy"?"graph ancestors or graph descendants":"graph predecessors or graph successors";throw new TypeError(`Relationship kind ${s.kind} uses ${a} traversal; use ${c}`)}i.add(s.kind)}return i}function Au(e,t,n,r,i){let o=e.registry(),s=e.neighborEdges(t,{direction:"both",...n===void 0?{}:{kinds:[...n]}}),a=[],c=new Set;for(let d of s.value){let l=o.require(d.edge.kind);n===void 0&&!l[r]||i(d,l,t)&&(c.has(d.id)||(c.add(d.id),a.push(d.id)))}return{neighbors:a,inspectedEdges:s.meta.inspectedEdges}}function Ou(e,t,n,r,i,o){if(t>=n)return e.neighbors.some(s=>!o.seen.has(s))&&(o.truncated=!0),!1;for(let s of e.neighbors)if(!o.seen.has(s)){if(o.seen.add(s),o.queue.push({id:s,depth:t+1}),!o.resumed){s===i&&(o.resumed=!0);continue}if(o.value.length>=r)return o.truncated=!0,!0;o.value.push(s)}return!1}function On(e,t,n,r,i){if(!e.hasNode(t))throw new TypeError(`Relationship node not found: ${t}`);let o=Du(e,n.kinds,r),s=n.limit??Number.POSITIVE_INFINITY,a=n.maxDepth??Number.POSITIVE_INFINITY,c=n.after,d={seen:new Set([t]),value:[],queue:[{id:t,depth:0}],resumed:c===void 0,truncated:!1},l=0,u=0;for(let f=0;f<d.queue.length;f+=1){n.signal?.throwIfAborted();let p=d.queue[f];l+=1;let m=Au(e,p.id,o,r,i);if(u+=m.inspectedEdges,Ou(m,p.depth,a,s,c,d))break}if(!d.resumed)throw new TypeError(`Traversal cursor not found in sequence: ${c}`);return{value:d.value,meta:{visitedNodes:l,inspectedEdges:u,truncated:d.truncated,nextCursor:d.value.at(-1)}}}function Ls(e,t){if(!e.hasNode(t))throw new TypeError(`Relationship node not found: ${t}`)}function Fs(e,t,n,r,i){let o=e.neighborEdges(t.nodes.at(-1),{direction:r,...n.kinds===void 0?{}:{kinds:n.kinds}});return i.inspectedEdges+=o.meta.inspectedEdges,o.value.filter(s=>!t.nodeSet.has(s.id))}function Lu(e,t,n,r,i,o,s){for(let a of Fs(e,t,r,i,s)){let c=[...t.nodes,a.id],d=new Set(t.nodeSet).add(a.id),l=[...t.edges,a.edge];if(a.id===n){if(s.value.push({nodes:c,edges:l,length:l.length}),s.value.length>=o)return!0}else s.queue.push({nodes:c,nodeSet:d,edges:l})}return!1}function Ms(e,t,n={}){return On(e,t,n,"hierarchy",(r,i)=>An(r.edge,i)===r.id)}function Ns(e,t,n={}){return On(e,t,n,"hierarchy",(r,i,o)=>An(r.edge,i)===o)}function $s(e,t,n={}){return On(e,t,n,"ordering",(r,i)=>yt(r.edge,i)===r.id)}function Ps(e,t,n={}){return On(e,t,n,"ordering",(r,i,o)=>yt(r.edge,i)===o)}function Fu(e,t,n,r,i,o,s,a){let c={value:[],queue:[{nodes:[t],nodeSet:new Set([t]),edges:[]}],inspectedEdges:0},d=0,l=!1,u=i+1;for(let f=0;f<c.queue.length;f+=1){if(r.signal?.throwIfAborted(),c.value.length>=u||d>=o){l=!0;break}let p=c.queue[f];if(d+=1,p.edges.length>=s){Fs(e,p,r,a,c).length>0&&(l=!0);continue}if(Lu(e,p,n,r,a,u,c)){l=!0;break}}return{value:c.value.slice(0,i),meta:{visitedNodes:d,inspectedEdges:c.inspectedEdges,truncated:l}}}function js(e,t,n,r={}){Ls(e,t),Ls(e,n);let i=r.maxPaths??Tu,o=r.maxVisitedPaths??Ru,s=r.maxDepth??xu;Br("maxPaths",i),Br("maxVisitedPaths",o),Br("maxDepth",s);let a=r.direction??"outgoing";r.signal?.throwIfAborted();for(let c of r.kinds??[])e.registry().require(c);return t===n?i===0?{value:[],meta:{visitedNodes:1,inspectedEdges:0,truncated:!0}}:{value:[{nodes:[t],edges:[],length:0}],meta:{visitedNodes:1,inspectedEdges:0,truncated:!1}}:Fu(e,t,n,r,i,o,s,a)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2ea07760-bca8-579d-9b3a-78051461485a")}catch{}})();var Mu=16,Nu=2,$u=8;function Ln(e,t){if(!Number.isInteger(t)||t<1)throw new TypeError(`Invalid ${e} bound: ${String(t)}`)}function Fn(e,t,n){let r=e.registry(),i=t===void 0?void 0:new Set(t.map(o=>r.require(o).kind));for(let o of e.edges()){if(o.source===o.target)continue;let s=r.require(o.kind);i!==void 0&&!(i.has(s.kind)||s.inverse!==void 0&&i.has(s.inverse))||n(o,s)}}function Pu(e,t){let n=new Map;Fn(e,t,r=>{Us(n,r.source,r.target),Us(n,r.target,r.source)});for(let r of n.values())r.sort();return n}function Us(e,t,n){let r=e.get(t);r===void 0?e.set(t,[n]):r.push(n)}function ju(e,t){let n=new Map;for(let o of e){let s=t.get(o);n.set(s,(n.get(s)??0)+1)}let r,i=0;for(let[o,s]of n)(s>i||s===i&&o<r)&&(r=o,i=s);return r}function Uu(e,t){let n=new Map;for(let[i,o]of e){let s=n.get(o);s===void 0?n.set(o,[i]):s.push(i)}let r=[];for(let i of n.values())i.length<t||(i.sort(),r.push({representative:i[0],size:i.length,members:i}));return r.sort((i,o)=>o.size-i.size||i.representative.localeCompare(o.representative))}function Hs(e,t={}){let n=t.maxIterations??Mu,r=t.minSize??Nu;Ln("maxIterations",n),Ln("minSize",r);let i=Pu(e,t.kinds),o=e.nodes(),s=new Map(o.map(u=>[u,u])),a=0,c=!1,d=0,l=0;for(;a<n&&!c;){t.signal?.throwIfAborted(),a+=1,c=!0;for(let u of o){d+=1;let f=i.get(u);if(f===void 0)continue;l+=f.length;let p=ju(f,s);p!==s.get(u)&&(s.set(u,p),c=!1)}}return{value:{communities:Uu(s,r),iterations:a,converged:c},meta:{visitedNodes:d,inspectedEdges:l,truncated:!c}}}function Mn(e){return e.direction==="directed"&&(e.ordering||e.hierarchy)}function Nn(e){return e.inverse!==void 0&&e.inverse<e.kind?e.inverse:e.kind}function Gr(e,t){return(t.hierarchy?An(e,t):e.source===yt(e,t)?e.target:e.source)===e.target?{from:e.source,to:e.target}:{from:e.target,to:e.source}}function Hu(e,t){if(t===void 0)return;let n=e.registry(),r=new Set;for(let i of t){let o=n.require(i);if(!Mn(o))throw new TypeError(`Relationship kind ${o.kind} is not a directed ordering or hierarchy kind`);r.add(Nn(o))}return r}function Bu(e,t){let n=e.registry(),r=new Map;for(let i of e.edges()){let o=n.require(i.kind);if(!Mn(o))continue;let s=Nn(o);if(t!==void 0&&!t.has(s))continue;let a=Gr(i,o);if(a.from===a.to)continue;let c=r.get(s);c===void 0&&(c={adjacency:new Map,records:[]},r.set(s,c));let d=c.adjacency.get(a.from);d===void 0?c.adjacency.set(a.from,new Set([a.to])):d.add(a.to),c.records.push({...a,edge:i})}return r}function Gu(e){let t=new Map;for(let[n,r]of e.adjacency)t.set(n,[...r].sort());return t}function Ku(e,t,n,r){let i=[r];for(let o=n;o!==t;o=e.get(o))i.push(o);return i.push(t),i.reverse()}function zu(e,t,n,r,i,o){for(let s of e.get(n.id)??[])if(o.inspectedEdges+=1,!(n.depth===0&&s===t.to)&&!r.has(s)){if(r.set(s,n.id),s===t.to)return Ku(r,t.from,n.id,s);i.push({id:s,depth:n.depth+1})}}function Vu(e,t,n,r){let i=new Map([[t.from,t.from]]),o=[{id:t.from,depth:0}];for(let s=0;s<o.length;s+=1){let a=o[s];if(r.visitedNodes+=1,a.depth>=n)continue;let c=zu(e,t,a,i,o,r);if(c!==void 0)return c}}function tt(e,t={}){let n=t.maxDepth??$u;Ln("maxDepth",n),t.limit!==void 0&&Ln("limit",t.limit);let r=t.limit??Number.POSITIVE_INFINITY,i=Hu(e,t.kinds),o=Bu(e,i),s=[],a={visitedNodes:0,inspectedEdges:0},c=!1;e:for(let d of[...o.keys()].sort()){let l=o.get(d),u=Gu(l);for(let f of l.records){t.signal?.throwIfAborted();let p=Vu(u,f,n,a);if(p!==void 0){if(s.length>=r){c=!0;break e}s.push({edge:f.edge,witness:p})}}}return{value:s,meta:{visitedNodes:a.visitedNodes,inspectedEdges:a.inspectedEdges,truncated:c}}}function qu(e,t,n,r,i){let o=new Set,s=[];for(let a of n){if(a.id===e||o.has(a.id))continue;if(!i.seen.has(a.id)){if(t>=r){i.truncated=!0;continue}i.seen.add(a.id),i.queue.push({id:a.id,depth:t+1})}o.add(a.id),s.push(a.id);let c=i.predecessors.get(a.id);c===void 0&&(c=new Set,i.predecessors.set(a.id,c)),c.add(e)}return s}function Wu(e,t,n){let r=n.direction??"outgoing",i=n.maxDepth??Number.POSITIVE_INFINITY,o=[],s=new Map,a={seen:new Set([t]),queue:[{id:t,depth:0}],predecessors:new Map,truncated:!1},c=0;for(let d=0;d<a.queue.length;d+=1){n.signal?.throwIfAborted();let{id:l,depth:u}=a.queue[d];o.push(l);let f=e.neighborEdges(l,{direction:r,...n.kinds===void 0?{}:{kinds:n.kinds}});c+=f.meta.inspectedEdges,s.set(l,qu(l,u,f.value,i,a))}return{order:o,successors:s,predecessors:a.predecessors,inspectedEdges:c,truncated:a.truncated}}function Yu(e,t){let n=[],r=new Set([t]),i=[{id:t,index:0}];for(;i.length>0;){let o=i.at(-1),s=e.successors.get(o.id);if(o.index<s.length){let a=s[o.index];o.index+=1,r.has(a)||(r.add(a),i.push({id:a,index:0}))}else n.push(o.id),i.pop()}return n.reverse()}function Xu(e,t,n,r){let i=e,o=t;for(;i!==o;){for(;r.get(i)>r.get(o);)i=n.get(i);for(;r.get(o)>r.get(i);)o=n.get(o)}return i}function Ju(e,t,n){let r;for(let i of[...e].sort())t.has(i)&&(r=r===void 0?i:Xu(r,i,t,n));return r}function Qu(e,t,n,r,i){let o=new Map([[t,t]]),s=!0;for(;s;){s=!1;for(let a of n){if(i?.throwIfAborted(),a===t)continue;let c=Ju(e.predecessors.get(a),o,r);c!==void 0&&o.get(a)!==c&&(o.set(a,c),s=!0)}}return o}function Bs(e,t,n={}){if(!e.hasNode(t))throw new TypeError(`Relationship node not found: ${t}`);if(n.maxDepth!==void 0&&(!Number.isInteger(n.maxDepth)||n.maxDepth<0))throw new TypeError(`Invalid maxDepth bound: ${String(n.maxDepth)}`);let r=Wu(e,t,n),i=Yu(r,t),o=new Map(i.map((d,l)=>[d,l])),s=Qu(r,t,i,o,n.signal),a=new Map(i.map(d=>[d,1]));for(let d=i.length-1;d>=0;d-=1){let l=i[d];if(l===t)continue;let u=s.get(l);a.set(u,a.get(u)+a.get(l))}let c=i.filter(d=>d!==t).map(d=>({id:d,idom:s.get(d),dominatedCount:a.get(d)-1})).sort((d,l)=>l.dominatedCount-d.dominatedCount||d.id.localeCompare(l.id));return{value:{root:t,reachableCount:r.order.length,rows:c},meta:{visitedNodes:r.order.length,inspectedEdges:r.inspectedEdges,truncated:r.truncated}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="aa8e4dc3-250e-50eb-b770-a11cbab6ebc3")}catch{}})();function Gs(e){return Math.round(e*1e6)/1e6}function Ks(e,t,n){let r=e.get(t);r===void 0?e.set(t,new Set([n])):r.add(n)}function zs(e,t){let n=new Map(e.nodes().map(i=>[i,new Set]));Fn(e,t,i=>{n.get(i.source).add(i.target),n.get(i.target).add(i.source)});let r=new Map;for(let[i,o]of n)r.set(i,[...o].sort());return r}function Zu(e,t){let n=new Map,r=new Map;return Fn(e,t,(i,o)=>{if(!o.ordering)return;let{predecessor:s,successor:a}=et(i,o);Ks(r,s,a),Ks(n,a,s)}),{incoming:n,outgoing:r}}function ef(e,t,n){let r=new Map([[e,0]]),i=new Map([[e,1]]),o=new Map,s=[],a=[e],c=0,d=0;for(let l=0;l<a.length;l+=1){let u=a[l];n.visitedNodes+=1,s.push(u);let f=r.get(u);u!==e&&(c+=1,d+=f);for(let p of t.get(u))if(n.inspectedEdges+=1,r.has(p)||(r.set(p,f+1),a.push(p)),r.get(p)===f+1){i.set(p,(i.get(p)??0)+i.get(u));let m=o.get(p);m===void 0?o.set(p,[u]):m.push(u)}}return{stack:s,sigma:i,predecessors:o,reachableCount:c,distanceSum:d}}function tf(e,t,n){let r=new Map;for(let i=e.stack.length-1;i>=0;i-=1){let o=e.stack[i],s=(1+(r.get(o)??0))/e.sigma.get(o);for(let a of e.predecessors.get(o)??[])r.set(a,(r.get(a)??0)+e.sigma.get(a)*s);o!==t&&n.set(o,(n.get(o)??0)+(r.get(o)??0))}}function nf(e,t){return t<=1||e.reachableCount===0?0:e.reachableCount/(t-1)*(e.reachableCount/e.distanceSum)}function rf(e,t,n,r,i){return{id:e,degree:t.get(e).length,inDegree:n.incoming.get(e)?.size??0,outDegree:n.outgoing.get(e)?.size??0,betweenness:Gs((r.get(e)??0)/2),closeness:Gs(i.get(e))}}function Vs(e,t={}){let n=zs(e,t.kinds),r=Zu(e,t.kinds),i=e.nodes(),o=new Map,s=new Map,a={visitedNodes:0,inspectedEdges:0};for(let l of i){t.signal?.throwIfAborted();let u=ef(l,n,a);s.set(l,nf(u,i.length)),tf(u,l,o)}let c=0;for(let l of n.values())c+=l.length;let d=i.map(l=>rf(l,n,r,o,s)).sort((l,u)=>u.betweenness-l.betweenness||u.degree-l.degree||l.id.localeCompare(u.id));return{value:{nodeCount:i.length,edgeCount:c/2,rows:d},meta:{visitedNodes:a.visitedNodes,inspectedEdges:a.inspectedEdges,truncated:!1}}}function of(e,t){return e<=t?{source:e,target:t}:{source:t,target:e}}function sf(e,t,n){let i=t.get(e.node)[e.neighborIndex];if(e.neighborIndex+=1,n.inspectedEdges+=1,i!==e.parent){if(n.discovery.has(i)){n.low.set(e.node,Math.min(n.low.get(e.node),n.discovery.get(i)));return}return e.children+=1,n.discovery.set(i,n.timer),n.low.set(i,n.timer),n.timer+=1,{node:i,parent:e.node,neighborIndex:0,children:0}}}function af(e,t,n){if(e.parent===null){e.children>1&&n.articulation.add(e.node);return}let r=e.parent,i=n.low.get(e.node);n.low.set(r,Math.min(n.low.get(r),i)),r!==t&&i>=n.discovery.get(r)&&n.articulation.add(r),i>n.discovery.get(r)&&n.bridges.push(of(r,e.node))}function cf(e,t,n,r){n.discovery.set(e,n.timer),n.low.set(e,n.timer),n.timer+=1;let i=[{node:e,parent:null,neighborIndex:0,children:0}];for(;i.length>0;){r?.throwIfAborted();let o=i.at(-1);if(o.neighborIndex<t.get(o.node).length){let s=sf(o,t,n);s!==void 0&&i.push(s)}else af(o,e,n),i.pop()}}function $n(e,t={}){let n=zs(e,t.kinds),r={discovery:new Map,low:new Map,timer:0,articulation:new Set,bridges:[],inspectedEdges:0};for(let i of e.nodes())r.discovery.has(i)||cf(i,n,r,t.signal);return{value:{articulationPoints:[...r.articulation].sort(),bridges:r.bridges.sort((i,o)=>i.source.localeCompare(o.source)||i.target.localeCompare(o.target))},meta:{visitedNodes:r.discovery.size,inspectedEdges:r.inspectedEdges,truncated:!1}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1c9d9d0c-e989-568c-a49a-202f77e94806")}catch{}})();function df(e){let t=e.registry(),n=new Map,r=new Set;for(let i of e.edges()){let o=t.require(i.kind);if(!o.ordering)continue;let{predecessor:s,successor:a}=et(i,o);if(r.add(s),r.add(a),s===a)continue;let c=n.get(s);c===void 0?n.set(s,new Set([a])):c.add(a)}return{forward:n,participants:r}}function lf(e,t,n,r){if(e===void 0)return r;let i=r;for(let o of e)t.has(o)&&(i=Math.min(i,n.get(o)));return i}function uf(e,t,n){let r=n-t;return{id:e,earliestStart:t,earliestFinish:t+1,latestStart:n,latestFinish:n+1,slack:r,critical:r===0}}function ff(e,t,n,r,i){let o=new Map;for(let s=e.length-1;s>=0;s-=1){let a=e[s],c=lf(t.forward.get(a),r,o,i);o.set(a,c-1)}return e.map(s=>uf(s,n[s],o.get(s))).sort((s,a)=>s.slack-a.slack||s.earliestStart-a.earliestStart||s.id.localeCompare(a.id))}function qs(e,t={}){t.signal?.throwIfAborted();let n=yn(e,{registry:e.registry()}),r=df(e),i=new Set(n.order),o=n.order.filter(d=>r.participants.has(d)),s=o.reduce((d,l)=>Math.max(d,n.depth[l]+1),0),a=ff(o,r,n.depth,i,s),c=a.length>0;return{exact:!0,acyclic:n.acyclic,makespan:s,scheduledCount:a.length,criticalPath:c?n.criticalPath:[],criticalPathLength:c?n.criticalPathLength:0,cycles:n.cycles,rows:a,provenance:{algorithm:"critical-path-method",edgeFamily:"ordering",weighting:"unit"}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6b2a7206-d480-51c1-9d46-4271bde24fa3")}catch{}})();function mf(e,t,n){for(let r=e.length-1;r>=0;r-=1){n?.throwIfAborted();let i=t.get(e[r]);for(let o of i.successors){n?.throwIfAborted();let s=t.get(o);if(s.latest===void 0||s.duration===void 0)continue;let a=s.latest-s.duration;(i.latest===void 0||a<i.latest)&&(i.latest=a,i.anchor=s.anchor)}}}function pf(e,t,n,r){let i=[],o=e;for(;o!==void 0&&i.length<n;)r?.throwIfAborted(),i.push(o),o=t.get(o).predecessor;return i.reverse(),{path:i,path_truncated:o!==void 0}}function hf(e,t,n,r,i){let o=new Map(t.map(a=>[a.id,a])),s=new Map;for(let a of e){i?.throwIfAborted();let c=o.get(a),d=c?.estimated_minutes,l=typeof d=="number"&&Number.isFinite(d)&&d>=0?d:void 0,u={item:c,duration:l,pending:0,successors:new Set,earliest:0};if(c?.deadline!==void 0){let f=Date.parse(c.deadline);Number.isFinite(f)?(u.deadline=(f-n)/6e4,u.latest=u.deadline,u.anchor=a):r(a,"invalid_deadline")}s.set(a,u)}return s}function gf(e,t,n){for(let r of e.edges()){n?.throwIfAborted();let i=e.registry().require(r.kind);if(!i.ordering)continue;let{predecessor:o,successor:s}=et(r,i),a=t.get(o);a.successors.has(s)||(a.successors.add(s),t.get(s).pending+=1)}}function _f(e,t,n){let r=e.filter(i=>t.get(i).pending===0);for(let i=0;i<r.length;i+=1){n?.throwIfAborted();let o=r[i],s=t.get(o),a=s.earliest===null||s.duration===void 0?null:s.earliest+s.duration;for(let c of s.successors){n?.throwIfAborted();let d=t.get(c);a===null?d.earliest=null:d.earliest!==null&&(a>d.earliest||a===d.earliest&&(d.predecessor===void 0||o<d.predecessor))&&(d.earliest=a,d.predecessor=o),d.pending-=1,d.pending===0&&r.push(c)}}return r}function yf(e,t,n,r,i,o,s,a){let c=t.duration;if(t.latest!==void 0){r.scheduled_count+=1;let d=t.latest-c;r.rows.length<o?r.rows.push({id:e,deadline_id:t.anchor,latest_start:new Date(i+d*6e4).toISOString(),slack_minutes:t.earliest===null?null:d-t.earliest}):r.truncated=!0}if(t.deadline!==void 0&&t.earliest!==null&&t.earliest+c>t.deadline)if(r.overcommitted_count+=1,r.overcommitted.length<o){let d=pf(e,n,Math.min(o,s.remaining),a);s.remaining-=d.path.length,d.path_truncated&&(r.truncated=!0),r.overcommitted.push({deadline_id:e,deadline:t.item.deadline,shortfall_minutes:t.earliest+c-t.deadline,...d})}else r.truncated=!0}function vf(e,t,n,r,i,o,s,a){let c={remaining:o};for(let d of e){a?.throwIfAborted();let l=t.get(d);if(l.pending>0){s(d,"cycle_or_gated_by_cycle");continue}if(l.duration===void 0){s(d,"unknown_estimate");continue}if(l.latest!==void 0&&!Number.isFinite(new Date(r+(l.latest-l.duration)*6e4).getTime())){s(d,"date_range_exceeded");continue}l.earliest===null&&s(d,"unknown_predecessor_estimate"),yf(d,l,t,n,r,i,c,a)}}function Ws(e,t,n={}){n.signal?.throwIfAborted();let r=Date.parse(n.now??new Date().toISOString());if(!Number.isFinite(r))throw new TypeError("Invalid scheduling clock");let i=n.maxWork??1e5,o=n.limit??10;for(let[f,p]of[["maxWork",i],["limit",o]])if(!Number.isSafeInteger(p)||p<1)throw new TypeError(`Invalid scheduling ${f}`);let s={as_of:new Date(r).toISOString(),basis:"derived_elapsed_minutes",complete:!0,truncated:!1,work_limit_exceeded:!1,scheduled_count:0,residual_count:0,overcommitted_count:0,rows:[],residuals:[],overcommitted:[]},a=e.nodes(),c=e.edges();if(a.length+c.length+t.length>i)return{...s,complete:!1,work_limit_exceeded:!0};let d=(f,p)=>{s.complete=!1,s.residual_count+=1,s.residuals.length<o?s.residuals.push({id:f,reason:p}):s.truncated=!0},l=hf(a,t,r,d,n.signal);gf(e,l,n.signal);let u=_f(a,l,n.signal);return mf(u,l,n.signal),vf(a,l,s,r,o,i,d,n.signal),s}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2bfc4e78-a376-5099-be50-38e339eac660")}catch{}})();function nt(){return{nodes:0,isolated:0,degree_leq_one:0,semantic_nodes:0,without_semantic_edges:0,degree_histogram:{}}}function Js(e,t,n,r){let i={all:nt(),active:nt(),terminal:nt()},o=new Map;for(let s of e.details){if(r?.throwIfAborted(),e.missingIdSet.has(s.id.toLowerCase())||s.status==="external")continue;let a=o.get(s.status)??nt();o.set(s.status,a);let c=e.graph.incidentEdges(s.id),d=c.some(l=>n(l.kind));for(let l of[i.all,i[t(s.status)?"terminal":"active"],a]){l.nodes+=1,l.isolated+=+(c.length===0),c.length<=1&&(l.degree_leq_one+=1),d?l.semantic_nodes+=1:l.without_semantic_edges+=1;let u=String(c.length);l.degree_histogram[u]=(l.degree_histogram[u]??0)+1}}return{coverage_by_lifecycle:i,coverage_by_status:Object.fromEntries([...o].sort(([s],[a])=>s.localeCompare(a)))}}function Ys(e){if(!Pn(e))return!1;let t=e;if(!["nodes","isolated","degree_leq_one","semantic_nodes","without_semantic_edges"].every(i=>Number.isSafeInteger(t[i])&&Number(t[i])>=0)||!Pn(t.degree_histogram))return!1;let r=Object.entries(t.degree_histogram);return r.every(([i,o])=>/^(0|[1-9]\d*)$/.test(i)&&Number.isSafeInteger(o)&&Number(o)>=0)&&r.reduce((i,[,o])=>i+Number(o),0)===t.nodes&&Number(t.isolated)<=Number(t.degree_leq_one)&&Number(t.degree_leq_one)<=Number(t.nodes)&&Number(t.semantic_nodes)+Number(t.without_semantic_edges)===t.nodes}function Pn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Qs(e){for(let r of["ordering_acyclic","active_ordering_acyclic"])if(e[r]!==void 0&&typeof e[r]!="boolean")return!1;let t=e.coverage_by_lifecycle,n=e.coverage_by_status;return t===void 0&&n===void 0?!0:!Pn(t)||!Pn(n)?!1:["all","active","terminal"].every(r=>Ys(t[r]))&&Object.values(n).every(Ys)}function Xs(e,t){return Object.fromEntries([...new Set([...Object.keys(e),...Object.keys(t)])].sort().map(n=>{let r=Object.hasOwn(e,n)?e[n]:nt(),i=Object.hasOwn(t,n)?t[n]:nt(),o=Object.fromEntries([...new Set([...Object.keys(r.degree_histogram),...Object.keys(i.degree_histogram)])].sort().map(s=>[s,(i.degree_histogram[s]??0)-(r.degree_histogram[s]??0)]));return[n,{nodes:i.nodes-r.nodes,isolated:i.isolated-r.isolated,degree_leq_one:i.degree_leq_one-r.degree_leq_one,semantic_nodes:i.semantic_nodes-r.semantic_nodes,without_semantic_edges:i.without_semantic_edges-r.without_semantic_edges,degree_histogram:o}]}))}function Zs(e,t){return!e.coverage_by_lifecycle||!t.coverage_by_lifecycle||!e.coverage_by_status||!t.coverage_by_status?{lifecycle_comparable:!1}:{lifecycle_comparable:!0,coverage_by_lifecycle:Xs(e.coverage_by_lifecycle,t.coverage_by_lifecycle),coverage_by_status:Xs(e.coverage_by_status,t.coverage_by_status)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="896e1553-b127-532f-ac39-e0d47f29eebc")}catch{}})();var rt=["missing_reference_active","missing_reference_terminal","legacy_no_blocker_sentinel","ordering_cycle","legacy_ordering_cycle","ordering_storage_contradiction","legacy_ordering_storage_contradiction","hierarchy_cycle","legacy_hierarchy_cycle","hierarchy_cardinality_violation","legacy_hierarchy_cardinality_violation","hierarchy_direction_violation","legacy_hierarchy_direction_violation","duplicate_edge","legacy_duplicate_edge","duplicate_dependency_row","legacy_duplicate_dependency_row","stale_lifecycle_block","isolated_active_node","sparse_active_node"];(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1335acb2-0730-5934-89a4-14fe4a160288")}catch{}})();var bf=25,wf="milestone",kf="outcome milestone:",Ef=new Set(["discovered_from","incident_from","recurs_from","supersedes","verifies"]);function jn(e){return Ef.has(e)}var ea={error:0,warning:1,info:2};function ta(e){return new Set((e??[]).filter(t=>typeof t=="string").map(t=>t.trim().toLowerCase()))}function it(e,t,n,r,i,o,s,a){let c=[...i].sort((d,l)=>d.localeCompare(l));return{code:e,severity:t,policy:n,message:r(c.length),count:c.length,sample:c.slice(0,o),sample_truncated:c.length>o,remediation:s,...a===void 0?{}:{evidence:[...a].sort((d,l)=>d.localeCompare(l)).slice(0,o)}}}function If(e,t){return e.cycles.map(n=>it(n.legacy_terminal?"legacy_hierarchy_cycle":"hierarchy_cycle",n.legacy_terminal?"info":"error","Structural hierarchy must be acyclic across scalar and registered dependency relationships.",r=>`${r} items participate in one hierarchy cycle.`,n.item_ids,t,n.legacy_terminal?"Preserve historical rows unless an explicit legacy repair is approved.":"Remove or retype one exact hierarchy relation before continuing mutation."))}function na(e,t,n){let r=e.cardinality_violations.filter(i=>i.legacy_terminal===n);return r.length===0?[]:[it(n?"legacy_hierarchy_cardinality_violation":"hierarchy_cardinality_violation",n?"info":"error","Every structural child must resolve to at most one logical parent across all hierarchy spellings.",i=>`${i} child item${i===1?"":"s"} resolve to multiple hierarchy parents.`,r.map(i=>i.child_id),t,n?"Preserve historical rows unless an explicit legacy repair is approved.":"Remove the exact surplus hierarchy rows so each child has one parent.",r.map(i=>`${i.child_id} <- ${i.parent_ids.join(", ")}`))]}function ra(e,t,n){let r=e.divergences.filter(i=>i.legacy_terminal===n);return r.length===0?[]:[it(n?"legacy_hierarchy_direction_violation":"hierarchy_direction_violation",n?"info":"error","Scalar parent metadata and dependency-backed hierarchy rows must resolve to the same logical parent.",i=>`${i} child item${i===1?"":"s"} have divergent hierarchy storage surfaces.`,r.map(i=>i.child_id),t,n?"Preserve historical rows unless an explicit legacy repair is approved.":"Align the scalar parent and exact dependency rows to one canonical parent.",r.map(i=>`${i.child_id}: scalar=${i.scalar_parent_id} dependencies=${i.dependency_parent_ids.join(",")}`))]}function Cf(e,t){let n=Sn(e);return n?[...If(n,t),...na(n,t,!1),...na(n,t,!0),...ra(n,t,!1),...ra(n,t,!0)]:[]}function Sf(e){let t=e.graph.registry(),n=new Map;for(let r of e.graph.edges()){let i=t.require(r.kind);if(!i.ordering)continue;let[o,s]=(i.precedence??"source_before_target")==="target_before_source"?[r.target,r.source]:[r.source,r.target],a=n.get(o);a?a.push(s):n.set(o,[s])}for(let r of n.values())r.sort((i,o)=>i.localeCompare(o));return n}function oa(e,t){t.indexes.set(e,t.nextIndex),t.lowLinks.set(e,t.nextIndex),t.nextIndex+=1,t.stack.push(e),t.onStack.add(e)}function Tf(e,t,n,r){let i=n.get(e.node)??[];if(e.neighborIndex>=i.length)return!1;let o=i[e.neighborIndex];return e.neighborIndex+=1,r.indexes.has(o)?r.onStack.has(o)&&r.lowLinks.set(e.node,Math.min(r.lowLinks.get(e.node),r.indexes.get(o))):(oa(o,r),t.push({node:o,neighborIndex:0})),!0}function Rf(e,t,n,r){t.pop();let i=t.at(-1);if(i&&r.lowLinks.set(i.node,Math.min(r.lowLinks.get(i.node),r.lowLinks.get(e.node))),r.lowLinks.get(e.node)!==r.indexes.get(e.node))return;let o=[];for(;;){let s=r.stack.pop();if(r.onStack.delete(s),o.push(s),s===e.node)break}(o.length>1||o.length===1&&n.get(o[0])?.includes(o[0]))&&r.components.push(o.sort((s,a)=>s.localeCompare(a)))}function xf(e){let t={indexes:new Map,lowLinks:new Map,onStack:new Set,stack:[],components:[],nextIndex:0},n=[...e.keys()].sort((r,i)=>r.localeCompare(i));for(let r of n){if(t.indexes.has(r))continue;let i=[{node:r,neighborIndex:0}];for(oa(r,t);i.length>0;){let o=i.at(-1);Tf(o,i,e,t)||Rf(o,i,e,t)}}return t.components.sort((r,i)=>r[0].localeCompare(i[0]))}function Kr(e){return`${e.holder_id} -> ${e.target_id} (${e.kind})`}function ee(e,t,n,r,i,o,s,a){t.length!==0&&e.push(it(r,i,o,s,t,n,a))}function Df(e,t,n){let r=[],i=[...e.dangling.active,...e.dangling.legacy_terminal].filter(o=>!o.no_active_blocker_sentinel);return ee(r,i.filter(o=>!t(o.holder_status)).map(Kr),n,"missing_reference_active","error","Active items must not reference absent targets; missing prerequisites distort scheduling.",o=>`${o} active dangling reference(s) to absent items`,"Restore or re-create the referenced item, or remove/retype the reference on the holder."),ee(r,i.filter(o=>t(o.holder_status)).map(Kr),n,"missing_reference_terminal","info","Terminal items may retain historical references, but absent targets remain unexplainable context.",o=>`${o} terminal dangling reference(s) to absent items`,"Leave as history debt or clean up in a dedicated changelog-safe closed-item batch."),ee(r,e.dangling.no_active_blocker_sentinels.map(Kr),n,"legacy_no_blocker_sentinel","info","The pre-structured-dependency no-active-blocker sentinel is retired; real edges carry blocker state.",o=>`${o} legacy no-active-blocker sentinel reference(s)`,"Delete the sentinel reference; blocker state is derived from blocked_by edges."),r}function Vr(e,t){let n=t.get(e);return n?!n.terminal:!0}function sa(e){return`${e.holder_id} -> ${e.target_id} (blocked_by scalar + ${e.dependency_kind} dependency)`}function Af(e,t){let n=[],r=[];for(let o of e.orderingContradictions??[])(o.legacy_terminal?r:n).push(sa(o));let i=[];return ee(i,n,t,"ordering_storage_contradiction","error","A scalar blocker and same-target structured ordering row must not assert opposite precedence.",o=>`${o} active scalar-versus-structured ordering contradiction(s)`,"Remove the structured dependency row that points the holder before its scalar blocker, or replace both representations with one unambiguous ordering edge."),ee(i,r,t,"legacy_ordering_storage_contradiction","info","Terminal scalar-versus-structured ordering contradictions are exact historical storage defects with no live scheduling effect.",o=>`${o} terminal scalar-versus-structured ordering contradiction(s)`,"Remove the contradictory blocks dependency row in a dedicated changelog-safe closed-item batch; preserve the scalar blocker as the historical precedence record."),i}function Of(e,t,n,r){let i=[],o=Sf(e);for(let c of xf(o)){let d=c.some(f=>Vr(f,t)),l=new Set(c.map(f=>f.toLowerCase())),u=(e.orderingContradictions??[]).filter(f=>l.has(f.holder_id.toLowerCase())&&l.has(f.target_id.toLowerCase())).map(sa);i.push(d?it("ordering_cycle","error","Order-bearing relationship kinds must stay acyclic; a cycle makes every member unschedulable.",f=>`execution-order cycle across ${f} item(s)`,c,r,"Remove or retype one ordering edge inside the cycle, or split the work so precedence is linear.",u.length===0?void 0:u):it("legacy_ordering_cycle","info","Ordering cycles between exclusively terminal items are historical contradictions with no scheduling effect.",f=>`terminal-only execution-order cycle across ${f} item(s)`,c,r,"Leave as history debt, or clean up in a dedicated changelog-safe closed-item batch; never repair closed items ad hoc.",u.length===0?void 0:u))}let s=new Map;for(let[c,d]of o)for(let l of d){let u=s.get(l);u?u.push(c):s.set(l,[c])}let a=[...t.values()].filter(c=>!c.missing&&!c.terminal&&n(c.status)&&!(s.get(c.id)??[]).some(d=>{let l=t.get(d);return l===void 0||!l.terminal})).map(c=>c.id);return ee(i,a,r,"stale_lifecycle_block","warning","A blocked lifecycle status must be backed by at least one open ordering predecessor.",c=>`${c} status-blocked item(s) with no open blocker edge`,'Add a local blocker edge, declare an external blocker with --dep "id=<external-ref>,kind=blocked_by,source_kind=external", or move the item back to an active status.'),i}function Un(e){let t=e.edges.map(n=>n.kind).sort((n,r)=>n.localeCompare(r));return`${e.from} -> ${e.to} (${t.join(" + ")})`}function qr(e){let t=e.graph.registry(),n=new Map;for(let i of e.graph.edges()){let o=t.require(i.kind);if(!Mn(o))continue;let s=Gr(i,o);if(s.from===s.to)continue;let a=`${Nn(o)}::${s.from}::${s.to}`,c=n.get(a);c?c.edges.push(i):n.set(a,{...s,edges:[i]})}let r=[...n.values()].filter(i=>i.edges.length>=2);for(let i of r)i.edges.sort((o,s)=>o.kind.localeCompare(s.kind));return r.sort((i,o)=>i.from.localeCompare(o.from)||i.to.localeCompare(o.to))}function Lf(e,t,n){let r=[],i=[];for(let s of qr(e))(Vr(s.from,t)||Vr(s.to,t)?r:i).push(Un(s));let o=[];return ee(o,r,n,"duplicate_edge","info","One semantic relationship should be stored once; parallel same-family spellings (reciprocal inverse pairs included) add no information and skew degree metrics.",s=>`${s} duplicated relationship(s) between active endpoints`,"Remove all but one stored spelling of the relationship; keep the canonical direction the holder declared first."),ee(o,i,n,"legacy_duplicate_edge","info","Duplicated spellings between exclusively terminal items are historical noise with no scheduling effect.",s=>`${s} duplicated relationship(s) between terminal endpoints`,"Leave as history debt or clean up in a dedicated changelog-safe closed-item batch."),o}function Ff(e,t){let n=[],r=[];for(let o of e.duplicateRows??[])(o.legacy_terminal?r:n).push(`${o.holder_id} -> ${o.target_id} (${o.kind} x${o.occurrences})`);let i=[];return ee(i,n,t,"duplicate_dependency_row","warning","One dependency row must be stored once per holder; identical repeated rows are a storage-layer defect invisible to the assembled graph.",o=>`${o} exactly duplicated stored dependency row(s) on active holder(s)`,"Remove the repeated rows so the dependency is stored exactly once; graph semantics are unchanged."),ee(i,r,t,"legacy_duplicate_dependency_row","info","Identical repeated dependency rows on terminal holders are historical storage noise with no scheduling effect.",o=>`${o} exactly duplicated stored dependency row(s) on terminal holder(s)`,"Leave as history debt or clean up in a dedicated changelog-safe closed-item batch."),i}function Mf(e,t){let n=new Map,r={source_to_target:[],target_to_source:[],both:[]};for(let s of e.graph.registry().list())s.outcomeTraversal!==void 0&&r[s.outcomeTraversal].push(s.kind);let i={source_to_target:r.source_to_target.join(","),target_to_source:r.target_to_source.join(","),both:r.both.join(",")},o=(s,a)=>{let c=n.get(a)??new Set;c.add(s),n.set(a,c)};for(let s of e.graph.edges()){t?.throwIfAborted();let a=e.graph.registry().require(s.kind);(a.outcomeTraversal==="source_to_target"||a.outcomeTraversal==="both")&&o(s.source,s.target),(a.outcomeTraversal==="target_to_source"||a.outcomeTraversal==="both")&&o(s.target,s.source)}return{basis:i,reverse:n}}function Nf(e,t,n){let r=new Set(e),i=[...e].sort();for(let o=0;o<i.length;o+=1){n?.throwIfAborted();for(let s of[...t.get(i[o])??[]].sort())r.has(s)||(r.add(s),i.push(s))}return r}function $f(e,t,n,r){let i=0,o=0,s=0,a=0;for(let p of e.values())if(r?.throwIfAborted(),!t.has(p.id)&&!(p.missing||p.status==="external")){if(p.terminal){s+=1,n.has(p.id)&&(a+=1);continue}n.has(p.id)?i+=1:o+=1}let c=i+o,d=s-a,l=i+a,u=o+d,f=l+u;return{active_outcome_reachable_nodes:i,active_outcome_unreachable_nodes:o,active_outcome_reachability_basis_points:c===0?0:Math.floor(i*1e4/c),terminal_nodes:s,terminal_outcome_reachable_nodes:a,terminal_outcome_unreachable_nodes:d,terminal_outcome_reachability_basis_points:s===0?0:Math.floor(a*1e4/s),outcome_reachable_nodes:l,outcome_unreachable_nodes:u,outcome_reachability_basis_points:f===0?0:Math.floor(l*1e4/f)}}function Pf(e,t,n){let r=new Set(e.details.filter(a=>a.type?.toLowerCase()===wf&&a.title.trim().toLowerCase().startsWith(kf)).map(a=>a.id)),{basis:i,reverse:o}=Mf(e,n),s=Nf(r,o,n);return{outcome_nodes:r.size,outcome_reachability_basis:i,...$f(t,r,s,n)}}function jf(e,t,n,r,i){e.active+=1;let o=t.type??"(untyped)",s=e.byType.get(o);s||(s={active:0,isolated:0,degree_leq_one:0},e.byType.set(o,s)),s.active+=1,!(n>1)&&(e.degreeLeqOne+=1,s.degree_leq_one+=1,n===0&&(e.isolated+=1,s.isolated+=1),!(r.has(t.id.toLowerCase())||i.has(o.toLowerCase()))&&(n===0?e.isolates.push(t.id):e.sparse.push(t.id)))}function Uf(e,t,n,r,i,o,s){let a={active:0,missing:0,isolated:0,degreeLeqOne:0,isolates:[],sparse:[],byType:new Map};for(let v of e.graph.nodes()){s?.throwIfAborted();let w=t.get(v);if(w){if(w.missing){a.missing+=1;continue}w.terminal||jf(a,w,e.graph.incidentEdges(v).length,n,r)}}let{isolates:c,sparse:d}=a,l=[];ee(l,c,i,"isolated_active_node","warning","Active work should be reachable from the graph unless explicitly declared a valid isolate.",v=>`${v} active item(s) with no relationships`,"Link the item to its parent, prerequisite, or origin \u2014 or register it as an exempt isolate."),ee(l,d,i,"sparse_active_node","info","Active items with a single edge often miss an honest semantic partner; sparse is not automatically defective.",v=>`${v} active item(s) with exactly one relationship`,"Investigate for an honest second edge (story->task, defect family, cross-epic complement); do not fabricate one.");let u=e.graph.edges().length,f=tt(e.graph,{signal:s}).value,p=new Set(f.map(({edge:v})=>`${v.source.toLowerCase()}\0${v.target.toLowerCase()}\0${v.kind}`));for(let v of e.orderingContradictions??[])p.add(`${v.holder_id.toLowerCase()}\0${v.target_id.toLowerCase()}\0${v.dependency_kind}`);let m=Object.fromEntries(Object.entries(o).sort(([v],[w])=>v.localeCompare(w))),h=Object.entries(m).reduce((v,[w,C])=>v+(jn(w)?C:0),0),y=$n(e.graph,{signal:s}).value,b=Pf(e,t,s);return{findings:l,profile:{nodes:e.graph.nodes().length,recorded_nodes:e.details.filter(v=>v.status!=="missing"&&v.status!=="external").length,edges:u,informative_edges:u-p.size,redundant_edges:f.length,ordering_contradiction_edges:e.orderingContradictions?.length??0,edge_basis:"deduplicated_directed",edges_by_kind:m,edge_share_by_kind:Object.fromEntries(Object.entries(m).map(([v,w])=>[v,w/u])),semantic_edges:h,semantic_edge_share:u===0?0:h/u,active_nodes:a.active,missing_nodes:a.missing,isolated_active_nodes:a.isolated,degree_leq_one_active_nodes:a.degreeLeqOne,coverage_by_type:Object.fromEntries([...a.byType.entries()].sort(([v],[w])=>v<w?-1:1)),articulation_points:y.articulationPoints.length,bridge_edges:y.bridges.length,...b,finding_subjects_by_code:Object.fromEntries(rt.map(v=>[v,0]))}}}function Hn(e,t={}){let n=t.isTerminal??(f=>f==="closed"||f==="canceled"),r=t.isBlocked??(f=>f==="blocked"),i=t.maxSampleSize??bf;if(!Number.isInteger(i)||i<1)throw new TypeError(`Invalid audit sample bound: ${String(t.maxSampleSize)}`);let o=ta(t.exemptIsolates),s=ta(t.isolateExemptTypes),a=new Map(e.details.map(f=>[f.id,{id:f.id,status:f.status,missing:e.missingIdSet.has(f.id.toLowerCase()),terminal:n(f.status),...f.type===void 0?{}:{type:f.type}}]));t.signal?.throwIfAborted();let c={};for(let f of e.graph.edges())c[f.kind]=(c[f.kind]??0)+1;let d=Df(e,n,i);d.push(...Cf(e,i)),t.signal?.throwIfAborted(),d.push(...Af(e,i)),t.signal?.throwIfAborted(),d.push(...Of(e,a,r,i)),t.signal?.throwIfAborted(),d.push(...Lf(e,a,i),...Ff(e,i)),t.signal?.throwIfAborted();let l=Uf(e,a,o,s,i,c,t.signal);d.push(...l.findings),d.sort((f,p)=>ea[f.severity]-ea[p.severity]||f.code.localeCompare(p.code)||f.sample[0].localeCompare(p.sample[0]));let u=l.profile.finding_subjects_by_code;for(let f of d)u[f.code]+=f.count;return{findings:d,profile:{...l.profile,...Js(e,n,jn,t.signal),ordering_acyclic:!d.some(f=>f.code==="ordering_cycle"||f.code==="legacy_ordering_cycle"),active_ordering_acyclic:!d.some(f=>f.code==="ordering_cycle"),finding_subjects_by_code:u}}}function zr(e,t){let n=[...new Set([...Object.keys(e),...Object.keys(t)])].sort(),r={};for(let i of n){let o=(t[i]??0)-(e[i]??0);o!==0&&(r[i]=o)}return r}function ia(e){return e.profile.coverage_by_type??{}}function Hf(e,t){let n={},r=ia(e),i=ia(t),o=[...new Set([...Object.keys(r),...Object.keys(i)])].sort();for(let s of o){let a=Object.assign({active:0,isolated:0,degree_leq_one:0},r[s]),c=Object.assign({active:0,isolated:0,degree_leq_one:0},i[s]),d={active:c.active-a.active,isolated:c.isolated-a.isolated,degree_leq_one:c.degree_leq_one-a.degree_leq_one};Object.values(d).some(l=>l!==0)&&(n[s]=d)}return n}function aa(e,t){let n=Hf(e,t),{edge_share_by_kind:r={},semantic_edges:i=0,semantic_edge_share:o=0}=e.profile,{edge_share_by_kind:s={},semantic_edges:a=0,semantic_edge_share:c=0}=t.profile,d=e.profile.recorded_nodes??e.profile.nodes,l=t.profile.recorded_nodes??t.profile.nodes,u=e.profile.informative_edges??e.profile.edges,f=t.profile.informative_edges??t.profile.edges,p=e.profile.redundant_edges??0,m=t.profile.redundant_edges??0,h=e.profile.ordering_contradiction_edges??0,y=t.profile.ordering_contradiction_edges??0;return{baseline_saved_at:e.saved_at,same_snapshot:e.fingerprint===t.fingerprint,affected_subjects_by_code:zr(e.affected_subjects_by_code,t.affected_subjects_by_code),profile:{nodes:t.profile.nodes-e.profile.nodes,recorded_nodes:l-d,edges:t.profile.edges-e.profile.edges,informative_edges:f-u,redundant_edges:m-p,ordering_contradiction_edges:y-h,active_nodes:t.profile.active_nodes-e.profile.active_nodes,missing_nodes:t.profile.missing_nodes-e.profile.missing_nodes,isolated_active_nodes:t.profile.isolated_active_nodes-e.profile.isolated_active_nodes,degree_leq_one_active_nodes:t.profile.degree_leq_one_active_nodes-e.profile.degree_leq_one_active_nodes,edges_by_kind:zr(e.profile.edges_by_kind,t.profile.edges_by_kind),edge_share_by_kind:zr(r,s),semantic_edges:a-i,semantic_edge_share:c-o,coverage_by_type:n,...Zs(e.profile,t.profile)}}}import ca from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="19264e42-25fa-5c93-9b0d-3b18a1ab9783")}catch{}})();var da=2,Wr=500,Bf=64,Gf="graph-durable-cache";function la(e){return Ke(e,Gf,30,`graph-cache:${process.pid}`,!1,!1,3e3)}function bt(e){return ca.join(e,"runtime","graph-cache.json")}function ua(e){return ca.join(e,"runtime","graph-audit-baseline.json")}function Yr(e){if(e!==null)try{let t=JSON.parse(e);return typeof t!="object"||t===null||t.version!==da||typeof t.fingerprint!="string"||typeof t.saved_at!="string"||typeof t.results!="object"||t.results===null||Array.isArray(t.results)?void 0:t}catch{return}}async function Xr(e,t){let n=await ge(bt(e)),r=Yr(n),i=r?.fingerprint===t;return{exists:n!==null,fresh:i,results:i?r.results:{}}}async function Jr(e,t,n,r,i){let o=await la(e);try{let s=Yr(await ge(bt(e))),a=s?.fingerprint===t?s.results:{};delete a[r],a[r]=i;let c=Object.keys(a);for(let d of c.slice(0,Math.max(0,c.length-Bf)))delete a[d];await W(bt(e),JSON.stringify({version:da,fingerprint:t,saved_at:new Date().toISOString(),results:a})),n.results=a}finally{await o()}}async function Qr(e){let t=await la(e);try{await co(bt(e))}finally{await t()}}async function fa(e,t){let n=bt(e),r=await ge(n),i=Yr(r);return i===void 0?{exists:r!==null,fresh:!1,entry_count:0}:{exists:!0,fresh:i.fingerprint===t,entry_count:Object.keys(i.results).length,fingerprint:i.fingerprint.slice(0,12),saved_at:i.saved_at,bytes:Buffer.byteLength(r,"utf8")}}function Zr(e,t){return t||e>=Wr}function Bn(e){return ot(e)&&Object.values(e).every(De)}function ot(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function De(e){return Number.isInteger(e)&&Number(e)>=0}function ma(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=1}function vt(e,t){return e===void 0||t(e)}function Kf(e){return ot(e)&&Object.values(e).every(ma)}function zf(e){return ot(e)?Object.values(e).every(t=>ot(t)&&[t.active,t.isolated,t.degree_leq_one].every(De)):!1}function Vf(e,t,n){let r=["recorded_nodes","informative_edges","redundant_edges","ordering_contradiction_edges"],i=r.filter(s=>e[s]!==void 0).length;if(i!==0&&i!==r.length||!r.every(s=>vt(e[s],De)))return;let o={recorded_nodes:e.recorded_nodes??t,informative_edges:e.informative_edges??n,redundant_edges:e.redundant_edges??0,ordering_contradiction_edges:e.ordering_contradiction_edges??0};return o.recorded_nodes<=t&&o.informative_edges<=n&&o.redundant_edges<=n&&o.ordering_contradiction_edges<=n?o:void 0}function qf(e,t,n){let r=[...t,...n,"finding_subjects_by_code"],i=r.filter(o=>e[o]!==void 0).length;return i!==0&&i!==r.length?!1:t.every(o=>vt(e[o],De))&&n.every(o=>vt(e[o],De)&&(e[o]===void 0||Number(e[o])<=1e4))&&vt(e.finding_subjects_by_code,Bn)}function Wf(e,t,n,r){let i=Vf(e,n,r);if(i===void 0)return;let o=["articulation_points","bridge_edges","outcome_nodes","active_outcome_reachable_nodes","active_outcome_unreachable_nodes","terminal_nodes","terminal_outcome_reachable_nodes","terminal_outcome_unreachable_nodes","outcome_reachable_nodes","outcome_unreachable_nodes"],s=["active_outcome_reachability_basis_points","terminal_outcome_reachability_basis_points","outcome_reachability_basis_points"];if(!qf(e,o,s)||e.edge_basis!==void 0&&e.edge_basis!=="deduplicated_directed")return;let a=Bn(e.finding_subjects_by_code)?e.finding_subjects_by_code:{};return{edge_basis:"deduplicated_directed",...i,...Object.fromEntries(o.map(c=>[c,e[c]??0])),...Object.fromEntries(s.map(c=>[c,e[c]??0])),finding_subjects_by_code:Object.fromEntries(rt.map(c=>[c,a[c]??t[c]??0]))}}function Yf(e,t,n,r,i){let o=[n,r,i],s=o.filter(d=>d!==void 0).length;if(s===0)return{edge_share_by_kind:{},semantic_edges:0,semantic_edge_share:0};if(s!==o.length||!Kf(n)||!De(r)||!ma(i))return;let a=Object.entries(t);if(a.reduce((d,[,l])=>d+l,0)!==e||Object.keys(n).length!==a.length||a.some(([d,l])=>n[d]!==(e===0?0:l/e)))return;let c=a.reduce((d,[l,u])=>d+(jn(l)?u:0),0);if(!(r!==c||i!==(e===0?0:c/e)))return{edge_share_by_kind:n,semantic_edges:r,semantic_edge_share:i}}function Xf(e){if(e!==null)try{let t=JSON.parse(e);if(!ot(t))return;let n=t,r=n.profile;if(typeof n.saved_at!="string"||typeof n.fingerprint!="string")return;let i=n.affected_subjects_by_code;if(!Bn(i)||!ot(r)||!Qs(r)||![r.nodes,r.edges,r.active_nodes,r.missing_nodes,r.isolated_active_nodes,r.degree_leq_one_active_nodes].every(De)||!Bn(r.edges_by_kind)||!vt(r.coverage_by_type,zf))return;let o=Yf(r.edges,r.edges_by_kind,r.edge_share_by_kind,r.semantic_edges,r.semantic_edge_share);if(o===void 0)return;let s=Wf(r,i,r.nodes,r.edges);if(s===void 0)return;let{coverage_by_type:a={}}=r;return{...n,profile:{...r,...o,...s,coverage_by_type:a}}}catch{return}}async function pa(e){return Xf(await ge(ua(e)))}async function ha(e,t){await W(ua(e),JSON.stringify(t))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="236ccc7d-6efd-57b1-8cce-6758d537f779")}catch{}})();var Jf={missing_reference_active:{op:"investigate",confidence:"medium",rationale:"Restore or re-create the referenced item, or remove/retype the reference on the active holder; the correct fix depends on why the target is absent."},missing_reference_terminal:{op:"waive",confidence:"high",rationale:"Terminal-holder reference to an absent item is historical debt; waive it or clean it up only in a dedicated changelog-safe closed-item batch."},legacy_no_blocker_sentinel:{op:"remove",confidence:"high",rationale:"The pre-structured-dependency no-active-blocker sentinel is retired and carries no information; blocker state derives from blocked_by edges."},ordering_cycle:{op:"investigate",confidence:"low",rationale:"Every cycle member is unschedulable until one ordering edge is removed or retyped; the planner never chooses which edge to cut."},legacy_ordering_cycle:{op:"waive",confidence:"high",rationale:"Terminal-only ordering cycles have no scheduling effect; repairing them would mutate closed history (changelog drag)."},ordering_storage_contradiction:{op:"remove",confidence:"high",rationale:"The structured ordering row asserts the opposite precedence from the same-target scalar blocker; remove that exact dependency row or replace both representations with one unambiguous edge."},legacy_ordering_storage_contradiction:{op:"remove",confidence:"high",rationale:"The terminal holder contains a proven contradictory structured ordering row; remove it in a dedicated changelog-safe batch while preserving the scalar blocker as history."},hierarchy_cycle:{op:"investigate",confidence:"low",rationale:"Cut or retype one exact structural relation in the cycle; the planner preserves every evidence row because intent determines the correct parent."},legacy_hierarchy_cycle:{op:"waive",confidence:"high",rationale:"Terminal-only hierarchy cycles are historical debt; waive them unless an explicit closed-history repair is approved."},hierarchy_cardinality_violation:{op:"investigate",confidence:"medium",rationale:"Choose the canonical parent and remove or retype the exact surplus hierarchy rows; the planner cannot infer ownership intent."},legacy_hierarchy_cardinality_violation:{op:"waive",confidence:"high",rationale:"Multiple parents confined to terminal items are historical debt; waive them unless a dedicated history repair is approved."},hierarchy_direction_violation:{op:"investigate",confidence:"medium",rationale:"Align the scalar parent and dependency-backed hierarchy rows to the intended canonical parent."},legacy_hierarchy_direction_violation:{op:"waive",confidence:"high",rationale:"Divergent hierarchy storage confined to terminal items is historical debt; waive it unless a dedicated history repair is approved."},duplicate_edge:{op:"remove",confidence:"high",rationale:"Parallel same-family spellings state one relationship twice; remove all but one stored spelling, keeping the holder's canonical direction."},legacy_duplicate_edge:{op:"waive",confidence:"high",rationale:"Duplicated spellings between terminal items are historical noise; waive or batch changelog-safe cleanup."},duplicate_dependency_row:{op:"remove",confidence:"high",rationale:"The identical dependency row is stored more than once on the holder; drop the repeats so the row exists exactly once \u2014 graph semantics are unchanged."},legacy_duplicate_dependency_row:{op:"waive",confidence:"high",rationale:"Repeated identical rows on terminal holders are storage noise; waive or clean up only in a changelog-safe closed-item batch."},stale_lifecycle_block:{op:"investigate",confidence:"medium",rationale:`Add a local ordering edge, declare an external blocker with --dep "id=<external-ref>,kind=blocked_by,source_kind=external", or move the item back to an active status; only the holder's owner knows which is true.`},isolated_active_node:{op:"investigate",confidence:"medium",rationale:"Link the item to its parent, prerequisite, or origin \u2014 or register it as an explicitly exempt isolate; the audit never fabricates an edge."},sparse_active_node:{op:"investigate",confidence:"low",rationale:"Investigate for an honest second edge (story-to-task, defect family, cross-epic complement); sparse is not automatically defective."}};function ga(e){return`${e.source} -${e.kind}-> ${e.target}`}function Qf(e){let[t,...n]=e.edges;return n.map(r=>({op:"remove",code:"duplicate_edge",subject:ga(r),rationale:"This stored spelling restates the kept canonical edge of the same semantic family; removing it leaves the relationship stated exactly once.",evidence:[`keep: ${ga(t)}`,`group: ${Un(e)}`],confidence:"high"}))}function Zf(e,t){if(e.code==="duplicate_edge")return e.sample.flatMap(r=>Qf(t.get(r)));let n=Jf[e.code];return e.sample.map(r=>({op:n.op,code:e.code,subject:r,rationale:n.rationale,evidence:[e.policy],confidence:n.confidence}))}function _a(e,t={}){let{redundancyLimit:n,...r}=t,i=Hn(e,r),o=new Map(qr(e).map(d=>[Un(d),d])),s=i.findings.flatMap(d=>Zf(d,o)),a=i.findings.some(d=>d.sample_truncated);t.signal?.throwIfAborted();let c=tt(e.graph,{limit:n??t.maxSampleSize??25,...t.signal===void 0?{}:{signal:t.signal}});for(let d of c.value)s.push({op:"remove",code:"redundant_edge",subject:`${d.edge.source} -> ${d.edge.target} (${d.edge.kind})`,rationale:"The stored edge is implied by a longer same-family witness path; shortcut edges are sometimes deliberate emphasis, so confirm intent before removing.",evidence:[`witness: ${d.witness.join(" -> ")}`],confidence:"medium"});return a=a||c.meta.truncated,{steps:s,report:i,truncated:a,cost:{visitedNodes:c.meta.visitedNodes,inspectedEdges:c.meta.inspectedEdges}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3a536c76-bbd6-5235-b06a-f18c5cf95a88")}catch{}})();var wa=new Set(["ancestors","descendants","predecessors","successors","paths","impact","dominators"]),be=10;function ya(e,t,n){let r=e;if(t&&e.subcommand==="audit"){let{nodes:i,recorded_nodes:o,edges:s,active_nodes:a,terminal_nodes:c,missing_nodes:d,ordering_acyclic:l,active_ordering_acyclic:u,coverage_by_lifecycle:f}=e.profile,p=Object.fromEntries(Object.entries(f).map(([m,h])=>{let{degree_histogram:y,...b}=h;return[m,b]}));r={...e,profile:{nodes:i,recorded_nodes:o,edges:s,active_nodes:a,terminal_nodes:c,missing_nodes:d,ordering_acyclic:l,active_ordering_acyclic:u,coverage_by_lifecycle:p}}}return{...r,projection:{mode:t?"summary":"full",declared_field_groups:n===void 0?[]:[{name:n,restore_with:"--full"}],included_field_groups:n===void 0||t?[]:[n]}}}function va(e){return e===void 0?[]:(Array.isArray(e)?e:[e]).flatMap(t=>t.split(",")).map(t=>t.trim()).filter(t=>t.length>0)}function em(e,t,n){let r=e.trim().toLowerCase();if(!wr.includes(r))throw po({command_path:"graph",token:r||"<empty>",allowed:wr});let i=r;if(wa.has(i)&&!t?.trim())throw new _(`graph ${i} requires an item id.`,g.USAGE);if(i==="paths"&&!n?.trim())throw new _("graph paths requires a source and a target item id.",g.USAGE);return i}function ei(e){throw e instanceof TypeError?new _(e.message,g.USAGE):e}function ti(e){return{truncated:e.truncated,cost:{visited_nodes:e.visitedNodes,inspected_edges:e.inspectedEdges}}}function ba(e,t){let n=t.trim().toLowerCase();for(let r of e.details)if(r.id.trim().toLowerCase()===n&&!e.missingIdSet.has(r.id.toLowerCase()))return r.id;throw new _(`Item ${t} not found`,g.NOT_FOUND)}function tm(e,t,n){let r={ancestors:Ms,descendants:Ns,predecessors:$s,successors:Ps}[e],i;try{i=r(n.assembly.graph,t,{...n.kinds===void 0?{}:{kinds:n.kinds},...n.maxDepth===void 0?{}:{maxDepth:n.maxDepth},...n.limit===void 0?{}:{limit:n.limit},...n.after===void 0?{}:{after:n.after}})}catch(s){ei(s)}let o=ti(i.meta);return{subcommand:e,root:t,count:i.value.length,...o,...i.meta.nextCursor===void 0?{}:{next_cursor:i.meta.nextCursor},...n.summary?{}:{ids:i.value}}}function nm(e,t,n){let r=js(n.assembly.graph,e,t,{direction:n.direction,...n.kinds===void 0?{}:{kinds:n.kinds},...n.maxDepth===void 0?{}:{maxDepth:n.maxDepth},...n.maxPaths===void 0?{}:{maxPaths:n.maxPaths}});return{subcommand:"paths",root:e,target:t,direction:n.direction,count:r.value.length,...ti(r.meta),...n.summary?{}:{paths:r.value.map(i=>({nodes:i.nodes,kinds:i.edges.map(o=>o.kind),length:i.length}))}}}function rm(e,t){let n;try{n=_n(t.assembly.graph,e,{direction:t.direction,...t.kinds===void 0?{}:{kinds:t.kinds},...t.maxDepth===void 0?{}:{maxDepth:t.maxDepth},...t.unbounded?{}:{limit:t.limit??be},...t.after===void 0?{}:{after:t.after}})}catch(r){ei(r)}return{subcommand:"impact",root:e,direction:t.direction,count:n.affected.length,truncated:n.truncated,...n.nextCursor===void 0?{}:{next_cursor:n.nextCursor},cost:{visited_nodes:n.cost.visitedNodes,inspected_edges:n.cost.inspectedEdges},...t.summary?{}:{affected:n.affected}}}function im(e,t,n){return{acyclic:e.acyclic,ordered_node_count:e.order.length,layer_count:e.layers.length,frontier_count:e.frontier.length,critical_path_length:e.criticalPathLength,cycle_count:e.cycles.length,...t?{}:{frontier:e.frontier.slice(0,n),critical_path:e.criticalPath.slice(0,n),cycles:e.cycles.slice(0,n)}}}function om(e,t,n){return{component_count:e.components.length,largest_component_size:e.components[0]?.length??0,orphan_count:e.orphans.length,...t?{}:{orphans:e.orphans.slice(0,n),hubs:e.hubs.slice(0,n)}}}function sm(e,t,n){let r=0,i=0,o=0;for(let s of e.cycles)r+=Number(s.legacy_terminal);for(let s of e.cardinality_violations)i+=Number(s.legacy_terminal);for(let s of e.divergences)o+=Number(s.legacy_terminal);return{acyclic:e.cycles.length===0,relation_count:e.relations.length,cycle_count:e.cycles.length,active_cycle_count:e.cycles.length-r,legacy_cycle_count:r,cardinality_violation_count:e.cardinality_violations.length,active_cardinality_violation_count:e.cardinality_violations.length-i,legacy_cardinality_violation_count:i,parent_divergence_count:e.divergences.length,active_parent_divergence_count:e.divergences.length-o,legacy_parent_divergence_count:o,...t?{}:{cycles:e.cycles.slice(0,n).map(s=>s.item_ids)}}}function am(e){let t=e.assembly.graph,n=e.limit??be,r=yn(t,{registry:t.registry()}),i=ms(t);return{subcommand:"analyze",node_count:t.nodes().length,edge_count:t.edges().length,edge_basis:"deduplicated_directed",sample_limit:n,execution:im(r,e.summary,n),knowledge:om(i,e.summary,n),hierarchy:sm(Sn(e.assembly),e.summary,n)}}function cm(e,t){let n=Hn(e.assembly,{isTerminal:t,...e.sample===void 0?{}:{maxSampleSize:e.sample},...e.exemptIsolates.length===0?{}:{exemptIsolates:e.exemptIsolates},...e.exemptIsolateTypes.length===0?{}:{isolateExemptTypes:e.exemptIsolateTypes}}),r={},i={},o={},s={};for(let d of n.findings)r[d.severity]=(r[d.severity]??0)+1,i[d.code]=(i[d.code]??0)+1,o[d.severity]=(o[d.severity]??0)+d.count,s[d.code]=(s[d.code]??0)+d.count;let{finding_subjects_by_code:a,...c}=n.profile;return{subcommand:"audit",finding_count:n.findings.length,findings_by_severity:r,findings_by_code:i,affected_subjects_by_severity:o,affected_subjects_by_code:s,profile:e.summary?c:n.profile,legacy_alias_counts:e.assembly.legacyAliasCounts,...e.summary?{}:{findings:n.findings}}}function dm(e){let t=e.limit??be,n={};e.kinds!==void 0&&(n.kinds=e.kinds);let r=Hs(e.assembly.graph,n),i=r.value;return{subcommand:"communities",community_count:i.communities.length,largest_community_size:i.communities[0]?.size??0,iterations:i.iterations,converged:i.converged,truncated:!i.converged||i.communities.length>t,cost:{visited_nodes:r.meta.visitedNodes,inspected_edges:r.meta.inspectedEdges},...e.summary?{}:{communities:i.communities.slice(0,t).map(o=>({representative:o.representative,size:o.size,members:o.members.slice(0,t)}))}}}function lm(e){let t;try{t=tt(e.assembly.graph,{...e.kinds===void 0?{}:{kinds:e.kinds},...e.maxDepth===void 0?{}:{maxDepth:e.maxDepth},...e.limit===void 0?{}:{limit:e.limit}})}catch(n){ei(n)}return{subcommand:"redundancy",redundant_count:t.value.length,...ti(t.meta),...e.summary?{}:{redundant:t.value.map(n=>({source:n.edge.source,target:n.edge.target,kind:n.edge.kind,witness:n.witness}))}}}function um(e,t){let n=t.limit??be,r=Bs(t.assembly.graph,e,{direction:t.direction,...t.kinds===void 0?{}:{kinds:t.kinds},...t.maxDepth===void 0?{}:{maxDepth:t.maxDepth}}),i=r.value.rows.filter(o=>o.dominatedCount>0);return{subcommand:"dominators",root:e,direction:t.direction,reachable_count:r.value.reachableCount,bottleneck_count:i.length,truncated:r.meta.truncated||i.length>n,cost:{visited_nodes:r.meta.visitedNodes,inspected_edges:r.meta.inspectedEdges},...t.summary?{}:{bottlenecks:i.slice(0,n).map(o=>({id:o.id,idom:o.idom,dominated_count:o.dominatedCount}))}}}function fm(e){let t=e.limit??be,n=qs(e.assembly.graph),r=n.rows.filter(i=>i.critical).length;return{subcommand:"slack",acyclic:n.acyclic,makespan:n.makespan,scheduled_count:n.scheduledCount,critical_count:r,critical_path_length:n.criticalPathLength,cycle_count:n.cycles.length,truncated:n.rows.length>t,...e.summary?{}:{critical_path:n.criticalPath,rows:n.rows.slice(0,t).map(i=>({id:i.id,earliest_start:i.earliestStart,latest_start:i.latestStart,slack:i.slack,critical:i.critical}))}}}function mm(e){let t=e.limit??be,n=Vs(e.assembly.graph,e.kinds===void 0?{}:{kinds:e.kinds}),r=n.value;return{subcommand:"centrality",node_count:r.nodeCount,edge_count:r.edgeCount,edge_basis:"simple_undirected",truncated:r.rows.length>t,cost:{visited_nodes:n.meta.visitedNodes,inspected_edges:n.meta.inspectedEdges},...e.summary?{}:{rows:r.rows.slice(0,t).map(i=>({id:i.id,degree:i.degree,in_degree:i.inDegree,out_degree:i.outDegree,betweenness:i.betweenness,closeness:i.closeness}))}}}function pm(e){let t=e.limit??be,n=$n(e.assembly.graph,e.kinds===void 0?{}:{kinds:e.kinds}),{articulationPoints:r,bridges:i}=n.value;return{subcommand:"articulation",articulation_count:r.length,bridge_count:i.length,truncated:r.length>t||i.length>t,cost:{visited_nodes:n.meta.visitedNodes,inspected_edges:n.meta.inspectedEdges},...e.summary?{}:{articulation_points:r.slice(0,t),bridges:i.slice(0,t)}}}function hm(e,t){let n=e.limit??be,r=_a(e.assembly,{isTerminal:t,redundancyLimit:n,...e.sample===void 0?{}:{maxSampleSize:e.sample},...e.exemptIsolates.length===0?{}:{exemptIsolates:e.exemptIsolates},...e.exemptIsolateTypes.length===0?{}:{isolateExemptTypes:e.exemptIsolateTypes}}),i={},o={};for(let s of r.steps)i[s.op]=(i[s.op]??0)+1,o[s.code]=(o[s.code]??0)+1;return{subcommand:"plan",step_count:r.steps.length,steps_by_op:i,steps_by_code:o,finding_count:r.report.findings.length,truncated:r.truncated||r.steps.length>n,cost:{visited_nodes:r.cost.visitedNodes,inspected_edges:r.cost.inspectedEdges},...e.summary?{}:{steps:r.steps.slice(0,n)}}}function ka(e,t,n,r){return JSON.stringify({subcommand:e,root:t??null,target:n??null,kinds:r.kinds??null,maxDepth:r.maxDepth??null,limit:r.limit??null,after:r.after??null,direction:r.direction,maxPaths:r.maxPaths??null,sample:r.sample??null,exemptIsolates:[...new Set(r.exemptIsolates.map(i=>i.toLowerCase()))].sort(),exemptIsolateTypes:[...new Set(r.exemptIsolateTypes.map(i=>i.toLowerCase()))].sort(),summary:r.summary,unbounded:r.unbounded})}function Ea(e,t,n,r,i){return e==="analyze"?am(r):e==="audit"?cm(r,i):e==="plan"?hm(r,i):e==="communities"?dm(r):e==="redundancy"?lm(r):e==="dominators"?um(t,r):e==="slack"?fm(r):e==="centrality"?mm(r):e==="articulation"?pm(r):e==="paths"?nm(t,n,r):e==="impact"?rm(t,r):tm(e,t,r)}function gm(e,t){if(e!=="index"&&(t.rebuild===!0||t.clear===!0))throw new _("--rebuild and --clear apply only to graph index.",g.USAGE);if(e!=="audit"&&t.saveBaseline===!0)throw new _("--save-baseline applies only to graph audit.",g.USAGE);if(e==="slack"&&t.kind!==void 0)throw new _("graph slack analyzes every ordering kind; --kind is not supported.",g.USAGE);if(t.rebuild===!0&&t.clear===!0)throw new _("graph index accepts either --rebuild or --clear, not both.",g.USAGE);if(e==="impact"&&t.full===!0&&t.limit!==void 0)throw new _("graph impact accepts either --full or --limit, not both.",g.USAGE)}async function _m(e,t,n,r,i,o){let s="status";if(o.clear===!0&&(await Qr(e),s="cleared"),o.rebuild===!0){await Qr(e);let c=await Xr(e,t),d={assembly:n.assembly,direction:"both",exemptIsolates:[],exemptIsolateTypes:[],saveBaseline:!1,summary:!0,unbounded:!1};for(let l of["analyze","audit"])await Jr(e,t,c,ka(l,void 0,void 0,d),Ea(l,void 0,void 0,d,i));s="rebuilt"}let a=await fa(e,t);return{subcommand:"index",action:s,state:a.exists?a.fresh?"fresh":"stale":"absent",entry_count:a.entry_count,item_count:r,min_items_threshold:Wr,persist_enabled:Zr(r,a.exists),current_fingerprint:t.slice(0,12),...a.saved_at===void 0?{}:{saved_at:a.saved_at},...a.bytes===void 0?{}:{bytes:a.bytes}}}async function ym(e,t,n,r){let i={saved_at:new Date().toISOString(),fingerprint:t,affected_subjects_by_code:n.affected_subjects_by_code,profile:{...n.profile,finding_subjects_by_code:Object.fromEntries(rt.map(s=>[s,n.affected_subjects_by_code[s]??0]))}},o=await pa(e);return r&&await ha(e,i),o===void 0?n:{...n,baseline:aa(o,i)}}async function vm(e,t,n,r,i){try{await Jr(e,t,n,r,i)}catch{}}function bm(e,t,n,r){if(e.subcommand!=="slack")return;let i=new Set(t.assembly.details.filter(f=>r(f.status)).map(f=>f.id)),o=t.assembly.graph,s=new zt(o.nodes().filter(f=>!i.has(f)),o.edges().filter(f=>!i.has(f.source)&&!i.has(f.target)),o.registry()),a=Ws(s,n.filter(f=>!i.has(f.id)),{now:R(),limit:t.limit??be}),{rows:c,residuals:d,overcommitted:l,...u}=a;e.deadline_schedule={population:"active",...u,...t.summary?{}:{rows:c,residuals:d,overcommitted:l}}}async function uk(e,t,n,r,i){let o=em(e,t,n);Jt(r.summary===!0,r.full===!0,"--summary");let s=O(process.cwd(),i.path);await U(s);let a=await F(s),c=L(a,D()),d=await de(s,a.item_format,c.type_to_folder,void 0,a.schema),l=J(a.schema),u=M=>j(M,l);gm(o,r);let f=z(),p=Hr(r.kind,f),m=Rn().lookup(s,Tn(d,u,f),()=>Qe(d,u,f)),h={assembly:m.assembly,...p===void 0?{}:{kinds:p},maxDepth:Dn(r.maxDepth),limit:fe(r.limit,"limit"),after:r.after?.trim()||void 0,direction:Ur(r.direction),maxPaths:fe(r.maxPaths,"max-paths"),sample:fe(r.sample,"sample"),exemptIsolates:va(r.exemptIsolate),exemptIsolateTypes:va(r.exemptIsolateType),saveBaseline:r.saveBaseline===!0,summary:r.summary===!0,unbounded:r.full===!0};if(o==="index")return ya(await _m(s,m.fingerprint,h,d.length,u,r),!1);let y=wa.has(o)?ba(h.assembly,t):void 0,b=o==="paths"?ba(h.assembly,n):void 0,v=ka(o,y,b,h),w=await Xr(s,m.fingerprint),C=w.results[v],S=m.memoize(v,()=>C!==void 0?structuredClone(C):Ea(o,y,b,h,u)),N=Zr(d.length,w.exists);!S.reused&&C===void 0&&N&&await vm(s,m.fingerprint,w,v,S.value);let $=S.value.subcommand==="audit"?await ym(s,m.fingerprint,S.value,h.saveBaseline):S.value;return $.cache={fingerprint:m.fingerprint.slice(0,12),assembly:m.assemblyReused?"hit":"miss",result:S.reused?"hit":"miss",durable:C!==void 0?"hit":N?"miss":"off"},bm($,h,d,u),ya($,h.summary,"result_rows")}import ni from"node:fs/promises";import ri from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ca035b42-148d-5a43-9912-4641a6207750")}catch{}})();var wm=8388608,km=new Set(["resolved","failed"]),Em=[{kind:"boolean",matches:e=>typeof e=="boolean"||typeof e=="string"&&/^(?:true|false)$/iu.test(e.trim())},{kind:"single_digit",matches:e=>typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=9||typeof e=="string"&&/^\d$/u.test(e.trim())}];function me(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ii(e){return Em.find(t=>t.matches(e))?.kind}function Ia(e){let t=new Map,n=0,r=0;return{entries:e.map(o=>{let s=me(o.agent_provenance)?o.agent_provenance:void 0;if(s===void 0||!Po(o).ok)return o;let a={},c=!1;for(let[l,u]of Object.entries(s)){let f=me(u)?ii(u.value):void 0;if(f===void 0){a[l]=u;continue}c=!0,r+=1;let p=o.agent_harness??"unknown",m=`${p}\0${l}\0${f}`,h=t.get(m)??{harness:p,dimension:l,kind:f,count:0};h.count+=1,t.set(m,h)}if(!c)return o;n+=1;let d={...o};return Object.keys(a).length===0?delete d.agent_provenance:d.agent_provenance=a,jo(o,d,{retainPriorRecord:!0,retainPriorRecordHash:!1})}),receipt:{changed:n>0,events_changed:n,observations_removed:r,invalid_values:[...t.values()].sort((o,s)=>o.harness.localeCompare(s.harness)||o.dimension.localeCompare(s.dimension)||o.kind.localeCompare(s.kind))}}}async function Ca(e){let t=[];for(let n of await Sa(e))try{let r=await ni.readFile(ri.join(e,"history",n),"utf8");for(let i of r.split(`
|
|
1
|
+
import{$d as Yt,$j as ce,Bi as Wo,Ci as Z,Cj as es,Df as Jt,Dh as rn,Di as Yo,E as hr,Ei as Xo,Ej as ts,Ff as Mo,Ge as Io,Gj as mn,He as Co,Hj as ns,Ie as So,Je as To,Jf as br,Kb as ne,Ke as Ro,Kf as Qt,Lf as Ie,Md as bo,Mf as ae,N as lo,Ni as Cr,Nn as cs,O as g,Oe as Ge,Oi as ln,Pa as Ue,Pb as zt,Pd as ye,Pf as No,Pj as rs,Q as _,Qf as ze,Rc as D,Rd as yr,Rh as kr,S as K,Sg as Zt,Tj as is,Ua as _r,Uh as $o,Va as Gt,Vh as Er,Vj as We,Wa as ho,Wh as on,Xe as xo,Xh as Ve,Yi as Jo,Zd as J,Zi as Qo,_c as Vt,_j as U,ab as L,ad as qt,ak as Se,ba as R,bb as Kt,bd as yo,bi as sn,bj as Sr,bk as os,cb as go,cf as ve,ci as Po,ck as ss,co as le,da as gr,df as Ke,di as jo,dk as de,do as ue,ea as uo,ec as E,ef as Do,ek as pn,fa as I,ff as Xt,fi as Uo,ga as fo,gc as re,gd as vo,ha as _e,hi as an,ib as O,ii as Ho,jf as Ao,ji as Bo,ke as Q,kf as Oo,le as x,lf as Lo,me as j,mf as vr,n as pr,ne as Be,nf as Fo,nj as un,o as Bt,oa as mo,ob as He,oi as qe,oj as fn,p as je,pi as Go,q as se,qa as po,qe as wo,qi as Ko,r as ge,rd as Wt,re as ko,ri as zo,s as W,se as Eo,si as Vo,t as co,tg as wr,ti as Ce,tj as Zo,tm as as,ui as Ir,vh as en,vi as qo,wi as cn,wj as F,xc as _o,xh as tn,xi as xe,yi as dn,zh as nn}from"./chunk-33PER336.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e252abd5-9585-56f7-9fc2-7b20459a2238")}catch{}})();async function Tr(e){let t=O(process.cwd(),e);await U(t);let n=await F(t),r=L(n,D());return{pmRoot:t,settings:n,typeRegistry:r}}async function hn(e,t,n,r){He(e,Cr(t));let i=await ce(e,t,n.id_prefix,n.item_format,r);if(i)return{id:i.id,historyPath:He(e,i.id),located:i};let o=ln(t,n.id_prefix),s=Cr(t),a=o===s?[o]:[o,s];for(let c of a){let d=He(e,c);if(await Bt(d))return{id:c,historyPath:d,located:null}}throw new _(`Item ${t} not found`,g.NOT_FOUND)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b6ef0b23-e861-50ec-b7b3-751863936631")}catch{}})();function $b(e,t){let n=Ce(e),r=e.length>0?e[e.length-1].after_hash:Ho(),i=t===void 0||n.item_hash_version===void 0?void 0:an(t,n.item_hash_version,ye(e.at(-1)?.hash_algorithm)),o=t===void 0?void 0:i===void 0?Uo(t):i[Math.max(0,i.indexOf(r))],s=o===void 0?void 0:o===r,a=[...n.errors];return s===!1&&a.push("verify_failed:current_item_hash_mismatch"),{ok:a.length===0,entries:e.length,errors:a,latest_after_hash:e.length>0?e[e.length-1].after_hash:void 0,current_item_hash:o,current_matches_latest:s}}async function Pb(e,t,n={}){let r=O(n.cwd??process.cwd(),n.pmRoot);await U(r);let i=await F(r),o=L(i,D()),s=await hn(r,e,i,o.type_to_folder),a=await Xt(s.historyPath,s.id);if(a.length===0)throw new _(`No history exists for ${s.id}; point-in-time reads are unavailable.`,g.NOT_FOUND);let c=ts(t,a),d=ns(mn(a,c.historyIndex),c),l=Ko(d,{schema:i.schema});if(l.metadata.id!==s.id)throw new _(`History target resolved to item ${l.metadata.id}, expected ${s.id}.`,g.GENERIC_FAILURE);let u=a[c.historyIndex],f=es(a,!0);return{document:l,reconstructed:!0,as_of_version:f===null?null:f+c.historyIndex+1,as_of_timestamp:u.ts,target:c,history_length:a.length}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b3394526-5a20-5881-9a03-411ada32bd49")}catch{}})();function Gd(e,t,n,r,i,o){if(e.seen.has(t))return"skip";if(e.cursorFound&&e.affected.length>=o)return"truncate";e.seen.add(t),e.parents.set(t,n.id);let s=n.depth+1;return e.queue.push({id:t,depth:s}),e.cursorFound?(e.affected.push({id:t,distance:s,path:Xd(r,t,e.parents)}),"continue"):(e.cursorFound=t===i,"skip")}function ls(e,t,n,r){let i=Ie("graph impact",{root:e,direction:n,kinds:[...t.kinds??[]].sort(),max_depth:Number.isFinite(r)?r:"unbounded"});return{fingerprint:i,after:t.after===void 0?void 0:No(t.after,i)}}function Ye(e,t,n){e.get(t).add(n)}function ft(e){return new Map(e.map(t=>[t,new Set]))}function us(e){for(let t of e)t.sort();return e.sort((t,n)=>n.length-t.length||t[0].localeCompare(n[0]))}function gn(e){if(Array.isArray(e))return e.map(n=>gn(n));if(e===null||typeof e!="object")return e;let t=e.toJSON;return typeof t=="function"?gn(t.call(e)):Object.fromEntries(Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,gn(r)]))}function ds(e){return JSON.stringify(gn(e))}function Kd(e,t,n,r){let i=[{id:e,expanded:!1}];for(;i.length>0;){let o=i.pop();if(o.expanded){r.push(o.id);continue}if(n.has(o.id))continue;n.add(o.id),i.push({id:o.id,expanded:!0});let s=[...t.get(o.id)].sort().reverse();for(let a of s)n.has(a)||i.push({id:a,expanded:!1})}}function zd(e,t){let n=new Set,r=[];for(let i of e)n.has(i)||Kd(i,t,n,r);return r}function Vd(e,t){let n=new Set,r=[];for(let i of[...e].reverse()){if(n.has(i))continue;let o=[],s=[i];for(n.add(i);s.length>0;){let a=s.pop();o.push(a);for(let c of t.get(a))n.has(c)||(n.add(c),s.push(c))}r.push(o)}return us(r)}function fs(e,t){let n=ft(e);for(let[r,i]of t)for(let o of i)Ye(n,o,r);return Vd(zd(e,t),n)}function qd(e,t){let n=ft(e.nodes());for(let r of e.edges()){let i=t.require(r.kind);if(!i.ordering)continue;let o=(i.precedence??"source_before_target")==="source_before_target";Ye(n,o?r.source:r.target,o?r.target:r.source)}return n}function Wd(e,t){let n=new Map(e.map(o=>[o,0]));for(let o of t.values())for(let s of o)n.set(s,n.get(s)+1);let r=e.filter(o=>n.get(o)===0).sort(),i=[];for(;r.length>0;){i.push(r);let o=[];for(let s of r)for(let a of t.get(s)){let c=n.get(a)-1;n.set(a,c),c===0&&o.push(a)}r=o.sort()}return i}function Yd(e,t){let n=new Map(e.map(s=>[s,0])),r=new Map;for(let s of e)for(let a of t.get(s)){if(!n.has(a))continue;let c=n.get(s)+1,d=r.get(a);(c>n.get(a)||c===n.get(a)&&(d===void 0||s.localeCompare(d)<0))&&(n.set(a,c),r.set(a,s))}let i=[...e].sort((s,a)=>n.get(a)-n.get(s)||s.localeCompare(a))[0],o=i===void 0?[]:[i];for(;o[0]!==void 0&&r.has(o[0]);)o.unshift(r.get(o[0]));return{depth:Object.fromEntries(n),path:o}}function Xd(e,t,n){let r=[t],i=t;for(;i!==e;)i=n.get(i),r.push(i);return r.reverse()}function yn(e,t={}){let n=t.registry??ne(),r=[...e.nodes()],i=qd(e,n),o=Wd(r,i),s=o.flat(),a=s.length===r.length,c=a?[]:fs(r,i).filter(l=>l.length>1||i.get(l[0]).has(l[0])),d=Yd(s,i);return{exact:!0,acyclic:a,order:s,layers:o,frontier:o[0]??[],depth:d.depth,criticalPath:d.path,criticalPathLength:Math.max(0,d.path.length-1),cycles:c,provenance:{algorithm:"kahn-longest-path",edgeFamily:"ordering"}}}function Jd(e,t,n){let r=ft(e.nodes()),i=n===void 0?void 0:new Set(n.map(s=>e.registry().require(s).kind)),o=e.edges();for(let s of o){let a=e.registry().require(s.kind);i!==void 0&&!i.has(s.kind)&&(a.inverse===void 0||!i.has(a.inverse))||Ye(r,t==="incoming"?s.target:s.source,t==="incoming"?s.source:s.target)}return{adjacency:r,inspectedEdges:o.length}}function Qd(e,t,n,r,i,o){let s=_n(e,t,{...n,after:void 0,direction:"incoming",limit:void 0}),a=_n(e,t,{...n,after:void 0,direction:"outgoing",limit:void 0}),c=new Map,d=[...s.affected,...a.affected].sort((m,h)=>m.distance-h.distance||m.id.localeCompare(h.id)||m.path.join("\0").localeCompare(h.path.join("\0")));for(let m of d)c.has(m.id)||c.set(m.id,m);let l=[...c.values()].sort((m,h)=>m.distance-h.distance||m.id.localeCompare(h.id)),u=r===void 0||r===t?-1:l.findIndex(m=>m.id===r);if(r!==void 0&&r!==t&&u<0)throw new TypeError(`Unknown impact cursor item: ${r}`);let f=l.slice(u+1,u+1+i),p=u+1+f.length<l.length;return{root:t,affected:f,exact:!0,truncated:s.truncated||a.truncated||p,...p?{nextCursor:ae(o,f.at(-1)?.id??t)}:{},cost:{visitedNodes:s.cost.visitedNodes+a.cost.visitedNodes,inspectedEdges:s.cost.inspectedEdges+a.cost.inspectedEdges}}}function Zd(e,t,n){let r=n.direction,i=n.maxDepth??Number.POSITIVE_INFINITY,o=n.limit??Number.POSITIVE_INFINITY,{fingerprint:s,after:a}=ls(t,n,r,i),{adjacency:c,inspectedEdges:d}=Jd(e,r,n.kinds),l={queue:[{id:t,depth:0}],seen:new Set([t]),parents:new Map,affected:[],cursorFound:a===void 0||a===t},u=0,f=!1,p=!1;e:for(let m=0;m<l.queue.length;m+=1){n.signal?.throwIfAborted();let h=l.queue[m];u+=1;let y=[...c.get(h.id)].sort();if(h.depth>=i){y.some(b=>!l.seen.has(b))&&(f=!0);continue}for(let b of y)if(Gd(l,b,h,t,a,o)==="truncate"){f=!0,p=!0;break e}}if(!l.cursorFound)throw new TypeError(`Unknown impact cursor item: ${a}`);return{root:t,affected:l.affected,exact:!0,truncated:f,...p?{nextCursor:ae(s,l.affected.at(-1)?.id??t)}:{},cost:{visitedNodes:u,inspectedEdges:d}}}function _n(e,t,n={}){let r=n.direction??"outgoing";if(r!=="both")return Zd(e,t,{...n,direction:r});let i=n.maxDepth??Number.POSITIVE_INFINITY,o=n.limit??Number.POSITIVE_INFINITY,{fingerprint:s,after:a}=ls(t,n,r,i);return Qd(e,t,n,a,o,s)}function ms(e){let t=[...e.nodes()],n=ft(t),r=ft(t);for(let c of e.edges())Ye(n,c.source,c.target),Ye(n,c.target,c.source),Ye(r,c.source,c.target);let i=[],o=new Set;for(let c of t){if(o.has(c))continue;let d=[],l=[c];for(o.add(c);l.length>0;){let u=l.pop();d.push(u);for(let f of n.get(u))o.has(f)||(o.add(f),l.push(f))}i.push(d)}let s=t.map(c=>({id:c,degree:n.get(c).size})),a=Math.max(0,...s.map(({degree:c})=>c));return{components:us(i),stronglyConnected:fs(t,r),orphans:s.filter(({degree:c})=>c===0).map(({id:c})=>c),hubs:s.filter(({degree:c})=>c>0&&c===a),exact:!0,provenance:{algorithm:"component-degree",edgeFamily:"all"}}}function Bb(e,t){let n=new Map(e.edges.map(i=>[ds(i),i])),r=new Map(t.edges.map(i=>[ds(i),i]));return{fromVersion:e.version,toVersion:t.version,added:[...r].filter(([i])=>!n.has(i)).map(([,i])=>i),removed:[...n].filter(([i])=>!r.has(i)).map(([,i])=>i),unchangedCount:[...n.keys()].filter(i=>r.has(i)).length,exact:!0}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fdc16f69-f63f-5e17-9139-35d54db7bab5")}catch{}})();function ie(e,t="--limit"){if(e===void 0)return;let n=String(e).trim(),r=n.length===0?Number.NaN:Number(n);if(!Number.isInteger(r)||r<0)throw new _(`${t} must be a non-negative integer`,g.USAGE);return r}function vn(e,t="--priority"){if(e===void 0)return;let n=String(e).trim(),r=n.length===0?Number.NaN:Number(n);if(!Number.isInteger(r)||r<0||r>4)throw new _(`${t} filter must be 0..4`,g.USAGE);return r}function ps(e,t,n="--type"){if(e===void 0)return;let r=Kt(e,t);if(!r)throw new _(`${n} filter must be one of ${t.types.join("|")}`,g.USAGE);return r}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="94a81e04-bb02-5c2e-9362-4cf7212d66e6")}catch{}})();var bn={version:1,aliases:{}};function wn(e=[]){let t=new Set(Ge),n=r=>{/^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(r)&&t.add(r)};for(let r of e){for(let i of Object.keys(r.provenance_environment_keys??{}))n(i);for(let i of Object.keys(r.provenance_resolvers??{}))n(i);for(let i of r.provenance_unavailable_dimensions??[])n(i)}return[...t].sort()}function hs(e){if(e===void 0)return;let n=(typeof e=="string"?[e]:e).flatMap(r=>r.split(",")).map(r=>r.trim()).filter(r=>r.length>0);return n.length===0?void 0:new Set(n)}function Rr(e,t){if(e.agent_harness?.trim())return{agent_harness:e.agent_harness,harness_source:"recorded"};let n=t.aliases[e.author];return n?{agent_harness:n,harness_source:"vocabulary"}:{harness_source:"unresolved"}}function xr(e,t=Ge){let n=new Set(t),r=new Map,i=e.provenance===void 0?[]:typeof e.provenance=="string"?[e.provenance]:e.provenance;for(let o of i.flatMap(s=>s.split(","))){let s=o.indexOf("=");if(s<0)throw new _(`Provenance predicate must use dimension=value; received "${o.trim()}".`,g.USAGE,{code:"invalid_provenance_predicate"});let a=o.slice(0,s).trim().toLowerCase(),c=o.slice(s+1).trim();if(!n.has(a))throw new _(`Unknown provenance dimension "${a||o.trim()}". Declared dimensions: ${[...n].sort().join(", ")}.`,g.USAGE,{code:"unknown_provenance_dimension"});if(c.length===0)throw new _(`Provenance predicate must use dimension=value; received "${o.trim()}".`,g.USAGE,{code:"invalid_provenance_predicate"});let d=r.get(a)??new Set;d.add(c),r.set(a,d)}return r}function kn(e,t=bn,n={}){let r=Rr(e,t);return{...n.itemId===void 0?{}:{item_id:n.itemId},...n.version===void 0?{}:{version:n.version},ts:e.ts,op:e.op,author:e.author,...e.author_source===void 0?{}:{author_source:e.author_source},...r,vocabulary_version:t.version,...e.agent_instance===void 0?{}:{agent_instance:e.agent_instance},agent_provenance:e.agent_provenance??{},...e.message===void 0?{}:{message:e.message}}}function Qb(e,t,n=bn,r=Ge){return Dr(t,n,r)(e)}function Dr(e,t=bn,n=Ge){let r=hs(e.harness),i=hs(e.agentInstance),o=xr(e,n);return s=>{let c=Rr(s,t).agent_harness;if(r&&(!c||!r.has(c))||i&&!i.has(s.agent_instance??""))return!1;for(let[d,l]of o){let u=s.agent_provenance?.[d];if(!u||!l.has(u.value))return!1}return!0}}function En(e,t=bn,n=Ge){let r=new Set(n),i=new Map,o=0;for(let s of e){for(let c of Object.keys(s.agent_provenance??{}))r.add(c);Rr(s,t).agent_harness?o+=1:i.set(s.author,(i.get(s.author)??0)+1)}return{entries:e.length,vocabulary_version:t.version,harness:{resolved:o,unresolved:e.length-o,unresolved_authors:[...i].map(([s,a])=>({author:s,entries:a})).sort((s,a)=>a.entries-s.entries||s.author.localeCompare(a.author)).slice(0,20)},dimensions:[...r].sort().map(s=>{let a=0,c=0;for(let d of e){let l=d.agent_provenance?.[s];l===null?c+=1:l!==void 0&&(a+=1)}return{dimension:s,observed:a,unavailable:c,legacy_missing:e.length-a-c}})}}import el from"node:fs/promises";import ys from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="03488490-bc4a-5988-9ceb-46800c6d7833")}catch{}})();var tl=20,nl=5,rl=15,il="-24h";function dw(e){let t={...e};return t.full===!0?(t.raw=!0,t.compact=!1):t.raw===!0&&t.compact===void 0&&(t.compact=!0),delete t.full,t}var ol={digest:"activity_digest",compact:"compact_activity",provenance:"provenance_activity",full:"activity"};function Ar(e,t){if(e===void 0)return;let n=e.trim();if(n.length===0)throw new _(`${t} must not be empty`,g.USAGE);return n}function gs(e,t,n){if(e===void 0)return;let r=e.trim();if(r.length===0)throw new _("Activity time bounds must not be empty",g.USAGE);let i=n==="--from"&&/^\d+[hdwm]$/iu.test(r)?`-${r}`:r;return _e(i,new Date(t),n)}function sl(e,t,n){return!(e.ts.length===0&&(t||n)||t&&I(e.ts,t)<0||n&&I(e.ts,n)>=0)}function _s(e,t){return t===void 0?e:e.slice(0,t)}function mt(e,t=""){return typeof e=="string"?e:t}function al(e,t){return{...t,id:e,ts:mt(t.ts),author:mt(t.author,"unknown"),op:mt(t.op,"unknown"),patch:Array.isArray(t.patch)?t.patch:[],before_hash:mt(t.before_hash),after_hash:mt(t.after_hash)}}function cl(e){return[...e].sort((t,n)=>{let r=n.ts.localeCompare(t.ts);if(r!==0)return r;let i=t.id.localeCompare(n.id);return i!==0?i:t.op.localeCompare(n.op)})}async function dl(e){try{return(await el.readdir(e)).filter(t=>t.endsWith(".jsonl")).sort((t,n)=>t.localeCompare(n))}catch(t){if(se(t))return[];throw t}}function ll(e){return e.raw!==!0&&e.compact!==!0&&e.provenance!==!0?"digest":e.provenance===!0?"provenance":e.compact===!0||e.raw===!0&&e.compact!==!1?"compact":"full"}function ul(e,t,n){if(e.unbounded!==!0)return t!==void 0?t:n==="digest"?rl:n==="compact"?tl:nl}function fl(e,t){let n=R(),r=t==="digest",i=gs(e.to??(r?n:void 0),n,"--to"),o=gs(e.from??(r?il:void 0),e.from===void 0&&r?i:n,"--from");if(o&&i&&I(o,i)>=0)throw new _("Activity --from must be before --to",g.USAGE);let s=Sr(e.limit);if(e.unbounded===!0&&s!==void 0)throw new _("Activity --unbounded cannot be combined with --limit",g.USAGE);return{id:Ar(e.id,"Activity --id"),op:Ar(e.op,"Activity --op"),author:Ar(e.author,"Activity --author"),from:o,to:i,limit:ul(e,s,t),limitSource:e.unbounded===!0||s!==void 0?"explicit":"default",harness:e.harness,agentInstance:e.agentInstance,provenance:e.provenanceFilter}}async function ml(e){let t=O(process.cwd(),e.path);return await U(t),{pmRoot:t,settings:await F(t)}}async function pl(e){let t=L(e.settings,D()),n=await de(e.pmRoot,e.settings.item_format,t.type_to_folder,void 0,e.settings.schema);await Wo({pmRoot:e.pmRoot,settings:e.settings,itemIds:n.map(i=>i.id),commandLabel:"activity"});let r=ys.join(e.pmRoot,"history");return await qt({path:r,scope:"project"}),{historyDir:r,itemsById:new Map(n.map(i=>[i.id,{title:i.title,type:i.type,status:i.status}]))}}function hl(e,t,n){return n.op&&e.op!==n.op||n.author&&e.author!==n.author?!1:sl(t,n.from,n.to)}async function gl(e,t){let n=[];for(let r of await dl(e)){let i=r.slice(0,-6);if(t.id&&i!==t.id)continue;let o=await Xt(ys.join(e,r),i);for(let s of o){let a=al(i,s);hl(s,a,t)&&n.push(a)}}return n}function _l(e){return e.map(t=>({id:t.id,op:t.op,ts:t.ts,author:t.author,...t.message?{msg:t.message}:{}}))}function yl(e){let t=[...e.entries()].sort(([r,i],[o,s])=>s-i||r.localeCompare(o)),n=t.slice(0,4).map(([r,i])=>`${r}:${i}`);return t.length>n.length&&n.push(`+${t.length-n.length}`),n.join(",")}function vl(e,t){let n=new Map;for(let r of e){let i=n.get(r.id);if(i===void 0){n.set(r.id,{firstTs:r.ts,lastTs:r.ts,eventCount:1,operations:new Map([[r.op,1]])});continue}i.eventCount+=1,I(r.ts,i.firstTs)<0&&(i.firstTs=r.ts),I(r.ts,i.lastTs)>0&&(i.lastTs=r.ts),i.operations.set(r.op,(i.operations.get(r.op)??0)+1)}return[...n.entries()].map(([r,i])=>{let o=t.get(r);return{id:r,type:o?.type??"unknown",status:o?.status??"unknown",title:(o?.title??"(item metadata unavailable)").slice(0,160),event_count:i.eventCount,first_ts:i.firstTs,last_ts:i.lastTs,operations:yl(i.operations)}}).sort((r,i)=>I(i.last_ts,r.last_ts)||r.id.localeCompare(i.id))}function bl(e){let t=new Map;for(let i of e)t.set(i.op,(t.get(i.op)??0)+1);let n=[...t.entries()].sort((i,o)=>o[1]-i[1]||i[0].localeCompare(o[0])),r=n.slice(0,8);return r.length<n.length&&r.push([`+${String(n.length-r.length)}`,n.slice(r.length).reduce((i,[,o])=>i+o,0)]),Object.fromEntries(r)}function wl(e,t,n,r,i){if(e==="digest"){let s=vl(t,r),a=_s(s,n);return{rows:{activity_digest:a},compact:!1,totalRows:s.length,returnedRows:a.length}}let o=_s(t,n);return e==="compact"?{rows:{compact_activity:_l(o)},compact:!0,totalRows:t.length,returnedRows:o.length}:e==="provenance"?{rows:{provenance_activity:o.map(i)},compact:!1,totalRows:t.length,returnedRows:o.length}:{rows:{activity:o},compact:!1,totalRows:t.length,returnedRows:o.length}}async function vs(e,t){let n=await ml(t),r=ll(e),i=fl(e,r),o=await pl(n),s=wn(n.settings.agent_identity.harness_signals),a=n.settings.agent_identity.identity_vocabulary,c=Dr({harness:i.harness,agentInstance:i.agentInstance,provenance:i.provenance},a,s),d=cl(await gl(o.historyDir,i)).filter(c),l=wl(r,d,i.limit,o.itemsById,f=>kn(f,a,{itemId:f.id})),u=l.totalRows-l.returnedRows;return{...l.rows,compact:l.compact,projection:{mode:r,row_key:ol[r]},omission_receipt:Mo("activity",r),count:l.returnedRows,total_count:l.totalRows,limit:i.limit??null,omitted_count:u,has_more:u>0,...r==="digest"?{activity_summary:{window:{from:i.from,to:i.to},event_count:d.length,item_count:l.totalRows,author_count:new Set(d.map(f=>f.author)).size,operation_counts:bl(d)}}:{},...e.provenanceSummary===!0?{provenance_summary:En(d,a,s)}:{},applied_bound:{kind:i.limit===void 0?"unbounded":"limit",source:i.limitSource,value:i.limit??null}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fdd874ad-e51d-5df2-9486-a0465ad65979")}catch{}})();var kl="global",pw="external",El=["open","closed","unknown"],pt=new Map,Il=240,Cl=2048;function bs(e,t,n){return(e?.trim()||t).slice(0,n)}function Sl(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;return typeof t.status=="string"&&(t.title==null||typeof t.title=="string")&&(t.source==null||typeof t.source=="string")&&(t.checkedAt==null||typeof t.checkedAt=="string")}function hw(e){let t=e.name.trim();if(t.length===0)throw new Error("External dependency resolver name must not be empty");if(pt.has(t))throw new Error(`External dependency resolver already registered: ${t}`);let n={name:t,supports:r=>e.supports(r),resolve:r=>e.resolve(r)};return pt.set(t,n),()=>{pt.get(t)===n&&pt.delete(t)}}async function gw(e,t={}){let n=e.trim();if(!le(n))return null;let r=[...pt.values()].filter(o=>{try{return o.supports(n)}catch{return!1}}),i=await Promise.allSettled(r.map(o=>Promise.resolve().then(()=>o.resolve(n))));for(let[o,s]of i.entries()){if(s.status!=="fulfilled"||!Sl(s.value))continue;let a=r[o],c=s.value,d=El.includes(c.status)?c.status:"unknown",l=bs(c.title,"",Il),u=bs(c.source,n,Cl),f=Date.parse(c.checkedAt?.trim()??""),p=Number.isFinite(f)?new Date(f).toISOString():t.now?.()??new Date().toISOString();return{id:n,status:d,resolved:d==="closed",title:l.length>0?l:null,source:u,checked_at:p,resolver:a.name}}return null}function _w(e){let t=e?.trim();if(t)return ue(t)?kl:t}function yw(e,t,n){return Tl(e,t,n)}function Tl(e,t,n){let r=e.trim();return ue(n)||le(r)?r:ln(r,t)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0a3dd0c1-2dea-5143-a2eb-65e758a0cc71")}catch{}})();function z(){let e=ne();for(let t of D()?.relationship_kinds??[])for(let n of t.definitions)e.register(n);return e}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="83d1acab-79a1-5e9f-b6a4-97dade07d74a")}catch{}})();function ht(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function In(e){return[e.parent_id,e.child_id,e.source,e.kind,e.holder_id,e.target_id??""].join("\0")}function Rl(e,t){let n=new Set,r=[];for(let i of[...e].sort()){if(n.has(i))continue;n.add(i);let o=[{nodeId:i,children:[...t.get(i)??[]].sort(),nextChild:0}];for(;o.length>0;){let s=o.at(-1),a=s.children[s.nextChild];a===void 0?(r.push(s.nodeId),o.pop()):(s.nextChild+=1,n.has(a)||(n.add(a),o.push({nodeId:a,children:[...t.get(a)??[]].sort(),nextChild:0})))}}return r}function xl(e,t){let n=[...e].sort(),r=Rl(n,t),i=new Set,o=Dl(n,t),s=[];for(let a of r.reverse()){if(i.has(a))continue;let c=Al(a,o,i);(c.length>1||t.get(c[0])?.has(c[0]))&&s.push(c)}return s.sort((a,c)=>a.join("\0").localeCompare(c.join("\0")))}function Dl(e,t){let n=new Map(e.map(r=>[r,new Set]));for(let[r,i]of t)for(let o of i)n.get(o)?.add(r);return n}function Al(e,t,n){let r=[],i=[e];for(n.add(e);i.length>0;){let o=i.pop();r.push(o);for(let s of[...t.get(o)].sort())n.has(s)||(n.add(s),i.push(s))}return r.sort()}function ws(e){let t=new Map;for(let n of e){let r=ht(n?.id);r&&!t.has(r)&&t.set(r,n)}return t}function Ol(e,t,n){let r=ht(t.parent);if(!(!r||!n.has(r)))return{parent_id:r,child_id:e,source:"scalar_parent",kind:"parent",holder_id:e,child_cardinality:"one"}}function Ll(e,t,n,r){let i=ht(t?.id),o=r.resolve(t?.kind);if(!i||!n.has(i)||!o?.hierarchy)return;let s=o.hierarchyDirection==="source_parent";return{parent_id:s?e:i,child_id:s?i:e,source:"dependency",kind:o.kind,holder_id:e,target_id:i,child_cardinality:s?o.incoming:o.outgoing}}function ks(e,t){let n=new Map;for(let[r,i]of e){let o=Ol(r,i,e);o&&n.set(In(o),o);for(let s of i.dependencies??[]){let a=Ll(r,s,e,t);a&&n.set(In(a),a)}}return[...n.values()].sort((r,i)=>In(r).localeCompare(In(i)))}function Es(e,t=z()){return ks(ws(e),t)}function Fl(e,t,n){let r=new Set(e.filter(i=>i.child_cardinality==="one").map(i=>i.child_id));return[...t].filter(([i,o])=>o.length>1&&r.has(i)).map(([i,o])=>({child_id:i,parent_ids:[...o],legacy_terminal:n.has(i)&&o.every(s=>n.has(s))})).sort((i,o)=>i.child_id.localeCompare(o.child_id))}function Ml(e,t,n){let r=new Map;for(let o of t){if(o.source!=="dependency")continue;let s=r.get(o.child_id)??new Set;s.add(o.parent_id),r.set(o.child_id,s)}let i=[];for(let[o,s]of e){let a=ht(s.parent);if(!a||!e.has(a))continue;let c=[...r.get(o)??[]].filter(d=>d!==a).sort();c.length!==0&&i.push({child_id:o,scalar_parent_id:a,dependency_parent_ids:c,legacy_terminal:n.has(o)&&n.has(a)&&c.every(d=>n.has(d))})}return i.sort((o,s)=>o.child_id.localeCompare(s.child_id))}function Cn(e,t=r=>r==="closed"||r==="canceled",n=z()){let r=ws(e),i=ks(r,n),o=Lr(i),s=new Set([...r].filter(([,c])=>t(c.status)).map(([c])=>c)),a=xl([...r.keys()],new Map([...o.children_by_parent].map(([c,d])=>[c,new Set(d)]))).map(c=>({item_ids:c,legacy_terminal:c.every(d=>s.has(d))}));return{relations:i,cycles:a,cardinality_violations:Fl(i,o.parents_by_child,s),divergences:Ml(r,i,s)}}function Sw(e){return e.source==="scalar_parent"?`${e.parent_id} -> ${e.child_id} (scalar parent on ${e.holder_id})`:`${e.parent_id} -> ${e.child_id} (${e.kind} dependency on ${e.holder_id})`}function Lr(e){let t=new Map,n=new Map;for(let r of e){let i=t.get(r.child_id)??new Set;i.add(r.parent_id),t.set(r.child_id,i);let o=n.get(r.parent_id)??new Set;o.add(r.child_id),n.set(r.parent_id,o)}return{parents_by_child:new Map([...t].map(([r,i])=>[r,[...i].sort()])),children_by_parent:new Map([...n].map(([r,i])=>[r,[...i].sort()]))}}function Or(e,t){let n=new Set(t);return e.every(r=>n.has(r))}function Tw(e,t,n,r,i){let o=ht(n);if(!o)return;let s=Cn(e,r,i),a=Cn(t,r,i),c=a.divergences.find(u=>!s.divergences.some(f=>f.child_id===u.child_id&&f.scalar_parent_id===u.scalar_parent_id&&Or(u.dependency_parent_ids,f.dependency_parent_ids)));if(c){let u=[c.scalar_parent_id,...c.dependency_parent_ids].sort();throw new _(`Hierarchy mutation would assign ${c.child_id} to multiple parents: ${u.join(", ")}.`,g.CONFLICT,{code:"hierarchy_parent_divergence_created",source_id:o,target_id:c.child_id,verification_errors:u})}let d=a.cardinality_violations.find(u=>(u.child_id===o||u.parent_ids.includes(o))&&!s.cardinality_violations.some(f=>f.child_id===u.child_id&&Or(u.parent_ids,f.parent_ids)));if(d)throw new _(`Hierarchy mutation would assign ${d.child_id} to multiple parents: ${d.parent_ids.join(", ")}.`,g.CONFLICT,{code:"hierarchy_cardinality_created",source_id:o,target_id:d.child_id,verification_errors:d.parent_ids});let l=a.cycles.find(u=>u.item_ids.includes(o)&&!s.cycles.some(f=>Or(u.item_ids,f.item_ids)));if(l)throw new _(`Hierarchy mutation would create a cycle: ${l.item_ids.join(" -> ")}.`,g.CONFLICT,{code:"hierarchy_cycle_created",source_id:o,verification_errors:l.item_ids})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="06ecc7a4-c593-5d99-89f5-714a4590d0a5")}catch{}})();function Je(e){if(typeof e!="string")return;let t=e.trim();if(!(!t||["none","null","n/a","na"].includes(t.toLowerCase())))return t}function gt(e){let t=Je(e);return t?.toLowerCase()==="no-active-blocker"?void 0:t}function _t(e,t,n=!0){let r=Je(e);return n&&(ue(t)||r!==void 0&&le(r))}function Fr(e,t){return _t(e,t)?`external\0${e}`:`local\0${e.toLowerCase()}`}function Is(e,t,n,r){return _t(e,t)?r.get(e):n.get(e.toLowerCase())}function Xe(e,t){let n=e.toLowerCase(),r=t.toLowerCase();return n!==r?n<r?-1:1:e!==t?e<t?-1:1:0}function Nl(e){let t=new Map;for(let n of e.dependencies??[]){if(typeof n!="object"||n===null)continue;let r=n,i=Je(r.id);if(!i)continue;let o=typeof r.kind=="string"?r.kind:"related",s=`${o}\0${Fr(i,r.source_kind)}`,a=t.get(s);a?a.count+=1:t.set(s,{target_id:i,kind:o,count:1})}return t}function $l(e,t=n=>n==="closed"||n==="canceled"){let n=[];for(let r of e)if(!(typeof r?.id!="string"||r.id.trim().length===0))for(let i of Nl(r).values())i.count<2||n.push({holder_id:r.id.trim(),target_id:i.target_id,kind:i.kind,occurrences:i.count,holder_status:r.status,legacy_terminal:t(r.status)});return n.sort((r,i)=>{let o=Xe(r.holder_id,i.holder_id);if(o!==0)return o;let s=Xe(r.target_id,i.target_id);return s!==0?s:Xe(r.kind,i.kind)})}function Pl(e,t,n,r,i){if(typeof n!="object"||n===null)return;let o=Je(n.id);if(!o||Fr(o,n.source_kind)!==Fr(t))return;let s=i.resolve(typeof n.kind=="string"?n.kind:"related");if(!(s?.ordering!==!0||(s.precedence??"source_before_target")!=="source_before_target"))return{holder_id:e.id.trim(),target_id:o,dependency_kind:s.kind,holder_status:e.status,legacy_terminal:r(e.status)}}function jl(e,t=r=>r==="closed"||r==="canceled",n=z()){let r=new Map;for(let i of e){if(typeof i?.id!="string"||i.id.trim().length===0)continue;let o=Je(i.blocked_by);if(o)for(let s of i.dependencies??[]){let a=Pl(i,o,s,t,n);a&&r.set(`${a.holder_id.toLowerCase()}\0${a.target_id.toLowerCase()}\0${a.dependency_kind}`,a)}}return[...r.values()].sort((i,o)=>{let s=Xe(i.holder_id,o.holder_id);if(s!==0)return s;let a=Xe(i.target_id,o.target_id);return a!==0?a:Xe(i.dependency_kind,o.dependency_kind)})}function Mr(e,t=n=>n==="closed"||n==="canceled"){let n=e.filter(c=>typeof c?.id=="string"&&c.id.trim().length>0),r=new Set(n.map(c=>c.id.trim().toLowerCase())),i=new Map,o=(c,d,l,u,f)=>{let p=Je(d);if(!p||r.has(p.toLowerCase())||_t(p,void 0,f))return;let m={holder_id:c.id.trim(),target_id:p,kind:l,source:u,holder_status:c.status,legacy_terminal:t(c.status),no_active_blocker_sentinel:p.toLowerCase()==="no-active-blocker"};i.set(`${m.holder_id}::${m.target_id}::${m.kind}::${m.source}`,m)};for(let c of n){o(c,c.parent,"parent","parent",!1),o(c,c.blocked_by,"blocked_by","blocked_by",!0);for(let d of c.dependencies??[]){if(typeof d!="object"||d===null)continue;let l=d;ue(l.source_kind)||o(c,l.id,typeof l.kind=="string"?l.kind:"related","dependency",!0)}}let s=[...i.values()].sort((c,d)=>c.holder_id.localeCompare(d.holder_id)||c.target_id.localeCompare(d.target_id)||c.kind.localeCompare(d.kind)||c.source.localeCompare(d.source)),a=s.filter(c=>c.legacy_terminal);return{active:s.filter(c=>!c.legacy_terminal),legacy_terminal:a,no_active_blocker_sentinels:s.filter(c=>c.no_active_blocker_sentinel)}}function Ul(e){let t=new Map;for(let n of[...e.active,...e.legacy_terminal]){if(n.no_active_blocker_sentinel)continue;let r=n.target_id.trim(),i=r.toLowerCase();t.has(i)||t.set(i,r)}return[...t.values()].sort((n,r)=>n.localeCompare(r))}function Hl(e){let t=new Map;for(let n of e){let r=gt(n.blocked_by);r&&_t(r)&&!t.has(r)&&t.set(r,r);for(let i of n.dependencies??[]){if(typeof i!="object"||i===null||!_t(i.id,i.source_kind))continue;let o=gt(i.id);o&&!t.has(o)&&t.set(o,o)}}return[...t.values()].sort((n,r)=>n.localeCompare(r))}var Cs=new WeakMap;function Sn(e){return e.hierarchyIntegrity??Cs.get(e)}function Bl(e,t=z()){let n={};for(let r of e)for(let i of r.dependencies??[]){if(typeof i!="object"||i===null)continue;let o=i.kind;if(typeof o!="string")continue;let s=o.trim().toLowerCase().replaceAll("-","_"),a=t.resolve(o);a&&s!==a.kind&&(n[s]=(n[s]??0)+1)}return Object.fromEntries(Object.entries(n).sort(([r],[i])=>r.localeCompare(i)))}function Qe(e,t,n){let r=n??z(),i=e.filter(m=>typeof m?.id=="string"&&m.id.trim().length>0),o=new Map(i.map(m=>[m.id.trim().toLowerCase(),m.id.trim()])),s=Mr(i,t),a=Ul(s);for(let m of a)o.set(m.toLowerCase(),m);let c=Hl(i),d=new Set(o.keys()),l=new Map;for(let m of c){let h=m;for(;d.has(h.toLowerCase());)h=`external:${h}`;l.set(m,h),d.add(h.toLowerCase())}let u=i.map(m=>{let h=gt(m.parent),y=gt(m.blocked_by),b=(m.dependencies??[]).flatMap(v=>{if(typeof v!="object"||v===null)return[];let w=v,C=gt(w.id);return C?[{id:Is(C,w.source_kind,o,l),kind:typeof w.kind=="string"?w.kind:"related"}]:[]});return{id:m.id.trim(),...h?{parent:o.get(h.toLowerCase())}:{},...y?{blocked_by:Is(y,void 0,o,l)}:{},dependencies:b}}),f=Cn(i,t,r),p={graph:zt.fromItems([...u,...a.map(m=>({id:m})),...c.map(m=>({id:l.get(m)}))],r),details:[...i.map(m=>({id:m.id.trim(),title:m.title,status:m.status,...typeof m.type=="string"&&m.type.trim().length>0?{type:m.type.trim()}:{}})),...a.map(m=>({id:m,title:`[missing] ${m}`,status:"missing"})),...c.map(m=>({id:l.get(m),title:`[external] ${m}`,status:"external"}))],missingIdSet:new Set(a.map(m=>m.toLowerCase())),dangling:s,duplicateRows:$l(i,t),orderingContradictions:jl(i,t,r),legacyAliasCounts:Bl(i,r),hierarchyIntegrity:f};return Cs.set(p,f),p}import{createHash as Gl}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="10f534cf-ee82-54a2-9807-390eca5fb0b8")}catch{}})();var Kl=64,zl=8;function Vl(e,t){let n=(e.dependencies??[]).map(r=>{if(typeof r!="object"||r===null)return"";let i=r;return`${typeof i.kind=="string"?i.kind:"related"}:${typeof i.id=="string"?i.id:""}`}).sort().join(",");return[e.id,e.title,e.status,t(e.status)?"1":"0",typeof e.type=="string"?e.type.trim():"",e.parent??"",e.blocked_by??"",n].join("\0")}function Tn(e,t=r=>r==="closed"||r==="canceled",n=ne()){let r=e.filter(o=>typeof o?.id=="string"&&o.id.trim().length>0).map(o=>Vl(o,t)).sort(),i=n.list().map(o=>E(o)).sort();return Gl("sha256").update(r.join("")).update("").update(i.join("")).digest("hex")}function Ss(e,t,n){let r=t??n;if(!Number.isInteger(r)||r<1)throw new TypeError(`Invalid ${e} bound: ${String(t)}`);return r}var Nr=class{#e=new Map;#t;#n;constructor(t={}){this.#t=Ss("maxResultsPerWorkspace",t.maxResultsPerWorkspace,Kl),this.#n=Ss("maxWorkspaces",t.maxWorkspaces,zl)}lookup(t,n,r){let i=this.#e.get(t),o=!0;(i===void 0||i.fingerprint!==n)&&(i={fingerprint:n,assembly:r(),results:new Map},o=!1,!this.#e.has(t)&&this.#e.size>=this.#n&&this.#e.delete(this.#e.keys().next().value)),this.#e.delete(t),this.#e.set(t,i);let s=i,a=this.#t;return{assembly:s.assembly,assemblyReused:o,fingerprint:n,memoize(c,d){let l=s.results.get(c);if(l!==void 0||s.results.has(c))return s.results.delete(c),s.results.set(c,l),{value:structuredClone(l),reused:!0};let u=d();return s.results.size>=a&&s.results.delete(s.results.keys().next().value),s.results.set(c,structuredClone(u)),{value:u,reused:!1}}}}clear(){this.#e.clear()}},Ts=new Nr;function Rn(){return Ts}function Pw(){Ts.clear()}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="47b3091f-a1a8-503c-83e9-46b85adf4207")}catch{}})();var ql=["prerequisite","dependent","ancestor","descendant","provenance","related"],Wl=new TextEncoder;function $r(e,t,n){let r=e??t;if(!Number.isInteger(r)||r<1)throw new TypeError(`Relationship context ${n} must be positive`);return r}function xn(e){return Math.max(1,Math.ceil(Wl.encode(JSON.stringify(e)).byteLength/4))}function Pr(e,t,n){let r=n.resolve(e.kind);if(r?.ordering){let o=(r.precedence??"source_before_target")==="source_before_target"?e.source:e.target;return t===o?"prerequisite":"dependent"}if(r?.hierarchy){let o=r.hierarchyDirection==="source_parent"?e.source:e.target;return t===o?"ancestor":"descendant"}return e.kind==="discovered_from"||e.kind==="incident_from"?"provenance":"related"}function Yl(e,t,n,r){let i=e.filter(o=>o.source===t&&o.target===n||o.target===t&&o.source===n).map(o=>Pr(o,n,r));return[...new Set(i)].sort()}function Xl(e){return ql.find(t=>e.includes(t))}function Jl(e,t,n,r){let i=r.direction??"both",o=r.maxDepth??3;if(!Number.isInteger(o)||o<0)throw new TypeError("Relationship context maxDepth must be non-negative");let s=new Set([t]),a=[{id:t,distance:0}],c=[],d=0,l=!1;for(let u=0;u<a.length;u+=1){r.signal?.throwIfAborted();let f=a[u];if(f.distance>=o&&l)continue;let p=e.neighborEdges(f.id,{direction:i,kinds:r.kinds,signal:r.signal});if(d+=p.meta.inspectedEdges,f.distance>=o){p.value.some(m=>!s.has(m.id))&&(l=!0);continue}for(let{id:m,edge:h}of p.value){if(s.has(m))continue;s.add(m);let y={id:m,distance:f.distance+1,via:f.id,role:Pr(h,m,n)};c.push(y),a.push(y)}}return c.sort((u,f)=>u.distance-f.distance||u.id.localeCompare(f.id)),{rows:c,visitedNodes:a.length,inspectedEdges:d,depthTruncated:l}}function Ql(e,t,n,r){let i={prerequisite:0,dependent:0,ancestor:0,descendant:0,provenance:0,related:0},o=e.neighborEdges(t,{direction:r.direction??"both",kinds:r.kinds,signal:r.signal}).value;for(let{id:s,edge:a}of o)i[Pr(a,s,n)]+=1;return{directEdges:i,directTotal:o.length,rootEdges:o.map(({edge:s})=>s)}}function Zl(e){let t=[],n=e.initialTokens;for(let r of e.candidates){if(t.length>=e.nodeLimit)break;let i=r.distance===1?Yl(e.rootEdges,e.rootId,r.id,e.registry):[],o={...e.details.get(r.id)??{id:r.id},distance:r.distance,role:i.length>0?Xl(i):r.role,via:r.via,reasons:i.length>0?i:[`${r.role} via ${r.via} (depth ${r.distance})`]},s=xn(o);if(n+s>e.tokenBudget)break;t.push(o),n+=s}if(e.candidates.length>0&&t.length===0)throw new TypeError("Relationship context tokenBudget cannot fit one node");return{nodes:t,usedTokens:n}}function eu(e){let t=e.options.kinds?new Set(e.options.kinds.map(o=>e.registry.require(o).kind)):void 0,n=e.graph.edges().filter(o=>{if(!e.included.has(o.source)||!e.included.has(o.target))return!1;if(t===void 0||t.has(o.kind))return!0;let s=e.registry.resolve(o.kind)?.inverse;return s!==void 0&&t.has(s)}),r=[],i=e.initialTokens;for(let o of n){if(r.length>=e.edgeLimit)break;let s=xn(o);if(i+s>e.tokenBudget)break;r.push(o),i+=s}return{edges:r,usedTokens:i,candidateCount:n.length}}function Rs(e,t,n,r={}){if(!e.nodes().includes(t))throw new TypeError(`Relationship node not found: ${t}`);let i=$r(r.nodeLimit,20,"nodeLimit"),o=$r(r.edgeLimit,40,"edgeLimit"),s=$r(r.tokenBudget,1200,"tokenBudget"),a=r.registry??ne(),c=new Map(n.map(q=>[q.id,q])),d=c.get(t)??{id:t},{evidence:l=[],...u}=d,f=[...l],p=Jl(e,t,a,r),{rootEdges:m,...h}=Ql(e,t,a,r),y=Ie("relationship-context",{rootId:t,direction:r.direction??"both",kinds:[...r.kinds??[]].sort(),maxDepth:r.maxDepth??3}),b=ze(p.rows,r.cursor,y,({id:q})=>q),v=p.rows.slice(b),w=xn(u)+xn(f);if(w>s)throw new TypeError("Relationship context tokenBudget cannot fit root and evidence");let C=Zl({candidates:v,details:c,rootEdges:m,rootId:t,registry:a,nodeLimit:i,tokenBudget:s,initialTokens:w}),{nodes:S}=C,N=new Set([t,...S.map(({id:q})=>q)]),$=eu({graph:e,included:N,options:r,registry:a,edgeLimit:o,tokenBudget:s,initialTokens:C.usedTokens}),{edges:M,usedTokens:Ee}=$,P=b+S.length,te=P<p.rows.length,V=S.at(-1),Y=$.candidateCount-M.length,he=p.depthTruncated||te||Y>0,X={rootId:t,...u.status===void 0?{}:{rootStatus:u.status},...h,discoveredNodes:p.rows.length,returnedNodes:S.length,returnedEdges:M.length,omittedNodes:p.rows.length-P,omittedEdges:Y,evidenceCount:f.length,hasMore:te};return{root:u,summary:X,nodes:S,edges:M,evidence:f,meta:{exact:!0,truncated:he,completeness:he?"truncated":"complete",nodeLimit:i,edgeLimit:o,tokenBudget:s,usedTokens:Ee,visitedNodes:p.visitedNodes,inspectedEdges:p.inspectedEdges,omittedNodes:p.rows.length-P,omittedEdges:Y,...te&&V?{nextCursor:ae(y,V.id,P-1)}:{}}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2f2a7df8-9c95-5ed1-bd43-33dde57dd7f0")}catch{}})();var tu=["tree","graph","context"],nu=["none","repeated"],ru=["outgoing","incoming","both"],iu=32,ou=200,su=400,au=16e3;function cu(e){let t=e?.trim().toLowerCase()??"tree";if(tu.includes(t))return t;throw new _(`Invalid --format value "${e}". Use "tree", "graph", or "context".`,g.USAGE)}function fe(e,t){if(e===void 0)return;let n=typeof e=="number"?e:Number(e.trim());if(!Number.isInteger(n)||n<1)throw new _(`Invalid --${t} value "${e}". Use a positive integer.`,g.USAGE);return n}function Dn(e){if(e===void 0)return;let t=typeof e=="number"?e:Number(e.trim());if(!Number.isInteger(t)||t<0)throw new _(`Invalid --max-depth value "${e}". Use a non-negative integer.`,g.USAGE);return t}function du(e){let t=e?.trim().toLowerCase()??"none";if(nu.includes(t))return t;throw new _(`Invalid --collapse value "${e}". Use "none" or "repeated".`,g.USAGE)}function Ur(e){let t=e?.trim().toLowerCase()??"both";if(ru.includes(t))return t;throw new _(`Invalid --direction value "${e}". Use "outgoing", "incoming", or "both".`,g.USAGE)}function Hr(e,t=ne()){if(e===void 0)return;let n=(Array.isArray(e)?e:[e]).flatMap(i=>i.split(",")).map(i=>i.trim()).filter(i=>i.length>0);if(n.length===0)return;let r=new Set;for(let i of n){let o=t.resolve(i);if(!o){let s=t.list().map(a=>a.kind).join(", ");throw new _(`Invalid --kind value "${i}". Registered kinds: ${s}.`,g.USAGE)}r.add(o.kind)}return[...r].sort()}function lu(e){if(!e||e.length===0)return[];let t=e.map(({id:r,kind:i})=>({id:r.trim(),kind:i.trim().toLowerCase()})).sort((r,i)=>{let o=r.kind.localeCompare(i.kind);return o!==0?o:r.id.localeCompare(i.id)}),n=new Map;for(let r of t){let i=`${r.kind.toLowerCase()}::${r.id.toLowerCase()}`;n.has(i)||n.set(i,{id:r.id,kind:r.kind})}return[...n.values()]}function uu(e){return{id:e.id,title:e.title,type:e.type,status:e.status,dependencies:lu(e.dependencies)}}function fu(e){return Zt(new TextEncoder().encode(JSON.stringify({...e,dependencies:void 0})).byteLength)}function mu(e,t,n,r,i,o,s,a,c){for(let d of t.dependencies){let l=Math.max(1,Math.ceil(JSON.stringify({from:e.id,to:d.id,kind:d.kind}).length/3));if(a.nodes>=a.nodeLimit){e.truncated=!0,a.reasons.add("node_limit");break}if(a.edges>=a.edgeLimit){e.truncated=!0,a.reasons.add("edge_limit");break}if(a.estimatedTokens+l>=a.tokenBudget){e.truncated=!0,a.reasons.add("token_budget");break}a.edges+=1,a.estimatedTokens+=l,e.dependencies.push(Ds(d.id,n,r,i,o,s,a,c+1,d.kind))}}function pu(e,t,n,r,i,o,s,a){return s.estimatedTokens>=s.tokenBudget&&t?.dependencies.length?(e.truncated=!0,s.reasons.add("token_budget"),!0):!t||e.cycle?!0:r!==void 0&&a>=r?(t.dependencies.length>0&&(e.truncated=!0,s.reasons.add("max_depth")),!0):i==="repeated"&&o.has(n)?(e.collapsed=!0,!0):!1}function Ds(e,t,n,r,i,o,s,a=0,c){let d=e.trim().toLowerCase(),l=t.get(d),u={id:l?.id??e,title:l?.title,type:l?.type,status:l?.status,via:c,missing:!l,cycle:n.has(d),dependencies:[]};if(s.nodes+=1,s.estimatedTokens+=fu(u),pu(u,l,d,r,i,o,s,a))return u;i==="repeated"&&o.add(d);let f=new Set(n);return f.add(d),mu(u,l,t,f,r,i,o,s,a),u}function xs(e,t){return!e||e.missing&&!t.missing?t:{...e,title:e.title??t.title,type:e.type??t.type,status:e.status??t.status}}function hu(e){let t=new Map,n=new Map,r=[e];for(;r.length>0;){let a=r.pop();t.set(a.id,xs(t.get(a.id),{id:a.id,title:a.title,type:a.type,status:a.status,missing:a.missing}));for(let c of a.dependencies){t.set(c.id,xs(t.get(c.id),{id:c.id,title:c.title,type:c.type,status:c.status,missing:c.missing}));let d=c.via??"related",l=`${a.id}::${c.id}::${d}`;n.has(l)||n.set(l,{from:a.id,to:c.id,kind:d}),c.cycle||r.push(c)}}let i=[...t.values()].sort((a,c)=>a.id.localeCompare(c.id)),o=[...n.values()].sort((a,c)=>{let d=a.from.localeCompare(c.from);if(d!==0)return d;let l=a.to.localeCompare(c.to);return l!==0?l:a.kind.localeCompare(c.kind)}),s=i.filter(a=>a.missing).map(a=>a.id);return{root_id:e.id,nodes:i,edges:o,missing_ids:s}}function As(e,t,n){let r=new Set,i=new Set,o=new Set,s=new Set,a=[{id:e,depth:0}],c=0;for(;c<a.length;){let d=a[c++],l=d.id.trim().toLowerCase();r.add(l);let u=t.get(l);if(!u){o.add(l);continue}if(!(n!==void 0&&d.depth>=n)&&!s.has(l)){s.add(l);for(let f of u.dependencies)i.add(`${l}::${f.id.trim().toLowerCase()}::${f.kind}`),a.push({id:f.id,depth:d.depth+1})}}return{node_count:r.size,edge_count:i.size,edge_basis:"deduplicated_directed",missing_count:o.size}}function gu(e,t=ne()){let n=Dn(e.maxDepth),r=fe(e.nodeLimit,"node-limit"),i=fe(e.edgeLimit,"edge-limit"),o=fe(e.tokenBudget,"token-budget"),s=Hr(e.kind,t);return{direction:Ur(e.direction),...s===void 0?{}:{kinds:s},...n===void 0?{}:{maxDepth:n},...r===void 0?{}:{nodeLimit:r},...i===void 0?{}:{edgeLimit:i},...o===void 0?{}:{tokenBudget:o},...e.cursor?.trim()?{cursor:e.cursor.trim()}:{}}}function _u(e,t,n,r){return Rs(e.graph,t,e.details.map(i=>i.id===t&&r.length>0?{...i,evidence:r}:i),n)}function jr(e,t,n,r){for(let i of n.slice(0,r)){let o=i?.trim();o&&e.push(`${t}:${o}`)}}async function yu(e,t,n,r){let i=await ce(e,t,n.id_prefix,n.item_format,r);if(!i)return[];let{document:o}=await Se(i,{schema:n.schema}),s=o.metadata,a=s.files??[],c=s.tests??[],d=s.docs??[],l=[["files",a.length],["tests",c.length],["docs",d.length],["comments",(s.comments??[]).length],["notes",(s.notes??[]).length],["learnings",(s.learnings??[]).length]];if(l.every(([,f])=>f===0))return[];let u=[`linked:${l.map(([f,p])=>`${f}=${p}`).join(",")}`];return jr(u,"file",a.map(f=>f.path),3),jr(u,"test",c.map(f=>f.command??f.path),2),jr(u,"doc",d.map(f=>f.path),2),u}function vu(e){let{canonicalId:t,context:n,missingCount:r,missingReferences:i,referenceLimit:o,summaryOnly:s}=e;return{id:t,format:"context",node_count:n.nodes.length+1,edge_count:n.edges.length,edge_basis:"deduplicated_directed",missing_count:r,missing_scope:"traversal",missing_reference_count:i.length,...s?{}:{missing_references:i.slice(0,o),context:n}}}function bu(e){let{row:t,missingReachableSet:n,packetIds:r,filteredKinds:i,registry:o}=e;if(t.no_active_blocker_sentinel||!n.has(t.target_id.trim().toLowerCase())||!r.has(t.holder_id))return!1;if(i===void 0)return!0;let s=o.resolve(t.kind);return s!==void 0&&(i.has(s.kind)||s.inverse!==void 0&&i.has(s.inverse))}function Os(e,t,n){let r;for(;;){let i=Zt(new TextEncoder().encode(kr(br("deps",e),t)).byteLength);if(i===r)return i;n(i),r=i}}function wu(e){return e instanceof TypeError&&e.message.startsWith("Relationship context tokenBudget cannot fit ")}function ku(e){try{return _u(e.assembly,e.canonicalId,{...e.contextOptions,...e.internalTokenBudget===void 0?{}:{tokenBudget:e.internalTokenBudget}},e.rootEvidence)}catch(t){if(e.smallestResult!==void 0&&wu(t))return e.smallestResult;throw t}}function Eu(e){let{assembly:t,canonicalId:n,contextOptions:r,rootEvidence:i,summaryOnly:o,outputFormat:s,missingCount:a,missingReferences:c}=e,l=r.edgeLimit??40,u=r.tokenBudget,f,p;for(;;){let m=ku({assembly:t,canonicalId:n,contextOptions:r,internalTokenBudget:u,rootEvidence:i,smallestResult:p});if("format"in m)return m;let h=m;f??=h.meta.tokenBudget,u??=f;let y=vu({canonicalId:n,context:h,missingCount:a,missingReferences:c,referenceLimit:l,summaryOnly:o});if(p=y,o||(h.meta.tokenBudget=f,h.meta.usedTokens=Os(Ze(y,!1),s,w=>{h.meta.usedTokens=w}),h.meta.usedTokens<=f))return y;if(l>0){l-=1;continue}let b=u,v=b*f/h.meta.usedTokens;u=Math.min(b-1,Math.max(1,Math.floor(v*.9)))}}function Iu(e){let{assembly:t,canonicalId:n,options:r,rootEvidence:i,summaryOnly:o,outputFormat:s}=e,a=gu(r,t.graph.registry()),c=t.graph.closure(n,{direction:a.direction,...a.kinds===void 0?{}:{kinds:a.kinds},maxDepth:a.maxDepth??3}),d=c.value.filter(h=>t.missingIdSet.has(h.toLowerCase())),l=new Set(d.map(h=>h.toLowerCase())),u=t.graph.registry(),f=a.kinds?new Set(a.kinds.map(h=>u.require(h).kind)):void 0,p=new Set([n,...c.value]),m=[...t.dangling.active,...t.dangling.legacy_terminal].filter(h=>bu({row:h,missingReachableSet:l,packetIds:p,filteredKinds:f,registry:u}));return Eu({assembly:t,canonicalId:n,contextOptions:a,rootEvidence:i,summaryOnly:o,outputFormat:s,missingCount:d.length,missingReferences:m})}function Cu(e){let t=[e],n;for(;t.length>0;){let r=t.pop();r.dependencies.length>0&&(n=r,t.push(...r.dependencies))}return n?(n.dependencies.pop(),n.truncated=!0,!0):!1}function Su(e,t,n,r,i,o,s){let a=i??iu,c=fe(n.nodeLimit,"node-limit")??ou,d=fe(n.edgeLimit,"edge-limit")??su,l=fe(n.tokenBudget,"token-budget")??au,u={nodeLimit:c,edgeLimit:d,tokenBudget:l,nodes:0,edges:0,estimatedTokens:0,reasons:new Set},f=Ds(e,r,new Set,a,t==="graph"?"repeated":o,new Set,u),p=As(e,r,void 0),m;for(;;){let h=hu(f),y=u.reasons.size===0?void 0:{reasons:[...u.reasons].sort(),limits:{max_depth:a,node_limit:c,edge_limit:d,token_budget:l},estimated_tokens:0,total_node_count:p.node_count,total_edge_count:p.edge_count,omitted_node_count:Math.max(0,p.node_count-h.nodes.length),omitted_edge_count:Math.max(0,p.edge_count-h.edges.length)},b={id:e,format:t,node_count:h.nodes.length,edge_count:h.edges.length,edge_basis:"deduplicated_directed",missing_count:h.missing_ids.length,...y?{truncation:y}:{}};if(m=t==="tree"?{...b,tree:f}:{...b,graph:h},(m.truncation===void 0?Zt(new TextEncoder().encode(kr(br("deps",Ze(m,!1)),s)).byteLength):Os(Ze(m,!1),s,w=>{m.truncation.estimated_tokens=w}))<=l)return m;if(!Cu(f))return u.reasons.add("token_budget"),m;u.reasons.add("token_budget")}}function Ze(e,t,n={}){let r={name:e.format==="tree"?"dependency_tree":e.format==="graph"?"dependency_graph":"relationship_context",restore_with:"--full"};return{...e,legacy_alias_counts:n,projection:{mode:t?"summary":"full",declared_field_groups:[r],included_field_groups:t?[]:[r.name]}}}async function s0(e,t,n){let r=O(process.cwd(),n.path);await U(r);let i=cu(t.format),o=Dn(t.maxDepth),s=du(t.collapse);Jt(t.summary===!0,t.full===!0,"--summary");let a=t.summary===!0,c=await F(r),d=L(c,D()),l=await de(r,c.item_format,d.type_to_folder,void 0,c.schema),u=J(c.schema),f=new Map(l.map(m=>[m.id.trim().toLowerCase(),uu(m)])),p=Mr(l,m=>j(m,u));for(let m of[...p.active,...p.legacy_terminal]){let h=f.get(m.holder_id.trim().toLowerCase()),y=m.kind.trim().toLowerCase();h&&!h.dependencies.some(b=>b.id.trim().toLowerCase()===m.target_id.trim().toLowerCase()&&b.kind===y)&&h.dependencies.push({id:m.target_id,kind:y})}if(!f.has(e.trim().toLowerCase()))throw new _(`Item ${e} not found`,g.NOT_FOUND);if(i==="context"){let m=f.get(e.trim().toLowerCase()).id,h=a?[]:await yu(r,m,c,d.type_to_folder),y=w=>j(w,u),b=z(),v=Rn().lookup(r,Tn(l,y,b),()=>Qe(l,y,b));return Ze(Iu({assembly:v.assembly,canonicalId:m,options:t,rootEvidence:h,summaryOnly:a,outputFormat:n.json===!0?"json":"toon"}),a,v.assembly.legacyAliasCounts)}return a?Ze({id:e,format:i,...As(e,f,o)},!0,Object.fromEntries(Object.entries(Qe(l,m=>j(m,u)).legacyAliasCounts))):Ze(Su(e,i,t,f,o,s,n.json===!0?"json":"toon"),!1,Object.fromEntries(Object.entries(Qe(l,m=>j(m,u)).legacyAliasCounts)))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f01a7c5d-0cb1-5dfa-90e8-14bb66bedd94")}catch{}})();var Tu=5,Ru=1e4,xu=8;function Br(e,t){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new TypeError(`Invalid path ${e} bound: ${String(t)}`)}function An(e,t){return t.hierarchyDirection==="target_parent"?e.target:e.source}function yt(e,t){return(t.precedence??"source_before_target")==="target_before_source"?e.target:e.source}function et(e,t){let n=yt(e,t);return{predecessor:n,successor:n===e.source?e.target:e.source}}function Du(e,t,n){if(t===void 0)return;let r=e.registry(),i=new Set;for(let o of t){let s=r.require(o),a=s.traversal;if(a==="association")throw new TypeError(`Relationship kind ${s.kind} uses association traversal; use graph impact --direction both`);if(a!==n&&a!=="semantic"){let c=a==="hierarchy"?"graph ancestors or graph descendants":"graph predecessors or graph successors";throw new TypeError(`Relationship kind ${s.kind} uses ${a} traversal; use ${c}`)}i.add(s.kind)}return i}function Au(e,t,n,r,i){let o=e.registry(),s=e.neighborEdges(t,{direction:"both",...n===void 0?{}:{kinds:[...n]}}),a=[],c=new Set;for(let d of s.value){let l=o.require(d.edge.kind);n===void 0&&!l[r]||i(d,l,t)&&(c.has(d.id)||(c.add(d.id),a.push(d.id)))}return{neighbors:a,inspectedEdges:s.meta.inspectedEdges}}function Ou(e,t,n,r,i,o){if(t>=n)return e.neighbors.some(s=>!o.seen.has(s))&&(o.truncated=!0),!1;for(let s of e.neighbors)if(!o.seen.has(s)){if(o.seen.add(s),o.queue.push({id:s,depth:t+1}),!o.resumed){s===i&&(o.resumed=!0);continue}if(o.value.length>=r)return o.truncated=!0,!0;o.value.push(s)}return!1}function On(e,t,n,r,i){if(!e.hasNode(t))throw new TypeError(`Relationship node not found: ${t}`);let o=Du(e,n.kinds,r),s=n.limit??Number.POSITIVE_INFINITY,a=n.maxDepth??Number.POSITIVE_INFINITY,c=n.after,d={seen:new Set([t]),value:[],queue:[{id:t,depth:0}],resumed:c===void 0,truncated:!1},l=0,u=0;for(let f=0;f<d.queue.length;f+=1){n.signal?.throwIfAborted();let p=d.queue[f];l+=1;let m=Au(e,p.id,o,r,i);if(u+=m.inspectedEdges,Ou(m,p.depth,a,s,c,d))break}if(!d.resumed)throw new TypeError(`Traversal cursor not found in sequence: ${c}`);return{value:d.value,meta:{visitedNodes:l,inspectedEdges:u,truncated:d.truncated,nextCursor:d.value.at(-1)}}}function Ls(e,t){if(!e.hasNode(t))throw new TypeError(`Relationship node not found: ${t}`)}function Fs(e,t,n,r,i){let o=e.neighborEdges(t.nodes.at(-1),{direction:r,...n.kinds===void 0?{}:{kinds:n.kinds}});return i.inspectedEdges+=o.meta.inspectedEdges,o.value.filter(s=>!t.nodeSet.has(s.id))}function Lu(e,t,n,r,i,o,s){for(let a of Fs(e,t,r,i,s)){let c=[...t.nodes,a.id],d=new Set(t.nodeSet).add(a.id),l=[...t.edges,a.edge];if(a.id===n){if(s.value.push({nodes:c,edges:l,length:l.length}),s.value.length>=o)return!0}else s.queue.push({nodes:c,nodeSet:d,edges:l})}return!1}function Ms(e,t,n={}){return On(e,t,n,"hierarchy",(r,i)=>An(r.edge,i)===r.id)}function Ns(e,t,n={}){return On(e,t,n,"hierarchy",(r,i,o)=>An(r.edge,i)===o)}function $s(e,t,n={}){return On(e,t,n,"ordering",(r,i)=>yt(r.edge,i)===r.id)}function Ps(e,t,n={}){return On(e,t,n,"ordering",(r,i,o)=>yt(r.edge,i)===o)}function Fu(e,t,n,r,i,o,s,a){let c={value:[],queue:[{nodes:[t],nodeSet:new Set([t]),edges:[]}],inspectedEdges:0},d=0,l=!1,u=i+1;for(let f=0;f<c.queue.length;f+=1){if(r.signal?.throwIfAborted(),c.value.length>=u||d>=o){l=!0;break}let p=c.queue[f];if(d+=1,p.edges.length>=s){Fs(e,p,r,a,c).length>0&&(l=!0);continue}if(Lu(e,p,n,r,a,u,c)){l=!0;break}}return{value:c.value.slice(0,i),meta:{visitedNodes:d,inspectedEdges:c.inspectedEdges,truncated:l}}}function js(e,t,n,r={}){Ls(e,t),Ls(e,n);let i=r.maxPaths??Tu,o=r.maxVisitedPaths??Ru,s=r.maxDepth??xu;Br("maxPaths",i),Br("maxVisitedPaths",o),Br("maxDepth",s);let a=r.direction??"outgoing";r.signal?.throwIfAborted();for(let c of r.kinds??[])e.registry().require(c);return t===n?i===0?{value:[],meta:{visitedNodes:1,inspectedEdges:0,truncated:!0}}:{value:[{nodes:[t],edges:[],length:0}],meta:{visitedNodes:1,inspectedEdges:0,truncated:!1}}:Fu(e,t,n,r,i,o,s,a)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2ea07760-bca8-579d-9b3a-78051461485a")}catch{}})();var Mu=16,Nu=2,$u=8;function Ln(e,t){if(!Number.isInteger(t)||t<1)throw new TypeError(`Invalid ${e} bound: ${String(t)}`)}function Fn(e,t,n){let r=e.registry(),i=t===void 0?void 0:new Set(t.map(o=>r.require(o).kind));for(let o of e.edges()){if(o.source===o.target)continue;let s=r.require(o.kind);i!==void 0&&!(i.has(s.kind)||s.inverse!==void 0&&i.has(s.inverse))||n(o,s)}}function Pu(e,t){let n=new Map;Fn(e,t,r=>{Us(n,r.source,r.target),Us(n,r.target,r.source)});for(let r of n.values())r.sort();return n}function Us(e,t,n){let r=e.get(t);r===void 0?e.set(t,[n]):r.push(n)}function ju(e,t){let n=new Map;for(let o of e){let s=t.get(o);n.set(s,(n.get(s)??0)+1)}let r,i=0;for(let[o,s]of n)(s>i||s===i&&o<r)&&(r=o,i=s);return r}function Uu(e,t){let n=new Map;for(let[i,o]of e){let s=n.get(o);s===void 0?n.set(o,[i]):s.push(i)}let r=[];for(let i of n.values())i.length<t||(i.sort(),r.push({representative:i[0],size:i.length,members:i}));return r.sort((i,o)=>o.size-i.size||i.representative.localeCompare(o.representative))}function Hs(e,t={}){let n=t.maxIterations??Mu,r=t.minSize??Nu;Ln("maxIterations",n),Ln("minSize",r);let i=Pu(e,t.kinds),o=e.nodes(),s=new Map(o.map(u=>[u,u])),a=0,c=!1,d=0,l=0;for(;a<n&&!c;){t.signal?.throwIfAborted(),a+=1,c=!0;for(let u of o){d+=1;let f=i.get(u);if(f===void 0)continue;l+=f.length;let p=ju(f,s);p!==s.get(u)&&(s.set(u,p),c=!1)}}return{value:{communities:Uu(s,r),iterations:a,converged:c},meta:{visitedNodes:d,inspectedEdges:l,truncated:!c}}}function Mn(e){return e.direction==="directed"&&(e.ordering||e.hierarchy)}function Nn(e){return e.inverse!==void 0&&e.inverse<e.kind?e.inverse:e.kind}function Gr(e,t){return(t.hierarchy?An(e,t):e.source===yt(e,t)?e.target:e.source)===e.target?{from:e.source,to:e.target}:{from:e.target,to:e.source}}function Hu(e,t){if(t===void 0)return;let n=e.registry(),r=new Set;for(let i of t){let o=n.require(i);if(!Mn(o))throw new TypeError(`Relationship kind ${o.kind} is not a directed ordering or hierarchy kind`);r.add(Nn(o))}return r}function Bu(e,t){let n=e.registry(),r=new Map;for(let i of e.edges()){let o=n.require(i.kind);if(!Mn(o))continue;let s=Nn(o);if(t!==void 0&&!t.has(s))continue;let a=Gr(i,o);if(a.from===a.to)continue;let c=r.get(s);c===void 0&&(c={adjacency:new Map,records:[]},r.set(s,c));let d=c.adjacency.get(a.from);d===void 0?c.adjacency.set(a.from,new Set([a.to])):d.add(a.to),c.records.push({...a,edge:i})}return r}function Gu(e){let t=new Map;for(let[n,r]of e.adjacency)t.set(n,[...r].sort());return t}function Ku(e,t,n,r){let i=[r];for(let o=n;o!==t;o=e.get(o))i.push(o);return i.push(t),i.reverse()}function zu(e,t,n,r,i,o){for(let s of e.get(n.id)??[])if(o.inspectedEdges+=1,!(n.depth===0&&s===t.to)&&!r.has(s)){if(r.set(s,n.id),s===t.to)return Ku(r,t.from,n.id,s);i.push({id:s,depth:n.depth+1})}}function Vu(e,t,n,r){let i=new Map([[t.from,t.from]]),o=[{id:t.from,depth:0}];for(let s=0;s<o.length;s+=1){let a=o[s];if(r.visitedNodes+=1,a.depth>=n)continue;let c=zu(e,t,a,i,o,r);if(c!==void 0)return c}}function tt(e,t={}){let n=t.maxDepth??$u;Ln("maxDepth",n),t.limit!==void 0&&Ln("limit",t.limit);let r=t.limit??Number.POSITIVE_INFINITY,i=Hu(e,t.kinds),o=Bu(e,i),s=[],a={visitedNodes:0,inspectedEdges:0},c=!1;e:for(let d of[...o.keys()].sort()){let l=o.get(d),u=Gu(l);for(let f of l.records){t.signal?.throwIfAborted();let p=Vu(u,f,n,a);if(p!==void 0){if(s.length>=r){c=!0;break e}s.push({edge:f.edge,witness:p})}}}return{value:s,meta:{visitedNodes:a.visitedNodes,inspectedEdges:a.inspectedEdges,truncated:c}}}function qu(e,t,n,r,i){let o=new Set,s=[];for(let a of n){if(a.id===e||o.has(a.id))continue;if(!i.seen.has(a.id)){if(t>=r){i.truncated=!0;continue}i.seen.add(a.id),i.queue.push({id:a.id,depth:t+1})}o.add(a.id),s.push(a.id);let c=i.predecessors.get(a.id);c===void 0&&(c=new Set,i.predecessors.set(a.id,c)),c.add(e)}return s}function Wu(e,t,n){let r=n.direction??"outgoing",i=n.maxDepth??Number.POSITIVE_INFINITY,o=[],s=new Map,a={seen:new Set([t]),queue:[{id:t,depth:0}],predecessors:new Map,truncated:!1},c=0;for(let d=0;d<a.queue.length;d+=1){n.signal?.throwIfAborted();let{id:l,depth:u}=a.queue[d];o.push(l);let f=e.neighborEdges(l,{direction:r,...n.kinds===void 0?{}:{kinds:n.kinds}});c+=f.meta.inspectedEdges,s.set(l,qu(l,u,f.value,i,a))}return{order:o,successors:s,predecessors:a.predecessors,inspectedEdges:c,truncated:a.truncated}}function Yu(e,t){let n=[],r=new Set([t]),i=[{id:t,index:0}];for(;i.length>0;){let o=i.at(-1),s=e.successors.get(o.id);if(o.index<s.length){let a=s[o.index];o.index+=1,r.has(a)||(r.add(a),i.push({id:a,index:0}))}else n.push(o.id),i.pop()}return n.reverse()}function Xu(e,t,n,r){let i=e,o=t;for(;i!==o;){for(;r.get(i)>r.get(o);)i=n.get(i);for(;r.get(o)>r.get(i);)o=n.get(o)}return i}function Ju(e,t,n){let r;for(let i of[...e].sort())t.has(i)&&(r=r===void 0?i:Xu(r,i,t,n));return r}function Qu(e,t,n,r,i){let o=new Map([[t,t]]),s=!0;for(;s;){s=!1;for(let a of n){if(i?.throwIfAborted(),a===t)continue;let c=Ju(e.predecessors.get(a),o,r);c!==void 0&&o.get(a)!==c&&(o.set(a,c),s=!0)}}return o}function Bs(e,t,n={}){if(!e.hasNode(t))throw new TypeError(`Relationship node not found: ${t}`);if(n.maxDepth!==void 0&&(!Number.isInteger(n.maxDepth)||n.maxDepth<0))throw new TypeError(`Invalid maxDepth bound: ${String(n.maxDepth)}`);let r=Wu(e,t,n),i=Yu(r,t),o=new Map(i.map((d,l)=>[d,l])),s=Qu(r,t,i,o,n.signal),a=new Map(i.map(d=>[d,1]));for(let d=i.length-1;d>=0;d-=1){let l=i[d];if(l===t)continue;let u=s.get(l);a.set(u,a.get(u)+a.get(l))}let c=i.filter(d=>d!==t).map(d=>({id:d,idom:s.get(d),dominatedCount:a.get(d)-1})).sort((d,l)=>l.dominatedCount-d.dominatedCount||d.id.localeCompare(l.id));return{value:{root:t,reachableCount:r.order.length,rows:c},meta:{visitedNodes:r.order.length,inspectedEdges:r.inspectedEdges,truncated:r.truncated}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="aa8e4dc3-250e-50eb-b770-a11cbab6ebc3")}catch{}})();function Gs(e){return Math.round(e*1e6)/1e6}function Ks(e,t,n){let r=e.get(t);r===void 0?e.set(t,new Set([n])):r.add(n)}function zs(e,t){let n=new Map(e.nodes().map(i=>[i,new Set]));Fn(e,t,i=>{n.get(i.source).add(i.target),n.get(i.target).add(i.source)});let r=new Map;for(let[i,o]of n)r.set(i,[...o].sort());return r}function Zu(e,t){let n=new Map,r=new Map;return Fn(e,t,(i,o)=>{if(!o.ordering)return;let{predecessor:s,successor:a}=et(i,o);Ks(r,s,a),Ks(n,a,s)}),{incoming:n,outgoing:r}}function ef(e,t,n){let r=new Map([[e,0]]),i=new Map([[e,1]]),o=new Map,s=[],a=[e],c=0,d=0;for(let l=0;l<a.length;l+=1){let u=a[l];n.visitedNodes+=1,s.push(u);let f=r.get(u);u!==e&&(c+=1,d+=f);for(let p of t.get(u))if(n.inspectedEdges+=1,r.has(p)||(r.set(p,f+1),a.push(p)),r.get(p)===f+1){i.set(p,(i.get(p)??0)+i.get(u));let m=o.get(p);m===void 0?o.set(p,[u]):m.push(u)}}return{stack:s,sigma:i,predecessors:o,reachableCount:c,distanceSum:d}}function tf(e,t,n){let r=new Map;for(let i=e.stack.length-1;i>=0;i-=1){let o=e.stack[i],s=(1+(r.get(o)??0))/e.sigma.get(o);for(let a of e.predecessors.get(o)??[])r.set(a,(r.get(a)??0)+e.sigma.get(a)*s);o!==t&&n.set(o,(n.get(o)??0)+(r.get(o)??0))}}function nf(e,t){return t<=1||e.reachableCount===0?0:e.reachableCount/(t-1)*(e.reachableCount/e.distanceSum)}function rf(e,t,n,r,i){return{id:e,degree:t.get(e).length,inDegree:n.incoming.get(e)?.size??0,outDegree:n.outgoing.get(e)?.size??0,betweenness:Gs((r.get(e)??0)/2),closeness:Gs(i.get(e))}}function Vs(e,t={}){let n=zs(e,t.kinds),r=Zu(e,t.kinds),i=e.nodes(),o=new Map,s=new Map,a={visitedNodes:0,inspectedEdges:0};for(let l of i){t.signal?.throwIfAborted();let u=ef(l,n,a);s.set(l,nf(u,i.length)),tf(u,l,o)}let c=0;for(let l of n.values())c+=l.length;let d=i.map(l=>rf(l,n,r,o,s)).sort((l,u)=>u.betweenness-l.betweenness||u.degree-l.degree||l.id.localeCompare(u.id));return{value:{nodeCount:i.length,edgeCount:c/2,rows:d},meta:{visitedNodes:a.visitedNodes,inspectedEdges:a.inspectedEdges,truncated:!1}}}function of(e,t){return e<=t?{source:e,target:t}:{source:t,target:e}}function sf(e,t,n){let i=t.get(e.node)[e.neighborIndex];if(e.neighborIndex+=1,n.inspectedEdges+=1,i!==e.parent){if(n.discovery.has(i)){n.low.set(e.node,Math.min(n.low.get(e.node),n.discovery.get(i)));return}return e.children+=1,n.discovery.set(i,n.timer),n.low.set(i,n.timer),n.timer+=1,{node:i,parent:e.node,neighborIndex:0,children:0}}}function af(e,t,n){if(e.parent===null){e.children>1&&n.articulation.add(e.node);return}let r=e.parent,i=n.low.get(e.node);n.low.set(r,Math.min(n.low.get(r),i)),r!==t&&i>=n.discovery.get(r)&&n.articulation.add(r),i>n.discovery.get(r)&&n.bridges.push(of(r,e.node))}function cf(e,t,n,r){n.discovery.set(e,n.timer),n.low.set(e,n.timer),n.timer+=1;let i=[{node:e,parent:null,neighborIndex:0,children:0}];for(;i.length>0;){r?.throwIfAborted();let o=i.at(-1);if(o.neighborIndex<t.get(o.node).length){let s=sf(o,t,n);s!==void 0&&i.push(s)}else af(o,e,n),i.pop()}}function $n(e,t={}){let n=zs(e,t.kinds),r={discovery:new Map,low:new Map,timer:0,articulation:new Set,bridges:[],inspectedEdges:0};for(let i of e.nodes())r.discovery.has(i)||cf(i,n,r,t.signal);return{value:{articulationPoints:[...r.articulation].sort(),bridges:r.bridges.sort((i,o)=>i.source.localeCompare(o.source)||i.target.localeCompare(o.target))},meta:{visitedNodes:r.discovery.size,inspectedEdges:r.inspectedEdges,truncated:!1}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1c9d9d0c-e989-568c-a49a-202f77e94806")}catch{}})();function df(e){let t=e.registry(),n=new Map,r=new Set;for(let i of e.edges()){let o=t.require(i.kind);if(!o.ordering)continue;let{predecessor:s,successor:a}=et(i,o);if(r.add(s),r.add(a),s===a)continue;let c=n.get(s);c===void 0?n.set(s,new Set([a])):c.add(a)}return{forward:n,participants:r}}function lf(e,t,n,r){if(e===void 0)return r;let i=r;for(let o of e)t.has(o)&&(i=Math.min(i,n.get(o)));return i}function uf(e,t,n){let r=n-t;return{id:e,earliestStart:t,earliestFinish:t+1,latestStart:n,latestFinish:n+1,slack:r,critical:r===0}}function ff(e,t,n,r,i){let o=new Map;for(let s=e.length-1;s>=0;s-=1){let a=e[s],c=lf(t.forward.get(a),r,o,i);o.set(a,c-1)}return e.map(s=>uf(s,n[s],o.get(s))).sort((s,a)=>s.slack-a.slack||s.earliestStart-a.earliestStart||s.id.localeCompare(a.id))}function qs(e,t={}){t.signal?.throwIfAborted();let n=yn(e,{registry:e.registry()}),r=df(e),i=new Set(n.order),o=n.order.filter(d=>r.participants.has(d)),s=o.reduce((d,l)=>Math.max(d,n.depth[l]+1),0),a=ff(o,r,n.depth,i,s),c=a.length>0;return{exact:!0,acyclic:n.acyclic,makespan:s,scheduledCount:a.length,criticalPath:c?n.criticalPath:[],criticalPathLength:c?n.criticalPathLength:0,cycles:n.cycles,rows:a,provenance:{algorithm:"critical-path-method",edgeFamily:"ordering",weighting:"unit"}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6b2a7206-d480-51c1-9d46-4271bde24fa3")}catch{}})();function mf(e,t,n){for(let r=e.length-1;r>=0;r-=1){n?.throwIfAborted();let i=t.get(e[r]);for(let o of i.successors){n?.throwIfAborted();let s=t.get(o);if(s.latest===void 0||s.duration===void 0)continue;let a=s.latest-s.duration;(i.latest===void 0||a<i.latest)&&(i.latest=a,i.anchor=s.anchor)}}}function pf(e,t,n,r){let i=[],o=e;for(;o!==void 0&&i.length<n;)r?.throwIfAborted(),i.push(o),o=t.get(o).predecessor;return i.reverse(),{path:i,path_truncated:o!==void 0}}function hf(e,t,n,r,i){let o=new Map(t.map(a=>[a.id,a])),s=new Map;for(let a of e){i?.throwIfAborted();let c=o.get(a),d=c?.estimated_minutes,l=typeof d=="number"&&Number.isFinite(d)&&d>=0?d:void 0,u={item:c,duration:l,pending:0,successors:new Set,earliest:0};if(c?.deadline!==void 0){let f=Date.parse(c.deadline);Number.isFinite(f)?(u.deadline=(f-n)/6e4,u.latest=u.deadline,u.anchor=a):r(a,"invalid_deadline")}s.set(a,u)}return s}function gf(e,t,n){for(let r of e.edges()){n?.throwIfAborted();let i=e.registry().require(r.kind);if(!i.ordering)continue;let{predecessor:o,successor:s}=et(r,i),a=t.get(o);a.successors.has(s)||(a.successors.add(s),t.get(s).pending+=1)}}function _f(e,t,n){let r=e.filter(i=>t.get(i).pending===0);for(let i=0;i<r.length;i+=1){n?.throwIfAborted();let o=r[i],s=t.get(o),a=s.earliest===null||s.duration===void 0?null:s.earliest+s.duration;for(let c of s.successors){n?.throwIfAborted();let d=t.get(c);a===null?d.earliest=null:d.earliest!==null&&(a>d.earliest||a===d.earliest&&(d.predecessor===void 0||o<d.predecessor))&&(d.earliest=a,d.predecessor=o),d.pending-=1,d.pending===0&&r.push(c)}}return r}function yf(e,t,n,r,i,o,s,a){let c=t.duration;if(t.latest!==void 0){r.scheduled_count+=1;let d=t.latest-c;r.rows.length<o?r.rows.push({id:e,deadline_id:t.anchor,latest_start:new Date(i+d*6e4).toISOString(),slack_minutes:t.earliest===null?null:d-t.earliest}):r.truncated=!0}if(t.deadline!==void 0&&t.earliest!==null&&t.earliest+c>t.deadline)if(r.overcommitted_count+=1,r.overcommitted.length<o){let d=pf(e,n,Math.min(o,s.remaining),a);s.remaining-=d.path.length,d.path_truncated&&(r.truncated=!0),r.overcommitted.push({deadline_id:e,deadline:t.item.deadline,shortfall_minutes:t.earliest+c-t.deadline,...d})}else r.truncated=!0}function vf(e,t,n,r,i,o,s,a){let c={remaining:o};for(let d of e){a?.throwIfAborted();let l=t.get(d);if(l.pending>0){s(d,"cycle_or_gated_by_cycle");continue}if(l.duration===void 0){s(d,"unknown_estimate");continue}if(l.latest!==void 0&&!Number.isFinite(new Date(r+(l.latest-l.duration)*6e4).getTime())){s(d,"date_range_exceeded");continue}l.earliest===null&&s(d,"unknown_predecessor_estimate"),yf(d,l,t,n,r,i,c,a)}}function Ws(e,t,n={}){n.signal?.throwIfAborted();let r=Date.parse(n.now??new Date().toISOString());if(!Number.isFinite(r))throw new TypeError("Invalid scheduling clock");let i=n.maxWork??1e5,o=n.limit??10;for(let[f,p]of[["maxWork",i],["limit",o]])if(!Number.isSafeInteger(p)||p<1)throw new TypeError(`Invalid scheduling ${f}`);let s={as_of:new Date(r).toISOString(),basis:"derived_elapsed_minutes",complete:!0,truncated:!1,work_limit_exceeded:!1,scheduled_count:0,residual_count:0,overcommitted_count:0,rows:[],residuals:[],overcommitted:[]},a=e.nodes(),c=e.edges();if(a.length+c.length+t.length>i)return{...s,complete:!1,work_limit_exceeded:!0};let d=(f,p)=>{s.complete=!1,s.residual_count+=1,s.residuals.length<o?s.residuals.push({id:f,reason:p}):s.truncated=!0},l=hf(a,t,r,d,n.signal);gf(e,l,n.signal);let u=_f(a,l,n.signal);return mf(u,l,n.signal),vf(a,l,s,r,o,i,d,n.signal),s}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2bfc4e78-a376-5099-be50-38e339eac660")}catch{}})();function nt(){return{nodes:0,isolated:0,degree_leq_one:0,semantic_nodes:0,without_semantic_edges:0,degree_histogram:{}}}function Js(e,t,n,r){let i={all:nt(),active:nt(),terminal:nt()},o=new Map;for(let s of e.details){if(r?.throwIfAborted(),e.missingIdSet.has(s.id.toLowerCase())||s.status==="external")continue;let a=o.get(s.status)??nt();o.set(s.status,a);let c=e.graph.incidentEdges(s.id),d=c.some(l=>n(l.kind));for(let l of[i.all,i[t(s.status)?"terminal":"active"],a]){l.nodes+=1,l.isolated+=+(c.length===0),c.length<=1&&(l.degree_leq_one+=1),d?l.semantic_nodes+=1:l.without_semantic_edges+=1;let u=String(c.length);l.degree_histogram[u]=(l.degree_histogram[u]??0)+1}}return{coverage_by_lifecycle:i,coverage_by_status:Object.fromEntries([...o].sort(([s],[a])=>s.localeCompare(a)))}}function Ys(e){if(!Pn(e))return!1;let t=e;if(!["nodes","isolated","degree_leq_one","semantic_nodes","without_semantic_edges"].every(i=>Number.isSafeInteger(t[i])&&Number(t[i])>=0)||!Pn(t.degree_histogram))return!1;let r=Object.entries(t.degree_histogram);return r.every(([i,o])=>/^(0|[1-9]\d*)$/.test(i)&&Number.isSafeInteger(o)&&Number(o)>=0)&&r.reduce((i,[,o])=>i+Number(o),0)===t.nodes&&Number(t.isolated)<=Number(t.degree_leq_one)&&Number(t.degree_leq_one)<=Number(t.nodes)&&Number(t.semantic_nodes)+Number(t.without_semantic_edges)===t.nodes}function Pn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Qs(e){for(let r of["ordering_acyclic","active_ordering_acyclic"])if(e[r]!==void 0&&typeof e[r]!="boolean")return!1;let t=e.coverage_by_lifecycle,n=e.coverage_by_status;return t===void 0&&n===void 0?!0:!Pn(t)||!Pn(n)?!1:["all","active","terminal"].every(r=>Ys(t[r]))&&Object.values(n).every(Ys)}function Xs(e,t){return Object.fromEntries([...new Set([...Object.keys(e),...Object.keys(t)])].sort().map(n=>{let r=Object.hasOwn(e,n)?e[n]:nt(),i=Object.hasOwn(t,n)?t[n]:nt(),o=Object.fromEntries([...new Set([...Object.keys(r.degree_histogram),...Object.keys(i.degree_histogram)])].sort().map(s=>[s,(i.degree_histogram[s]??0)-(r.degree_histogram[s]??0)]));return[n,{nodes:i.nodes-r.nodes,isolated:i.isolated-r.isolated,degree_leq_one:i.degree_leq_one-r.degree_leq_one,semantic_nodes:i.semantic_nodes-r.semantic_nodes,without_semantic_edges:i.without_semantic_edges-r.without_semantic_edges,degree_histogram:o}]}))}function Zs(e,t){return!e.coverage_by_lifecycle||!t.coverage_by_lifecycle||!e.coverage_by_status||!t.coverage_by_status?{lifecycle_comparable:!1}:{lifecycle_comparable:!0,coverage_by_lifecycle:Xs(e.coverage_by_lifecycle,t.coverage_by_lifecycle),coverage_by_status:Xs(e.coverage_by_status,t.coverage_by_status)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="896e1553-b127-532f-ac39-e0d47f29eebc")}catch{}})();var rt=["missing_reference_active","missing_reference_terminal","legacy_no_blocker_sentinel","ordering_cycle","legacy_ordering_cycle","ordering_storage_contradiction","legacy_ordering_storage_contradiction","hierarchy_cycle","legacy_hierarchy_cycle","hierarchy_cardinality_violation","legacy_hierarchy_cardinality_violation","hierarchy_direction_violation","legacy_hierarchy_direction_violation","duplicate_edge","legacy_duplicate_edge","duplicate_dependency_row","legacy_duplicate_dependency_row","stale_lifecycle_block","isolated_active_node","sparse_active_node"];(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1335acb2-0730-5934-89a4-14fe4a160288")}catch{}})();var bf=25,wf="milestone",kf="outcome milestone:",Ef=new Set(["discovered_from","incident_from","recurs_from","supersedes","verifies"]);function jn(e){return Ef.has(e)}var ea={error:0,warning:1,info:2};function ta(e){return new Set((e??[]).filter(t=>typeof t=="string").map(t=>t.trim().toLowerCase()))}function it(e,t,n,r,i,o,s,a){let c=[...i].sort((d,l)=>d.localeCompare(l));return{code:e,severity:t,policy:n,message:r(c.length),count:c.length,sample:c.slice(0,o),sample_truncated:c.length>o,remediation:s,...a===void 0?{}:{evidence:[...a].sort((d,l)=>d.localeCompare(l)).slice(0,o)}}}function If(e,t){return e.cycles.map(n=>it(n.legacy_terminal?"legacy_hierarchy_cycle":"hierarchy_cycle",n.legacy_terminal?"info":"error","Structural hierarchy must be acyclic across scalar and registered dependency relationships.",r=>`${r} items participate in one hierarchy cycle.`,n.item_ids,t,n.legacy_terminal?"Preserve historical rows unless an explicit legacy repair is approved.":"Remove or retype one exact hierarchy relation before continuing mutation."))}function na(e,t,n){let r=e.cardinality_violations.filter(i=>i.legacy_terminal===n);return r.length===0?[]:[it(n?"legacy_hierarchy_cardinality_violation":"hierarchy_cardinality_violation",n?"info":"error","Every structural child must resolve to at most one logical parent across all hierarchy spellings.",i=>`${i} child item${i===1?"":"s"} resolve to multiple hierarchy parents.`,r.map(i=>i.child_id),t,n?"Preserve historical rows unless an explicit legacy repair is approved.":"Remove the exact surplus hierarchy rows so each child has one parent.",r.map(i=>`${i.child_id} <- ${i.parent_ids.join(", ")}`))]}function ra(e,t,n){let r=e.divergences.filter(i=>i.legacy_terminal===n);return r.length===0?[]:[it(n?"legacy_hierarchy_direction_violation":"hierarchy_direction_violation",n?"info":"error","Scalar parent metadata and dependency-backed hierarchy rows must resolve to the same logical parent.",i=>`${i} child item${i===1?"":"s"} have divergent hierarchy storage surfaces.`,r.map(i=>i.child_id),t,n?"Preserve historical rows unless an explicit legacy repair is approved.":"Align the scalar parent and exact dependency rows to one canonical parent.",r.map(i=>`${i.child_id}: scalar=${i.scalar_parent_id} dependencies=${i.dependency_parent_ids.join(",")}`))]}function Cf(e,t){let n=Sn(e);return n?[...If(n,t),...na(n,t,!1),...na(n,t,!0),...ra(n,t,!1),...ra(n,t,!0)]:[]}function Sf(e){let t=e.graph.registry(),n=new Map;for(let r of e.graph.edges()){let i=t.require(r.kind);if(!i.ordering)continue;let[o,s]=(i.precedence??"source_before_target")==="target_before_source"?[r.target,r.source]:[r.source,r.target],a=n.get(o);a?a.push(s):n.set(o,[s])}for(let r of n.values())r.sort((i,o)=>i.localeCompare(o));return n}function oa(e,t){t.indexes.set(e,t.nextIndex),t.lowLinks.set(e,t.nextIndex),t.nextIndex+=1,t.stack.push(e),t.onStack.add(e)}function Tf(e,t,n,r){let i=n.get(e.node)??[];if(e.neighborIndex>=i.length)return!1;let o=i[e.neighborIndex];return e.neighborIndex+=1,r.indexes.has(o)?r.onStack.has(o)&&r.lowLinks.set(e.node,Math.min(r.lowLinks.get(e.node),r.indexes.get(o))):(oa(o,r),t.push({node:o,neighborIndex:0})),!0}function Rf(e,t,n,r){t.pop();let i=t.at(-1);if(i&&r.lowLinks.set(i.node,Math.min(r.lowLinks.get(i.node),r.lowLinks.get(e.node))),r.lowLinks.get(e.node)!==r.indexes.get(e.node))return;let o=[];for(;;){let s=r.stack.pop();if(r.onStack.delete(s),o.push(s),s===e.node)break}(o.length>1||o.length===1&&n.get(o[0])?.includes(o[0]))&&r.components.push(o.sort((s,a)=>s.localeCompare(a)))}function xf(e){let t={indexes:new Map,lowLinks:new Map,onStack:new Set,stack:[],components:[],nextIndex:0},n=[...e.keys()].sort((r,i)=>r.localeCompare(i));for(let r of n){if(t.indexes.has(r))continue;let i=[{node:r,neighborIndex:0}];for(oa(r,t);i.length>0;){let o=i.at(-1);Tf(o,i,e,t)||Rf(o,i,e,t)}}return t.components.sort((r,i)=>r[0].localeCompare(i[0]))}function Kr(e){return`${e.holder_id} -> ${e.target_id} (${e.kind})`}function ee(e,t,n,r,i,o,s,a){t.length!==0&&e.push(it(r,i,o,s,t,n,a))}function Df(e,t,n){let r=[],i=[...e.dangling.active,...e.dangling.legacy_terminal].filter(o=>!o.no_active_blocker_sentinel);return ee(r,i.filter(o=>!t(o.holder_status)).map(Kr),n,"missing_reference_active","error","Active items must not reference absent targets; missing prerequisites distort scheduling.",o=>`${o} active dangling reference(s) to absent items`,"Restore or re-create the referenced item, or remove/retype the reference on the holder."),ee(r,i.filter(o=>t(o.holder_status)).map(Kr),n,"missing_reference_terminal","info","Terminal items may retain historical references, but absent targets remain unexplainable context.",o=>`${o} terminal dangling reference(s) to absent items`,"Leave as history debt or clean up in a dedicated changelog-safe closed-item batch."),ee(r,e.dangling.no_active_blocker_sentinels.map(Kr),n,"legacy_no_blocker_sentinel","info","The pre-structured-dependency no-active-blocker sentinel is retired; real edges carry blocker state.",o=>`${o} legacy no-active-blocker sentinel reference(s)`,"Delete the sentinel reference; blocker state is derived from blocked_by edges."),r}function Vr(e,t){let n=t.get(e);return n?!n.terminal:!0}function sa(e){return`${e.holder_id} -> ${e.target_id} (blocked_by scalar + ${e.dependency_kind} dependency)`}function Af(e,t){let n=[],r=[];for(let o of e.orderingContradictions??[])(o.legacy_terminal?r:n).push(sa(o));let i=[];return ee(i,n,t,"ordering_storage_contradiction","error","A scalar blocker and same-target structured ordering row must not assert opposite precedence.",o=>`${o} active scalar-versus-structured ordering contradiction(s)`,"Remove the structured dependency row that points the holder before its scalar blocker, or replace both representations with one unambiguous ordering edge."),ee(i,r,t,"legacy_ordering_storage_contradiction","info","Terminal scalar-versus-structured ordering contradictions are exact historical storage defects with no live scheduling effect.",o=>`${o} terminal scalar-versus-structured ordering contradiction(s)`,"Remove the contradictory blocks dependency row in a dedicated changelog-safe closed-item batch; preserve the scalar blocker as the historical precedence record."),i}function Of(e,t,n,r){let i=[],o=Sf(e);for(let c of xf(o)){let d=c.some(f=>Vr(f,t)),l=new Set(c.map(f=>f.toLowerCase())),u=(e.orderingContradictions??[]).filter(f=>l.has(f.holder_id.toLowerCase())&&l.has(f.target_id.toLowerCase())).map(sa);i.push(d?it("ordering_cycle","error","Order-bearing relationship kinds must stay acyclic; a cycle makes every member unschedulable.",f=>`execution-order cycle across ${f} item(s)`,c,r,"Remove or retype one ordering edge inside the cycle, or split the work so precedence is linear.",u.length===0?void 0:u):it("legacy_ordering_cycle","info","Ordering cycles between exclusively terminal items are historical contradictions with no scheduling effect.",f=>`terminal-only execution-order cycle across ${f} item(s)`,c,r,"Leave as history debt, or clean up in a dedicated changelog-safe closed-item batch; never repair closed items ad hoc.",u.length===0?void 0:u))}let s=new Map;for(let[c,d]of o)for(let l of d){let u=s.get(l);u?u.push(c):s.set(l,[c])}let a=[...t.values()].filter(c=>!c.missing&&!c.terminal&&n(c.status)&&!(s.get(c.id)??[]).some(d=>{let l=t.get(d);return l===void 0||!l.terminal})).map(c=>c.id);return ee(i,a,r,"stale_lifecycle_block","warning","A blocked lifecycle status must be backed by at least one open ordering predecessor.",c=>`${c} status-blocked item(s) with no open blocker edge`,'Add a local blocker edge, declare an external blocker with --dep "id=<external-ref>,kind=blocked_by,source_kind=external", or move the item back to an active status.'),i}function Un(e){let t=e.edges.map(n=>n.kind).sort((n,r)=>n.localeCompare(r));return`${e.from} -> ${e.to} (${t.join(" + ")})`}function qr(e){let t=e.graph.registry(),n=new Map;for(let i of e.graph.edges()){let o=t.require(i.kind);if(!Mn(o))continue;let s=Gr(i,o);if(s.from===s.to)continue;let a=`${Nn(o)}::${s.from}::${s.to}`,c=n.get(a);c?c.edges.push(i):n.set(a,{...s,edges:[i]})}let r=[...n.values()].filter(i=>i.edges.length>=2);for(let i of r)i.edges.sort((o,s)=>o.kind.localeCompare(s.kind));return r.sort((i,o)=>i.from.localeCompare(o.from)||i.to.localeCompare(o.to))}function Lf(e,t,n){let r=[],i=[];for(let s of qr(e))(Vr(s.from,t)||Vr(s.to,t)?r:i).push(Un(s));let o=[];return ee(o,r,n,"duplicate_edge","info","One semantic relationship should be stored once; parallel same-family spellings (reciprocal inverse pairs included) add no information and skew degree metrics.",s=>`${s} duplicated relationship(s) between active endpoints`,"Remove all but one stored spelling of the relationship; keep the canonical direction the holder declared first."),ee(o,i,n,"legacy_duplicate_edge","info","Duplicated spellings between exclusively terminal items are historical noise with no scheduling effect.",s=>`${s} duplicated relationship(s) between terminal endpoints`,"Leave as history debt or clean up in a dedicated changelog-safe closed-item batch."),o}function Ff(e,t){let n=[],r=[];for(let o of e.duplicateRows??[])(o.legacy_terminal?r:n).push(`${o.holder_id} -> ${o.target_id} (${o.kind} x${o.occurrences})`);let i=[];return ee(i,n,t,"duplicate_dependency_row","warning","One dependency row must be stored once per holder; identical repeated rows are a storage-layer defect invisible to the assembled graph.",o=>`${o} exactly duplicated stored dependency row(s) on active holder(s)`,"Remove the repeated rows so the dependency is stored exactly once; graph semantics are unchanged."),ee(i,r,t,"legacy_duplicate_dependency_row","info","Identical repeated dependency rows on terminal holders are historical storage noise with no scheduling effect.",o=>`${o} exactly duplicated stored dependency row(s) on terminal holder(s)`,"Leave as history debt or clean up in a dedicated changelog-safe closed-item batch."),i}function Mf(e,t){let n=new Map,r={source_to_target:[],target_to_source:[],both:[]};for(let s of e.graph.registry().list())s.outcomeTraversal!==void 0&&r[s.outcomeTraversal].push(s.kind);let i={source_to_target:r.source_to_target.join(","),target_to_source:r.target_to_source.join(","),both:r.both.join(",")},o=(s,a)=>{let c=n.get(a)??new Set;c.add(s),n.set(a,c)};for(let s of e.graph.edges()){t?.throwIfAborted();let a=e.graph.registry().require(s.kind);(a.outcomeTraversal==="source_to_target"||a.outcomeTraversal==="both")&&o(s.source,s.target),(a.outcomeTraversal==="target_to_source"||a.outcomeTraversal==="both")&&o(s.target,s.source)}return{basis:i,reverse:n}}function Nf(e,t,n){let r=new Set(e),i=[...e].sort();for(let o=0;o<i.length;o+=1){n?.throwIfAborted();for(let s of[...t.get(i[o])??[]].sort())r.has(s)||(r.add(s),i.push(s))}return r}function $f(e,t,n,r){let i=0,o=0,s=0,a=0;for(let p of e.values())if(r?.throwIfAborted(),!t.has(p.id)&&!(p.missing||p.status==="external")){if(p.terminal){s+=1,n.has(p.id)&&(a+=1);continue}n.has(p.id)?i+=1:o+=1}let c=i+o,d=s-a,l=i+a,u=o+d,f=l+u;return{active_outcome_reachable_nodes:i,active_outcome_unreachable_nodes:o,active_outcome_reachability_basis_points:c===0?0:Math.floor(i*1e4/c),terminal_nodes:s,terminal_outcome_reachable_nodes:a,terminal_outcome_unreachable_nodes:d,terminal_outcome_reachability_basis_points:s===0?0:Math.floor(a*1e4/s),outcome_reachable_nodes:l,outcome_unreachable_nodes:u,outcome_reachability_basis_points:f===0?0:Math.floor(l*1e4/f)}}function Pf(e,t,n){let r=new Set(e.details.filter(a=>a.type?.toLowerCase()===wf&&a.title.trim().toLowerCase().startsWith(kf)).map(a=>a.id)),{basis:i,reverse:o}=Mf(e,n),s=Nf(r,o,n);return{outcome_nodes:r.size,outcome_reachability_basis:i,...$f(t,r,s,n)}}function jf(e,t,n,r,i){e.active+=1;let o=t.type??"(untyped)",s=e.byType.get(o);s||(s={active:0,isolated:0,degree_leq_one:0},e.byType.set(o,s)),s.active+=1,!(n>1)&&(e.degreeLeqOne+=1,s.degree_leq_one+=1,n===0&&(e.isolated+=1,s.isolated+=1),!(r.has(t.id.toLowerCase())||i.has(o.toLowerCase()))&&(n===0?e.isolates.push(t.id):e.sparse.push(t.id)))}function Uf(e,t,n,r,i,o,s){let a={active:0,missing:0,isolated:0,degreeLeqOne:0,isolates:[],sparse:[],byType:new Map};for(let v of e.graph.nodes()){s?.throwIfAborted();let w=t.get(v);if(w){if(w.missing){a.missing+=1;continue}w.terminal||jf(a,w,e.graph.incidentEdges(v).length,n,r)}}let{isolates:c,sparse:d}=a,l=[];ee(l,c,i,"isolated_active_node","warning","Active work should be reachable from the graph unless explicitly declared a valid isolate.",v=>`${v} active item(s) with no relationships`,"Link the item to its parent, prerequisite, or origin \u2014 or register it as an exempt isolate."),ee(l,d,i,"sparse_active_node","info","Active items with a single edge often miss an honest semantic partner; sparse is not automatically defective.",v=>`${v} active item(s) with exactly one relationship`,"Investigate for an honest second edge (story->task, defect family, cross-epic complement); do not fabricate one.");let u=e.graph.edges().length,f=tt(e.graph,{signal:s}).value,p=new Set(f.map(({edge:v})=>`${v.source.toLowerCase()}\0${v.target.toLowerCase()}\0${v.kind}`));for(let v of e.orderingContradictions??[])p.add(`${v.holder_id.toLowerCase()}\0${v.target_id.toLowerCase()}\0${v.dependency_kind}`);let m=Object.fromEntries(Object.entries(o).sort(([v],[w])=>v.localeCompare(w))),h=Object.entries(m).reduce((v,[w,C])=>v+(jn(w)?C:0),0),y=$n(e.graph,{signal:s}).value,b=Pf(e,t,s);return{findings:l,profile:{nodes:e.graph.nodes().length,recorded_nodes:e.details.filter(v=>v.status!=="missing"&&v.status!=="external").length,edges:u,informative_edges:u-p.size,redundant_edges:f.length,ordering_contradiction_edges:e.orderingContradictions?.length??0,edge_basis:"deduplicated_directed",edges_by_kind:m,edge_share_by_kind:Object.fromEntries(Object.entries(m).map(([v,w])=>[v,w/u])),semantic_edges:h,semantic_edge_share:u===0?0:h/u,active_nodes:a.active,missing_nodes:a.missing,isolated_active_nodes:a.isolated,degree_leq_one_active_nodes:a.degreeLeqOne,coverage_by_type:Object.fromEntries([...a.byType.entries()].sort(([v],[w])=>v<w?-1:1)),articulation_points:y.articulationPoints.length,bridge_edges:y.bridges.length,...b,finding_subjects_by_code:Object.fromEntries(rt.map(v=>[v,0]))}}}function Hn(e,t={}){let n=t.isTerminal??(f=>f==="closed"||f==="canceled"),r=t.isBlocked??(f=>f==="blocked"),i=t.maxSampleSize??bf;if(!Number.isInteger(i)||i<1)throw new TypeError(`Invalid audit sample bound: ${String(t.maxSampleSize)}`);let o=ta(t.exemptIsolates),s=ta(t.isolateExemptTypes),a=new Map(e.details.map(f=>[f.id,{id:f.id,status:f.status,missing:e.missingIdSet.has(f.id.toLowerCase()),terminal:n(f.status),...f.type===void 0?{}:{type:f.type}}]));t.signal?.throwIfAborted();let c={};for(let f of e.graph.edges())c[f.kind]=(c[f.kind]??0)+1;let d=Df(e,n,i);d.push(...Cf(e,i)),t.signal?.throwIfAborted(),d.push(...Af(e,i)),t.signal?.throwIfAborted(),d.push(...Of(e,a,r,i)),t.signal?.throwIfAborted(),d.push(...Lf(e,a,i),...Ff(e,i)),t.signal?.throwIfAborted();let l=Uf(e,a,o,s,i,c,t.signal);d.push(...l.findings),d.sort((f,p)=>ea[f.severity]-ea[p.severity]||f.code.localeCompare(p.code)||f.sample[0].localeCompare(p.sample[0]));let u=l.profile.finding_subjects_by_code;for(let f of d)u[f.code]+=f.count;return{findings:d,profile:{...l.profile,...Js(e,n,jn,t.signal),ordering_acyclic:!d.some(f=>f.code==="ordering_cycle"||f.code==="legacy_ordering_cycle"),active_ordering_acyclic:!d.some(f=>f.code==="ordering_cycle"),finding_subjects_by_code:u}}}function zr(e,t){let n=[...new Set([...Object.keys(e),...Object.keys(t)])].sort(),r={};for(let i of n){let o=(t[i]??0)-(e[i]??0);o!==0&&(r[i]=o)}return r}function ia(e){return e.profile.coverage_by_type??{}}function Hf(e,t){let n={},r=ia(e),i=ia(t),o=[...new Set([...Object.keys(r),...Object.keys(i)])].sort();for(let s of o){let a=Object.assign({active:0,isolated:0,degree_leq_one:0},r[s]),c=Object.assign({active:0,isolated:0,degree_leq_one:0},i[s]),d={active:c.active-a.active,isolated:c.isolated-a.isolated,degree_leq_one:c.degree_leq_one-a.degree_leq_one};Object.values(d).some(l=>l!==0)&&(n[s]=d)}return n}function aa(e,t){let n=Hf(e,t),{edge_share_by_kind:r={},semantic_edges:i=0,semantic_edge_share:o=0}=e.profile,{edge_share_by_kind:s={},semantic_edges:a=0,semantic_edge_share:c=0}=t.profile,d=e.profile.recorded_nodes??e.profile.nodes,l=t.profile.recorded_nodes??t.profile.nodes,u=e.profile.informative_edges??e.profile.edges,f=t.profile.informative_edges??t.profile.edges,p=e.profile.redundant_edges??0,m=t.profile.redundant_edges??0,h=e.profile.ordering_contradiction_edges??0,y=t.profile.ordering_contradiction_edges??0;return{baseline_saved_at:e.saved_at,same_snapshot:e.fingerprint===t.fingerprint,affected_subjects_by_code:zr(e.affected_subjects_by_code,t.affected_subjects_by_code),profile:{nodes:t.profile.nodes-e.profile.nodes,recorded_nodes:l-d,edges:t.profile.edges-e.profile.edges,informative_edges:f-u,redundant_edges:m-p,ordering_contradiction_edges:y-h,active_nodes:t.profile.active_nodes-e.profile.active_nodes,missing_nodes:t.profile.missing_nodes-e.profile.missing_nodes,isolated_active_nodes:t.profile.isolated_active_nodes-e.profile.isolated_active_nodes,degree_leq_one_active_nodes:t.profile.degree_leq_one_active_nodes-e.profile.degree_leq_one_active_nodes,edges_by_kind:zr(e.profile.edges_by_kind,t.profile.edges_by_kind),edge_share_by_kind:zr(r,s),semantic_edges:a-i,semantic_edge_share:c-o,coverage_by_type:n,...Zs(e.profile,t.profile)}}}import ca from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="19264e42-25fa-5c93-9b0d-3b18a1ab9783")}catch{}})();var da=2,Wr=500,Bf=64,Gf="graph-durable-cache";function la(e){return Ke(e,Gf,30,`graph-cache:${process.pid}`,!1,!1,3e3)}function bt(e){return ca.join(e,"runtime","graph-cache.json")}function ua(e){return ca.join(e,"runtime","graph-audit-baseline.json")}function Yr(e){if(e!==null)try{let t=JSON.parse(e);return typeof t!="object"||t===null||t.version!==da||typeof t.fingerprint!="string"||typeof t.saved_at!="string"||typeof t.results!="object"||t.results===null||Array.isArray(t.results)?void 0:t}catch{return}}async function Xr(e,t){let n=await ge(bt(e)),r=Yr(n),i=r?.fingerprint===t;return{exists:n!==null,fresh:i,results:i?r.results:{}}}async function Jr(e,t,n,r,i){let o=await la(e);try{let s=Yr(await ge(bt(e))),a=s?.fingerprint===t?s.results:{};delete a[r],a[r]=i;let c=Object.keys(a);for(let d of c.slice(0,Math.max(0,c.length-Bf)))delete a[d];await W(bt(e),JSON.stringify({version:da,fingerprint:t,saved_at:new Date().toISOString(),results:a})),n.results=a}finally{await o()}}async function Qr(e){let t=await la(e);try{await co(bt(e))}finally{await t()}}async function fa(e,t){let n=bt(e),r=await ge(n),i=Yr(r);return i===void 0?{exists:r!==null,fresh:!1,entry_count:0}:{exists:!0,fresh:i.fingerprint===t,entry_count:Object.keys(i.results).length,fingerprint:i.fingerprint.slice(0,12),saved_at:i.saved_at,bytes:Buffer.byteLength(r,"utf8")}}function Zr(e,t){return t||e>=Wr}function Bn(e){return ot(e)&&Object.values(e).every(De)}function ot(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function De(e){return Number.isInteger(e)&&Number(e)>=0}function ma(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=1}function vt(e,t){return e===void 0||t(e)}function Kf(e){return ot(e)&&Object.values(e).every(ma)}function zf(e){return ot(e)?Object.values(e).every(t=>ot(t)&&[t.active,t.isolated,t.degree_leq_one].every(De)):!1}function Vf(e,t,n){let r=["recorded_nodes","informative_edges","redundant_edges","ordering_contradiction_edges"],i=r.filter(s=>e[s]!==void 0).length;if(i!==0&&i!==r.length||!r.every(s=>vt(e[s],De)))return;let o={recorded_nodes:e.recorded_nodes??t,informative_edges:e.informative_edges??n,redundant_edges:e.redundant_edges??0,ordering_contradiction_edges:e.ordering_contradiction_edges??0};return o.recorded_nodes<=t&&o.informative_edges<=n&&o.redundant_edges<=n&&o.ordering_contradiction_edges<=n?o:void 0}function qf(e,t,n){let r=[...t,...n,"finding_subjects_by_code"],i=r.filter(o=>e[o]!==void 0).length;return i!==0&&i!==r.length?!1:t.every(o=>vt(e[o],De))&&n.every(o=>vt(e[o],De)&&(e[o]===void 0||Number(e[o])<=1e4))&&vt(e.finding_subjects_by_code,Bn)}function Wf(e,t,n,r){let i=Vf(e,n,r);if(i===void 0)return;let o=["articulation_points","bridge_edges","outcome_nodes","active_outcome_reachable_nodes","active_outcome_unreachable_nodes","terminal_nodes","terminal_outcome_reachable_nodes","terminal_outcome_unreachable_nodes","outcome_reachable_nodes","outcome_unreachable_nodes"],s=["active_outcome_reachability_basis_points","terminal_outcome_reachability_basis_points","outcome_reachability_basis_points"];if(!qf(e,o,s)||e.edge_basis!==void 0&&e.edge_basis!=="deduplicated_directed")return;let a=Bn(e.finding_subjects_by_code)?e.finding_subjects_by_code:{};return{edge_basis:"deduplicated_directed",...i,...Object.fromEntries(o.map(c=>[c,e[c]??0])),...Object.fromEntries(s.map(c=>[c,e[c]??0])),finding_subjects_by_code:Object.fromEntries(rt.map(c=>[c,a[c]??t[c]??0]))}}function Yf(e,t,n,r,i){let o=[n,r,i],s=o.filter(d=>d!==void 0).length;if(s===0)return{edge_share_by_kind:{},semantic_edges:0,semantic_edge_share:0};if(s!==o.length||!Kf(n)||!De(r)||!ma(i))return;let a=Object.entries(t);if(a.reduce((d,[,l])=>d+l,0)!==e||Object.keys(n).length!==a.length||a.some(([d,l])=>n[d]!==(e===0?0:l/e)))return;let c=a.reduce((d,[l,u])=>d+(jn(l)?u:0),0);if(!(r!==c||i!==(e===0?0:c/e)))return{edge_share_by_kind:n,semantic_edges:r,semantic_edge_share:i}}function Xf(e){if(e!==null)try{let t=JSON.parse(e);if(!ot(t))return;let n=t,r=n.profile;if(typeof n.saved_at!="string"||typeof n.fingerprint!="string")return;let i=n.affected_subjects_by_code;if(!Bn(i)||!ot(r)||!Qs(r)||![r.nodes,r.edges,r.active_nodes,r.missing_nodes,r.isolated_active_nodes,r.degree_leq_one_active_nodes].every(De)||!Bn(r.edges_by_kind)||!vt(r.coverage_by_type,zf))return;let o=Yf(r.edges,r.edges_by_kind,r.edge_share_by_kind,r.semantic_edges,r.semantic_edge_share);if(o===void 0)return;let s=Wf(r,i,r.nodes,r.edges);if(s===void 0)return;let{coverage_by_type:a={}}=r;return{...n,profile:{...r,...o,...s,coverage_by_type:a}}}catch{return}}async function pa(e){return Xf(await ge(ua(e)))}async function ha(e,t){await W(ua(e),JSON.stringify(t))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="236ccc7d-6efd-57b1-8cce-6758d537f779")}catch{}})();var Jf={missing_reference_active:{op:"investigate",confidence:"medium",rationale:"Restore or re-create the referenced item, or remove/retype the reference on the active holder; the correct fix depends on why the target is absent."},missing_reference_terminal:{op:"waive",confidence:"high",rationale:"Terminal-holder reference to an absent item is historical debt; waive it or clean it up only in a dedicated changelog-safe closed-item batch."},legacy_no_blocker_sentinel:{op:"remove",confidence:"high",rationale:"The pre-structured-dependency no-active-blocker sentinel is retired and carries no information; blocker state derives from blocked_by edges."},ordering_cycle:{op:"investigate",confidence:"low",rationale:"Every cycle member is unschedulable until one ordering edge is removed or retyped; the planner never chooses which edge to cut."},legacy_ordering_cycle:{op:"waive",confidence:"high",rationale:"Terminal-only ordering cycles have no scheduling effect; repairing them would mutate closed history (changelog drag)."},ordering_storage_contradiction:{op:"remove",confidence:"high",rationale:"The structured ordering row asserts the opposite precedence from the same-target scalar blocker; remove that exact dependency row or replace both representations with one unambiguous edge."},legacy_ordering_storage_contradiction:{op:"remove",confidence:"high",rationale:"The terminal holder contains a proven contradictory structured ordering row; remove it in a dedicated changelog-safe batch while preserving the scalar blocker as history."},hierarchy_cycle:{op:"investigate",confidence:"low",rationale:"Cut or retype one exact structural relation in the cycle; the planner preserves every evidence row because intent determines the correct parent."},legacy_hierarchy_cycle:{op:"waive",confidence:"high",rationale:"Terminal-only hierarchy cycles are historical debt; waive them unless an explicit closed-history repair is approved."},hierarchy_cardinality_violation:{op:"investigate",confidence:"medium",rationale:"Choose the canonical parent and remove or retype the exact surplus hierarchy rows; the planner cannot infer ownership intent."},legacy_hierarchy_cardinality_violation:{op:"waive",confidence:"high",rationale:"Multiple parents confined to terminal items are historical debt; waive them unless a dedicated history repair is approved."},hierarchy_direction_violation:{op:"investigate",confidence:"medium",rationale:"Align the scalar parent and dependency-backed hierarchy rows to the intended canonical parent."},legacy_hierarchy_direction_violation:{op:"waive",confidence:"high",rationale:"Divergent hierarchy storage confined to terminal items is historical debt; waive it unless a dedicated history repair is approved."},duplicate_edge:{op:"remove",confidence:"high",rationale:"Parallel same-family spellings state one relationship twice; remove all but one stored spelling, keeping the holder's canonical direction."},legacy_duplicate_edge:{op:"waive",confidence:"high",rationale:"Duplicated spellings between terminal items are historical noise; waive or batch changelog-safe cleanup."},duplicate_dependency_row:{op:"remove",confidence:"high",rationale:"The identical dependency row is stored more than once on the holder; drop the repeats so the row exists exactly once \u2014 graph semantics are unchanged."},legacy_duplicate_dependency_row:{op:"waive",confidence:"high",rationale:"Repeated identical rows on terminal holders are storage noise; waive or clean up only in a changelog-safe closed-item batch."},stale_lifecycle_block:{op:"investigate",confidence:"medium",rationale:`Add a local ordering edge, declare an external blocker with --dep "id=<external-ref>,kind=blocked_by,source_kind=external", or move the item back to an active status; only the holder's owner knows which is true.`},isolated_active_node:{op:"investigate",confidence:"medium",rationale:"Link the item to its parent, prerequisite, or origin \u2014 or register it as an explicitly exempt isolate; the audit never fabricates an edge."},sparse_active_node:{op:"investigate",confidence:"low",rationale:"Investigate for an honest second edge (story-to-task, defect family, cross-epic complement); sparse is not automatically defective."}};function ga(e){return`${e.source} -${e.kind}-> ${e.target}`}function Qf(e){let[t,...n]=e.edges;return n.map(r=>({op:"remove",code:"duplicate_edge",subject:ga(r),rationale:"This stored spelling restates the kept canonical edge of the same semantic family; removing it leaves the relationship stated exactly once.",evidence:[`keep: ${ga(t)}`,`group: ${Un(e)}`],confidence:"high"}))}function Zf(e,t){if(e.code==="duplicate_edge")return e.sample.flatMap(r=>Qf(t.get(r)));let n=Jf[e.code];return e.sample.map(r=>({op:n.op,code:e.code,subject:r,rationale:n.rationale,evidence:[e.policy],confidence:n.confidence}))}function _a(e,t={}){let{redundancyLimit:n,...r}=t,i=Hn(e,r),o=new Map(qr(e).map(d=>[Un(d),d])),s=i.findings.flatMap(d=>Zf(d,o)),a=i.findings.some(d=>d.sample_truncated);t.signal?.throwIfAborted();let c=tt(e.graph,{limit:n??t.maxSampleSize??25,...t.signal===void 0?{}:{signal:t.signal}});for(let d of c.value)s.push({op:"remove",code:"redundant_edge",subject:`${d.edge.source} -> ${d.edge.target} (${d.edge.kind})`,rationale:"The stored edge is implied by a longer same-family witness path; shortcut edges are sometimes deliberate emphasis, so confirm intent before removing.",evidence:[`witness: ${d.witness.join(" -> ")}`],confidence:"medium"});return a=a||c.meta.truncated,{steps:s,report:i,truncated:a,cost:{visitedNodes:c.meta.visitedNodes,inspectedEdges:c.meta.inspectedEdges}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3a536c76-bbd6-5235-b06a-f18c5cf95a88")}catch{}})();var wa=new Set(["ancestors","descendants","predecessors","successors","paths","impact","dominators"]),be=10;function ya(e,t,n){let r=e;if(t&&e.subcommand==="audit"){let{nodes:i,recorded_nodes:o,edges:s,active_nodes:a,terminal_nodes:c,missing_nodes:d,ordering_acyclic:l,active_ordering_acyclic:u,coverage_by_lifecycle:f}=e.profile,p=Object.fromEntries(Object.entries(f).map(([m,h])=>{let{degree_histogram:y,...b}=h;return[m,b]}));r={...e,profile:{nodes:i,recorded_nodes:o,edges:s,active_nodes:a,terminal_nodes:c,missing_nodes:d,ordering_acyclic:l,active_ordering_acyclic:u,coverage_by_lifecycle:p}}}return{...r,projection:{mode:t?"summary":"full",declared_field_groups:n===void 0?[]:[{name:n,restore_with:"--full"}],included_field_groups:n===void 0||t?[]:[n]}}}function va(e){return e===void 0?[]:(Array.isArray(e)?e:[e]).flatMap(t=>t.split(",")).map(t=>t.trim()).filter(t=>t.length>0)}function em(e,t,n){let r=e.trim().toLowerCase();if(!wr.includes(r))throw po({command_path:"graph",token:r||"<empty>",allowed:wr});let i=r;if(wa.has(i)&&!t?.trim())throw new _(`graph ${i} requires an item id.`,g.USAGE);if(i==="paths"&&!n?.trim())throw new _("graph paths requires a source and a target item id.",g.USAGE);return i}function ei(e){throw e instanceof TypeError?new _(e.message,g.USAGE):e}function ti(e){return{truncated:e.truncated,cost:{visited_nodes:e.visitedNodes,inspected_edges:e.inspectedEdges}}}function ba(e,t){let n=t.trim().toLowerCase();for(let r of e.details)if(r.id.trim().toLowerCase()===n&&!e.missingIdSet.has(r.id.toLowerCase()))return r.id;throw new _(`Item ${t} not found`,g.NOT_FOUND)}function tm(e,t,n){let r={ancestors:Ms,descendants:Ns,predecessors:$s,successors:Ps}[e],i;try{i=r(n.assembly.graph,t,{...n.kinds===void 0?{}:{kinds:n.kinds},...n.maxDepth===void 0?{}:{maxDepth:n.maxDepth},...n.limit===void 0?{}:{limit:n.limit},...n.after===void 0?{}:{after:n.after}})}catch(s){ei(s)}let o=ti(i.meta);return{subcommand:e,root:t,count:i.value.length,...o,...i.meta.nextCursor===void 0?{}:{next_cursor:i.meta.nextCursor},...n.summary?{}:{ids:i.value}}}function nm(e,t,n){let r=js(n.assembly.graph,e,t,{direction:n.direction,...n.kinds===void 0?{}:{kinds:n.kinds},...n.maxDepth===void 0?{}:{maxDepth:n.maxDepth},...n.maxPaths===void 0?{}:{maxPaths:n.maxPaths}});return{subcommand:"paths",root:e,target:t,direction:n.direction,count:r.value.length,...ti(r.meta),...n.summary?{}:{paths:r.value.map(i=>({nodes:i.nodes,kinds:i.edges.map(o=>o.kind),length:i.length}))}}}function rm(e,t){let n;try{n=_n(t.assembly.graph,e,{direction:t.direction,...t.kinds===void 0?{}:{kinds:t.kinds},...t.maxDepth===void 0?{}:{maxDepth:t.maxDepth},...t.unbounded?{}:{limit:t.limit??be},...t.after===void 0?{}:{after:t.after}})}catch(r){ei(r)}return{subcommand:"impact",root:e,direction:t.direction,count:n.affected.length,truncated:n.truncated,...n.nextCursor===void 0?{}:{next_cursor:n.nextCursor},cost:{visited_nodes:n.cost.visitedNodes,inspected_edges:n.cost.inspectedEdges},...t.summary?{}:{affected:n.affected}}}function im(e,t,n){return{acyclic:e.acyclic,ordered_node_count:e.order.length,layer_count:e.layers.length,frontier_count:e.frontier.length,critical_path_length:e.criticalPathLength,cycle_count:e.cycles.length,...t?{}:{frontier:e.frontier.slice(0,n),critical_path:e.criticalPath.slice(0,n),cycles:e.cycles.slice(0,n)}}}function om(e,t,n){return{component_count:e.components.length,largest_component_size:e.components[0]?.length??0,orphan_count:e.orphans.length,...t?{}:{orphans:e.orphans.slice(0,n),hubs:e.hubs.slice(0,n)}}}function sm(e,t,n){let r=0,i=0,o=0;for(let s of e.cycles)r+=Number(s.legacy_terminal);for(let s of e.cardinality_violations)i+=Number(s.legacy_terminal);for(let s of e.divergences)o+=Number(s.legacy_terminal);return{acyclic:e.cycles.length===0,relation_count:e.relations.length,cycle_count:e.cycles.length,active_cycle_count:e.cycles.length-r,legacy_cycle_count:r,cardinality_violation_count:e.cardinality_violations.length,active_cardinality_violation_count:e.cardinality_violations.length-i,legacy_cardinality_violation_count:i,parent_divergence_count:e.divergences.length,active_parent_divergence_count:e.divergences.length-o,legacy_parent_divergence_count:o,...t?{}:{cycles:e.cycles.slice(0,n).map(s=>s.item_ids)}}}function am(e){let t=e.assembly.graph,n=e.limit??be,r=yn(t,{registry:t.registry()}),i=ms(t);return{subcommand:"analyze",node_count:t.nodes().length,edge_count:t.edges().length,edge_basis:"deduplicated_directed",sample_limit:n,execution:im(r,e.summary,n),knowledge:om(i,e.summary,n),hierarchy:sm(Sn(e.assembly),e.summary,n)}}function cm(e,t){let n=Hn(e.assembly,{isTerminal:t,...e.sample===void 0?{}:{maxSampleSize:e.sample},...e.exemptIsolates.length===0?{}:{exemptIsolates:e.exemptIsolates},...e.exemptIsolateTypes.length===0?{}:{isolateExemptTypes:e.exemptIsolateTypes}}),r={},i={},o={},s={};for(let d of n.findings)r[d.severity]=(r[d.severity]??0)+1,i[d.code]=(i[d.code]??0)+1,o[d.severity]=(o[d.severity]??0)+d.count,s[d.code]=(s[d.code]??0)+d.count;let{finding_subjects_by_code:a,...c}=n.profile;return{subcommand:"audit",finding_count:n.findings.length,findings_by_severity:r,findings_by_code:i,affected_subjects_by_severity:o,affected_subjects_by_code:s,profile:e.summary?c:n.profile,legacy_alias_counts:e.assembly.legacyAliasCounts,...e.summary?{}:{findings:n.findings}}}function dm(e){let t=e.limit??be,n={};e.kinds!==void 0&&(n.kinds=e.kinds);let r=Hs(e.assembly.graph,n),i=r.value;return{subcommand:"communities",community_count:i.communities.length,largest_community_size:i.communities[0]?.size??0,iterations:i.iterations,converged:i.converged,truncated:!i.converged||i.communities.length>t,cost:{visited_nodes:r.meta.visitedNodes,inspected_edges:r.meta.inspectedEdges},...e.summary?{}:{communities:i.communities.slice(0,t).map(o=>({representative:o.representative,size:o.size,members:o.members.slice(0,t)}))}}}function lm(e){let t;try{t=tt(e.assembly.graph,{...e.kinds===void 0?{}:{kinds:e.kinds},...e.maxDepth===void 0?{}:{maxDepth:e.maxDepth},...e.limit===void 0?{}:{limit:e.limit}})}catch(n){ei(n)}return{subcommand:"redundancy",redundant_count:t.value.length,...ti(t.meta),...e.summary?{}:{redundant:t.value.map(n=>({source:n.edge.source,target:n.edge.target,kind:n.edge.kind,witness:n.witness}))}}}function um(e,t){let n=t.limit??be,r=Bs(t.assembly.graph,e,{direction:t.direction,...t.kinds===void 0?{}:{kinds:t.kinds},...t.maxDepth===void 0?{}:{maxDepth:t.maxDepth}}),i=r.value.rows.filter(o=>o.dominatedCount>0);return{subcommand:"dominators",root:e,direction:t.direction,reachable_count:r.value.reachableCount,bottleneck_count:i.length,truncated:r.meta.truncated||i.length>n,cost:{visited_nodes:r.meta.visitedNodes,inspected_edges:r.meta.inspectedEdges},...t.summary?{}:{bottlenecks:i.slice(0,n).map(o=>({id:o.id,idom:o.idom,dominated_count:o.dominatedCount}))}}}function fm(e){let t=e.limit??be,n=qs(e.assembly.graph),r=n.rows.filter(i=>i.critical).length;return{subcommand:"slack",acyclic:n.acyclic,makespan:n.makespan,scheduled_count:n.scheduledCount,critical_count:r,critical_path_length:n.criticalPathLength,cycle_count:n.cycles.length,truncated:n.rows.length>t,...e.summary?{}:{critical_path:n.criticalPath,rows:n.rows.slice(0,t).map(i=>({id:i.id,earliest_start:i.earliestStart,latest_start:i.latestStart,slack:i.slack,critical:i.critical}))}}}function mm(e){let t=e.limit??be,n=Vs(e.assembly.graph,e.kinds===void 0?{}:{kinds:e.kinds}),r=n.value;return{subcommand:"centrality",node_count:r.nodeCount,edge_count:r.edgeCount,edge_basis:"simple_undirected",truncated:r.rows.length>t,cost:{visited_nodes:n.meta.visitedNodes,inspected_edges:n.meta.inspectedEdges},...e.summary?{}:{rows:r.rows.slice(0,t).map(i=>({id:i.id,degree:i.degree,in_degree:i.inDegree,out_degree:i.outDegree,betweenness:i.betweenness,closeness:i.closeness}))}}}function pm(e){let t=e.limit??be,n=$n(e.assembly.graph,e.kinds===void 0?{}:{kinds:e.kinds}),{articulationPoints:r,bridges:i}=n.value;return{subcommand:"articulation",articulation_count:r.length,bridge_count:i.length,truncated:r.length>t||i.length>t,cost:{visited_nodes:n.meta.visitedNodes,inspected_edges:n.meta.inspectedEdges},...e.summary?{}:{articulation_points:r.slice(0,t),bridges:i.slice(0,t)}}}function hm(e,t){let n=e.limit??be,r=_a(e.assembly,{isTerminal:t,redundancyLimit:n,...e.sample===void 0?{}:{maxSampleSize:e.sample},...e.exemptIsolates.length===0?{}:{exemptIsolates:e.exemptIsolates},...e.exemptIsolateTypes.length===0?{}:{isolateExemptTypes:e.exemptIsolateTypes}}),i={},o={};for(let s of r.steps)i[s.op]=(i[s.op]??0)+1,o[s.code]=(o[s.code]??0)+1;return{subcommand:"plan",step_count:r.steps.length,steps_by_op:i,steps_by_code:o,finding_count:r.report.findings.length,truncated:r.truncated||r.steps.length>n,cost:{visited_nodes:r.cost.visitedNodes,inspected_edges:r.cost.inspectedEdges},...e.summary?{}:{steps:r.steps.slice(0,n)}}}function ka(e,t,n,r){return JSON.stringify({subcommand:e,root:t??null,target:n??null,kinds:r.kinds??null,maxDepth:r.maxDepth??null,limit:r.limit??null,after:r.after??null,direction:r.direction,maxPaths:r.maxPaths??null,sample:r.sample??null,exemptIsolates:[...new Set(r.exemptIsolates.map(i=>i.toLowerCase()))].sort(),exemptIsolateTypes:[...new Set(r.exemptIsolateTypes.map(i=>i.toLowerCase()))].sort(),summary:r.summary,unbounded:r.unbounded})}function Ea(e,t,n,r,i){return e==="analyze"?am(r):e==="audit"?cm(r,i):e==="plan"?hm(r,i):e==="communities"?dm(r):e==="redundancy"?lm(r):e==="dominators"?um(t,r):e==="slack"?fm(r):e==="centrality"?mm(r):e==="articulation"?pm(r):e==="paths"?nm(t,n,r):e==="impact"?rm(t,r):tm(e,t,r)}function gm(e,t){if(e!=="index"&&(t.rebuild===!0||t.clear===!0))throw new _("--rebuild and --clear apply only to graph index.",g.USAGE);if(e!=="audit"&&t.saveBaseline===!0)throw new _("--save-baseline applies only to graph audit.",g.USAGE);if(e==="slack"&&t.kind!==void 0)throw new _("graph slack analyzes every ordering kind; --kind is not supported.",g.USAGE);if(t.rebuild===!0&&t.clear===!0)throw new _("graph index accepts either --rebuild or --clear, not both.",g.USAGE);if(e==="impact"&&t.full===!0&&t.limit!==void 0)throw new _("graph impact accepts either --full or --limit, not both.",g.USAGE)}async function _m(e,t,n,r,i,o){let s="status";if(o.clear===!0&&(await Qr(e),s="cleared"),o.rebuild===!0){await Qr(e);let c=await Xr(e,t),d={assembly:n.assembly,direction:"both",exemptIsolates:[],exemptIsolateTypes:[],saveBaseline:!1,summary:!0,unbounded:!1};for(let l of["analyze","audit"])await Jr(e,t,c,ka(l,void 0,void 0,d),Ea(l,void 0,void 0,d,i));s="rebuilt"}let a=await fa(e,t);return{subcommand:"index",action:s,state:a.exists?a.fresh?"fresh":"stale":"absent",entry_count:a.entry_count,item_count:r,min_items_threshold:Wr,persist_enabled:Zr(r,a.exists),current_fingerprint:t.slice(0,12),...a.saved_at===void 0?{}:{saved_at:a.saved_at},...a.bytes===void 0?{}:{bytes:a.bytes}}}async function ym(e,t,n,r){let i={saved_at:new Date().toISOString(),fingerprint:t,affected_subjects_by_code:n.affected_subjects_by_code,profile:{...n.profile,finding_subjects_by_code:Object.fromEntries(rt.map(s=>[s,n.affected_subjects_by_code[s]??0]))}},o=await pa(e);return r&&await ha(e,i),o===void 0?n:{...n,baseline:aa(o,i)}}async function vm(e,t,n,r,i){try{await Jr(e,t,n,r,i)}catch{}}function bm(e,t,n,r){if(e.subcommand!=="slack")return;let i=new Set(t.assembly.details.filter(f=>r(f.status)).map(f=>f.id)),o=t.assembly.graph,s=new zt(o.nodes().filter(f=>!i.has(f)),o.edges().filter(f=>!i.has(f.source)&&!i.has(f.target)),o.registry()),a=Ws(s,n.filter(f=>!i.has(f.id)),{now:R(),limit:t.limit??be}),{rows:c,residuals:d,overcommitted:l,...u}=a;e.deadline_schedule={population:"active",...u,...t.summary?{}:{rows:c,residuals:d,overcommitted:l}}}async function uk(e,t,n,r,i){let o=em(e,t,n);Jt(r.summary===!0,r.full===!0,"--summary");let s=O(process.cwd(),i.path);await U(s);let a=await F(s),c=L(a,D()),d=await de(s,a.item_format,c.type_to_folder,void 0,a.schema),l=J(a.schema),u=M=>j(M,l);gm(o,r);let f=z(),p=Hr(r.kind,f),m=Rn().lookup(s,Tn(d,u,f),()=>Qe(d,u,f)),h={assembly:m.assembly,...p===void 0?{}:{kinds:p},maxDepth:Dn(r.maxDepth),limit:fe(r.limit,"limit"),after:r.after?.trim()||void 0,direction:Ur(r.direction),maxPaths:fe(r.maxPaths,"max-paths"),sample:fe(r.sample,"sample"),exemptIsolates:va(r.exemptIsolate),exemptIsolateTypes:va(r.exemptIsolateType),saveBaseline:r.saveBaseline===!0,summary:r.summary===!0,unbounded:r.full===!0};if(o==="index")return ya(await _m(s,m.fingerprint,h,d.length,u,r),!1);let y=wa.has(o)?ba(h.assembly,t):void 0,b=o==="paths"?ba(h.assembly,n):void 0,v=ka(o,y,b,h),w=await Xr(s,m.fingerprint),C=w.results[v],S=m.memoize(v,()=>C!==void 0?structuredClone(C):Ea(o,y,b,h,u)),N=Zr(d.length,w.exists);!S.reused&&C===void 0&&N&&await vm(s,m.fingerprint,w,v,S.value);let $=S.value.subcommand==="audit"?await ym(s,m.fingerprint,S.value,h.saveBaseline):S.value;return $.cache={fingerprint:m.fingerprint.slice(0,12),assembly:m.assemblyReused?"hit":"miss",result:S.reused?"hit":"miss",durable:C!==void 0?"hit":N?"miss":"off"},bm($,h,d,u),ya($,h.summary,"result_rows")}import ni from"node:fs/promises";import ri from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ca035b42-148d-5a43-9912-4641a6207750")}catch{}})();var wm=8388608,km=new Set(["resolved","failed"]),Em=[{kind:"boolean",matches:e=>typeof e=="boolean"||typeof e=="string"&&/^(?:true|false)$/iu.test(e.trim())},{kind:"single_digit",matches:e=>typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=9||typeof e=="string"&&/^\d$/u.test(e.trim())}];function me(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ii(e){return Em.find(t=>t.matches(e))?.kind}function Ia(e){let t=new Map,n=0,r=0;return{entries:e.map(o=>{let s=me(o.agent_provenance)?o.agent_provenance:void 0;if(s===void 0||!Po(o).ok)return o;let a={},c=!1;for(let[l,u]of Object.entries(s)){let f=me(u)?ii(u.value):void 0;if(f===void 0){a[l]=u;continue}c=!0,r+=1;let p=o.agent_harness??"unknown",m=`${p}\0${l}\0${f}`,h=t.get(m)??{harness:p,dimension:l,kind:f,count:0};h.count+=1,t.set(m,h)}if(!c)return o;n+=1;let d={...o};return Object.keys(a).length===0?delete d.agent_provenance:d.agent_provenance=a,jo(o,d,{retainPriorRecord:!0,retainPriorRecordHash:!1})}),receipt:{changed:n>0,events_changed:n,observations_removed:r,invalid_values:[...t.values()].sort((o,s)=>o.harness.localeCompare(s.harness)||o.dimension.localeCompare(s.dimension)||o.kind.localeCompare(s.kind))}}}async function Ca(e){let t=[];for(let n of await Sa(e))try{let r=await ni.readFile(ri.join(e,"history",n),"utf8");for(let i of r.split(`
|
|
2
2
|
`)){if(i.trim().length===0)continue;let o=Ta(i);if(o===null||!me(o.agent_provenance))continue;if(Object.values(o.agent_provenance).some(a=>me(a)&&ii(a.value)!==void 0)){t.push(n.slice(0,-6));break}}}catch{}return t}async function Sa(e){try{return(await ni.readdir(ri.join(e,"history"))).filter(t=>t.endsWith(".jsonl")).sort()}catch{return[]}}async function Im(e,t,n){let r;try{r=await ni.open(ri.join(e,"history",t),"r");let i=(await r.stat()).size,o=Math.min(i,Math.max(0,n)),s=Buffer.alloc(o),{bytesRead:a}=await r.read(s,0,o,0),c=s.subarray(0,a).toString("utf8"),d=a>=i,l=c.lastIndexOf(`
|
|
3
3
|
`),u=c;return d||(u=l===-1?"":c.slice(0,l+1)),{content:u,bytesRead:a,complete:d}}catch{return null}finally{await r?.close()}}function Ta(e){try{let t=JSON.parse(e);return me(t)?t:null}catch{return null}}function Cm(e,t,n){let r=typeof e.agent_harness=="string"?e.agent_harness:void 0;if(r===void 0)return;let i=me(e.agent_provenance)?e.agent_provenance:{};if(Object.entries(i).forEach(([s,a])=>{if(!me(a))return;let c=ii(a.value);if(!c)return;let d=`${r}\0${s}\0${c}`,l=n.get(d)??{harness:r,dimension:s,kind:c,count:0};l.count+=1,n.set(d,l)}),!me(e.context))return;let o=e.context.agent_provenance_outcomes;me(o)&&Object.entries(o).forEach(([s,a])=>{if(!me(a)||typeof a.resolver!="string"||!km.has(String(a.status)))return;let c=`${r}\0${s}\0${a.resolver}`,d=t.get(c)??{harness:r,dimension:s,resolver:a.resolver,attempts:0,successes:0};d.attempts+=1,a.status==="resolved"&&(d.successes+=1),t.set(c,d)})}function Sm(e,t,n,r,i){let o=i;for(let s of e.split(`
|
|
4
4
|
`)){if(s.trim().length===0)continue;if(o>=r)return{eventsRead:o,truncated:!0};o+=1;let a=Ta(s);a&&Cm(a,t,n)}return{eventsRead:o,truncated:!1}}async function gk(e,t=1e4){let n=new Map,r=new Map,i=0,o=0,s=!1;for(let d of await Sa(e)){let l=await Im(e,d,Math.max(0,wm-o));if(l===null)continue;o+=l.bytesRead;let u=Sm(l.content,n,r,t,i);if(i=u.eventsRead,u.truncated){s=!0;break}if(!l.complete){s=!0;break}}let a=[...n.values()].sort((d,l)=>d.harness.localeCompare(l.harness)||d.dimension.localeCompare(l.dimension)||d.resolver.localeCompare(l.resolver)),c=[...r.values()].sort((d,l)=>d.harness.localeCompare(l.harness)||d.dimension.localeCompare(l.dimension)||d.kind.localeCompare(l.kind));return{outcomes:a,invalid_values:c,warnings:s?[]:[...a.filter(d=>d.attempts>0&&d.successes===0).map(d=>`provenance_resolver_zero_success:${d.harness}:${d.dimension}:${d.resolver}:${String(d.attempts)}`),...c.map(d=>`provenance_value_domain_invalid:${d.harness}:${d.dimension}:${d.kind}:${String(d.count)}`)],events_read:i,truncated:s}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a917834c-52c2-54c6-af84-a57d4c4b3855")}catch{}})();var Tm=Object.freeze({pm_item_scalar_missing:!0});function st(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.keys(e).length===1&&e.pm_item_scalar_missing===!0}function T(e){return e===void 0?Tm:e}function Te(e){return re(E(e===void 0?{pm_item_scalar_presence:"missing"}:{pm_item_scalar_presence:"present",value:e}))}function oi(e,t){let n=Be(e);if(n)throw new _(`History merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,g.GENERIC_FAILURE);let r=[];for(let[i,o]of e.split(/\r?\n/).entries()){let s=o.trim();if(s)try{let a=JSON.parse(s);if(typeof a!="object"||a===null||Array.isArray(a))throw new TypeError("history entry must be an object");r.push(a)}catch{throw new _(`History merge input (${t}) contains invalid JSON at line ${i+1}.`,g.GENERIC_FAILURE)}}return r}function we(e){return E({ts:e.ts,author:e.author,op:e.op,patch:e.patch,message:e.message??null})}function Rm(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&we(e[r])===we(t[r]);)r+=1;return r}function Sk(e,t,n){let r=oi(e,"base"),i=oi(t,"ours"),o=oi(n,"theirs"),s=[r,i,o].map(p=>p.filter(m=>m.op==="create"));if(s[0].length===0&&s.slice(1).every(p=>p.length>0)||s.some(p=>p.length>1)||new Set(s.flat().map(we)).size>1)throw new _("Duplicate item identity: history contains independent or unproven create events. Preserve both branches and assign distinct item ids before merging.",g.CONFLICT,{code:"item_identity_conflict"});let a=Rm(i,o);if(a===i.length&&a===o.length)return{merged:xe(i),strategy:"identical",common_entries:a,entries_from_ours:0,entries_from_theirs:0,entries_total:i.length,reanchored:!1};if(a===o.length)return{merged:xe(i),strategy:"fast_forward_ours",common_entries:a,entries_from_ours:i.length-a,entries_from_theirs:0,entries_total:i.length,reanchored:!1};if(a===i.length)return{merged:xe(o),strategy:"fast_forward_theirs",common_entries:a,entries_from_ours:0,entries_from_theirs:o.length-a,entries_total:o.length,reanchored:!1};let c=i.slice(a),d=new Set(c.map(we)),l=o.slice(a).filter(p=>!d.has(we(p))),u=[...c,...l].sort((p,m)=>{let h=I(p.ts,m.ts);if(h!==0)return h;let y=d.has(we(p)),b=d.has(we(m));return y!==b?Number(b)-Number(y):we(p).localeCompare(we(m))}),f=cn([...i.slice(0,a),...u],void 0,{continuousHashSurface:!0});if(f.skippedOps>0)throw new _(`History union cannot preserve ${f.skippedOps} patch operation(s) after deterministic suffix ordering; leave the file unresolved for manual recovery.`,g.GENERIC_FAILURE);return{merged:xe(f.entries),strategy:"union_reanchor",common_entries:a,entries_from_ours:c.length,entries_from_theirs:l.length,entries_total:f.entries.length,reanchored:!0}}function si(e,t){let n=Be(e);if(n)throw new _(`Relationship merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,g.GENERIC_FAILURE);let r=[];for(let[i,o]of e.split(/\r?\n/).entries()){let s=o.trim();if(!s)continue;let a;try{a=JSON.parse(s)}catch{throw new _(`Relationship merge input (${t}) contains invalid JSON at line ${i+1}.`,g.GENERIC_FAILURE)}if(typeof a!="object"||a===null||Array.isArray(a)||typeof a.eventId!="string"||typeof a.sequence!="number")throw new _(`Relationship merge input (${t}) line ${i+1} is not a relationship event (eventId + sequence required).`,g.GENERIC_FAILURE);r.push(a)}return r}function Gn(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
|
|
@@ -17,4 +17,4 @@ import{$d as Yt,$j as ce,Bi as Wo,Ci as Z,Cj as es,Df as Jt,Dh as rn,Di as Yo,E
|
|
|
17
17
|
`)}catch{o.push("workspace_memory_write_failed")}return{snapshot:c,cache_status:"rebuilt",warnings:o}}function yy(e,t,n=ud){let r=Math.max(0,Math.floor(t)),i=0,o=[];for(let s of e.rollups){if(o.length>=Math.max(0,Math.floor(n)))break;let a=Math.ceil(JSON.stringify(s).length/4);i+a>r||(o.push(s),i+=a)}return o}function md(e,t,n=ud){if(e.snapshot===null)return;let r=yy(e.snapshot,t,n);if(r.length!==0)return{cache_status:e.cache_status==="fresh"?"fresh":"rebuilt",source_cursor:e.snapshot.source_cursor,...e.snapshot.completion_time_sources?{completion_time_sources:{...e.snapshot.completion_time_sources}}:{},rollups:r}}function vy(e,t,n=5){if(e===null)return[];let r=t.trim().toLowerCase().split(/\s+/u).filter(Boolean);return r.length===0?[]:e.rollups.map(i=>({rollup:i,score:r.filter(o=>[i.key,i.label,...i.outcomes,...i.representative_items.flatMap(s=>[s.id,s.title])].join(" ").toLowerCase().includes(o)).length})).filter(({score:i})=>i>0).sort((i,o)=>o.score-i.score||o.rollup.last_closed_at.localeCompare(i.rollup.last_closed_at)||i.rollup.key.localeCompare(o.rollup.key)).slice(0,Math.max(0,Math.floor(n))).map(({rollup:i})=>i)}function fS(e,t,n=5){let r=vy(e.snapshot,t,n);if(r.length!==0)return{cache_status:e.cache_status==="fresh"?"fresh":"rebuilt",matches:r}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="05df81b3-2fbd-5d83-88e3-be300091dd09")}catch{}})();var pd=16;async function hd(e,t,n){let r=L(t,D()).type_to_folder,i=[],o=new Set,s=n;for(;s&&i.length<pd;){let a=s.trim().toLowerCase();if(!a||o.has(a))break;o.add(a);let c=await ce(e,s,t.id_prefix,t.item_format,r);if(!c)break;let d=await Se(c,{schema:t.schema});i.push(d.document.metadata.id),s=d.document.metadata.parent}return i}async function yS(e){await So({pmRoot:e.pmRoot,principal:e.principal,itemId:e.itemId,lineageIds:await hd(e.pmRoot,e.settings,e.itemId)})}async function vS(e){await To(e)}async function bS(e){await Ro({pmRoot:e.pmRoot,principal:e.principal,...e.itemId?{itemId:e.itemId,lineageIds:await hd(e.pmRoot,e.settings,e.itemId)}:{}})}var wS={lineage_depth:pd,active_items:64,evidence_rows:32};function gd(e){if(!e)return;let t={};for(let n of e.active_item_ids)t[n]=1;e.focused_item_id&&(t[e.focused_item_id]=1);for(let n of e.evidence){let r=/^lineage:(.+)$/u.exec(n)?.[1];r&&t[r]===void 0&&(t[r]=.75)}return Object.keys(t).length>0?t:void 0}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ec0faae4-1fdb-5c7c-bcf1-eb338d73958a")}catch{}})();var by=["markdown","toon","json","ndjson"],dr=new Set(["Epic","Feature"]),wd=10,kd=1e4,Ed=["hierarchy","activity","progress","recently_created","unparented","workload"],wy=[...Ed,"blockers","files","staleness","tests"],ky=/^(\d{4})-(\d{2})-(\d{2})/,Ey=/^(\d{4})(\d{2})(\d{2})(?:[T ]?\d{2}|$)/,Iy=/^(\d{4})(\d{2})(\d{2})$/,Cy=/^(\d{4})(\d{2})(\d{2})(?:[T\s]?)(\d{2})(\d{2})(\d{2})?(Z|[+-]\d{2}:?\d{2})?$/i;function Sy(e){if(!e)return;let t=e.trim().toLowerCase();if(!by.includes(t))throw new _("Context format must be one of markdown|toon|json|ndjson",g.USAGE);return t}var _d=new Set(["id","title","type","status","priority","order","deadline","assignee","tags","tags_inherited","updated_at","parent","children_total","children_closed","completion_pct","blocked","blocker_ids","created_at"]);function Ty(e){if(e===void 0)return;let t=[];for(let n of e.split(",")){let r=n.trim().toLowerCase();if(r.length!==0){if(!_d.has(r))throw new _(`Context --fields value not projectable: ${r} (valid: ${[..._d].join(", ")})`,g.USAGE);t.includes(r)||t.push(r)}}if(t.length===0)throw new _("Context --fields requires at least one field name",g.USAGE);return t}function Mt(e,t){return e.map(n=>{let r={},i=n;for(let o of t)r[o]=i[o]??null;return r})}function BS(e,t){let n=Sy(e.format);if(t.json&&n&&n!=="json"&&n!=="ndjson")throw new _("Cannot combine --json with --format markdown|toon",g.USAGE);return t.json?n==="ndjson"?"ndjson":"json":n??"toon"}function Ry(e,t){return ie(e,"--limit")??(t==="full"?Number.MAX_SAFE_INTEGER:wd)}function Qi(e,t){if(e===void 0)return t;let n=typeof e=="number"?e:Number(e);if(!Number.isInteger(n)||n<1)throw new _("--token-budget must be a positive integer",g.USAGE);return n}function xy(e,t){return t>=kd&&e===Number.MAX_SAFE_INTEGER?wd:e}function Dy(e,t){if(!e)return t.default_depth;let n=e.trim().toLowerCase();if(!_r.includes(n))throw new _(`Context --depth must be one of ${_r.join("|")}`,g.USAGE);return n}function Ay(e,t,n){if(e&&e.length>0){let i=[];for(let o of e){let s=o.trim().toLowerCase();if(!Gt.includes(s))throw new _(`Context --section must be one of ${Gt.join("|")}`,g.USAGE);i.includes(s)||i.push(s)}return i}return t==="brief"?[]:t==="full"?[...Gt]:(t==="deep"?wy:Ed).filter(i=>n.sections[i])}function Oy(e,t){return e?ie(e,"--activity-limit")??t.activity_limit:t.activity_limit}function Ly(e,t){if(!e)return t.stale_threshold_days;let n=e.trim().toLowerCase(),r=/^(\d+)d?$/.exec(n);if(!r)throw new _("--stale-threshold must be a number of days (e.g. 7 or 7d)",g.USAGE);let i=parseInt(r[1],10);if(i<=0)throw new _("--stale-threshold must be positive",g.USAGE);return i}function yd(e,t){let n=x(e,t),r=Q("blocked",t),i=Q("draft",t);return n===t.in_progress_status?0:t.active_statuses.has(n)?1:r&&n===r?2:i&&n===i?3:t.blocked_statuses.has(n)?5:t.terminal_statuses.has(n)?7:6}function Nt(e,t){let n=Q("closed",t);return x(e,t)===n}function Zi(e,t){return x(e,t)===t.in_progress_status}function Id(e,t){let n=x(e,t);return n!==t.in_progress_status&&t.active_statuses.has(n)}function Fy(e,t){return t.blocked_statuses.has(x(e,t))}var My=["compact","brief","fields","includeBody","include_body","parent"];function Ny(e){let t={...e};for(let n of My)delete t[n];return t}function eo(e,t){let n=t.trim().toLowerCase(),r=e.find(a=>a.id.trim().toLowerCase()===n);if(!r)return{ids:new Set,found:!1};let i=lt(e),o=$t(r.id,i);return{ids:new Set([r.id,...o.map(a=>a.id)].map(a=>a.trim().toLowerCase())),found:!0}}function $y(e){if(e===void 0)return;let t=e.trim();if(t.length===0)throw new _("Context --parent requires an item id",g.USAGE);return t}function Py(e,t){let n=e??null,r=t??null;return n===null&&r===null?0:n===null?1:r===null?-1:n-r}function jy(e,t){let n=e??null,r=t??null;return n===null&&r===null?0:n===null?1:r===null?-1:I(n,r)}function Uy(e,t){return new Date(Date.UTC(e,t+1,0)).getUTCDate()}function Hy(e){let t=ky.exec(e)??Ey.exec(e);if(!t)return!0;let n=Number.parseInt(t[1],10),r=Number.parseInt(t[2],10),i=Number.parseInt(t[3],10);return r>=1&&r<=12&&i>=1&&i<=Uy(n,r-1)}function By(e){let t=Iy.exec(e);if(t)return`${t[1]}-${t[2]}-${t[3]}`;let n=Cy.exec(e);if(n){let[,r,i,o,s,a,c,d]=n,l=c?`:${c}`:"",u=d&&d.length===5&&d!=="Z"?`${d.slice(0,3)}:${d.slice(3)}`:d??"";return`${r}-${i}-${o}T${s}:${a}${l}${u}`}return e}function Cd(e){if(typeof e!="string")return Number.NaN;let t=e.trim();if(t.length===0||!Hy(t))return Number.NaN;let n=Date.parse(By(t));return Number.isFinite(n)?n:Number.NaN}function Ji(e){let t=Cd(e);return Number.isFinite(t)?new Date(t).toISOString():""}function Gy(e){let t=Cd(e);return Number.isFinite(t)?new Date(t).toISOString().slice(0,10):"unknown"}function to(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function Ne(e,t,n){let r=yd(e.status,n)-yd(t.status,n);if(r!==0)return r;let i=e.priority-t.priority;if(i!==0)return i;let o=Py(e.order,t.order);if(o!==0)return o;let s=jy(e.deadline,t.deadline);if(s!==0)return s;let a=I(Ji(t.updated_at),Ji(e.updated_at)),c=e.id.localeCompare(t.id);return a!==0?a:c}function Xi(e){return Math.max(1,Math.ceil(Buffer.byteLength(JSON.stringify(e),"utf8")/4))}function no(e,t,n=new Set,r="context"){return nd(e.ranked.map(i=>({id:i.id,item:i.item,rank:i.rank,score:i.score,required:n.has(i.id),cluster:i.item.parent?.trim()||i.item.type,token_costs:{identity:Xi({id:i.id,title:i.item.title}),summary:Xi({id:i.id,title:i.item.title,type:i.item.type,status:i.item.status,priority:i.item.priority,parent:i.item.parent}),full:Xi(i.item)}})),{tokenBudget:t,profile:r,latencyBudgetMs:25})}function ro(e){return{...e,included:e.included.map(t=>({id:t.id,projection:t.projection,tokens:t.tokens}))}}function io(e,t,n){let r=n===void 0?e.ranked:e.ranked.filter(i=>n.has(i.id));return{model:e.model,available_signals:e.available_signals,items:r.map(i=>({id:i.id,rank:i.rank,baseline_rank:i.baseline_rank,score:i.score,contributions:i.contributions,...i.signal_provenance===void 0?{}:{recency:i.signal_provenance.recency}})),candidate_count:e.ranked.length,omitted_count:e.ranked.length-r.length,...t?{feature_store:{source:t.snapshot.source,cache_status:t.cache_status,source_cursor:t.snapshot.source_cursor,generated_at:t.snapshot.generated_at}}:{}}}function Sd(e,t){return t>0?Math.round(e/t*100):0}function lt(e){let t=new Map;for(let n of e){let r=to(n.parent);if(!r)continue;let i=t.get(r)??[];i.push(n),t.set(r,i)}return t}function Pt(e,t,n){let r={id:e.id,title:e.title,type:e.type,status:e.status,priority:e.priority,order:e.order??null,deadline:e.deadline??null,assignee:e.assignee??null,tags:Array.isArray(e.tags)?[...e.tags]:[],updated_at:e.updated_at,parent:to(e.parent)};if(t&&n){let i=$t(e.id,n),o=i.length;if(o>0){let s=i.filter(a=>Nt(a.status,t)).length;r.children_total=o,r.children_closed=s,r.completion_pct=Sd(s,o)}}return r}function Ky(e){let t=0,n=0,r=0,i=new Set;for(let o of e){if(i.add(o.item_id),o.kind==="deadline"){t+=1;continue}if(o.kind==="reminder"){n+=1;continue}r+=1}return{events:e.length,items:i.size,deadlines:t,reminders:n,scheduled:r}}function lr(...e){return[...new Set(e.flatMap(t=>t??[]))].sort((t,n)=>t.localeCompare(n))}function zy(e,t){return e.filter(n=>!t.terminal_statuses.has(x(n.item_status,t)))}function Vy(e,t,n,r){let i=new Map;for(let c of e)i.set(c.id,c);let o=lt(e),s=new Set(t.filter(c=>dr.has(c.type)).map(c=>c.id)),a=[];for(let c of s){let d=i.get(c);if(!d)continue;let l=$t(c,o),u=o.get(c)??[],f=0,p=0,m=0,h=0;for(let b of l)Nt(b.status,n)?f++:Zi(b.status,n)?m++:Fy(b.status,n)?h++:Id(b.status,n)&&p++;let y=u.sort((b,v)=>Ne(b,v,n)).slice(0,r).map(b=>{let v=$t(b.id,o),w=v.filter(C=>Nt(C.status,n)).length;return{id:b.id,title:b.title,type:b.type,status:b.status,children_total:v.length,children_closed:w}});a.push({id:d.id,title:d.title,type:d.type,status:d.status,children_total:l.length,children_closed:f,children_open:p,children_in_progress:m,children_blocked:h,children:y})}return a.sort((c,d)=>{let l=i.get(c.id),u=i.get(d.id);return Ne(l,u,n)}).slice(0,r)}function $t(e,t){let n=[],r=[e],i=new Set;for(;r.length>0;){let o=r.pop();if(i.has(o))continue;i.add(o);let s=t.get(o)??[];for(let a of s)n.push(a),r.push(a.id)}return n}async function qy(e,t){return(await vs({compact:!0,limit:String(e)},t)).compact_activity??[]}function Wy(e,t,n,r,i){let o=new Map;for(let c of e){if(!c.parent)continue;let d=o.get(c.parent)??[];d.push(c),o.set(c.parent,d)}let s=t.filter(c=>dr.has(c.type)),a=[];for(let c of s){let d=$t(c.id,o),l=d.length;if(l===0)continue;let u=0,f=0,p=0,m=0;for(let h of d)Nt(h.status,r)?u++:n.has(h.id.trim().toLowerCase())?m++:Zi(h.status,r)?p++:Id(h.status,r)&&f++;a.push({id:c.id,title:c.title,type:c.type,total:l,closed:u,open:f,in_progress:p,blocked:m,completion_pct:Sd(u,l)})}return a.sort((c,d)=>c.completion_pct-d.completion_pct).slice(0,i)}function Yy(e,t,n,r){let i=new Map(t.map(o=>[o.id.trim().toLowerCase(),o]));return e.slice(0,r).map(o=>{let s=tr(o,i,n),a=s.find(d=>!d.resolved)?.id??s[0]?.id??null,c=a?i.get(a.trim().toLowerCase()):void 0;return{id:o.id,title:o.title,blocked_by:a,blocked_by_title:c?.title??null,blocked_by_status:c?.status??null,blocked_reason:o.blocked_reason??null,unblock_note:o.unblock_note??null}})}function Xy(e,t){let n=new Map;for(let r of e)for(let i of r.files??[]){let o=n.get(i.path)??new Set;o.add(r.id),n.set(i.path,o)}return[...n.entries()].map(([r,i])=>({path:r,references:i.size,items:[...i].sort()})).sort((r,i)=>i.references-r.references).slice(0,t)}function Jy(e,t,n){let r=new Map;for(let i of e){let o=i.assignee??null,s=r.get(o)??[];s.push(i),r.set(o,s)}return[...r.entries()].map(([i,o])=>({assignee:i,active:o.length,in_progress:o.filter(s=>Zi(s.status,t)).length,items:o.map(s=>s.id).sort()})).sort((i,o)=>o.active-i.active).slice(0,n)}function Qy(e,t,n,r){let i=new Date(n).getTime()-t*24*60*60*1e3;return e.filter(o=>new Date(o.updated_at).getTime()<i).map(o=>({id:o.id,title:o.title,status:o.status,updated_at:o.updated_at,stale_days:Math.floor((new Date(n).getTime()-new Date(o.updated_at).getTime())/(1440*60*1e3))})).sort((o,s)=>s.stale_days-o.stale_days).slice(0,r)}function Zy(e,t,n,r){return e.map(i=>({item:i,sortKey:Ji(i.created_at)})).sort((i,o)=>{let s=I(o.sortKey,i.sortKey);return s!==0?s:i.item.id.localeCompare(o.item.id)}).slice(0,r).map(({item:i})=>({...Pt(i,t,n),created_at:i.created_at}))}function ev(e,t,n,r){return e.filter(i=>!to(i.parent)&&!dr.has(i.type)).sort((i,o)=>Ne(i,o,t)).slice(0,r).map(i=>Pt(i,t,n))}function tv(e){let t=0,n=0,r=0,i=0,o=0,s=[];for(let a of e){(a.tests??[]).length>0&&t++;let c=a.test_runs??[];if(c.length>0){n++;let d=!1;for(let l of c)r+=l.passed??0,i+=l.failed??0,o+=l.skipped??0,(l.failed??0)>0&&(d=!0);d&&s.push(a.id)}}return{items_with_tests:t,items_with_recent_runs:n,recent_runs:{passed:r,failed:i,skipped:o},items_failing:s.sort()}}function vd(e){return`${new Date(e).toISOString().slice(11,16)}Z`}function Td(e){let t=e.order===null?"-":String(e.order),n=e.deadline??"-",r=e.parent?` parent:${e.parent}`:"",i=e.children_total!==void 0&&e.children_closed!==void 0&&e.completion_pct!==void 0?` children:${e.children_closed}/${e.children_total} done:${e.completion_pct}%`:"",o=e.blocked===!0?` blocked:${e.blocker_ids?.join(",")||"lifecycle"}`:"";return`${e.id} p${e.priority} ${e.status} ${e.type} order:${t} deadline:${n}${r}${i}${o} ${e.title}`}function nv(e,t){let n=e;return t.map(r=>{let i=n[r];return Array.isArray(i)?`${r}:${i.join(",")}`:`${r}:${i??"-"}`}).join(" ")}function rv(e){if("reference_only"in e){let n=e.kind==="reminder"?` \u2014 ${e.reminder_text??"reminder"}`:e.kind==="event"?` \u2014 ${e.event_title??"event"}${e.event_recurring?" (recurring)":""}`:"";return`${vd(e.at)} [${e.kind}] ${e.item_id} (see focus item)${n}`}let t=`${vd(e.at)} [${e.kind}] ${e.item_id} p${e.item_priority} ${e.item_status} ${e.item_title}`;if(e.kind==="reminder")return`${t} \u2014 ${e.reminder_text}`;if(e.kind==="event"){let n=e.event_recurring?" (recurring)":"",r=e.event_title??e.item_title;return`${t} \u2014 ${r}${n}`}return t}function bd(e,t,n,r,i){if(e.push(`## ${t}`),n.length===0)e.push(r);else for(let o of n)e.push(`- ${i(o)}`);e.push("")}function iv(e,t,n){if(t.blocked_fallback.length!==0){e.push("## Blocked fallback");for(let r of t.blocked_fallback)e.push(`- ${n(r)}`);e.push("")}}function ov(e,t){if(e.push("## Agenda"),e.push(`- events: ${t.agenda.summary.events} (deadlines: ${t.agenda.summary.deadlines}, reminders: ${t.agenda.summary.reminders}, scheduled: ${t.agenda.summary.scheduled})`),t.agenda.events.length===0)e.push("No agenda events matched the selected filters.");else for(let n of t.agenda.events)e.push(`- ${rv(n)}`);e.push("")}function sv(e,t){if(!(!t.hierarchy||t.hierarchy.length===0)){e.push("## Hierarchy");for(let n of t.hierarchy){let r=n.children_total>0?Math.round(n.children_closed/n.children_total*100):0;e.push(`- ${n.id} ${n.type} ${n.status} "${n.title}" [${n.children_closed}/${n.children_total} done ${r}%]`);for(let i of n.children){let o=i.children_total>0?Math.round(i.children_closed/i.children_total*100):0;e.push(` - ${i.id} ${i.type} ${i.status} "${i.title}" [${i.children_closed}/${i.children_total} done ${o}%]`)}}e.push("")}}function av(e,t){if(!(!t.progress||t.progress.length===0)){e.push("## Progress");for(let n of t.progress)e.push(`- ${n.id} "${n.title}" ${n.completion_pct}% (${n.closed}/${n.total} closed, ${n.in_progress} wip, ${n.open} open, ${n.blocked} blocked)`);e.push("")}}function cv(e,t,n,r){if(!(!t.recently_created||t.recently_created.length===0)){e.push("## Recently created");for(let i of t.recently_created)e.push(n?`- ${r(i)}`:`- ${Gy(i.created_at)} ${Td(i)}`);e.push("")}}function dv(e,t,n){if(!(!t.unparented||t.unparented.length===0)){e.push("## Unparented");for(let r of t.unparented)e.push(`- ${n(r)}`);e.push("")}}function lv(e,t){if(!(!t.activity||t.activity.length===0)){e.push("## Recent activity");for(let n of t.activity){let r=n.msg?` ${n.msg}`:"";e.push(`- ${n.ts.slice(0,16)}Z ${n.id} ${n.op} by:${n.author}${r}`)}e.push("")}}function uv(e,t){if(!(!t.blockers||t.blockers.length===0)){e.push("## Blockers");for(let n of t.blockers){let r=n.blocked_by?`blocked_by:${n.blocked_by}(${n.blocked_by_status??"?"})`:"blocked_by:-",i=n.blocked_reason?` reason:"${n.blocked_reason}"`:"",o=n.unblock_note?` unblock:"${n.unblock_note}"`:"";e.push(`- ${n.id} "${n.title}" ${r}${i}${o}`)}e.push("")}}function fv(e,t){if(!(!t.files||t.files.length===0)){e.push("## Hot files");for(let n of t.files)e.push(`- ${n.path} refs:${n.references} items:[${n.items.join(",")}]`);e.push("")}}function mv(e,t){if(!(!t.workload||t.workload.length===0)){e.push("## Workload");for(let n of t.workload){let r=n.assignee??"(unassigned)";e.push(`- ${r} active:${n.active} wip:${n.in_progress} items:[${n.items.join(",")}]`)}e.push("")}}function pv(e,t){if(!(!t.staleness||t.staleness.length===0)){e.push("## Stale items");for(let n of t.staleness)e.push(`- ${n.id} ${n.status} stale:${n.stale_days}d last:${n.updated_at.slice(0,10)} "${n.title}"`);e.push("")}}function hv(e,t){t.tests&&(e.push("## Test health"),e.push(`- items_with_tests: ${t.tests.items_with_tests}`),e.push(`- items_with_recent_runs: ${t.tests.items_with_recent_runs}`),e.push(`- passed: ${t.tests.recent_runs.passed}, failed: ${t.tests.recent_runs.failed}, skipped: ${t.tests.recent_runs.skipped}`),t.tests.items_failing.length>0&&e.push(`- items_failing: [${t.tests.items_failing.join(",")}]`),e.push(""))}function gv(e,t){t.summary.active_items===0&&t.summary.blocked===0&&t.agenda.summary.events===0&&(e.push("## Suggestions"),e.push("No active work items or upcoming events. Consider:"),e.push('- `pm create --type Task --title "..."` to add a new work item'),e.push("- `pm list --status closed --limit 5` to review recent completions"),e.push("- `pm search <keywords>` to find related past work"),e.push("- `pm aggregate` for a full project status overview"))}function GS(e){let t=[],n=e.focus_fields,r=o=>n?nv(o,n):Td(o);if(t.push("# pm context"),t.push(""),t.push(`- now: ${e.now}`),t.push(`- depth: ${e.depth}`),e.filters.parent&&t.push(`- scope: subtree of ${e.filters.parent}`),t.push(`- active_items: ${e.summary.active_items} (in_progress: ${e.summary.in_progress}, open: ${e.summary.open})`),e.summary.total_items!==void 0&&t.push(`- total_items: ${e.summary.total_items} (closed: ${e.summary.closed??0}, canceled: ${e.summary.canceled??0})`),t.push(`- agenda_events: ${e.summary.agenda_events}`),t.push(`- blocked_fallback_used: ${e.summary.blocked_fallback_used}`),e.extension_health){let o=e.extension_health.packages.filter(s=>s.status==="degraded").map(s=>s.name);t.push(`- extensions: ${e.extension_health.ok} ok, ${e.extension_health.degraded} degraded${o.length>0?` (${o.join(", ")})`:""}`)}let i=e.sections_included.filter(o=>o!=="blockers"||(e.blockers?.length??0)>0);if(i.length>0&&t.push(`- sections: ${i.join(", ")}`),t.push(""),bd(t,"High-level focus",e.high_level,"No high-level active items.",r),bd(t,"Low-level focus",e.low_level,"No low-level active items.",r),iv(t,e,r),ov(t,e),e.workspace_memory){t.push("## Workspace memory");for(let o of e.workspace_memory.rollups)t.push(`- ${o.kind}:${o.key} \u2014 ${o.label} (${o.item_count} completed, latest ${o.last_closed_at})`);t.push("")}return sv(t,e),av(t,e),cv(t,e,n,r),dv(t,e,r),lv(t,e),uv(t,e),fv(t,e),mv(t,e),pv(t,e),hv(t,e),gv(t,e),t.join(`
|
|
18
18
|
`)}async function _v(e,t){let n=O(process.cwd(),t.path),r=await F(n),i=r.context??lo.context,o=J(r.schema),s=Dy(e.depth,i),a=Ry(e.limit??e.maxItems,s);return{settings:r,contextSettings:i,statusRegistry:o,depth:s,limit:a,sectionsIncluded:Ay(e.section,s,i),activityLimit:Oy(e.activityLimit,i),staleThresholdDays:Ly(e.staleThreshold,i),parentScope:$y(e.parent),focusFields:Ty(e.fields),baseListOptions:Ny(e)}}function yv(e){return e.some(t=>["hierarchy","progress","blockers","staleness","recently_created","unparented"].includes(t))}function vv(e,t){return{...e,...t,noTruncate:!0,limit:void 0,offset:void 0,after:void 0}}async function bv(e,t){let n=await At(void 0,vv(t.baseListOptions,{excludeTerminal:!1}),e),r=n.items,i=r.filter(a=>!j(a.status,t.statusRegistry)),o=r,s=wv(t.parentScope,r);return s&&(i=i.filter(a=>s.has(a.id.trim().toLowerCase())),o=o.filter(a=>s.has(a.id.trim().toLowerCase()))),{listed:n,listedItemMetadata:i,allItems:o,fullCorpus:r,subtreeIds:s}}function wv(e,t){if(e===void 0)return;let n=eo(t,e);if(!n.found)throw new _(`Context --parent item not found: ${e}`,g.NOT_FOUND);return n.ids}function kv(e,t,n,r){let i=new Set(Tt(e,t,n,r).containers.map(o=>o.item.id));return new Set(e.filter(o=>dr.has(o.type)||i.has(o.id)||Re(o.type,r)!=="agent").map(o=>o.id))}async function Ev(e,t,n,r,i,o,s,a,c,d,l,u,f,p,m,h){let y=[...e].sort((k,Pe)=>Ne(k,Pe,i)),b=await rn({pmRoot:f,author:c,enabled:process.env.PM_CONTEXT_USAGE_DISABLED!=="1"}),v=await cr(y,{pmRoot:f,storeKey:"context",statusRegistry:i,now:a,author:c,usageAffinity:b.affinity,claimFocus:m}),w=await ar("context",v.candidates),C=w.ranked.map(k=>k.item),S=i.active_statuses,N=C.filter(k=>S.has(x(k.status,i))),$=u?ze(N,d,l,k=>k.id):0,M=u?N.slice($,$+s):N,Ee=u&&M.length>0&&$+M.length<N.length,P=Ee&&M.length>0?ae(l,M[M.length-1].id,$+M.length-1):void 0,te=C.filter(k=>r.has(k.id.trim().toLowerCase())),V=new Set([...M.map(k=>k.id),...te.slice(0,s).map(k=>k.id)]),Y=no({...w,ranked:w.ranked.filter(k=>V.has(k.id))},p,new Set(Object.entries(m??{}).filter(([,k])=>k>=1).map(([k])=>k))),he=Y.included.map(k=>k.item),X=he.filter(k=>S.has(x(k.status,i))),q=he.filter(k=>r.has(k.id.trim().toLowerCase())),ut=lt(t),$e=yv(o)?ut:void 0,fr=new Map(n.map(k=>[k.id.trim().toLowerCase(),k])),H=k=>{let Pe=Pt(k,i,$e);return r.has(k.id.trim().toLowerCase())&&(Pe.blocked=!0,Pe.blocker_ids=tr(k,fr,i).filter(mr=>!mr.resolved).map(mr=>mr.id)),Pe},G=kv(X,n,i,h),Hd=X.filter(k=>G.has(k.id)).slice(0,u?M.length:s).map(H),Bd=X.filter(k=>!G.has(k.id)).slice(0,u?M.length:s).map(H),ao=N.length===0;return{activeItems:X,blockedItems:q,highLevel:Hd,lowLevel:Bd,blockedFallback:ao?q.slice(0,s).map(H):[],blockedFallbackUsed:ao,ranking:w,packing:Y,featureStore:v,pageExtras:{...u?{applied_limit:s}:{},...Ee?{has_more:!0,truncated:!0}:{},...P?{next_cursor:P}:{}}}}function Iv(e){return Ie("context",Qt(e,cs))}function Cv(e,t){return e.limit!==void 0||e.maxItems!==void 0||e.after!==void 0||t>=kd}async function Sv(e,t,n,r){let i={...t.baseListOptions,view:"agenda",include:"all",limit:t.parentScope===void 0?String(t.limit):void 0},o=await Jc(i,e),s=n===void 0?o.events:o.events.filter(d=>n.has(d.item_id.trim().toLowerCase())),a=zy(s,t.statusRegistry).slice(0,t.limit),c=a.map(d=>r.has(d.item_id)?{at:d.at,date:d.date,kind:d.kind,item_id:d.item_id,reference_only:!0,...d.kind==="reminder"?{reminder_text:d.reminder_text}:{},...d.kind==="event"?{event_title:d.event_title,event_recurring:d.event_recurring}:{}}:d);return{agenda:o,agendaEvents:c,agendaSummary:Ky(a)}}function Rd(e,t,n){let r=String(t);return e.filter(i=>x(i.status,n)===r).length}async function Tv(e){let{runtime:t,allItems:n,fullCorpus:r,blockedIds:i,focusGroups:o,now:s,global:a}=e,c=lt(n),d=n.filter(u=>!j(u.status,t.statusRegistry)),l=u=>t.sectionsIncluded.includes(u);return{hierarchy:l("hierarchy")?Vy(n,o.activeItems,t.statusRegistry,t.limit):void 0,activity:l("activity")?await qy(t.activityLimit,a):void 0,progress:l("progress")?Wy(n,o.activeItems,i,t.statusRegistry,t.limit):void 0,blockersSection:l("blockers")?Yy(o.blockedItems,r,t.statusRegistry,t.limit):void 0,recentlyCreated:l("recently_created")?Zy(d,t.statusRegistry,c,t.limit):void 0,unparented:l("unparented")?ev(d,t.statusRegistry,c,t.limit):void 0,filesSection:l("files")?Xy(o.activeItems,t.limit):void 0,workload:l("workload")?Jy(o.activeItems,t.statusRegistry,t.limit):void 0,staleness:l("staleness")?Qy(d,t.staleThresholdDays,s,t.limit):void 0,tests:l("tests")?tv(o.activeItems):void 0}}function Rv(e,t,n){let r=Q("canceled",t),i=e.filter(s=>t.active_statuses.has(x(s.status,t))),o=Rd(i,t.in_progress_status,t);return{scope:"matching_items",active_items:i.length,open:i.length-o,in_progress:o,blocked:e.filter(s=>n.has(s.id.trim().toLowerCase())).length,total_items:e.length,closed:e.filter(s=>Nt(s.status,t)).length,canceled:e.filter(s=>x(s.status,t)===r).length}}function xv(e,t,n){t.hierarchy&&(e.hierarchy=t.hierarchy),t.activity&&(e.activity=t.activity),t.progress&&(e.progress=t.progress),t.blockersSection&&(e.blockers=t.blockersSection),t.recentlyCreated&&(e.recently_created=t.recentlyCreated),t.unparented&&(e.unparented=t.unparented),t.filesSection&&(e.files=t.filesSection),t.workload&&(e.workload=t.workload),t.staleness&&(e.staleness=t.staleness),t.tests&&(e.tests=t.tests),n!==void 0&&n.length>0&&(e.warning_details=n)}function Dv(e,t){t&&(e.focus_fields=t,e.high_level=Mt(e.high_level,t),e.low_level=Mt(e.low_level,t),e.blocked_fallback=Mt(e.blocked_fallback,t),e.recently_created&&(e.recently_created=Mt(e.recently_created,t)),e.unparented&&(e.unparented=Mt(e.unparented,t)))}function Av(e,t){let n=[e.high_level,e.low_level,e.blocked_fallback,e.recently_created??[],e.unparented??[]].flat();if(t){for(let o of n)delete o.tags,delete o.tags_inherited;return}let r=new Map(n.map(o=>[o.id,o])),i=new Map(n.map(o=>[o.id,o.tags?[...o.tags].sort().join("\0"):void 0]));for(let o of n){if(!o.parent||!o.tags)continue;let s=r.get(o.parent);s&&i.get(o.id)===i.get(s.id)&&(delete o.tags,o.tags_inherited=s.id)}}function Ov(e,t,n){t.length>0||n.length>0||e.agenda.events.length>0||(e.suggestions=['pm create --type Task --title "..." to add a new work item',"pm list --status closed --limit 5 to review recent completions","pm search <keywords> to find related past work","pm aggregate for a full project status overview"])}async function Lv(e,t,n,r){try{let i=new Set(t.packing.included.map(c=>c.id)),o=t.ranking.ranked.map(c=>({id:c.id,rank:c.rank,included:i.has(c.id)})),s=new Set(o.map(c=>c.id));for(let c of tn(e,"context"))s.has(c)||(o.push({id:c,rank:o.length+1,included:!1}),s.add(c));let a=await nn({pmRoot:n,author:r,surface:"context",profile:t.packing.profile,rows:o,enabled:process.env.PM_CONTEXT_USAGE_DISABLED!=="1"});en(e,a)}catch{e.warnings=lr(e.warnings,["context_usage_feedback_write_failed"])}}async function Fv(e,t,n){if(e)return{};let i=(await _o({pmRoot:t,settings:n,cwd:process.cwd(),noExtensions:!1})).discovered.map(s=>({name:s.name??s.directory,status:s.status==="ok"?"ok":"degraded"})).sort((s,a)=>s.name.localeCompare(a.name)),o=i.filter(s=>s.status==="degraded").length;return i.length===0?{}:{extension_health:{total:i.length,ok:i.length-o,degraded:o,packages:i.slice(0,20),...i.length>20?{truncated:!0}:{}}}}async function Mv(e,t){let n=xo(),r=await Io(e),i=n.instance||Co(t);return gd(r.semantic_attribution?.[i])}async function KS(e,t){let n=O(process.cwd(),t.path),r=await _v(e,t),i=await bv(t,r),o=xy(r.limit,i.fullCorpus.length),s={...r,limit:o,tokenBudget:Qi(e.tokenBudget,Math.max(256,o*160))},a=ve(void 0,s.settings.author_default),c=await Mv(n,a),d=Fv(e.noExtensionHealth===!0,n,s.settings),l=St(i.fullCorpus,s.statusRegistry),u=await Ev(i.listedItemMetadata,i.allItems,i.fullCorpus,l,s.statusRegistry,s.sectionsIncluded,s.limit,R(),a,e.after,Iv(e),Cv(e,i.fullCorpus.length),n,s.tokenBudget,c,L(s.settings,D())),f=await Sv(t,s,i.subtreeIds,new Set([...u.highLevel,...u.lowLevel,...u.blockedFallback].map(C=>C.id))),p=await fd(i.fullCorpus,{pmRoot:n,statusRegistry:s.statusRegistry,now:f.agenda.now}),m=lr(i.listed.warnings,f.agenda.warnings,u.ranking.warnings,[...u.featureStore.warnings],p.warnings),h=Rd(u.activeItems,s.statusRegistry.in_progress_status,s.statusRegistry),y=u.activeItems.length-h,b=await Tv({runtime:s,allItems:i.allItems,fullCorpus:i.fullCorpus,blockedIds:l,focusGroups:u,now:f.agenda.now,global:t}),v=Rv(i.allItems,s.statusRegistry,l),w={output_default:"toon",now:f.agenda.now,depth:s.depth,sections_included:s.sectionsIncluded,window:{anchor:f.agenda.anchor,start:f.agenda.range.start,end:f.agenda.range.end,past:f.agenda.range.past,from:f.agenda.range.from,to:f.agenda.range.to},filters:{type:e.type??null,tag:e.tag??null,priority:e.priority??null,assignee:e.assignee??null,assignee_filter:e.assigneeFilter??null,sprint:e.sprint??null,release:e.release??null,limit:e.limit??e.maxItems??null,parent:s.parentScope??null,token_budget:s.tokenBudget,runtime_filters:i.listed.filters.runtime_filters??f.agenda.filters.runtime_filters??{}},summary:{returned_focus:{active_items:u.activeItems.length,in_progress:h,open:y,blocked:u.blockedItems.length},blocked_fallback_used:u.blockedFallbackUsed,high_level:u.highLevel.length,low_level:u.lowLevel.length,agenda_events:f.agendaSummary.events,...v},high_level:u.highLevel,low_level:u.lowLevel,blocked_fallback:u.blockedFallback,agenda:{summary:f.agendaSummary,events:f.agendaEvents},...u.pageExtras};return w.workspace_memory=md(p,Math.min(800,Math.floor(s.tokenBudget*.2))),Object.assign(w,await d),xv(w,b,u.featureStore.warning_details),Av(w,e.noTags===!0),e.explainRanking===!0&&(w.ranking=io(u.ranking,u.featureStore,new Set([...u.highLevel,...u.lowLevel,...u.blockedFallback].map(C=>C.id))),w.packing=ro(u.packing)),Dv(w,s.focusFields),m.length>0&&(w.warnings=m),Ov(w,u.activeItems,u.blockedItems),await Lv(w,u,n,a),w}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="045ff474-f6d9-50c5-b554-ebc947a52443")}catch{}})();var Nv=["markdown","toon","json"],$v=5,Pv=1440*60*1e3;function jv(e){if(!e)return;let t=e.trim().toLowerCase();if(!Nv.includes(t))throw new _("Next format must be one of markdown|toon|json",g.USAGE);return t}function tT(e,t){let n=jv(e.format);if(t.json&&n&&n!=="json")throw new _("Cannot combine --json with --format markdown|toon",g.USAGE);return t.json?"json":n??"toon"}function xd(e,t,n){let r=ie(e,t);return r===void 0||r<=0?n:r}function jt(e,t,n,r){return{...Pt(e.item,t,n),open_blocker_count:e.open_blockers.length,blockers:e.open_blockers.map(i=>({id:i.id,title:i.title,status:i.status,...i.external?{external:!0}:{},...i.blocked_since?{blocked_since:i.blocked_since}:{},...i.external?{resolver:i.resolver??null}:{}})),unblocks:e.unblocks,rank:r}}function Uv(e,t,n,r){let i=e.item,o=[],s=Q("in_progress",t);return o.push(x(i.status,t)===s?"in progress \u2014 resume to finish":"open and ready to start"),r&&o.push("completed container \u2014 governance closeout"),o.push(`priority p${i.priority}${i.priority===0?" (highest)":""}`),typeof i.deadline=="string"&&i.deadline.trim().length>0&&o.push(Hv(i.deadline,n)),o.push(Le(i).length>0?"all blockers resolved":"no blockers"),typeof i.parent=="string"&&i.parent.trim().length>0&&o.push(`advances ${i.parent.trim()}`),e.unblocks.length>0&&o.push(`unblocks ${e.unblocks.length} item(s)`),o}function Dd(e,t,n){let r=ve(n,t),i=[],o=[];for(let s of e){let a=typeof s.item.assignee=="string"?s.item.assignee.trim():"";a.length>0&&a!==r?o.push({id:s.item.id,assignee:a}):i.push(s)}return{available:i,held:o}}var nT={partitionCallerOwnedReady:Dd,resolveNextCallerAuthor:(e,t)=>Ad(e,t)};function rT(e,t,n){let r=e.filter(i=>Re(i.item.type,n)==="human");return{agent:t?e:e.filter(i=>Re(i.item.type,n)!=="human"),decisions:t?[]:r}}function Hv(e,t){let n=Date.parse(e);if(!Number.isFinite(n))return`deadline ${e.trim()}`;let r=new Date(n).toISOString().slice(0,10),i=new Date(Date.parse(t)).toISOString().slice(0,10),o=Math.round((Date.parse(r)-Date.parse(i))/Pv);return o<0?`deadline ${r} (overdue ${-o}d)`:o===0?`deadline ${r} (due today)`:`deadline ${r} (in ${o}d)`}function Bv(e,t){let n=Q("in_progress",t);return e.filter(r=>x(r.status,t)===n).length}function oo(e,t){return(t.get(e.id.trim().toLowerCase())??[]).length>0}function Gv(e,t){return{type:e.type,tag:e.tag,priority:typeof e.priority=="number"?String(e.priority):e.priority,assignee:e.assignee,assigneeFilter:e.assigneeFilter,sprint:e.sprint,release:e.release,noTruncate:!0,...t}}function ur(e,t,n){return[...e].sort((r,i)=>{let o=oo(r.item,t),s=oo(i.item,t);return o!==s?Number(o)-Number(s):Ne(r.item,i.item,n)})}function Kv(e){return e.projectedReady.length===0?null:{...e.readyRows[0],reasons:Uv(e.projectedReady[0],e.statusRegistry,e.now,e.completedContainer)}}function zv(e,t,n){if(e!==null)return;let r=n>0?["No executable recommendation: outcome gates require verification. Inspect gate_needed, or use pm next --include-gates to opt in."]:[];if(t.length>0){let i=t.find(o=>o.blockers.length>0);return[...r,i?`${t.length} item(s) are blocked; unblock the top one by closing ${i.blockers.map(o=>o.id).join(", ")}`:`${t.length} item(s) are blocked; add blocker context or move the top item back to an active status`,"pm next --ready-only after a blocker closes to re-check ready work",'pm create --type Task --title "..." to add new ready work']}return[...r,'pm create --type Task --title "..." to add a new work item',"pm list --status in_progress to review work already underway","pm context --depth deep for the full project snapshot"]}function Vv(e,t,n){let r={};return e>n&&(r.decision_needed_total=e),t>n&&(r.held_by_others_total=t),Object.keys(r).length>0?r:void 0}async function qv(e){try{let t=new Set(e.packing.included.map(o=>o.id)),n=e.ranking.ranked.map(o=>({id:o.id,rank:o.rank,included:t.has(o.id)})),r=new Set(n.map(o=>o.id));for(let o of tn(e.result,"next"))r.has(o)||(n.push({id:o,rank:n.length+1,included:!1}),r.add(o));let i=await nn({pmRoot:e.pmRoot,author:e.author,surface:"next",profile:e.packing.profile,rows:n,enabled:process.env.PM_CONTEXT_USAGE_DISABLED!=="1"});en(e.result,i)}catch{e.result.warnings=lr(e.result.warnings,["context_usage_feedback_write_failed"])}}async function Wv(e){let t=[...new Set([...e.candidatesWarnings??[],...e.corpusWarnings??[],...e.readyRanking.warnings??[],...e.featureStore.warnings])].sort((n,r)=>n.localeCompare(r));return t.length>0&&(e.result.warnings=t),e.explainRanking&&(e.result.ranking=io(e.readyRanking,e.featureStore),e.result.packing=ro(e.packing)),e.result.suggestions=zv(e.recommended,e.blockedRows,e.gateCount),await qv({result:e.result,pmRoot:e.pmRoot,author:e.author,packing:e.packing,ranking:e.readyRanking}),e.result}function Yv(e,t,n){if(!n)return e;let r=eo(t,n);if(!r.found)throw new _(`Next --parent item not found: ${n}`,g.NOT_FOUND);return e.filter(i=>r.ids.has(i.id.trim().toLowerCase()))}async function Xv(e,t,n,r,i,o,s,a){let c=e.filter(y=>!oo(y.item,t)),d=a||c.length===0?e:c,l=await rn({pmRoot:o,author:i,enabled:process.env.PM_CONTEXT_USAGE_DISABLED!=="1"}),u=await cr(d.map(y=>y.item),{pmRoot:o,storeKey:"next",statusRegistry:n,now:r,author:i,usageAffinity:l.affinity}),f=await ar("next",u.candidates),p=no(f,s,new Set,"next"),m=new Map(d.map(y=>[y.item.id,y]));return{projectedReady:f.ranked.map(y=>m.get(y.id)).filter(y=>y!==void 0),ranking:f,completedContainer:c.length===0&&!a,packing:p,featureStore:u}}function Ad(e,t){let n=e.assignee?.trim();return ve(e.callerAuthor??(n&&n.length>0?n:void 0),t)}async function iT(e,t){let n=O(process.cwd(),t.path),r=await F(n),i=Ad(e,r.author_default),o=J(r.schema),s=L(r,D()),a=R(),c=xd(e.limit,"--limit",$v),d=Qi(e.tokenBudget,Math.max(192,c*128)),l=xd(e.blockedLimit,"--blocked-limit",c),u=e.readyOnly===!0,f=typeof e.parent=="string"?e.parent.trim():"",p=await At(void 0,Gv(e,{excludeTerminal:!0}),t),m=await At(void 0,{excludeTerminal:!1,noTruncate:!0},t),h=Yv(p.items,m.items,f),y=m.items,b=Tt(h,y,o,s),v=lt(y),w=Ti(b,o,e,s),C=Dd(w.ready,r.author_default,i),S=ur(C.available,v,o),N=[...b.blocked].sort((H,G)=>Ne(H.item,G.item,o)),{projectedReady:$,ranking:M,completedContainer:Ee,packing:P,featureStore:te}=await Xv(S,v,o,a,i,n,d,e.includeContainers===!0),V=$.map((H,G)=>jt(H,o,v,G+1)),Y=N.map((H,G)=>jt(H,o,v,G+1)),he=ur(w.decisions,v,o).map((H,G)=>jt(H,o,v,G+1)),X=ur(w.gates,v,o).map((H,G)=>jt(H,o,v,G+1)),q=ur(b.containers,v,o).map((H,G)=>jt(H,o,v,G+1)),ut=Kv({projectedReady:$,readyRows:V,statusRegistry:o,now:a,completedContainer:Ee}),$e=Vv(he.length,C.held.length,c)??{};X.length>c&&($e.gate_needed_total=X.length),q.length>c&&($e.containers_total=q.length);let fr={output_default:"toon",now:a,recommended:ut,ready:V.slice(1,c+1),decision_needed:he.slice(0,c),gate_needed:X.slice(0,c),containers:q.slice(0,c),blocked:u?[]:Y.slice(0,l),held_by_others:C.held.slice(0,c),summary:{recommended:ut!==null,ready:V.length,blocked:Y.length,in_progress:Bv(V,o),candidates:b.active_count,containers:b.container_count,decision_needed:he.length,gate_needed:X.length,held_by_others:C.held.length},filters:{type:e.type??null,tag:e.tag??null,priority:e.priority??null,assignee:e.assignee??null,assignee_filter:e.assigneeFilter??null,sprint:e.sprint??null,release:e.release??null,parent:f.length>0?f:null,limit:c,blocked_limit:l,ready_only:u,include_decisions:e.includeDecisions===!0,include_gates:e.includeGates===!0,include_containers:e.includeContainers===!0,token_budget:d},truncation:Object.keys($e).length>0?$e:void 0};return Wv({result:fr,recommended:ut,blockedRows:Y,gateCount:X.length,candidatesWarnings:p.warnings,corpusWarnings:m.warnings,readyRanking:M,explainRanking:e.explainRanking===!0,pmRoot:n,author:i,packing:P,featureStore:te})}function oT(e){let t=["# pm next","",...Jv(e)];for(let[n,r]of[["Gate verification needed",e.gate_needed],["Containers",e.containers]])r&&r.length>0&&t.push(...Ut(n,r.map(i=>`- ${Ht(i)}`),""));if(t.push(...Ut("Recommended",Qv(e.recommended),"No ready work.")),t.push(...Ut("Decision needed",(e.decision_needed??[]).map(n=>`- ${Ht(n)}`),"No human-gated decisions.")),t.push(...Ut("Ready",e.ready.map(n=>`- ${Ht(n)}`),"No ready items.")),e.filters.ready_only||t.push(...Ut("Blocked",e.blocked.map(n=>`- ${Zv(n)}`),"No blocked items.")),e.suggestions&&e.suggestions.length>0){t.push("## Suggestions");for(let n of e.suggestions)t.push(`- ${n}`)}return t.join(`
|
|
19
19
|
`).trimEnd()}function Jv(e){let t=[`- now: ${e.now}`,`- ready: ${e.summary.ready} (in_progress: ${e.summary.in_progress}), blocked: ${e.summary.blocked}, candidates: ${e.summary.candidates}`];return e.filters.parent&&t.push(`- scope: subtree of ${e.filters.parent}`),t.push(""),t}function Qv(e){return e?[`- ${Ht(e)}`,` why: ${e.reasons.join("; ")}`]:[]}function Ut(e,t,n){return[`## ${e}`,...t.length===0?[n]:t,""]}function Zv(e){let t=e.blockers.map(n=>`${n.id}(${n.status??"?"})`).join(", ");return`${Ht(e)} blocked_by:${t}`}function Ht(e){let t=e.deadline??"-",n=e.parent?` parent:${e.parent}`:"",r=e.unblocks.length>0?` unblocks:${e.unblocks.length}`:"";return`${Number.isInteger(e.rank)?`#${e.rank} `:""}${e.id} p${e.priority} ${e.status} ${e.type} deadline:${t}${n}${r} ${e.title}`}import{createHash as eb}from"node:crypto";import{setTimeout as tb}from"node:timers/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="117a463a-c0ab-569f-92e9-e85d14a1cf91")}catch{}})();var Ld=1,Fd=/^[A-Za-z0-9_-]+$/,nb=100,Od=1e3,rb=250,_T=Object.freeze({batch_to_row_ratio:.6,fixture_events:200});function oe(e){if(e===void 0)return;let t=typeof e=="string"?[e]:e,n=[...new Set(t.flatMap(r=>r.split(",")).map(r=>r.trim()).filter(Boolean))].sort((r,i)=>r.localeCompare(i));return n.length===0?void 0:n}function Md(e){return eb("sha256").update(E({type:oe(e.type),author:oe(e.author),item:oe(e.item),harness:oe(e.harness),agent_instance:oe(e.agentInstance),provenance:oe(e.provenanceFilter)})).digest("hex").slice(0,24)}function so(e,t){let n={version:Ld,fingerprint:t,ts:e.entry.ts,stream_id:e.stream_id,stream_offset:e.stream_offset};return Buffer.from(JSON.stringify(n),"utf8").toString("base64url")}function Nd(e,t){if(typeof e!="object"||e===null)return!1;let n=e;return[n.version===Ld,n.fingerprint===t,typeof n.ts=="string",typeof n.stream_id=="string",typeof n.stream_offset=="number",Number.isSafeInteger(n.stream_offset),Number(n.stream_offset)>=0].every(Boolean)}function $d(e,t){let n=e.trim();if(n.length===0||n.length>4096||!Fd.test(n))throw new _("Invalid mutation event cursor.",g.USAGE,{code:"invalid_event_cursor"});let r;try{r=JSON.parse(Buffer.from(n,"base64url").toString("utf8"))}catch{throw new _("Invalid mutation event cursor.",g.USAGE,{code:"invalid_event_cursor"})}if(!Nd(r,t))throw new _("Mutation event cursor does not match this query.",g.USAGE,{code:"event_cursor_query_mismatch"});return r}function Pd(e){let t=e??nb;if(!Number.isSafeInteger(t)||t<0||t>Od)throw new _(`Mutation event limit must be an integer from 0 to ${Od}.`,g.USAGE,{code:"invalid_event_limit"});return t}function jd(e){return e instanceof Error&&e.name==="AbortError"}function Ud(e,t){let n=e?.trim();if(!n)return{};if(Fd.test(n))return{cursor:$d(n,t)};let r=Date.parse(n);if(!Number.isFinite(r))throw new _("Mutation event --since must be an event cursor or ISO timestamp.",g.USAGE,{code:"invalid_event_since"});return{sinceTimestamp:new Date(r).toISOString()}}async function ib(e,t){let n=await vr(e,t);if(n===null){if(!await Oo(e))return{...await Lo(e,t),source:"authoritative_history"};n=await vr(e,t)}if(n===null)throw new _("Mutation event index could not be opened after rebuild.",g.GENERIC_FAILURE,{code:"event_index_unavailable"});return{...n,source:"derived_index"}}function ob(e){let t=e??"batch";if(t!=="batch"&&t!=="row")throw new _("Mutation event cursor mode must be batch or row.",g.USAGE,{code:"invalid_event_cursor_mode"});return t}async function sb(e={}){let t=O(e.cwd??process.cwd(),e.pmRoot);await U(t);let n=Pd(e.limit),r=ob(e.cursorMode);if(e.full===!0&&e.provenance===!0)throw new _("Mutation event projections are mutually exclusive. Use --provenance or --full.",g.USAGE);let i=await F(t),o=i.agent_identity.identity_vocabulary,s=wn(i.agent_identity.harness_signals),a=xr({provenance:e.provenanceFilter},s),c=oe(e.harness),d=Md(e),{cursor:l,sinceTimestamp:u}=Ud(e.since,d),f={...l?{after_ts:l.ts,after_stream_id:l.stream_id,after_stream_offset:l.stream_offset}:u?{since_ts:u}:{},ops:oe(e.type),authors:oe(e.author),harnesses:c,harness_alias_authors:c?Object.entries(o.aliases).filter(([,h])=>c.includes(h)).map(([h])=>h):void 0,agent_instances:oe(e.agentInstance),provenance:[...a].map(([h,y])=>({dimension:h,values:[...y]})),stream_ids:oe(e.item),limit:n},p=await ib(t,f),m=p.events.map(h=>({...r==="row"?{cursor:so(h,d)}:{},item_id:h.stream_id,version:h.stream_offset+1,ts:h.entry.ts,author:h.entry.author,type:h.entry.op,...h.entry.message===void 0?{}:{message:h.entry.message},patch_count:h.entry.patch.length,...e.full===!0?{entry:h.entry}:{},...e.provenance===!0?{provenance:kn(h.entry,o,{itemId:h.stream_id,version:h.stream_offset+1})}:{}}));return{events:m,count:m.length,has_more:p.has_more,cursor_mode:r,...p.events.length===0?{}:{next_cursor:so(p.events[p.events.length-1],d)},source:p.source,...e.provenanceSummary===!0?{provenance_summary:En(p.events.map(h=>h.entry),o,s)}:{}}}async function*ab(e={}){let t=e.intervalMs??rb;if(!Number.isSafeInteger(t)||t<10)throw new _("Mutation event follow interval must be an integer of at least 10ms.",g.USAGE,{code:"invalid_event_follow_interval"});let n=e.since;for(;e.signal?.aborted!==!0;){let r=await sb({...e,cursorMode:e.cursorMode??"batch",since:n});if(yield r.next_cursor===void 0&&n!==void 0?{...r,next_cursor:n}:r,r.events.length>0){n=r.next_cursor;continue}try{await tb(t,void 0,{signal:e.signal})}catch(o){if(jd(o))return;throw o}}}async function*yT(e={}){for await(let t of ab({...e,cursorMode:"row"}))for(let n of t.events)yield n}var vT={decodeMutationEventCursor:$d,encodeMutationEventCursor:so,eventQueryFingerprint:Md,isAbortError:jd,isMutationEventCursorEnvelope:Nd,parseMutationEventLimit:Pd,resolveMutationEventStart:Ud};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e15abc24-c46a-512b-b859-015186c960df")}catch{}})();function wT(e,t){let n=t??{};return e.filter(r=>n[r.id]!==r.updated_at).map(r=>r.id).sort((r,i)=>r.localeCompare(i))}export{Tr as a,hn as b,$b as c,Pb as d,yn as e,_n as f,ms as g,Bb as h,ie as i,vn as j,ps as k,bn as l,wn as m,xr as n,kn as o,Qb as p,Dr as q,En as r,dw as s,vs as t,kl as u,pw as v,El as w,hw as x,gw as y,_w as z,yw as A,Tl as B,z as C,Es as D,Cn as E,Sw as F,Lr as G,Tw as H,gt as I,$l as J,jl as K,Mr as L,Ul as M,Qe as N,Tn as O,Nr as P,Rn as Q,Pw as R,Rs as S,fe as T,s0 as U,Ms as V,Ns as W,$s as X,Ps as Y,js as Z,Fn as _,Hs as $,tt as aa,Bs as ba,Vs as ca,$n as da,qs as ea,Ws as fa,xf as ga,sa as ha,Un as ia,qr as ja,Hn as ka,aa as la,da as ma,Wr as na,bt as oa,ua as pa,Xr as qa,Jr as ra,Qr as sa,fa as ta,Zr as ua,pa as va,ha as wa,_a as xa,em as ya,uk as za,Za as Aa,wT as Ba,Ia as Ca,Ca as Da,gk as Ea,Tm as Fa,st as Ga,T as Ha,Te as Ia,Sk as Ja,Tk as Ka,Dm as La,Om as Ma,Rk as Na,xk as Oa,Uk as Pa,Fa as Qa,qn as Ra,vi as Sa,sE as Ta,Jn as Ua,Ep as Va,aE as Wa,cE as Xa,dE as Ya,lE as Za,Cp as _a,za as $a,Bp as ab,Jp as bb,TI as cb,RI as db,Re as eb,eh as fb,Le as gb,er as hb,sc as ib,tr as jb,St as kb,Ti as lb,Tt as mb,Ri as nb,Rt as ob,cc as pb,dc as qb,hc as rb,Fi as sb,_c as tb,WI as ub,YI as vb,bc as wb,wc as xb,JI as yb,xi as zb,Di as Ab,rh as Bb,Ai as Cb,BI as Db,GI as Eb,KI as Fb,zI as Gb,Th as Hb,Dc as Ib,Cc as Jb,Sc as Kb,Oh as Lb,Lh as Mb,Fh as Nb,At as Ob,LC as Pb,FC as Qb,MC as Rb,Jc as Sb,Qc as Tb,Ot as Ub,Ki as Vb,sr as Wb,C_ as Xb,td as Yb,D_ as Zb,ar as _b,A_ as $b,O_ as ac,N_ as bc,$_ as cc,GC as dc,P_ as ec,nd as fc,zi as gc,Vi as hc,W_ as ic,ey as jc,eS as kc,qi as lc,Wi as mc,cr as nc,dd as oc,nS as pc,ay as qc,uy as rc,fd as sc,yy as tc,md as uc,vy as vc,fS as wc,hd as xc,yS as yc,vS as zc,bS as Ac,wS as Bc,gd as Cc,by as Dc,Ty as Ec,Mt as Fc,BS as Gc,Qi as Hc,Dy as Ic,Ay as Jc,eo as Kc,Ne as Lc,no as Mc,ro as Nc,io as Oc,lt as Pc,Pt as Qc,lr as Rc,GS as Sc,Av as Tc,KS as Uc,Nv as Vc,tT as Wc,nT as Xc,rT as Yc,iT as Zc,oT as _c,_T as $c,sb as ad,ab as bd,yT as cd,vT as dd};
|
|
20
|
-
//# sourceMappingURL=chunk-
|
|
20
|
+
//# sourceMappingURL=chunk-D5AJQU7F.js.map
|