@unbrained/pm-cli 2026.10.26 → 2026.10.28
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 +1 -1
- package/CHANGELOG.md +39 -1
- package/dist/cli/commander-usage.js +2 -2
- package/dist/cli/error-guidance.js +2 -2
- package/dist/cli/register-list-query.js +5 -5
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/chunk-2J7I54MQ.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-25MTQAHX.js → chunk-3KMYHYJV.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-7V37RC2L.js +114 -0
- package/dist/cli-bundle/chunks/chunk-AHVN4GHF.js +31 -0
- package/dist/cli-bundle/chunks/{chunk-VS2IIV3F.js → chunk-CS7QDSUX.js} +28 -28
- package/dist/cli-bundle/chunks/{chunk-T7T4WLUY.js → chunk-CXUQEZDX.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-ZT64RDMF.js → chunk-D3AIQZXF.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-7UDQAINZ.js → chunk-D6P6IBPN.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-TGOG5BFM.js → chunk-DKLEDWVW.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-MWCG25PO.js → chunk-DM3PICGU.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-Y42DYMZX.js → chunk-E5QBZ4HI.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-XAIR53QZ.js → chunk-JESLOJD7.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-57YPOOED.js → chunk-LWW4F4G2.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-PQLRKFPZ.js +20 -0
- package/dist/cli-bundle/chunks/{chunk-ONC4BBQP.js → chunk-RZQNFHXO.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-SPPHDVZE.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-ER7RLJW5.js → chunk-TH5KPAN4.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-OCDRHIVQ.js → chunk-XHONSCLJ.js} +6 -6
- package/dist/cli-bundle/chunks/{chunk-NGKTROAO.js → chunk-YUBUNECD.js} +42 -42
- package/dist/cli-bundle/chunks/{chunk-Z35XAHUN.js → chunk-YYD5MNAV.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-UF6EXZSP.js → chunk-ZX3XMTZG.js} +2 -2
- package/dist/cli-bundle/chunks/indexed-receipt-blobs-LHLE7PSG.js +4 -0
- package/dist/cli-bundle/chunks/{mutation-admission-VTNV6JV2.js → mutation-admission-GKDKHRTZ.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-LZDWUZS4.js → register-list-query-MHJJUM6M.js} +9 -9
- package/dist/cli-bundle/chunks/{register-mutation-M2A7PH42.js → register-mutation-SN425O3R.js} +2 -2
- package/dist/cli-bundle/chunks/{register-operations-E7P2JTXM.js → register-operations-EYUIUGPW.js} +2 -2
- package/dist/cli-bundle/chunks/{register-setup-DOV7KGSH.js → register-setup-WUZ2ZSMY.js} +2 -2
- package/dist/cli-bundle/chunks/{settlement-hook-SVD6CO7U.js → settlement-hook-MN3Y7LVX.js} +2 -2
- package/dist/cli-bundle/chunks/{stage-LYLEOAQB.js → stage-2FYJGGG3.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-3EHVI673.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-46WLWK73.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-E5C24MCV.js → chunk-4GN2ZPT5.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-NLZUI234.js → chunk-6L4KKRK7.js} +18 -18
- package/dist/cli-bundle/focused-chunks/{chunk-D5YQ4KAE.js → chunk-6VDRAJYX.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-KTXU5WU6.js → chunk-7SZPZOIC.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-YQKLKRMW.js → chunk-B4ZQJEMT.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-NE27VCU7.js → chunk-BZSACRVX.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-ADSBGYLW.js → chunk-C2GLO7HU.js} +55 -55
- package/dist/cli-bundle/focused-chunks/{chunk-UP765R2V.js → chunk-DRN4W3YJ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-EGN2HFRU.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-CSCZYSNZ.js → chunk-F6UQJJYB.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-I7H3XF25.js → chunk-I4X6AKOO.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-IQKLJFJE.js +79 -0
- package/dist/cli-bundle/focused-chunks/{chunk-KERJNFXY.js → chunk-JTCGDODH.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-IF6C43IP.js → chunk-L5GX2FGZ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-PK5FJIVA.js → chunk-LPWZERVD.js} +11 -11
- package/dist/cli-bundle/focused-chunks/{chunk-YW5GHQN2.js → chunk-ML5JIUM6.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-BL77VCRB.js → chunk-OASYSUOH.js} +16 -16
- package/dist/cli-bundle/focused-chunks/{chunk-BH7RE2ZY.js → chunk-ON5WFDCG.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-WDWHUJQW.js → chunk-QUPGBO2L.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-226XKW3W.js → chunk-R3EA3SDW.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-B266DDBJ.js → chunk-TUN4M757.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-YTEC2EPM.js → chunk-Z26ZPQH6.js} +3 -3
- package/dist/cli-bundle/focused-chunks/indexed-receipt-blobs-5H6RMRTK.js +4 -0
- package/dist/cli-bundle/focused-chunks/{mutation-admission-L42E3U5U.js → mutation-admission-TM3SVU2O.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{settlement-hook-3CADO4XZ.js → settlement-hook-LBVWWSCF.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{stage-TUQHWU7N.js → stage-7ZBRX2Q2.js} +2 -2
- package/dist/cli-bundle/main.js +21 -21
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +2 -2
- package/dist/cli-bundle/sdk-core.js +34 -33
- 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 +57 -57
- 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 +11 -11
- package/dist/core/history/event-index.d.ts +6 -0
- package/dist/core/history/event-index.js +7 -6
- package/dist/core/history/read.d.ts +3 -1
- package/dist/core/history/read.js +1 -1
- package/dist/core/item/priority.js +1 -1
- package/dist/core/shared/errors.d.ts +2 -0
- package/dist/core/shared/errors.js +1 -1
- package/dist/core/store/item-store.js +1 -1
- package/dist/mcp/tool-definitions.js +1 -1
- package/dist/sdk/agent/command-recovery.d.ts +5 -0
- package/dist/sdk/agent/command-recovery.js +1 -1
- package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
- package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
- package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
- package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
- package/dist/sdk/cli-contracts/tool-schema.js +1 -1
- package/dist/sdk/command-line.d.ts +6 -0
- package/dist/sdk/command-line.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/index.d.ts +1 -1
- package/dist/sdk/index.js +1 -1
- package/dist/sdk/lifecycle/close.js +1 -1
- package/dist/sdk/lifecycle/create.js +1 -1
- package/dist/sdk/lifecycle/update-many.js +1 -1
- package/dist/sdk/lifecycle/update.js +1 -1
- package/dist/sdk/merge/indexed-receipt-blobs.d.ts +3 -1
- package/dist/sdk/merge/indexed-receipt-blobs.js +2 -2
- package/dist/sdk/merge/receipt-file-boundary.d.ts +2 -0
- package/dist/sdk/merge/receipt-file-boundary.js +1 -1
- package/dist/sdk/merge/receipts.js +2 -2
- package/dist/sdk/mutation-events.d.ts +6 -0
- package/dist/sdk/mutation-events.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/history.d.ts +4 -0
- package/dist/sdk/query/history.js +1 -1
- package/dist/sdk/runtime/actions.js +1 -1
- package/dist/sdk/runtime-extended-actions.js +1 -1
- package/dist/sdk/runtime.js +1 -1
- package/dist/sdk/test/command-resolution.d.ts +5 -0
- package/dist/sdk/test/command-resolution.js +3 -0
- package/dist/sdk/test/execution.js +3 -3
- package/dist/sdk/test/receipt-index-snapshot.d.ts +2 -0
- package/dist/sdk/test/receipt-index-snapshot.js +2 -0
- package/dist/sdk/test/workspace-snapshot.d.ts +1 -1
- package/dist/sdk/test/workspace-snapshot.js +1 -1
- package/docs/COMMANDS.md +28 -1
- package/docs/PERFORMANCE.md +21 -6
- package/docs/RELEASING.md +11 -0
- package/docs/SDK.md +40 -0
- package/docs/SDK_CONTEXT_COORDINATION.md +35 -4
- package/docs/TESTING.md +42 -3
- package/docs/generated/FLAG_LEXICON_BUDGETS.md +2 -2
- package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +4 -3
- package/marketplace.json +1 -1
- package/package.json +1 -1
- 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-claude/package.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/pm-codex/package.json +1 -1
- package/plugins/pm-codex/plugin.json +1 -1
- package/runtime-dependencies.json +1 -1
- package/dist/cli-bundle/chunks/chunk-N6FTEILW.js +0 -20
- package/dist/cli-bundle/chunks/chunk-OUDR2HWR.js +0 -113
- package/dist/cli-bundle/chunks/chunk-RUKSEZE7.js +0 -2
- package/dist/cli-bundle/chunks/chunk-YJBIPNDL.js +0 -2
- package/dist/cli-bundle/chunks/chunk-ZLVFUZI4.js +0 -30
- package/dist/cli-bundle/chunks/indexed-receipt-blobs-NWQIDTH7.js +0 -4
- package/dist/cli-bundle/focused-chunks/chunk-ABMNYWV6.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-NFN2P4TW.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-UHWTPOM4.js +0 -78
- package/dist/cli-bundle/focused-chunks/chunk-VVRXF4JO.js +0 -2
- package/dist/cli-bundle/focused-chunks/indexed-receipt-blobs-YFDNGHCM.js +0 -4
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import{A as Ds,E as As,G as Qe,Gb as Ns,J as me,K as Re,L as Os,Lc as Fs,M as Ls,N as pe,O as kn,Tc as In,V as Ie,a as Cs,c as Ss,cd as $s,dd as Ps,e as bn,f as Ts,gc as En,h as qr,hd as Vr,i as wn,jf as he,kf as ge,ma as Ms,sd as Cn,td as Sn,v as Rs,z as xs}from"./chunk-CS7QDSUX.js";import{a as Tn,b as _t}from"./chunk-SPPHDVZE.js";import{$c as on,$h as _s,Ae as sn,Af as Vo,Ah as pn,Bg as Jo,Bh as hn,Bi as N,Cd as Ke,Ch as gt,D as K,Da as Ge,Db as Do,Df as jr,Dh as fe,Ef as Ur,Eg as Q,Eh as Gr,Fg as T,Fh as us,G as To,Ge as an,Gf as Br,Gg as P,Gh as gn,He as le,Hg as Ve,Hh as Me,Ie as ue,Je as Bo,Ke as Ho,Le as Go,Lg as Qo,Lh as fs,Me as ze,Mg as Zo,Ne as Ko,Ng as es,Nh as ms,Oc as x,Of as Wo,Oh as ps,Pa as E,Pd as Fo,Ph as Kr,Qd as $o,Qh as hs,Ra as ie,Rc as Oo,Rh as gs,Sd as $r,Sh as zr,Tf as U,Th as _n,Ue as D,Ug as ts,Uh as Je,Vg as ns,We as Pr,Wg as rs,Xe as cn,Xg as is,Ye as C,Yg as os,Zc as rn,Ze as zo,_e as we,_h as yn,ad as Lo,ag as Xo,ah as We,ai as ys,be as ht,ca as He,ci as vs,df as qe,dg as ke,ei as vn,fd as Mo,fi as bs,gi as ws,ha as Nr,hf as dn,ia as tn,ib as Fr,ii as Z,ja as Ro,jf as ln,jh as ss,ji as ks,ki as Es,lf as un,me as Po,nd as pt,o as re,og as J,pa as M,pd as No,pf as fn,q as Qt,qa as nn,qg as mn,qh as Ee,ra as xo,re as jo,rh as as,sh as Xe,t as Zt,th as Hr,uc as Ao,vh as cs,we as Uo,wi as Is,xa as O,xh as Ye,yh as ds,zf as qo,zg as Yo,zh as ls}from"./chunk-7V37RC2L.js";import{A as g,C as h,D as Mr,E as en,F as Be,G as de,H as be,K as X,M as So,y as Co}from"./chunk-RZQNFHXO.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]="cf5a7b37-5b40-52b4-a19c-18b08de649c4")}catch{}})();function Wr(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function Zb(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;if(!Wr(t.requested_tokens)||t.basis!=="canonical_retry")return!1;switch(t.minimum_status){case"exact":return Wr(t.minimum_feasible_tokens)&&t.feasible_tokens===t.minimum_feasible_tokens&&t.reason===void 0;case"feasible_only":return t.minimum_feasible_tokens===null&&Wr(t.feasible_tokens)&&t.reason===void 0;case"unavailable":return t.minimum_feasible_tokens===null&&t.feasible_tokens===null&&["query_cost_limit","search_limit","output_constraints"].includes(t.reason);default:return!1}}var $l="PmCliError";function ew(e){if(!jl(e)||e.code!=="item_already_exists"||e.exitCode!==g.CONFLICT)return!1;let t=e.context;return typeof t=="object"&&t!==null&&t.code==="item_already_exists"&&typeof t.id=="string"&&t.id.trim().length>0&&typeof t.path=="string"&&t.path.trim().length>0}function Pl(e){if(!Number.isFinite(e))throw new TypeError("createPmCliExpectedError options.exitCode must be a finite number");let t=Math.trunc(e);if(t<=g.SUCCESS)throw new TypeError("createPmCliExpectedError options.exitCode must be a positive exit code");return t}function js(e,t={}){if(typeof e!="string"||e.trim().length===0)throw new TypeError("createPmCliExpectedError message must be a non-empty string");let n=new h(e,Pl(t.exitCode??g.USAGE),t.context??{});return"cause"in t&&Object.defineProperty(n,"cause",{value:t.cause,enumerable:!1,configurable:!0,writable:!0}),n}function jl(e){if(!(e instanceof Error)||e.name!==$l)return!1;let t=e;return typeof t.exitCode=="number"&&Number.isFinite(t.exitCode)}(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]="59842825-3a81-53f4-845d-db2257ec6286")}catch{}})();async function Xr(e){let t=O(process.cwd(),e);await U(t);let n=await N(t),r=M(n,x());return{pmRoot:t,settings:n,typeRegistry:r}}async function Rn(e,t,n,r){Ge(e,qr(t));let i=await me(e,t,n.id_prefix,n.item_format,r);if(i)return{id:i.id,historyPath:Ge(e,i.id),located:i};let o=wn(t,n.id_prefix),s=qr(t),a=o===s?[o]:[o,s];for(let c of a){let d=Ge(e,c);if(await en(d))return{id:c,historyPath:d,located:null}}throw new h(`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]="eb2e6046-156c-56ee-a03a-ecaa1cccfb45")}catch{}})();function Aw(e,t){let n=fe(e),r=e.length>0?e[e.length-1].after_hash:bs(),i=t===void 0||n.item_hash_version===void 0?void 0:vn(t,n.item_hash_version,ke(e.at(-1)?.hash_algorithm)),o=t===void 0?void 0:i===void 0?vs(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 Ow(e,t,n={}){let r=O(n.cwd??process.cwd(),n.pmRoot);await U(r);let i=await N(r),o=M(i,x()),s=await Rn(r,e,i,o.type_to_folder),a=await Xe(s.historyPath,s.id);if(a.length===0)throw new h(`No history exists for ${s.id}; point-in-time reads are unavailable.`,g.NOT_FOUND);let c=Ss(t,a),d=Ts(bn(a,c.historyIndex),c),l=ls(d,{schema:i.schema});if(l.metadata.id!==s.id)throw new h(`History target resolved to item ${l.metadata.id}, expected ${s.id}.`,g.GENERIC_FAILURE);let u=a[c.historyIndex],f=Cs(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]="403706c5-987d-5db1-95d2-b0eaded98e92")}catch{}})();function Ul(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:Vl(r,t,e.parents)}),"continue"):(e.cursorFound=t===i,"skip")}function Bs(e,t,n,r){let i=le("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:Go(t.after,i)}}function Ze(e,t,n){e.get(t).add(n)}function yt(e){return new Map(e.map(t=>[t,new Set]))}function Hs(e){for(let t of e)t.sort();return e.sort((t,n)=>n.length-t.length||t[0].localeCompare(n[0]))}function xn(e){if(Array.isArray(e))return e.map(n=>xn(n));if(e===null||typeof e!="object")return e;let t=e.toJSON;return typeof t=="function"?xn(t.call(e)):Object.fromEntries(Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,xn(r)]))}function Us(e){return JSON.stringify(xn(e))}function Bl(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 Hl(e,t){let n=new Set,r=[];for(let i of e)n.has(i)||Bl(i,t,n,r);return r}function Gl(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 Hs(r)}function Gs(e,t){let n=yt(e);for(let[r,i]of t)for(let o of i)Ze(n,o,r);return Gl(Hl(e,t),n)}function Kl(e,t){let n=yt(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";Ze(n,o?r.source:r.target,o?r.target:r.source)}return n}function zl(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 ql(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 Vl(e,t,n){let r=[t],i=t;for(;i!==e;)i=n.get(i),r.push(i);return r.reverse()}function An(e,t={}){let n=t.registry??re(),r=[...e.nodes()],i=Kl(e,n),o=zl(r,i),s=o.flat(),a=s.length===r.length,c=a?[]:Gs(r,i).filter(l=>l.length>1||i.get(l[0]).has(l[0])),d=ql(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 Wl(e,t,n){let r=yt(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))||Ze(r,t==="incoming"?s.target:s.source,t==="incoming"?s.source:s.target)}return{adjacency:r,inspectedEdges:o.length}}function Xl(e,t,n,r,i,o){let s=Dn(e,t,{...n,after:void 0,direction:"incoming",limit:void 0}),a=Dn(e,t,{...n,after:void 0,direction:"outgoing",limit:void 0}),c=new Map,d=[...s.affected,...a.affected].sort((p,_)=>p.distance-_.distance||p.id.localeCompare(_.id)||p.path.join("\0").localeCompare(_.path.join("\0")));for(let p of d)c.has(p.id)||c.set(p.id,p);let l=[...c.values()].sort((p,_)=>p.distance-_.distance||p.id.localeCompare(_.id)),u=r===void 0||r===t?-1:l.findIndex(p=>p.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),m=u+1+f.length<l.length;return{root:t,affected:f,exact:!0,truncated:s.truncated||a.truncated||m,...m?{nextCursor:ue(o,f.at(-1)?.id??t)}:{},cost:{visitedNodes:s.cost.visitedNodes+a.cost.visitedNodes,inspectedEdges:s.cost.inspectedEdges+a.cost.inspectedEdges}}}function Yl(e,t,n){let r=n.direction,i=n.maxDepth??Number.POSITIVE_INFINITY,o=n.limit??Number.POSITIVE_INFINITY,{fingerprint:s,after:a}=Bs(t,n,r,i),{adjacency:c,inspectedEdges:d}=Wl(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,m=!1;e:for(let p=0;p<l.queue.length;p+=1){n.signal?.throwIfAborted();let _=l.queue[p];u+=1;let y=[...c.get(_.id)].sort();if(_.depth>=i){y.some(b=>!l.seen.has(b))&&(f=!0);continue}for(let b of y)if(Ul(l,b,_,t,a,o)==="truncate"){f=!0,m=!0;break e}}if(!l.cursorFound)throw new TypeError(`Unknown impact cursor item: ${a}`);return{root:t,affected:l.affected,exact:!0,truncated:f,...m?{nextCursor:ue(s,l.affected.at(-1)?.id??t)}:{},cost:{visitedNodes:u,inspectedEdges:d}}}function Dn(e,t,n={}){let r=n.direction??"outgoing";if(r!=="both")return Yl(e,t,{...n,direction:r});let i=n.maxDepth??Number.POSITIVE_INFINITY,o=n.limit??Number.POSITIVE_INFINITY,{fingerprint:s,after:a}=Bs(t,n,r,i);return Xl(e,t,n,a,o,s)}function Ks(e){let t=[...e.nodes()],n=yt(t),r=yt(t);for(let c of e.edges())Ze(n,c.source,c.target),Ze(n,c.target,c.source),Ze(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:Hs(i),stronglyConnected:Gs(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 Fw(e,t){let n=new Map(e.edges.map(i=>[Us(i),i])),r=new Map(t.edges.map(i=>[Us(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]="a319e7d9-e248-573b-bf1f-35217ce49fd0")}catch{}})();function xe(e,t){return(t===void 0?void 0:xo(e,t))?.execution_role??Ro[e.trim().toLowerCase()]??"agent"}var Jr="blocked_by",zs="blocks",Jl=Object.freeze([Jr,zs]),Yr="no-active-blocker";function A(e){return e.trim().toLowerCase()}function On(e,t){return t?`external:${e}`:`local:${A(e)}`}function Ne(e){let t=new Map,n=typeof e.blocked_by=="string"?e.blocked_by.trim():"";if(n.length>0&&A(n)!==Yr){let r=he(n);t.set(On(n,r),r?n:A(n))}for(let r of e.dependencies??[]){let i=typeof r.id=="string"?r.id.trim():"";if(Qt(r.kind)===Jr&&i.length>0&&A(i)!==Yr){let o=he(i)||ge(r.source_kind);t.set(On(i,o),o?i:A(i))}}return[...t.values()].sort((r,i)=>r.localeCompare(i))}function Ln(e){let t=new Map;for(let n of e){let r=A(n.id);r.length!==0&&t.set(r,new Set(Ne(n)))}for(let n of e){let r=A(n.id);if(r.length!==0)for(let i of n.dependencies??[]){let o=Qt(i.kind)===zs&&typeof i.id=="string"?A(i.id):"";if(o.length===0||o===Yr)continue;let s=t.get(o)??new Set;s.add(r),t.set(o,s)}}return new Map([...t].map(([n,r])=>[n,[...r].sort((i,o)=>i.localeCompare(o))]))}function qs(e,t){let n=A(e.id);return n.length>0?Ln(t).get(n)??Ne(e):Ne(e)}function Qr(e,t,n,r){let i=e,o=typeof i.id=="string"?r?.get(A(i.id))??qs(i,[...t.values()]):Ne(e),s=new Set((e.dependencies??[]).filter(a=>Qt(a.kind)===Jr&&ge(a.source_kind)&&typeof a.id=="string"&&a.id.trim().length>0).map(a=>On(a.id.trim(),!0)));return o.map(a=>{if(he(a)||s.has(On(a,!0)))return{id:a,title:null,status:null,resolved:!1,external:!0,...typeof e.updated_at=="string"?{blocked_since:e.updated_at}:{},resolver:null};let c=t.get(A(a));return c?{id:a,title:c.title,status:c.status,resolved:P(c.status,n)}:{id:a,title:null,status:null,resolved:!1}})}function Mn(e,t,n){return Qr(e,t,n)}function vt(e,t){let n=new Map(e.map(s=>[A(s.id),s])),r=Ln(e),i=new Set([...Vs(t),...t.blocked_statuses]),o=new Set;for(let s of e){let a=T(s.status,t);i.has(a)&&(t.blocked_statuses.has(a)||Qr(s,n,t,r).some(c=>!c.resolved))&&o.add(A(s.id))}return o}function Zr(e,t,n={},r){let i=[...e.ready,...e.decisions,...e.gates];n.includeContainers===!0&&i.push(...e.containers.filter(s=>s.open_blockers.length===0&&!t.blocked_statuses.has(T(s.item.status,t))));let o={ready:[],decisions:[],gates:[]};for(let s of i){let a=xe(s.item.type,r);a==="human"&&n.includeDecisions!==!0?o.decisions.push(s):a==="gate"&&n.includeGates!==!0?o.gates.push(s):o.ready.push(s)}return o}function Vs(e){return e.active_statuses.size>0?e.active_statuses:new Set([e.open_status])}function Ql(e,t,n){let r=[A(e)],i=new Set;for(;r.length>0;){let o=r.pop();if(!i.has(o)){i.add(o);for(let s of t.get(o)??[]){if(!P(s.status,n))return!0;r.push(A(s.id))}}}return!1}function Zl(e){let t=new Map,n=new Map,r=new Map,i=Ln(e);for(let o of e){t.set(A(o.id),o);let s=typeof o.parent=="string"?o.parent.trim():"";if(s.length>0){let a=A(s),c=n.get(a)??[];c.push(o),n.set(a,c)}for(let a of i.get(A(o.id))){let c=A(a),d=r.get(c)??[];d.push(o.id),r.set(c,d)}}return{itemsById:t,childrenByParent:n,blockedByReverse:r,blockerIdsByItem:i}}function bt(e,t,n,r){let{itemsById:i,childrenByParent:o,blockedByReverse:s,blockerIdsByItem:a}=Zl(t),c=new Set([...Vs(n),...n.blocked_statuses]),d=new Set(t.filter(y=>!P(y.status,n)).map(y=>A(y.id))),l=[],u=[],f=[],m=[],p=[],_=0;for(let y of e){if(!c.has(T(y.status,n)))continue;_+=1;let b=Qr(y,i,n,a).filter(S=>!S.resolved),v=(s.get(A(y.id))??[]).filter(S=>d.has(A(S))).sort((S,L)=>S.localeCompare(L)),w={item:y,open_blockers:b,unblocks:v};if(Ql(y.id,o,n)){f.push(w);continue}let k=n.blocked_statuses.has(T(y.status,n));if(b.length===0&&!k){let S=xe(y.type,r);S==="human"?m.push(w):S==="gate"?p.push(w):l.push(w)}else u.push(w)}return{ready:l,blocked:u,containers:f,decisions:m,gates:p,active_count:_,container_count:f.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]="ae1c56b3-148d-502d-9450-e807fdfab4da")}catch{}})();(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]="738a98bc-eaf0-578d-88e3-1c5f83c8894b")}catch{}})();function oe(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 h(`${t} must be a non-negative integer`,g.USAGE);return r}function Nn(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 h(`${t} filter must be 0..4`,g.USAGE);return r}function Ws(e,t,n="--type"){if(e===void 0)return;let r=nn(e,t);if(!r)throw new h(`${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]="75ecca0c-fac8-5a9b-9043-c65731daad4a")}catch{}})();function ei(e,t){if(e===void 0)return;let n=[],r="";for(let s=0;s<e.length;s+=1){let a=e[s];if(a==="\\"){let c=e[s+1];if(c===","||c==="\\"){r+=c,s+=1;continue}r+=a;continue}if(a===","){n.push(r),r="";continue}r+=a}n.push(r);let i=n.map(s=>s.trim());if(i.some(s=>s.length===0))throw new h(`${t.label} requires at least one non-empty value`,g.USAGE);let o=i.map(s=>t.normalize?.(s)??s);return[...new Set(o)]}function wt(e,t){let n=ei(e,t);return n===void 0?void 0:new Set(n)}function Xs(e,t,n="--type"){let r=ei(e,{label:n});if(r===void 0)return;let i=r.map(o=>{let s=nn(o,t);if(!s)throw new h(`${n} filter token "${o}" must be one of ${t.types.join("|")}`,g.USAGE);return s});return new Set(i)}function Ys(e,t="--priority"){let n=ei(e,{label:t});if(n!==void 0)return new Set(n.map(r=>Nn(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]="6c580b70-76eb-51db-8587-99b73dd20875")}catch{}})();var eu="global",i0="external",tu=["open","closed","unknown"],kt=new Map,nu=240,ru=2048;function Js(e,t,n){return(e?.trim()||t).slice(0,n)}function iu(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 o0(e){let t=e.name.trim();if(t.length===0)throw new Error("External dependency resolver name must not be empty");if(kt.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 kt.set(t,n),()=>{kt.get(t)===n&&kt.delete(t)}}async function s0(e,t={}){let n=e.trim();if(!he(n))return null;let r=[...kt.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"||!iu(s.value))continue;let a=r[o],c=s.value,d=tu.includes(c.status)?c.status:"unknown",l=Js(c.title,"",nu),u=Js(c.source,n,ru),f=Date.parse(c.checkedAt?.trim()??""),m=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:m,resolver:a.name}}return null}function a0(e){let t=e?.trim();if(t)return ge(t)?eu:t}function c0(e,t,n){return ou(e,t,n)}function ou(e,t,n){let r=e.trim();return ge(n)||he(r)?r:wn(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]="283dfa35-9a8e-524c-b6e2-d433d51215ca")}catch{}})();function z(){let e=re();for(let t of x()?.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]="8b57e560-4ac4-53b6-9fb1-eebb1f30562a")}catch{}})();function Et(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function Fn(e){return[e.parent_id,e.child_id,e.source,e.kind,e.holder_id,e.target_id??""].join("\0")}function su(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 au(e,t){let n=[...e].sort(),r=su(n,t),i=new Set,o=cu(n,t),s=[];for(let a of r.reverse()){if(i.has(a))continue;let c=du(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 cu(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 du(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 Qs(e){let t=new Map;for(let n of e){let r=Et(n?.id);r&&!t.has(r)&&t.set(r,n)}return t}function lu(e,t,n){let r=Et(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 uu(e,t,n,r){let i=Et(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 Zs(e,t){let n=new Map;for(let[r,i]of e){let o=lu(r,i,e);o&&n.set(Fn(o),o);for(let s of i.dependencies??[]){let a=uu(r,s,e,t);a&&n.set(Fn(a),a)}}return[...n.values()].sort((r,i)=>Fn(r).localeCompare(Fn(i)))}function ea(e,t=z()){return Zs(Qs(e),t)}function fu(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 mu(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=Et(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 $n(e,t=r=>r==="closed"||r==="canceled",n=z()){let r=Qs(e),i=Zs(r,n),o=ni(i),s=new Set([...r].filter(([,c])=>t(c.status)).map(([c])=>c)),a=au([...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:fu(i,o.parents_by_child,s),divergences:mu(r,i,s)}}function g0(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 ni(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 ti(e,t){let n=new Set(t);return e.every(r=>n.has(r))}function _0(e,t,n,r,i){let o=Et(n);if(!o)return;let s=$n(e,r,i),a=$n(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&&ti(u.dependency_parent_ids,f.dependency_parent_ids)));if(c){let u=[c.scalar_parent_id,...c.dependency_parent_ids].sort();throw new h(`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&&ti(u.parent_ids,f.parent_ids)));if(d)throw new h(`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=>ti(u.item_ids,f.item_ids)));if(l)throw new h(`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]="41f814be-ee87-5cae-b674-69c2e7f42655")}catch{}})();function tt(e){if(typeof e!="string")return;let t=e.trim();if(!(!t||["none","null","n/a","na"].includes(t.toLowerCase())))return t}function It(e){let t=tt(e);return t?.toLowerCase()==="no-active-blocker"?void 0:t}function Ct(e,t,n=!0){let r=tt(e);return n&&(ge(t)||r!==void 0&&he(r))}function ri(e,t){return Ct(e,t)?`external\0${e}`:`local\0${e.toLowerCase()}`}function ta(e,t,n,r){return Ct(e,t)?r.get(e):n.get(e.toLowerCase())}function et(e,t){let n=e.toLowerCase(),r=t.toLowerCase();return n!==r?n<r?-1:1:e!==t?e<t?-1:1:0}function pu(e){let t=new Map;for(let n of e.dependencies??[]){if(typeof n!="object"||n===null)continue;let r=n,i=tt(r.id);if(!i)continue;let o=typeof r.kind=="string"?r.kind:"related",s=`${o}\0${ri(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 hu(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 pu(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=et(r.holder_id,i.holder_id);if(o!==0)return o;let s=et(r.target_id,i.target_id);return s!==0?s:et(r.kind,i.kind)})}function gu(e,t,n,r,i){if(typeof n!="object"||n===null)return;let o=tt(n.id);if(!o||ri(o,n.source_kind)!==ri(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 _u(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=tt(i.blocked_by);if(o)for(let s of i.dependencies??[]){let a=gu(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=et(i.holder_id,o.holder_id);if(s!==0)return s;let a=et(i.target_id,o.target_id);return a!==0?a:et(i.dependency_kind,o.dependency_kind)})}function ii(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 m=tt(d);if(!m||r.has(m.toLowerCase())||Ct(m,void 0,f))return;let p={holder_id:c.id.trim(),target_id:m,kind:l,source:u,holder_status:c.status,legacy_terminal:t(c.status),no_active_blocker_sentinel:m.toLowerCase()==="no-active-blocker"};i.set(`${p.holder_id}::${p.target_id}::${p.kind}::${p.source}`,p)};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;ge(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 yu(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 vu(e){let t=new Map;for(let n of e){let r=It(n.blocked_by);r&&Ct(r)&&!t.has(r)&&t.set(r,r);for(let i of n.dependencies??[]){if(typeof i!="object"||i===null||!Ct(i.id,i.source_kind))continue;let o=It(i.id);o&&!t.has(o)&&t.set(o,o)}}return[...t.values()].sort((n,r)=>n.localeCompare(r))}var na=new WeakMap;function Pn(e){return e.hierarchyIntegrity??na.get(e)}function bu(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 St(e,t,n){let r=n??z(),i=e.filter(p=>typeof p?.id=="string"&&p.id.trim().length>0),o=new Map(i.map(p=>[p.id.trim().toLowerCase(),p.id.trim()])),s=ii(i,t),a=yu(s);for(let p of a)o.set(p.toLowerCase(),p);let c=vu(i),d=new Set(o.keys()),l=new Map;for(let p of c){let _=p;for(;d.has(_.toLowerCase());)_=`external:${_}`;l.set(p,_),d.add(_.toLowerCase())}let u=i.map(p=>{let _=It(p.parent),y=It(p.blocked_by),b=(p.dependencies??[]).flatMap(v=>{if(typeof v!="object"||v===null)return[];let w=v,k=It(w.id);return k?[{id:ta(k,w.source_kind,o,l),kind:typeof w.kind=="string"?w.kind:"related"}]:[]});return{id:p.id.trim(),..._?{parent:o.get(_.toLowerCase())}:{},...y?{blocked_by:ta(y,void 0,o,l)}:{},dependencies:b}}),f=$n(i,t,r),m={graph:Zt.fromItems([...u,...a.map(p=>({id:p})),...c.map(p=>({id:l.get(p)}))],r),details:[...i.map(p=>({id:p.id.trim(),title:p.title,status:p.status,...typeof p.type=="string"&&p.type.trim().length>0?{type:p.type.trim()}:{}})),...a.map(p=>({id:p,title:`[missing] ${p}`,status:"missing"})),...c.map(p=>({id:l.get(p),title:`[external] ${p}`,status:"external"}))],missingIdSet:new Set(a.map(p=>p.toLowerCase())),dangling:s,duplicateRows:hu(i,t),orderingContradictions:_u(i,t,r),legacyAliasCounts:bu(i,r),hierarchyIntegrity:f};return na.set(m,f),m}(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]="f9d73d74-7c4e-5ea9-b34c-c984b4c15ab3")}catch{}})();function ra(e,t){let n=e.trim().toLowerCase();return t.alias_to_id.get(n)??n}function aa(e){return{isTerminal(t){return e.terminal_statuses.has(ra(t,e))},classify(t){let n=ra(t,e);return e.terminal_canceled_statuses.has(n)?"canceled":e.terminal_statuses.has(n)?"closed":e.blocked_statuses.has(n)?"blocked":e.draft_statuses.has(n)?"draft":n===e.open_status?"open":e.active_statuses.has(n)?"in_progress":"other"}}}function oi(e){return K(e.acceptance_criteria)===void 0}function si(e){return!Number.isFinite(e.estimated_minutes)}function ca(e,t){return t.isTerminal(e.status)?K(e.resolution)===void 0:!1}function wu(e){return K(e.reviewer)===void 0}function ku(e){return K(e.risk)===void 0}function Eu(e){return typeof e.confidence=="number"?!Number.isFinite(e.confidence):K(e.confidence)===void 0}function Iu(e){return K(e.sprint)===void 0}function Cu(e){return K(e.release)===void 0}function ai(e){return!!(e.acMissing||e.estimatesMissing||e.resolutionMissing||e.reviewerMissing||e.riskMissing||e.confidenceMissing||e.sprintMissing||e.releaseMissing||e.metadataMissing)}function Su(e,t,n){return[[t.acMissing,oi(e)],[t.estimatesMissing,si(e)],[t.resolutionMissing,ca(e,n)],[t.reviewerMissing,wu(e)],[t.riskMissing,ku(e)],[t.confidenceMissing,Eu(e)],[t.sprintMissing,Iu(e)],[t.releaseMissing,Cu(e)]].every(([r,i])=>r!==!0||i)}function Tu(e,t){return oi(e)||si(e)||ca(e,t)}function da(e,t,n){return ai(t)?!(!Su(e,t,n)||t.metadataMissing&&!Tu(e,n)):!0}var ci=["acceptance_criteria","estimated_minutes","resolution","tags","parent"];function Ru(e,t){switch(t){case"acceptance_criteria":return!oi(e);case"estimated_minutes":return!si(e);case"resolution":return K(e.resolution)!==void 0;case"tags":return Array.isArray(e.tags)&&e.tags.length>0;default:return K(e.parent)!==void 0}}function xu(e,t,n){return t==="resolution"?n.isTerminal(e.status):!0}function Du(e,t){return t===0?100:Math.round(e/t*1e3)/10}function ia(){let e={};for(let t of ci)e[t]={present:0,applicable:0,percent:100};return e}function oa(e,t,n){for(let r of ci){if(!xu(t,r,n))continue;let i=e[r];i.applicable+=1,Ru(t,r)&&(i.present+=1)}}function sa(e){for(let t of ci){let n=e[t];n.percent=Du(n.present,n.applicable)}}function S0(e,t){let n=ia(),r={};for(let i of e){oa(n,i,t);let o=r[i.type]??(r[i.type]=ia());oa(o,i,t)}sa(n);for(let i of Object.values(r))sa(i);return{overall:n,by_type:r}}var Au={assignee:"(unassigned)",priority:"(no priority)",tag:"(untagged)",parent:"(unparented)",type:"(untyped)",status:"(no status)"};function Ou(e){return Au[e]}function Lu(){return{open:0,in_progress:0,blocked:0,draft:0,closed:0,canceled:0,other:0}}function Mu(e,t,n){switch(t){case"assignee":return[K(e.assignee)??null];case"parent":return[K(e.parent)??null];case"type":return[K(e.type)??null];case"status":return[K(e.status)??null];case"priority":return[typeof e.priority=="number"?`P${e.priority}`:null];default:{let r=n.tagPrefix?.trim(),i=(Array.isArray(e.tags)?e.tags:[]).filter(o=>typeof o=="string"&&o.length>0&&(!r||o.startsWith(r)));return i.length>0?i:[null]}}}function T0(e,t,n,r={}){let i=new Map,o=0;for(let a of e){o+=1;let c=n.classify(a.status);for(let d of Mu(a,t,r)){let l=d??"\0empty",u=i.get(l);u||(u={label:d??Ou(t),key:d,buckets:Lu(),total:0},i.set(l,u)),u.buckets[c]+=1,u.total+=1}}let s=[...i.values()].sort((a,c)=>c.total!==a.total?c.total-a.total:a.key===null?1:c.key===null?-1:a.label.localeCompare(c.label));return{dimension:t,rows:s,total_items:o}}(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]="67f9184e-08b6-5f21-9f92-e60974adbf1e")}catch{}})();var nt=["notes","learnings","files","docs","tests","comments","deps","body","linked_command"];function Fe(e){return Array.isArray(e)&&e.length>0}function Nu(e){return typeof e=="string"&&e.trim().length>0}function Fu(e){return Array.isArray(e)?e.some(t=>{if(typeof t!="object"||t===null)return!1;let n=t.command;return typeof n=="string"&&n.trim().length>0}):!1}function ua(e,t){switch(t){case"notes":return Fe(e.notes);case"learnings":return Fe(e.learnings);case"files":return Fe(e.files);case"docs":return Fe(e.docs);case"tests":return Fe(e.tests);case"comments":return Fe(e.comments);case"deps":return Fe(e.dependencies);case"body":return Nu(e.body);case"linked_command":return Fu(e.tests)}}function fa(e){return nt.some(t=>e[t]!==void 0)}function ma(e,t){for(let n of nt){let r=t[n];if(r===void 0)continue;let i=ua(e,n);if(r==="present"&&!i||r==="absent"&&i)return!1}return!0}function pa(e){return nt.some(t=>t!=="body"&&e[t]!==void 0)}function ha(e){return e.body!==void 0}function la(e,t){return t===0?100:Math.round(e/t*1e3)/10}function $u(){let e={};for(let t of nt)e[t]={present:0,total:0,percent:100};return e}function x0(e){let t=$u(),n=e.length;for(let s of e)for(let a of nt)ua(s,a)&&(t[a].present+=1);for(let s of nt)t[s].total=n,t[s].percent=la(t[s].present,n);let r=t.body,i=n-r.present,o={present:i,total:n,percent:la(i,n)};return{total_items:n,fields:t,body_populated:r,empty_body:o}}(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]="084aad9c-485f-5bdc-8da7-225c9c4f695c")}catch{}})();var Pu=e=>({acMissing:e.filterAcMissing===!0,estimatesMissing:e.filterEstimatesMissing===!0,resolutionMissing:e.filterResolutionMissing===!0,metadataMissing:e.filterMetadataMissing===!0,reviewerMissing:e.filterReviewerMissing===!0,riskMissing:e.filterRiskMissing===!0,confidenceMissing:e.filterConfidenceMissing===!0,sprintMissing:e.filterSprintMissing===!0,releaseMissing:e.filterReleaseMissing===!0}),ga=[{field:"notes",presentKey:"hasNotes",absentKey:"noNotes",presentFlag:"--has-notes",absentFlag:"--no-notes"},{field:"learnings",presentKey:"hasLearnings",absentKey:"noLearnings",presentFlag:"--has-learnings",absentFlag:"--no-learnings"},{field:"files",presentKey:"hasFiles",absentKey:"noFiles",presentFlag:"--has-files",absentFlag:"--no-files"},{field:"docs",presentKey:"hasDocs",absentKey:"noDocs",presentFlag:"--has-docs",absentFlag:"--no-docs"},{field:"tests",presentKey:"hasTests",absentKey:"noTests",presentFlag:"--has-tests",absentFlag:"--no-tests"},{field:"comments",presentKey:"hasComments",absentKey:"noComments",presentFlag:"--has-comments",absentFlag:"--no-comments"},{field:"deps",presentKey:"hasDeps",absentKey:"noDeps",presentFlag:"--has-deps",absentFlag:"--no-deps"},{field:"body",presentKey:"hasBody",absentKey:"emptyBody",presentFlag:"--has-body",absentFlag:"--empty-body"},{field:"linked_command",presentKey:"hasLinkedCommand",absentKey:"noLinkedCommand",presentFlag:"--has-linked-command",absentFlag:"--no-linked-command"}],ka=e=>{let t=ga.find(n=>e[n.presentKey]===!0&&e[n.absentKey]===!0);if(t)throw new h(`Cannot combine ${t.presentFlag} with ${t.absentFlag} for the same field.`,g.USAGE);return Object.fromEntries(ga.flatMap(n=>e[n.presentKey]===!0?[[n.field,"present"]]:e[n.absentKey]===!0?[[n.field,"absent"]]:[]))},_a=["priority","deadline","updated_at","created_at","title","parent"],ya=["asc","desc"],Ea=new Set(As);function ju(e,t,n){let r=e.filter(s=>s.startsWith("item_list_item_read_failed:")).length,i=e.filter(s=>s.startsWith("item_list_directory_read_failed:")).length,o={status:t?"unchecked":r+i>0?"partial":"complete",unreadable_item_count:r,unreadable_directory_count:i};if(n&&o.status==="partial")throw new h(`List source is incomplete: ${r} item document(s) and ${i} item directory/directories could not be read.`,g.GENERIC_FAILURE,{code:"list_source_incomplete",why:"Strict list reads fail closed so agents and SDK consumers never treat an omitted item as a complete workspace.",nextSteps:["Run pm validate --check-storage-integrity to locate unreadable tracker artifacts.","Repair the reported files or align the installed decoder version, then retry."]});return o}function Uu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.keys(e).length>0}var Bu=[{key:"hasNotes",summaryKey:"has_notes"},{key:"hasLearnings",summaryKey:"has_learnings"},{key:"hasFiles",summaryKey:"has_files"},{key:"hasDocs",summaryKey:"has_docs"},{key:"hasTests",summaryKey:"has_tests"},{key:"hasComments",summaryKey:"has_comments"},{key:"hasDeps",summaryKey:"has_deps"},{key:"hasBody",summaryKey:"has_body"},{key:"hasLinkedCommand",summaryKey:"has_linked_command"},{key:"noNotes",summaryKey:"no_notes"},{key:"noLearnings",summaryKey:"no_learnings"},{key:"noFiles",summaryKey:"no_files"},{key:"noDocs",summaryKey:"no_docs"},{key:"noTests",summaryKey:"no_tests"},{key:"noComments",summaryKey:"no_comments"},{key:"noDeps",summaryKey:"no_deps"},{key:"emptyBody",summaryKey:"empty_body"},{key:"noLinkedCommand",summaryKey:"no_linked_command"}],Hu=[{key:"filterReviewerMissing",summaryKey:"filter_reviewer_missing"},{key:"filterRiskMissing",summaryKey:"filter_risk_missing"},{key:"filterConfidenceMissing",summaryKey:"filter_confidence_missing"},{key:"filterSprintMissing",summaryKey:"filter_sprint_missing"},{key:"filterReleaseMissing",summaryKey:"filter_release_missing"}];function Ia(e,t){for(let n of Bu)t[n.key]===!0&&(e[n.summaryKey]=!0)}function Ca(e,t){for(let n of Hu)t[n.key]===!0&&(e[n.summaryKey]=!0)}function Gu(e,t,n){for(let r of n){let i=t[r.optionKey];i!==void 0&&(e[r.summaryKey]=r.normalize?r.normalize(i):i)}}function Ku(e){let t={};return Ia(t,e),t}function zu(e){let t={};return Ca(t,e),t}var qu=[{optionKey:"type",summaryKey:"type"},{optionKey:"tag",summaryKey:"tag"},{optionKey:"priority",summaryKey:"priority"},{optionKey:"deadlineBefore",summaryKey:"deadline_before"},{optionKey:"deadlineAfter",summaryKey:"deadline_after"},{optionKey:"updatedAfter",summaryKey:"updated_after"},{optionKey:"updatedBefore",summaryKey:"updated_before"},{optionKey:"createdAfter",summaryKey:"created_after"},{optionKey:"createdBefore",summaryKey:"created_before"},{optionKey:"ids",summaryKey:"ids"},{optionKey:"assignee",summaryKey:"assignee"},{optionKey:"assigneeFilter",summaryKey:"assignee_filter"},{optionKey:"parent",summaryKey:"parent"},{optionKey:"sprint",summaryKey:"sprint"},{optionKey:"release",summaryKey:"release"}],Vu=[{optionKey:"type",summaryKey:"type"},{optionKey:"tag",summaryKey:"tag"},{optionKey:"priority",summaryKey:"priority"},{optionKey:"deadlineBefore",summaryKey:"deadline_before"},{optionKey:"deadlineAfter",summaryKey:"deadline_after"},{optionKey:"updatedAfter",summaryKey:"updated_after"},{optionKey:"updatedBefore",summaryKey:"updated_before"},{optionKey:"createdAfter",summaryKey:"created_after"},{optionKey:"createdBefore",summaryKey:"created_before"},{optionKey:"ids",summaryKey:"ids"},{optionKey:"assignee",summaryKey:"assignee"},{optionKey:"assigneeFilter",summaryKey:"assignee_filter"},{optionKey:"parent",summaryKey:"parent"},{optionKey:"sprint",summaryKey:"sprint"},{optionKey:"release",summaryKey:"release"},{optionKey:"limit",summaryKey:"limit"},{optionKey:"offset",summaryKey:"offset"},{optionKey:"includeBody",summaryKey:"include_body"},{optionKey:"compact",summaryKey:"compact"},{optionKey:"fields",summaryKey:"fields"}],Wu=[{key:"filterAcMissing",summaryKey:"filter_ac_missing"},{key:"filterEstimatesMissing",summaryKey:"filter_estimates_missing"},{key:"filterResolutionMissing",summaryKey:"filter_resolution_missing"},{key:"filterMetadataMissing",summaryKey:"filter_metadata_missing"}],Xu="-7d";function Yu(e){let{filtersStatus:t,options:n,treeEnabled:r,treeDepth:i,sortField:o,sortOrder:s,runtimeFieldFilters:a}=e,c={};return t!==null&&(c.status=t),n.dependencyBlocked===!0&&(c.blocked_semantics="status_or_dependency"),Gu(c,n,qu),Ta(c,n),n.filterAcMissing===!0&&(c.filter_ac_missing=!0),n.filterEstimatesMissing===!0&&(c.filter_estimates_missing=!0),n.filterResolutionMissing===!0&&(c.filter_resolution_missing=!0),n.filterMetadataMissing===!0&&(c.filter_metadata_missing=!0),Ca(c,n),Ia(c,n),n.limit!==void 0&&(c.limit=n.limit),n.offset!==void 0&&(c.offset=n.offset),n.includeBody===!0&&(c.include_body=!0),n.fields!==void 0&&(c.fields=n.fields),r&&(c.tree=!0,i!==void 0&&(c.tree_depth=i)),o!==void 0&&(c.sort=o,c.order=s),Uu(a)&&(c.runtime_filters=a),c}function Sa(e,t,n){let r=P(e.status,n),i=P(t.status,n);if(r!==i)return r?1:-1;let o=e.priority-t.priority;if(o!==0)return o;let s=C(t.updated_at,e.updated_at);return s!==0?s:(e.id??"").localeCompare(t.id??"")}function Ju(e,t){return[...e].sort((n,r)=>Sa(n,r,t))}function va(e,t){if(e!==void 0)return we(e,new Date,t)}function Tt(e,t){if(e==null)return;let n=String(e).trim();if(n.length!==0)return we(n,new Date,t)}function Qu(e){let t=e.updatedAfter!=null&&String(e.updatedAfter).trim().length>0;if([e.today===!0,e.recent===!0,t].filter(n=>n).length>1)throw new h("Choose only one updated_at window: --today, --recent, or --updated-after.",g.USAGE);if(e.today===!0){let n=new Date;return n.setHours(0,0,0,0),n.toISOString()}return e.recent===!0?Tt(Xu,"recent"):Tt(e.updatedAfter,"updated-after")}function Ta(e,t){t.today===!0&&(e.today=!0),t.recent===!0&&(e.recent=!0)}function Zu(e){if(e==null)return;let t=String(e).trim();if(t.length===0)throw new h("--ids requires at least one non-empty item ID",g.USAGE);let n=t.split(",").map(r=>r.trim()).filter(r=>r.length>0);if(n.length===0)throw new h("--ids requires at least one non-empty item ID",g.USAGE);return new Set(n)}function Ra(e){if(e===void 0)return;let t=String(e).trim(),n=t.length===0?Number.NaN:Number(t);if(!Number.isInteger(n)||n<0)throw new h("Offset filter must be a non-negative integer",g.USAGE);return n}function ef(e){if(e===void 0)return;let t=e.split(",").map(n=>n.trim()).filter(n=>n.length>0);if(t.length===0)throw new h("List --fields requires a comma-separated list of field names",g.USAGE);return[...new Set(t)]}function tf(e,t=e.projectionCommand??"list"){let n=e.compact===!0,r=e.brief===!0,i=e.full===!0,o=ef(e.fields);if(Number(n)+Number(r)+Number(i)+ +(o!==void 0)>1)throw new h("List projection options are mutually exclusive. Use one of --compact, --brief, --full, or --fields.",g.USAGE,{code:"projection_options_mutually_exclusive",recovery:{suggested_retry:`pm ${t} --brief`,suggested_retry_args:[t,"--brief"]}});if(i)return{mode:"full",fields:[]};if(r){let s=xa(e.sort);return{mode:"brief",fields:[...new Set([...Ur,s??"priority"])]}}return n?{mode:"compact",fields:[...jr]}:o?{mode:"fields",fields:[...new Set(o.map(s=>$e(s)))]}:{mode:"full",fields:[]}}function $e(e){return e.startsWith("item.")?e.slice(5):e}function nf(e,t,n){if(e.mode!=="fields")return;let r=Br(t),i=new Set(r.map(s=>$e(s))),o=e.fields.filter(s=>!i.has($e(s)));if(o.length>0){let s=[n,"--fields",e.fields.filter(a=>!o.includes(a)).join(",")||"id,title,status"];throw new h(`Unknown list --fields value(s): ${o.join(", ")}`,g.USAGE,{code:"unknown_field_projection",examples:["pm list --status open --fields id,title,status","pm list --fields id,title,parent,priority --limit 10","pm list --all --fields id,title,body --limit 5"],recovery:{allowed_values:r,suggested_retry:Ke(s),suggested_retry_args:s}})}}var rf=new Map([["updated","updated_at"],["update","updated_at"],["modified","updated_at"],["created","created_at"],["create","created_at"]]);function xa(e){if(e===void 0)return;let t=e.trim().toLowerCase(),n=rf.get(t);if(n)return n;if(!_a.includes(t))throw new h(`Sort field must be one of ${_a.join("|")} (aliases: updated->updated_at, created->created_at)`,g.USAGE);return t}function of(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(!ya.includes(t))throw new h(`Sort order must be one of ${ya.join("|")}`,g.USAGE);return t}function sf(e){return oe(e,"--tree-depth")}function af(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(!t)throw new h("Assignee filter must be one of assigned|unassigned",g.USAGE);if(t!=="assigned"&&t!=="unassigned")throw new h(`Invalid assignee filter "${e}". Allowed: assigned|unassigned`,g.USAGE);return t}function ba(e,t){return Ps(e,t,{strict:!0})}function Da(e){return wt(e,{label:"--tag",normalize:t=>t.toLowerCase()})}function cf(e,t,n){let r=Da(t);if(r===void 0)return;let i=new Set(e.flatMap(s=>s.tags.map(a=>a.trim().toLowerCase()))),o=[...r].filter(s=>!i.has(s));o.length>0&&n.push(`unknown_tags:${o.join(",")}`)}function df(e,t){if(e&&[...e].some(n=>n.toLowerCase()==="none"||n.toLowerCase()==="null"))throw new h('--assignee no longer accepts "none" or "null". Use --assignee-filter unassigned.',g.USAGE);if(e!==void 0&&t==="unassigned")throw new h("Cannot combine --assignee with --assignee-filter unassigned",g.USAGE)}function lf(e,t,n,r){let i=wt(t.assignee,{label:"--assignee"}),o=af(t.assigneeFilter);df(i,o);let s=Pu(t),a=ka(t);return{idsFilter:Zu(t.ids),statusSet:e&&e.length>0?new Set(e):void 0,excludeTerminal:t.excludeTerminal===!0,typeFilter:Xs(t.type,n),tagFilters:Da(t.tag),priorityFilter:Ys(t.priority),deadlineBefore:va(t.deadlineBefore,"deadline-before"),deadlineAfter:va(t.deadlineAfter,"deadline-after"),updatedAfter:Qu(t),updatedBefore:Tt(t.updatedBefore,"updated-before"),createdAfter:Tt(t.createdAfter,"created-after"),createdBefore:Tt(t.createdBefore,"created-before"),assigneeFilter:i,assigneeModeFilter:o,parentFilter:t.parent?.trim(),treeEnabled:t.tree===!0,sprintFilter:wt(t.sprint,{label:"--sprint"}),releaseFilter:wt(t.release,{label:"--release"}),missingMetadataFilters:s,missingMetadataActive:ai(s),lifecycleClassifier:aa(r),contentFieldFilters:a,contentFiltersActive:fa(a)}}function uf(e,t,n){return t.idsFilter&&!t.idsFilter.has(e.id)||t.statusSet&&!t.statusSet.has(e.status)||t.excludeTerminal&&P(e.status,n)||t.typeFilter&&!t.typeFilter.has(e.type)||t.tagFilters&&![...t.tagFilters].some(r=>(e.tags??[]).some(i=>i.trim().toLowerCase()===r))?!1:t.priorityFilter===void 0||t.priorityFilter.has(e.priority)}function ff(e,t){return zo(e,t)}function mf(e,t){return t.assigneeModeFilter==="assigned"&&!e.assignee||t.assigneeModeFilter==="unassigned"&&e.assignee?!1:t.assigneeFilter===void 0||e.assignee!==void 0&&t.assigneeFilter.has(e.assignee)}function pf(e,t,n){let r=e.parent?.trim().toLowerCase(),i=[...new Set([...n?.get(e.id.trim().toLowerCase())??[],...r?[r]:[]])];return t.parentFilter!==void 0&&!t.treeEnabled&&!i.includes(t.parentFilter.trim().toLowerCase())||t.sprintFilter!==void 0&&(e.sprint===void 0||!t.sprintFilter.has(e.sprint))?!1:t.releaseFilter===void 0||e.release!==void 0&&t.releaseFilter.has(e.release)}function hf(e,t,n,r,i){return!(!uf(e,t,n)||!ff(e,t)||!mf(e,t)||!pf(e,t,i)||t.missingMetadataActive&&!da(e,t.missingMetadataFilters,t.lifecycleClassifier)||t.contentFiltersActive&&!ma(e,t.contentFieldFilters)||!Sn(e,r))}function gf(e,t,n,r,i,o,s){let a=lf(t,n,r,i);return e.filter(c=>hf(c,a,i,o,s))}function Rt(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function wa(e,t,n,r){let i=e,o=typeof i.title=="string"?i.title:"",s=r??Rt(typeof i.parent=="string"?i.parent:void 0)??null;return{...e,tree_depth:t,tree_parent:s,tree_children:n,tree_title:`${" ".repeat(t)}${o}`}}function _f(e,t){let n=new Map,r=new Map;for(let i of e){let o=i.id.trim().toLowerCase();n.set(o,i);let s=t?t.parents_by_child.get(o)??[]:[Rt(i.parent)?.toLowerCase()].filter(a=>a!==void 0);for(let a of s){let c=r.get(a)??[];c.push(i),r.set(a,c)}}return{byId:n,childrenByParent:r}}function yf(e,t,n,r,i){return t?[...r.get(t.toLowerCase())??[]]:e.filter(o=>(i?i.parents_by_child.get(o.id.trim().toLowerCase())??[]:[Rt(o.parent)?.toLowerCase()].filter(s=>s!==void 0)).every(s=>!n.has(s)))}function vf(e,t,n,r,i=e){let{byId:o,childrenByParent:s}=_f(e,r),a=yf(e,t,o,s,r),c=[],d=new Set,l=new Map(i.map(f=>[f.id.trim().toLowerCase(),f.id.trim()])),u=[...a].reverse().map(f=>({node:f,depth:0,parentId:t===void 0?void 0:l.get(t.trim().toLowerCase())??t.trim()}));for(;u.length>0;){let{node:f,depth:m,parentId:p}=u.pop(),_=f.id.trim().toLowerCase();if(d.has(_))continue;d.add(_);let y=s.get(_)??[];if(c.push(wa(f,m,y.length,p)),!(n!==void 0&&m>=n))for(let b of[...y].reverse())u.push({node:b,depth:m+1,parentId:l.get(_)})}if(t===void 0&&n===void 0)for(let f of e){let m=f.id.trim().toLowerCase();d.has(m)||(d.add(m),c.push(wa(f,0,s.get(m)?.length??0)))}return c}function bf(e,t){return e===t?0:e===null?1:t===null?-1:e.localeCompare(t)}function wf(e,t){return e===t?0:e===null?1:t===null?-1:C(e,t)}function kf(e,t,n){switch(n){case"priority":return e.priority-t.priority;case"deadline":return wf(e.deadline??null,t.deadline??null);case"updated_at":return C(e.updated_at,t.updated_at);case"created_at":return C(e.created_at,t.created_at);case"title":return(e.title??"").localeCompare(t.title??"");case"parent":return bf(e.parent??null,t.parent??null);default:return 0}}function Ef(e,t,n,r){return t?[...e].sort((i,o)=>{let s=kf(i,o,t);if(s!==0)return n==="desc"?-s:s;let a=Sa(i,o,r);return n==="desc"?-a:a}):Ju(e,r)}function If(e,t,n=!1){let r=$e(t.trim());if(r.length===0)return null;let i=e;return n&&r==="title"&&typeof i.tree_title=="string"?i.tree_title:Object.prototype.hasOwnProperty.call(i,r)?i[r]??null:null}function Aa(e,t,n=!1){return t.mode==="full"?e:e.map(r=>{let i={};for(let o of t.fields)i[o]=If(r,o,n);return i})}function Cf(e){let t=[];for(let n of e)t.push(n.metadata_key);return[...t,...Rs(x())]}function Sf(e,t){let n=oe(e.limit);if(n!==void 0)return n;if(e.noTruncate!==!0)return t>=1e4?20:void 0}function Tf(e,t,n){return t.after===void 0?Ra(t.offset)??0:ze(e,t.after,n,r=>r.id)}function Oa(e,t,n){return{...e!==void 0?{applied_limit:e}:{},has_more:t,truncated:t,next_cursor:n??null}}async function Rf(e,t){let n=O(process.cwd(),t.path);await U(n);let r=await N(n),i=J(r.schema),o=mn(r.schema),s=e.projectionCommand??"list",a=tf(e,s);return nf(a,Cf(o.definitions),s),{pmRoot:n,settings:r,statusRegistry:i,runtimeFieldFilters:Cn(e,o,"list"),typeRegistry:M(r,x()),projection:a}}async function xf(e,t,n){let r=t.projection.fields.some(c=>$e(c)==="body"),i=t.projection.mode==="full"||t.projection.fields.some(c=>Ea.has($e(c))),o=ka(e),s=pa(o),a=ha(o);return e.includeBody||r||a?await kn(t.pmRoot,t.settings.item_format,t.typeRegistry.type_to_folder,n,t.settings.schema):i||s?await Ls(t.pmRoot,t.settings.item_format,t.typeRegistry.type_to_folder,n,t.settings.schema):await pe(t.pmRoot,t.settings.item_format,t.typeRegistry.type_to_folder,n,t.settings.schema)}function Df(e){let t=xa(e.sort),n=of(e.order)??"asc",r=e.tree===!0;if(!r&&e.treeDepth!==void 0)throw new h("List --tree-depth requires --tree",g.USAGE);if(!t&&e.order!==void 0)throw new h("List --order requires --sort",g.USAGE);return{sortField:t,sortOrder:n,treeEnabled:r,treeDepth:r?sf(e.treeDepth):void 0,parentRoot:r?Rt(e.parent):void 0}}function Af(e,t,n){let r=ba(t.status,n),i;t.lifecycleBucket==="in_progress"?i=[n.in_progress_status]:t.lifecycleBucket==="open"&&(i=[...n.active_statuses].filter(d=>d!==n.in_progress_status).sort((d,l)=>d.localeCompare(l)));let o=r??i??ba(e,n),s=$s(t.status),a=r||s?{...t,excludeTerminal:!1}:t,c="all";return s?c="all":r!==void 0?c=r.length===1?r[0]:r:t.lifecycleBucket!==void 0?c=t.lifecycleBucket:o!==void 0?c=o.length===1?o[0]:o:a.excludeTerminal===!0&&(c=null),{resolvedStatus:o,explicitAllStatuses:s,effectiveOptions:a,filtersStatus:c}}function Of(e,t,n,r,i){if(t.after!==void 0&&t.offset!==void 0)throw new h("List --after cannot be combined with --offset.",g.USAGE);let o=Sf(t,e.length),s=Tf(e,t,i),a=o===void 0?e.slice(s):e.slice(s,s+o),c=Aa(a,n,r),d=e.length,l=a.length>0&&s+a.length<d,u=l&&a.length>0?ue(i,a[a.length-1].id,s+a.length-1):void 0;return{projected:c,totalMatched:d,pageExtras:Oa(o,l,u)}}function La(e,t,n,r){return le("list",{pmRoot:r,status:e,options:an(t,Ms),sort:n.sortField??"default",order:n.sortOrder,tree:n.treeEnabled,tree_depth:n.treeDepth??null})}async function Lf(e){let{options:t,runtime:n,statusSelection:r,ordering:i}=e,o=new Set(["status","limit","offset","compact","brief","full","fields","format","stream","includeBody","excludeTerminal","dependencyBlocked","lifecycleBucket","noTruncate","projectionCommand","truncate","notes","learnings","files","docs","tests","comments","deps","linkedCommand"]),s=[n.projection.mode==="full",n.projection.fields.some(m=>{let p=$e(m);return p==="body"||Ea.has(p)})].includes(!0);if([t.limit===void 0,t.after!==void 0,t.noTruncate===!0,t.includeBody===!0,t.dependencyBlocked===!0,t.strictRead===!0,i.treeEnabled,i.sortField!==void 0,s,Lo(),Object.keys(n.runtimeFieldFilters).length>0,Object.entries(t).some(([m,p])=>p!==void 0&&!o.has(m))].includes(!0))return null;let a=await Qe(n.pmRoot,[...new Set(Object.values(n.typeRegistry.type_to_folder))]);if(!a)return null;let c=oe(t.limit),d=Ra(t.offset)??0,l=await Ds({pmRoot:n.pmRoot,expectedSourceCursor:a.source_cursor,query:{statuses:r.resolvedStatus,excludeStatuses:r.resolvedStatus===void 0&&r.effectiveOptions.excludeTerminal===!0?[...n.statusRegistry.terminal_statuses]:void 0,terminalStatuses:[...n.statusRegistry.terminal_statuses],limit:c,offset:d}});if(!l)return null;let u=l.items.length>0&&d+l.items.length<l.total,f=u?ue(La(r.filtersStatus,t,i,n.pmRoot),l.items.at(-1).id,d+l.items.length-1):void 0;return{projected:Aa(l.items,n.projection,!1),totalMatched:l.total,pageExtras:Oa(c,u,f)}}function Mf(e){let{filtersStatus:t,options:n,noTruncate:r,treeEnabled:i,treeDepth:o,sortField:s,sortOrder:a,runtimeFieldFilters:c}=e,d={};t!==null&&(d.status=t),n.dependencyBlocked===!0&&(d.blocked_semantics="status_or_dependency");let l=n;for(let u of Vu){let f=l[u.optionKey];f!=null&&(d[u.summaryKey]=f)}for(let u of Wu)l[u.key]===!0&&(d[u.summaryKey]=!0);return Object.assign(d,zu(n),Ku(n)),Ta(d,n),r&&(d.no_truncate=!0),n.strictRead===!0&&(d.strict_read=!0),i&&(d.tree=!0,o!==void 0&&(d.tree_depth=o)),s!==void 0&&(d.sort=s,d.order=a),d.runtime_filters=c,d}async function xt(e,t,n){let r=await Rf(t,n),i=[],o=Df(t),s=Af(e,t,r.statusRegistry),a=t.noTruncate===!0,c=await Lf({options:t,runtime:r,statusSelection:s,ordering:o}),d=c;if(!d){let p=await xf(t,r,i),_=o.treeEnabled||Rt(t.parent)!==void 0?ni(ea(p,z())):void 0;cf(p,t.tag,i);let y=gf(p,s.resolvedStatus,s.effectiveOptions,r.typeRegistry,r.statusRegistry,r.runtimeFieldFilters,_?.parents_by_child),b=t.dependencyBlocked===!0?(()=>{let k=vt(p,r.statusRegistry);return y.filter(S=>k.has(S.id.trim().toLowerCase()))})():y,v=Ef(b,o.sortField,o.sortOrder,r.statusRegistry),w=o.treeEnabled?vf(v,o.parentRoot,o.treeDepth,_,p):v;d=Of(w,t,r.projection,o.treeEnabled,La(s.filtersStatus,t,o,r.pmRoot))}let l=D(),u=[...new Set(i)].sort((p,_)=>p.localeCompare(_)),f=ju(u,c!==null,t.strictRead===!0),m=r.projection.mode==="full"?null:[...r.projection.fields];if(r.projection.mode==="compact"&&t.compact===!0){let p=Yu({filtersStatus:s.filtersStatus,options:t,treeEnabled:o.treeEnabled,treeDepth:o.treeDepth,sortField:o.sortField,sortOrder:o.sortOrder,runtimeFieldFilters:r.runtimeFieldFilters});return{items:d.projected,count:d.projected.length,total:d.totalMatched,...d.pageExtras,completeness:f,filters:p,projection:{mode:"compact",fields:m},...u.length>0?{warnings:u}:{}}}return{items:d.projected,count:d.projected.length,total:d.totalMatched,...d.pageExtras,completeness:f,filters:Mf({filtersStatus:s.filtersStatus,options:t,noTruncate:a,treeEnabled:o.treeEnabled,treeDepth:o.treeDepth,sortField:o.sortField,sortOrder:o.sortOrder,runtimeFieldFilters:r.runtimeFieldFilters}),projection:{mode:r.projection.mode,fields:m},sorting:{sort:o.sortField??"default",order:o.sortField?o.sortOrder:"asc",...o.sortField===void 0&&!o.treeEnabled?{effective_keys:[["status_registry:nonterminal_before_terminal","asc"],["priority","asc"],["updated_at","desc"],["id","asc"]]}:{}},now:l,...u.length>0?{warnings:u}:{}}}import{createHash as Nf}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]="e31ef0fb-e803-500b-b1e5-db9edfc880c4")}catch{}})();var Ff=64,$f=8;function Pf(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 jn(e,t=r=>r==="closed"||r==="canceled",n=re()){let r=e.filter(o=>typeof o?.id=="string"&&o.id.trim().length>0).map(o=>Pf(o,t)).sort(),i=n.list().map(o=>E(o)).sort();return Nf("sha256").update(r.join("")).update("").update(i.join("")).digest("hex")}function Ma(e,t,n){let r=t??n;if(!Number.isInteger(r)||r<1)throw new TypeError(`Invalid ${e} bound: ${String(t)}`);return r}var di=class{#e=new Map;#t;#n;constructor(t={}){this.#t=Ma("maxResultsPerWorkspace",t.maxResultsPerWorkspace,Ff),this.#n=Ma("maxWorkspaces",t.maxWorkspaces,$f)}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()}},Na=new di;function Un(){return Na}function fk(){Na.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]="3b494263-6359-57e9-8f34-b0bdcdeda93f")}catch{}})();var At=1200,jf=["prerequisite","dependent","ancestor","descendant","provenance","related"],Uf=new TextEncoder;function li(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 Dt(e){return Math.max(1,Math.ceil(Uf.encode(JSON.stringify(e)).byteLength/4))}function Bn(e,t,n){let r=n.resolve(e.kind);if(r?.ordering){let i=(r.precedence??"source_before_target")==="source_before_target"?e.source:e.target;return t===i?"prerequisite":"dependent"}if(r?.hierarchy){let i=r.hierarchyDirection==="source_parent"?e.source:e.target;return t===i?"ancestor":"descendant"}return e.kind==="discovered_from"||e.kind==="incident_from"?"provenance":"related"}function Bf(e,t,n,r){let i=e.filter(o=>o.source===t&&o.target===n||o.target===t&&o.source===n).map(o=>Bn(o,n,r));return[...new Set(i)].sort()}function Hf(e){return jf.find(t=>e.includes(t))}function Gf(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 m=e.neighborEdges(f.id,{direction:i,kinds:r.kinds,signal:r.signal});if(d+=m.meta.inspectedEdges,f.distance>=o){m.value.some(p=>!s.has(p.id))&&(l=!0);continue}for(let{id:p,edge:_}of m.value){if(s.has(p))continue;s.add(p);let y={id:p,distance:f.distance+1,via:f.id,role:Bn(_,p,n)};c.push(y),a.push(y)}}return{rows:c,visitedNodes:a.length,inspectedEdges:d,depthTruncated:l}}function Kf(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[Bn(a,s,n)]+=1;return{directEdges:i,directTotal:o.length,rootEdges:o.map(({edge:s})=>s)}}function zf(e,t,n,r){let i=new Set;for(let o of t){let s=o.source===n?o.target:o.source,a=Bn(o,s,r);(a==="prerequisite"||a==="ancestor")&&i.add(s)}return[...e].sort((o,s)=>Number(i.has(s.id))-Number(i.has(o.id))||o.distance-s.distance||o.id.localeCompare(s.id))}function qf(e,t){let n=e.distance===1?Bf(t.rootEdges,t.rootId,e.id,t.registry):[];return{...t.details.get(e.id)??{id:e.id},distance:e.distance,role:n.length>0?Hf(n):e.role,via:e.via,reasons:n.length>0?n:[`${e.role} via ${e.via} (depth ${e.distance})`]}}function Vf(e){let t=[],n=e.initialTokens,r=0;for(let i of e.candidates){if(t.length>=e.nodeLimit)break;let o=qf(i,e),s=Dt(o);if(n+s>e.tokenBudget)break;let a=e.rootEdges.filter(c=>c.source===i.id||c.target===i.id).reduce((c,d)=>c+Dt(d),0);if(n+r+s+a>e.tokenBudget){if(t.length>0)break}else r+=a;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 Wf(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)}).sort((o,s)=>+(s.source===e.rootId||s.target===e.rootId)-+(o.source===e.rootId||o.target===e.rootId)),r=[],i=e.initialTokens;for(let o of n){if(r.length>=e.edgeLimit)break;let s=Dt(o);i+s>e.tokenBudget||(r.push(o),i+=s)}return{edges:r,usedTokens:i,candidateCount:n.length}}function Fa(e,t,n,r={}){if(!e.nodes().includes(t))throw new TypeError(`Relationship node not found: ${t}`);let i=li(r.nodeLimit,20,"nodeLimit"),o=li(r.edgeLimit,40,"edgeLimit"),s=li(r.tokenBudget,At,"tokenBudget"),a=r.registry??re(),c=new Map(n.map(V=>[V.id,V])),d=c.get(t)??{id:t},{evidence:l=[],...u}=d,f=[...l],m=Gf(e,t,a,r),{rootEdges:p,..._}=Kf(e,t,a,r),y=zf(m.rows,p,t,a),b=le("relationship-context",{rootId:t,direction:r.direction??"both",kinds:[...r.kinds??[]].sort(),maxDepth:r.maxDepth??3,ordering:"required-root-evidence-first-v1"}),v=ze(y,r.cursor,b,({id:V})=>V,"--cursor"),w=y.slice(v),k=Dt(u)+Dt(f);if(k>s)throw new TypeError("Relationship context tokenBudget cannot fit root and evidence");let S=Vf({candidates:w,details:c,rootEdges:p,rootId:t,registry:a,nodeLimit:i,tokenBudget:s,initialTokens:k}),{nodes:L}=S,B=new Set([t,...L.map(({id:V})=>V)]),$=Wf({graph:e,rootId:t,included:B,options:r,registry:a,edgeLimit:o,tokenBudget:s,initialTokens:S.usedTokens}),{edges:ce,usedTokens:H}=$,j=v+L.length,q=j<y.length,te=L.at(-1),Y=$.candidateCount-ce.length,ne=m.depthTruncated||q||Y>0,Te={rootId:t,...u.status===void 0?{}:{rootStatus:u.status},..._,discoveredNodes:y.length,returnedNodes:L.length,returnedEdges:ce.length,omittedNodes:y.length-j,omittedEdges:Y,evidenceCount:f.length,hasMore:q};return{root:u,summary:Te,nodes:L,edges:ce,evidence:f,meta:{exact:!0,truncated:ne,completeness:ne?"truncated":"complete",nodeLimit:i,edgeLimit:o,tokenBudget:s,usedTokens:H,visitedNodes:m.visitedNodes,inspectedEdges:m.inspectedEdges,omittedNodes:y.length-j,omittedEdges:Y,...q&&te?{nextCursor:ue(b,te.id,j-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]="196b7f2d-b09b-5432-b4ef-9cdf82e92731")}catch{}})();var Xf=["tree","graph","context"],Yf=["none","repeated"],Jf=["outgoing","incoming","both"],Qf=32,Zf=200,em=400,tm=16e3;function nm(e){let t=e?.trim().toLowerCase()??"tree";if(Xf.includes(t))return t;throw new h(`Invalid --format value "${e}". Use "tree", "graph", or "context".`,g.USAGE)}function _e(e,t){if(e===void 0)return;let n=typeof e=="number"?e:Number(e.trim());if(!Number.isInteger(n)||n<1)throw new h(`Invalid --${t} value "${e}". Use a positive integer.`,g.USAGE);return n}function Hn(e){if(e===void 0)return;let t=typeof e=="number"?e:Number(e.trim());if(!Number.isInteger(t)||t<0)throw new h(`Invalid --max-depth value "${e}". Use a non-negative integer.`,g.USAGE);return t}function rm(e){let t=e?.trim().toLowerCase()??"none";if(Yf.includes(t))return t;throw new h(`Invalid --collapse value "${e}". Use "none" or "repeated".`,g.USAGE)}function fi(e){let t=e?.trim().toLowerCase()??"both";if(Jf.includes(t))return t;throw new h(`Invalid --direction value "${e}". Use "outgoing", "incoming", or "both".`,g.USAGE)}function mi(e,t=re()){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 h(`Invalid --kind value "${i}". Registered kinds: ${s}.`,g.USAGE)}r.add(o.kind)}return[...r].sort()}function im(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 om(e){return{id:e.id,title:e.title,type:e.type,status:e.status,dependencies:im(e.dependencies)}}function sm(e){return ht(new TextEncoder().encode(JSON.stringify({...e,dependencies:void 0})).byteLength)}function am(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(Pa(d.id,n,r,i,o,s,a,c+1,d.kind))}}function cm(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 Pa(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+=sm(u),cm(u,l,d,r,i,o,s,a))return u;i==="repeated"&&o.add(d);let f=new Set(n);return f.add(d),am(u,l,t,f,r,i,o,s,a),u}function $a(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 dm(e){let t=new Map,n=new Map,r=[e];for(;r.length>0;){let a=r.pop();t.set(a.id,$a(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,$a(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 ja(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 lm(e,t=re()){let n=Hn(e.maxDepth),r=_e(e.nodeLimit,"node-limit"),i=_e(e.edgeLimit,"edge-limit"),o=_e(e.tokenBudget,"token-budget"),s=mi(e.kind,t);return{direction:fi(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 um(e,t,n,r){return Fa(e.graph,t,e.details.map(i=>i.id===t&&r.length>0?{...i,evidence:r}:i),n)}function ui(e,t,n,r){for(let i of n.slice(0,r)){let o=i?.trim();o&&e.push(`${t}:${o}`)}}async function fm(e,t,n,r){let i=await me(e,t,n.id_prefix,n.item_format,r);if(!i)return[];let{document:o}=await Re(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,m])=>`${f}=${m}`).join(",")}`];return ui(u,"file",a.map(f=>f.path),3),ui(u,"test",c.map(f=>f.command??f.path),2),ui(u,"doc",d.map(f=>f.path),2),u}function mm(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 pm(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 Ua(e,t){let n=Oo(),r=t.commandOptionsOverride??(n?.command==="deps"?n.options:t.commandOptions);return qo("deps",{...r,...t.global,resolvedOutputFormat:t.format},e)}function pi(e,t){let n=Ua(e,t),r=i=>Wo(i,t.format,t.global.lean===!0);return r(t.global.tokenAccounting===!0?Vo(n,r):n)}function Ba(e,t,n){let r;for(;;){let i=ht(new TextEncoder().encode(pi(e,t)).byteLength);if(i===r)return i;n(i),r=i}}function Ha(e){return e instanceof TypeError&&e.message.startsWith("Relationship context tokenBudget cannot fit ")}function Ga(e){let{assembly:t,canonicalId:n,contextOptions:r,rootEvidence:i,summaryOnly:o,rendering:s,missingCount:a,missingReferences:c}=e,d=r.edgeLimit??40,l=Math.min(d,c.length),u=r.tokenBudget,f;for(;;){let m=um(t,n,{...r,...u===void 0?{}:{tokenBudget:u}},i);f??=m.meta.tokenBudget,u??=f;let p=mm({canonicalId:n,context:m,missingCount:a,missingReferences:c,referenceLimit:l,summaryOnly:o});if(o){if(ht(new TextEncoder().encode(pi(De(p,!0,s.legacyAliasCounts),s)).byteLength)>f)throw new TypeError("Relationship context tokenBudget cannot fit the rendered summary");return p}if(m.meta.tokenBudget=f,m.meta.usedTokens=Ba(De(p,!1,s.legacyAliasCounts),s,b=>{m.meta.usedTokens=b}),m.meta.usedTokens<=f)return p;if(l>0){l-=1;continue}let _=u,y=_*f/m.meta.usedTokens;u=Math.min(_-1,Math.max(1,Math.floor(y*.9)))}}function Ka(e,t){let n=e.contextOptions,r={...e.rendering.global,outputFormat:e.rendering.format},i=["--pm-path",e.pmRoot,"item","deps",e.canonicalId,"--format","context","--output-format",e.rendering.format,"--token-budget"],o=i.length;i.push(String(t));let s=new Set(["--pm-path","--format","--output-format","--token-budget"]),a={format:"context",tokenBudget:t,kind:n.kinds},c=[["--max-depth","maxDepth",n.maxDepth],["--node-limit","nodeLimit",n.nodeLimit],["--edge-limit","edgeLimit",n.edgeLimit],["--direction","direction",n.direction],["--cursor","cursor",n.cursor],["--output-include","outputInclude",r.outputInclude],["--output-limit","outputLimit",r.outputLimit],["--output-budget","outputBudget",r.outputBudget],["--output-session","outputSession",r.outputSession],["--output-cursor","outputCursor",r.outputCursor]];for(let[u,f,m]of c)m!==void 0&&(i.push(u,String(m)),s.add(u),a[f]=m);for(let u of n.kinds??[])i.push("--kind",u),s.add("--kind");let d=[["--summary","summary",e.summaryOnly],["--full","full",e.rendering.commandOptions.full],["--json","json",r.json],["--lean","lean",r.lean],["--output-row-contract","outputRowContract",r.outputRowContract],["--token-accounting","tokenAccounting",r.tokenAccounting],["--no-extensions","noExtensions",r.noExtensions],["--no-pager","noPager",r.noPager]];for(let[u,f,m]of d)m===!0&&(i.push(u),s.add(u),a[f]=!0);let l=jo.find(u=>u.command==="deps");return Reflect.set(a,Po,{canonical_include_modes:[],cli_invocation_observed:!0,explicit_legacy_aliases:Object.values(l.dimensions).flatMap(u=>u.legacy_aliases.flatMap(f=>s.has(f.flag)?[f.flag]:[]))}),Uo("deps",a),pt(a.summary===!0,a.full===!0,"--summary"),r.outputInclude=a.outputInclude,{args:i,budgetIndex:o,summaryOnly:a.summary===!0,rendering:{...e.rendering,global:r,commandOptionsOverride:a}}}function hm(e,t,n){let r={...t.rendering,commandOptionsOverride:{...t.rendering.commandOptionsOverride,tokenBudget:n}},i;try{i=Ga({...e,contextOptions:{...e.contextOptions,tokenBudget:n},summaryOnly:t.summaryOnly,rootEvidence:t.summaryOnly?[]:e.rootEvidence,rendering:r})}catch(s){if(!Ha(s))throw s;return"native_floor"}let o=Ua(De(i,t.summaryOnly,r.legacyAliasCounts),r);return sn(o)?"output_constraints":"fits"}async function gm(e,t){let n=e.contextOptions.tokenBudget??At,r=Ka(e,n),i=(r.summaryOnly?1:1+Math.min(e.contextOptions.edgeLimit??40,e.missingReferences.length))*(e.assembly.details.reduce((u,f)=>u+f.id.length+f.title.length+f.status.length+(f.type?.length??0),e.assembly.graph.edges().length+e.missingReferences.length)+(r.summaryOnly?[]:e.rootEvidence).reduce((u,f)=>u+f.length,0)),{findContextBudgetRecovery:o}=await import("./context-budget-recovery-L2WP5S26.js"),s=o({requested:n,initialBudget:At,workUnits:i,probe:u=>hm(e,r,u)}),a=["--pm-path",e.pmRoot,"item","deps",e.canonicalId,"--format","tree","--summary"],c=Ke(a),d=s.feasible_tokens===null?a:[...r.args];s.feasible_tokens!==null&&(d[r.budgetIndex]=String(s.feasible_tokens));let l=Ke(d);return js("Relationship context tokenBudget cannot fit the required rendered packet",{exitCode:g.USAGE,cause:t,context:{code:"invalid_argument_value",field:"tokenBudget",value:String(n),required:s.feasible_tokens===null?"Inspect the compact summary and review the output constraints.":"Retry the preserved context query with --token-budget "+s.feasible_tokens+".",why:"Budget advice is verified against the current query. A minimum is reported only after every smaller positive budget is checked.",examples:[l,c],nextSteps:[l],recovery:{recovery_mode:"compact",suggested_flags:["--token-budget"],token_budget:s,suggested_retry_args:d,suggested_retry:l,next_best_command:c,fallback_candidates:[{source:"relationship_summary",command:c,reason:"Inspect bounded counts separately from context rows."}]}}})}async function _m(e){let{pmRoot:t,assembly:n,canonicalId:r,options:i,rootEvidence:o,summaryOnly:s,rendering:a}=e,c=lm(i,n.graph.registry()),d=n.graph.closure(r,{direction:c.direction,...c.kinds===void 0?{}:{kinds:c.kinds},maxDepth:c.maxDepth??3}),l=d.value.filter(b=>n.missingIdSet.has(b.toLowerCase())),u=new Set(l.map(b=>b.toLowerCase())),f=n.graph.registry(),m=c.kinds?new Set(c.kinds.map(b=>f.require(b).kind)):void 0,p=new Set([r,...d.value]),_=[...n.dangling.active,...n.dangling.legacy_terminal].filter(b=>pm({row:b,missingReachableSet:u,packetIds:p,filteredKinds:m,registry:f})),y={pmRoot:t,assembly:n,canonicalId:r,contextOptions:c,rootEvidence:o,summaryOnly:s,rendering:a,missingCount:l.length,missingReferences:_};try{return Ga(y)}catch(b){if(b instanceof h&&b.code==="invalid_query_cursor"){let v=Ka({...y,contextOptions:{...c,cursor:void 0},rendering:{...a,global:{...a.global,outputCursor:void 0}}},c.tokenBudget??At),w=Ke(v.args);throw new h(b.message,b.exitCode,{...b.context,nextSteps:[...b.context.nextSteps,w],recovery:{suggested_retry:w,suggested_retry_args:v.args}})}throw Ha(b)?await gm(y,b):b}}function ym(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 vm(e,t,n,r,i,o,s){let a=i??Qf,c=_e(n.nodeLimit,"node-limit")??Zf,d=_e(n.edgeLimit,"edge-limit")??em,l=_e(n.tokenBudget,"token-budget")??tm,u={nodeLimit:c,edgeLimit:d,tokenBudget:l,nodes:0,edges:0,estimatedTokens:0,reasons:new Set},f=Pa(e,r,new Set,a,t==="graph"?"repeated":o,new Set,u),m=ja(e,r,void 0),p;for(;;){let _=dm(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:m.node_count,total_edge_count:m.edge_count,omitted_node_count:Math.max(0,m.node_count-_.nodes.length),omitted_edge_count:Math.max(0,m.edge_count-_.edges.length)},b={id:e,format:t,node_count:_.nodes.length,edge_count:_.edges.length,edge_basis:"deduplicated_directed",missing_count:_.missing_ids.length,...y?{truncation:y}:{}};if(p=t==="tree"?{...b,tree:f}:{...b,graph:_},(p.truncation===void 0?ht(new TextEncoder().encode(pi(De(p,!1,s.legacyAliasCounts),s)).byteLength):Ba(De(p,!1,s.legacyAliasCounts),s,v=>{p.truncation.estimated_tokens=v}))<=l)return p;if(!ym(f))return u.reasons.add("token_budget"),p;u.reasons.add("token_budget")}}function De(e,t,n={}){let r={name:e.format==="tree"?"dependency_tree":e.format==="graph"?"dependency_graph":"relationship_context",restore_with:"--full"},i=e.context?.meta.truncated?[{name:"relationship_context_bounds",restore_with:"--token-budget <n> --node-limit <n> --edge-limit <n> --max-depth <n>"}]:[];return{...e,legacy_alias_counts:n,projection:{mode:t?"summary":"full",declared_field_groups:[r,...i],included_field_groups:t?[]:[r.name]}}}async function Uk(e,t,n){let r=O(process.cwd(),n.path);await U(r);let i=nm(t.format),o=Hn(t.maxDepth),s=rm(t.collapse);pt(t.summary===!0,t.full===!0,"--summary");let a=t.summary===!0,c=await N(r),d=M(c,x()),l=await pe(r,c.item_format,d.type_to_folder,void 0,c.schema),u=J(c.schema),f=new Map(l.map(y=>[y.id.trim().toLowerCase(),om(y)])),m=ii(l,y=>P(y,u));for(let y of[...m.active,...m.legacy_terminal]){let b=f.get(y.holder_id.trim().toLowerCase()),v=y.kind.trim().toLowerCase();b&&!b.dependencies.some(w=>w.id.trim().toLowerCase()===y.target_id.trim().toLowerCase()&&w.kind===v)&&b.dependencies.push({id:y.target_id,kind:v})}if(!f.has(e.trim().toLowerCase()))throw new h(`Item ${e} not found`,g.NOT_FOUND);let p=n.outputFormat??(n.json===!0||n.json===void 0&&n.defaultOutputFormat==="json"?"json":"toon");if(i==="context"){let y=f.get(e.trim().toLowerCase()).id,b=a?[]:await fm(r,y,c,d.type_to_folder),v=S=>P(S,u),w=z(),k=Un().lookup(r,jn(l,v,w),()=>St(l,v,w));return De(await _m({pmRoot:r,assembly:k.assembly,canonicalId:y,options:t,rootEvidence:b,summaryOnly:a,rendering:{format:p,global:n,commandOptions:t,legacyAliasCounts:k.assembly.legacyAliasCounts}}),a,k.assembly.legacyAliasCounts)}let _=Object.fromEntries(Object.entries(St(l,y=>P(y,u)).legacyAliasCounts));return a?De({id:e,format:i,...ja(e,f,o)},!0,_):De(vm(e,i,t,f,o,s,{format:p,global:n,commandOptions:t,legacyAliasCounts:_}),!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]="f60c628a-2e42-5770-a001-39cce5f92595")}catch{}})();var bm=Ie.paths,wm=Ie.visited_paths,km=Ie.path_depth;function hi(e,t){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new TypeError(`Invalid path ${e} bound: ${String(t)}`)}function Gn(e,t){return t.hierarchyDirection==="target_parent"?e.target:e.source}function Ot(e,t){return(t.precedence??"source_before_target")==="target_before_source"?e.target:e.source}function rt(e,t){let n=Ot(e,t);return{predecessor:n,successor:n===e.source?e.target:e.source}}function Em(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 Im(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 Cm(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 Kn(e,t,n,r,i){if(!e.hasNode(t))throw new TypeError(`Relationship node not found: ${t}`);let o=Em(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 m=d.queue[f];l+=1;let p=Im(e,m.id,o,r,i);if(u+=p.inspectedEdges,Cm(p,m.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 za(e,t){if(!e.hasNode(t))throw new TypeError(`Relationship node not found: ${t}`)}function qa(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 Sm(e,t,n,r,i,o,s){for(let a of qa(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 Va(e,t,n={}){return Kn(e,t,n,"hierarchy",(r,i)=>Gn(r.edge,i)===r.id)}function Wa(e,t,n={}){return Kn(e,t,n,"hierarchy",(r,i,o)=>Gn(r.edge,i)===o)}function Xa(e,t,n={}){return Kn(e,t,n,"ordering",(r,i)=>Ot(r.edge,i)===r.id)}function Ya(e,t,n={}){return Kn(e,t,n,"ordering",(r,i,o)=>Ot(r.edge,i)===o)}function Tm(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 m=c.queue[f];if(d+=1,m.edges.length>=s){qa(e,m,r,a,c).length>0&&(l=!0);continue}if(Sm(e,m,n,r,a,u,c)){l=!0;break}}return{value:c.value.slice(0,i),meta:{visitedNodes:d,inspectedEdges:c.inspectedEdges,truncated:l}}}function Ja(e,t,n,r={}){za(e,t),za(e,n);let i=r.maxPaths??bm,o=r.maxVisitedPaths??wm,s=r.maxDepth??km;hi("maxPaths",i),hi("maxVisitedPaths",o),hi("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}}:Tm(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]="789f7451-ceb1-5e5c-b2b6-45eec49580ce")}catch{}})();var Rm=16,xm=2,Dm=8;function zn(e,t){if(!Number.isInteger(t)||t<1)throw new TypeError(`Invalid ${e} bound: ${String(t)}`)}function qn(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 Am(e,t){let n=new Map;qn(e,t,r=>{Qa(n,r.source,r.target),Qa(n,r.target,r.source)});for(let r of n.values())r.sort();return n}function Qa(e,t,n){let r=e.get(t);r===void 0?e.set(t,[n]):r.push(n)}function Om(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 Lm(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 Za(e,t={}){let n=t.maxIterations??Rm,r=t.minSize??xm;zn("maxIterations",n),zn("minSize",r);let i=Am(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 m=Om(f,s);m!==s.get(u)&&(s.set(u,m),c=!1)}}return{value:{communities:Lm(s,r),iterations:a,converged:c},meta:{visitedNodes:d,inspectedEdges:l,truncated:!c}}}function Vn(e){return e.direction==="directed"&&(e.ordering||e.hierarchy)}function Wn(e){return e.inverse!==void 0&&e.inverse<e.kind?e.inverse:e.kind}function gi(e,t){return(t.hierarchy?Gn(e,t):e.source===Ot(e,t)?e.target:e.source)===e.target?{from:e.source,to:e.target}:{from:e.target,to:e.source}}function Mm(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(!Vn(o))throw new TypeError(`Relationship kind ${o.kind} is not a directed ordering or hierarchy kind`);r.add(Wn(o))}return r}function Nm(e,t){let n=e.registry(),r=new Map;for(let i of e.edges()){let o=n.require(i.kind);if(!Vn(o))continue;let s=Wn(o);if(t!==void 0&&!t.has(s))continue;let a=gi(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 Fm(e){let t=new Map;for(let[n,r]of e.adjacency)t.set(n,[...r].sort());return t}function $m(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 Pm(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 $m(r,t.from,n.id,s);i.push({id:s,depth:n.depth+1})}}function jm(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=Pm(e,t,a,i,o,r);if(c!==void 0)return c}}function it(e,t={}){let n=t.maxDepth??Dm;zn("maxDepth",n),t.limit!==void 0&&zn("limit",t.limit);let r=t.limit??Number.POSITIVE_INFINITY,i=Mm(e,t.kinds),o=Nm(e,i),s=[],a={visitedNodes:0,inspectedEdges:0},c=!1;e:for(let d of[...o.keys()].sort()){let l=o.get(d),u=Fm(l);for(let f of l.records){t.signal?.throwIfAborted();let m=jm(u,f,n,a);if(m!==void 0){if(s.length>=r){c=!0;break e}s.push({edge:f.edge,witness:m})}}}return{value:s,meta:{visitedNodes:a.visitedNodes,inspectedEdges:a.inspectedEdges,truncated:c}}}function Um(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 Bm(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,Um(l,u,f.value,i,a))}return{order:o,successors:s,predecessors:a.predecessors,inspectedEdges:c,truncated:a.truncated}}function Hm(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 Gm(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 Km(e,t,n){let r;for(let i of[...e].sort())t.has(i)&&(r=r===void 0?i:Gm(r,i,t,n));return r}function zm(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=Km(e.predecessors.get(a),o,r);c!==void 0&&o.get(a)!==c&&(o.set(a,c),s=!0)}}return o}function ec(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=Bm(e,t,n),i=Hm(r,t),o=new Map(i.map((d,l)=>[d,l])),s=zm(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]="3cef3a97-fda4-5811-9e69-04ff722e40a1")}catch{}})();function tc(e){return Math.round(e*1e6)/1e6}function nc(e,t,n){let r=e.get(t);r===void 0?e.set(t,new Set([n])):r.add(n)}function rc(e,t){let n=new Map(e.nodes().map(i=>[i,new Set]));qn(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 qm(e,t){let n=new Map,r=new Map;return qn(e,t,(i,o)=>{if(!o.ordering)return;let{predecessor:s,successor:a}=rt(i,o);nc(r,s,a),nc(n,a,s)}),{incoming:n,outgoing:r}}function Vm(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 m of t.get(u))if(n.inspectedEdges+=1,r.has(m)||(r.set(m,f+1),a.push(m)),r.get(m)===f+1){i.set(m,(i.get(m)??0)+i.get(u));let p=o.get(m);p===void 0?o.set(m,[u]):p.push(u)}}return{stack:s,sigma:i,predecessors:o,reachableCount:c,distanceSum:d}}function Wm(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 Xm(e,t){return t<=1||e.reachableCount===0?0:e.reachableCount/(t-1)*(e.reachableCount/e.distanceSum)}function Ym(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:tc((r.get(e)??0)/2),closeness:tc(i.get(e))}}function ic(e,t={}){let n=rc(e,t.kinds),r=qm(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=Vm(l,n,a);s.set(l,Xm(u,i.length)),Wm(u,l,o)}let c=0;for(let l of n.values())c+=l.length;let d=i.map(l=>Ym(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 Jm(e,t){return e<=t?{source:e,target:t}:{source:t,target:e}}function Qm(e,t,n){let r=t.get(e.node)[e.neighborIndex];if(e.neighborIndex+=1,n.inspectedEdges+=1,r!==e.parent){if(n.discovery.has(r)){n.low.set(e.node,Math.min(n.low.get(e.node),n.discovery.get(r)));return}return e.children+=1,n.discovery.set(r,n.timer),n.low.set(r,n.timer),n.timer+=1,{node:r,parent:e.node,neighborIndex:0,children:0}}}function Zm(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(Jm(r,e.node))}function ep(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=Qm(o,t,n);s!==void 0&&i.push(s)}else Zm(o,e,n),i.pop()}}function Xn(e,t={}){let n=rc(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)||ep(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]="32f3ce0d-64ac-5ad4-b27a-2a279718de22")}catch{}})();function tp(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}=rt(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 np(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 rp(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 ip(e,t,n,r,i){let o=new Map;for(let s=e.length-1;s>=0;s-=1){let a=e[s],c=np(t.forward.get(a),r,o,i);o.set(a,c-1)}return e.map(s=>rp(s,n[s],o.get(s))).sort((s,a)=>s.slack-a.slack||s.earliestStart-a.earliestStart||s.id.localeCompare(a.id))}function oc(e,t={}){t.signal?.throwIfAborted();let n=An(e,{registry:e.registry()}),r=tp(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=ip(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]="fa17672a-97a2-5f94-bdfe-9df970cc038b")}catch{}})();function op(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 sp(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 ap(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 cp(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}=rt(r,i),a=t.get(o);a.successors.has(s)||(a.successors.add(s),t.get(s).pending+=1)}}function dp(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 lp(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=sp(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 up(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"),lp(d,l,t,n,r,i,c,a)}}function sc(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,m]of[["maxWork",i],["limit",o]])if(!Number.isSafeInteger(m)||m<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,m)=>{s.complete=!1,s.residual_count+=1,s.residuals.length<o?s.residuals.push({id:f,reason:m}):s.truncated=!0},l=ap(a,t,r,d,n.signal);cp(e,l,n.signal);let u=dp(a,l,n.signal);return op(u,l,n.signal),up(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]="ccb7d865-8baa-5379-a810-7be494eadcb1")}catch{}})();function ot(){return{nodes:0,isolated:0,degree_leq_one:0,semantic_nodes:0,without_semantic_edges:0,degree_histogram:{}}}function dc(e,t,n,r){let i={all:ot(),active:ot(),terminal:ot()},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)??ot();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 ac(e){if(!Yn(e))return!1;let t=e;if(!["nodes","isolated","degree_leq_one","semantic_nodes","without_semantic_edges"].every(r=>Number.isSafeInteger(t[r])&&Number(t[r])>=0)||!Yn(t.degree_histogram))return!1;let n=Object.entries(t.degree_histogram);return n.every(([r,i])=>/^(0|[1-9]\d*)$/.test(r)&&Number.isSafeInteger(i)&&Number(i)>=0)&&n.reduce((r,[,i])=>r+Number(i),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 Yn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function lc(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:!Yn(t)||!Yn(n)?!1:["all","active","terminal"].every(r=>ac(t[r]))&&Object.values(n).every(ac)}function cc(e,t){return Object.fromEntries([...new Set([...Object.keys(e),...Object.keys(t)])].sort().map(n=>{let r=Object.hasOwn(e,n)?e[n]:ot(),i=Object.hasOwn(t,n)?t[n]:ot(),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 uc(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:cc(e.coverage_by_lifecycle,t.coverage_by_lifecycle),coverage_by_status:cc(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 st=["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]="34b2e83e-f6a1-57e7-84ee-4ad83acb2e19")}catch{}})();var fp=25,mp="milestone",pp="outcome milestone:",hp=new Set(["discovered_from","incident_from","recurs_from","supersedes","verifies"]);function Jn(e){return hp.has(e)}var fc={error:0,warning:1,info:2};function mc(e){return new Set((e??[]).filter(t=>typeof t=="string").map(t=>t.trim().toLowerCase()))}function at(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 gp(e,t){return e.cycles.map(n=>at(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 pc(e,t,n){let r=e.cardinality_violations.filter(i=>i.legacy_terminal===n);return r.length===0?[]:[at(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 hc(e,t,n){let r=e.divergences.filter(i=>i.legacy_terminal===n);return r.length===0?[]:[at(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 _p(e,t){let n=Pn(e);return n?[...gp(n,t),...pc(n,t,!1),...pc(n,t,!0),...hc(n,t,!1),...hc(n,t,!0)]:[]}function yp(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 _c(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 vp(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))):(_c(o,r),t.push({node:o,neighborIndex:0})),!0}function bp(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 wp(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(_c(r,t);i.length>0;){let o=i.at(-1);vp(o,i,e,t)||bp(o,i,e,t)}}return t.components.sort((r,i)=>r[0].localeCompare(i[0]))}function _i(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(at(r,i,o,s,t,n,a))}function kp(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(_i),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(_i),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(_i),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 vi(e,t){let n=t.get(e);return n?!n.terminal:!0}function yc(e){return`${e.holder_id} -> ${e.target_id} (blocked_by scalar + ${e.dependency_kind} dependency)`}function Ep(e,t){let n=[],r=[];for(let o of e.orderingContradictions??[])(o.legacy_terminal?r:n).push(yc(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 Ip(e,t,n,r){let i=[],o=yp(e);for(let c of wp(o)){let d=c.some(f=>vi(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(yc);i.push(d?at("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):at("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 Qn(e){let t=e.edges.map(n=>n.kind).sort((n,r)=>n.localeCompare(r));return`${e.from} -> ${e.to} (${t.join(" + ")})`}function bi(e){let t=e.graph.registry(),n=new Map;for(let i of e.graph.edges()){let o=t.require(i.kind);if(!Vn(o))continue;let s=gi(i,o);if(s.from===s.to)continue;let a=`${Wn(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 Cp(e,t,n){let r=[],i=[];for(let s of bi(e))(vi(s.from,t)||vi(s.to,t)?r:i).push(Qn(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 Sp(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 Tp(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 Rp(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 xp(e,t,n,r){let i=0,o=0,s=0,a=0;for(let m of e.values())if(r?.throwIfAborted(),!t.has(m.id)&&!(m.missing||m.status==="external")){if(m.terminal){s+=1,n.has(m.id)&&(a+=1);continue}n.has(m.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 Dp(e,t,n){let r=new Set(e.details.filter(a=>a.type?.toLowerCase()===mp&&a.title.trim().toLowerCase().startsWith(pp)).map(a=>a.id)),{basis:i,reverse:o}=Tp(e,n),s=Rp(r,o,n);return{outcome_nodes:r.size,outcome_reachability_basis:i,...xp(t,r,s,n)}}function Ap(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 Op(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||Ap(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=it(e.graph,{signal:s}).value,m=new Set(f.map(({edge:v})=>`${v.source.toLowerCase()}\0${v.target.toLowerCase()}\0${v.kind}`));for(let v of e.orderingContradictions??[])m.add(`${v.holder_id.toLowerCase()}\0${v.target_id.toLowerCase()}\0${v.dependency_kind}`);let p=Object.fromEntries(Object.entries(o).sort(([v],[w])=>v.localeCompare(w))),_=Object.entries(p).reduce((v,[w,k])=>v+(Jn(w)?k:0),0),y=Xn(e.graph,{signal:s}).value,b=Dp(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-m.size,redundant_edges:f.length,ordering_contradiction_edges:e.orderingContradictions?.length??0,edge_basis:"deduplicated_directed",edges_by_kind:p,edge_share_by_kind:Object.fromEntries(Object.entries(p).map(([v,w])=>[v,w/u])),semantic_edges:_,semantic_edge_share:u===0?0:_/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(st.map(v=>[v,0]))}}}function Zn(e,t={}){let n=t.isTerminal??(f=>f==="closed"||f==="canceled"),r=t.isBlocked??(f=>f==="blocked"),i=t.maxSampleSize??fp;if(!Number.isInteger(i)||i<1)throw new TypeError(`Invalid audit sample bound: ${String(t.maxSampleSize)}`);let o=mc(t.exemptIsolates),s=mc(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=kp(e,n,i);d.push(..._p(e,i)),t.signal?.throwIfAborted(),d.push(...Ep(e,i)),t.signal?.throwIfAborted(),d.push(...Ip(e,a,r,i)),t.signal?.throwIfAborted(),d.push(...Cp(e,a,i),...Sp(e,i)),t.signal?.throwIfAborted();let l=Op(e,a,o,s,i,c,t.signal);d.push(...l.findings),d.sort((f,m)=>fc[f.severity]-fc[m.severity]||f.code.localeCompare(m.code)||f.sample[0].localeCompare(m.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,...dc(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 yi(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 gc(e){return e.profile.coverage_by_type??{}}function Lp(e,t){let n={},r=gc(e),i=gc(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 vc(e,t){let n=Lp(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,m=e.profile.redundant_edges??0,p=t.profile.redundant_edges??0,_=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:yi(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:p-m,ordering_contradiction_edges:y-_,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:yi(e.profile.edges_by_kind,t.profile.edges_by_kind),edge_share_by_kind:yi(r,s),semantic_edges:a-i,semantic_edge_share:c-o,coverage_by_type:n,...uc(e.profile,t.profile)}}}import bc 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]="e5089f2d-3fc5-5843-95ab-ba3dd2ab9582")}catch{}})();var wc=2,wi=500,Mp=64,Np="graph-durable-cache";function kc(e){return qe(e,Np,30,`graph-cache:${process.pid}`,!1,!1,3e3)}function Mt(e){return bc.join(e,"runtime","graph-cache.json")}function Ec(e){return bc.join(e,"runtime","graph-audit-baseline.json")}function ki(e){if(e!==null)try{let t=JSON.parse(e);return typeof t!="object"||t===null||t.version!==wc||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 Ei(e,t){let n=await be(Mt(e)),r=ki(n),i=r?.fingerprint===t;return{exists:n!==null,fresh:i,results:i?r.results:{}}}async function Ii(e,t,n,r,i){let o=await kc(e);try{let s=ki(await be(Mt(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-Mp)))delete a[d];await X(Mt(e),JSON.stringify({version:wc,fingerprint:t,saved_at:new Date().toISOString(),results:a})),n.results=a}finally{await o()}}async function Ci(e){let t=await kc(e);try{await So(Mt(e))}finally{await t()}}async function Ic(e,t){let n=Mt(e),r=await be(n),i=ki(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 Si(e,t){return t||e>=wi}function er(e){return ct(e)&&Object.values(e).every(Pe)}function ct(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Pe(e){return Number.isInteger(e)&&Number(e)>=0}function Cc(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=1}function Lt(e,t){return e===void 0||t(e)}function Fp(e){return ct(e)&&Object.values(e).every(Cc)}function $p(e){return ct(e)?Object.values(e).every(t=>ct(t)&&[t.active,t.isolated,t.degree_leq_one].every(Pe)):!1}function Pp(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=>Lt(e[s],Pe)))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 jp(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=>Lt(e[o],Pe))&&n.every(o=>Lt(e[o],Pe)&&(e[o]===void 0||Number(e[o])<=1e4))&&Lt(e.finding_subjects_by_code,er)}function Up(e,t,n,r){let i=Pp(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(!jp(e,o,s)||e.edge_basis!==void 0&&e.edge_basis!=="deduplicated_directed")return;let a=er(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(st.map(c=>[c,a[c]??t[c]??0]))}}function Bp(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||!Fp(n)||!Pe(r)||!Cc(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 Hp(e){if(e!==null)try{let t=JSON.parse(e);if(!ct(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(!er(i)||!ct(r)||!lc(r)||![r.nodes,r.edges,r.active_nodes,r.missing_nodes,r.isolated_active_nodes,r.degree_leq_one_active_nodes].every(Pe)||!er(r.edges_by_kind)||!Lt(r.coverage_by_type,$p))return;let o=Bp(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=Up(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 Sc(e){return Hp(await be(Ec(e)))}async function Tc(e,t){await X(Ec(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]="253f392d-4e91-57ec-b656-6134583d57e5")}catch{}})();var Gp={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 Rc(e){return`${e.source} -${e.kind}-> ${e.target}`}function Kp(e){let[t,...n]=e.edges;return n.map(r=>({op:"remove",code:"duplicate_edge",subject:Rc(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: ${Rc(t)}`,`group: ${Qn(e)}`],confidence:"high"}))}function zp(e,t){if(e.code==="duplicate_edge")return e.sample.flatMap(r=>Kp(t.get(r)));let n=Gp[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 xc(e,t={}){let{redundancyLimit:n,...r}=t,i=Zn(e,r),o=new Map(bi(e).map(d=>[Qn(d),d])),s=i.findings.flatMap(d=>zp(d,o)),a=i.findings.some(d=>d.sample_truncated);t.signal?.throwIfAborted();let c=it(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]="66df3949-0caf-5f01-8cec-3bba3d1e6111")}catch{}})();var Lc=new Set(["ancestors","descendants","predecessors","successors","paths","impact","dominators"]);function Dc(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,m=Object.fromEntries(Object.entries(f).map(([p,_])=>{let{degree_histogram:y,...b}=_;return[p,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:m}}}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 qp(e,t,n,r){return{assembly:t,...n===void 0?{}:{kinds:n},maxDepth:Hn(r.maxDepth),limit:e==="impact"&&Number(r.limit)===0?0:_e(r.limit,"limit")??(r.full===!0?Number.MAX_SAFE_INTEGER:Ie.rows),after:r.after?.trim()||void 0,direction:fi(r.direction),maxPaths:_e(r.maxPaths,"max-paths"),sample:_e(r.sample,"sample")??Ie.samples,exemptIsolates:Ac(r.exemptIsolate),exemptIsolateTypes:Ac(r.exemptIsolateType),saveBaseline:r.saveBaseline===!0,summary:r.summary===!0,unbounded:r.full===!0}}function Ac(e){return e===void 0?[]:(Array.isArray(e)?e:[e]).flatMap(t=>t.split(",")).map(t=>t.trim()).filter(t=>t.length>0)}function Vp(e,t,n){let r=e.trim().toLowerCase();if(!Fr.includes(r))throw Fs({command_path:"graph",token:r||"<empty>",allowed:Fr});let i=r;if(Lc.has(i)&&!t?.trim())throw new h(`graph ${i} requires an item id.`,g.USAGE);if(i==="paths"&&!n?.trim())throw new h("graph paths requires a source and a target item id.",g.USAGE);return i}function Ti(e){throw e instanceof TypeError?new h(e.message,g.USAGE):e}function Ri(e){return{truncated:e.truncated,cost:{visited_nodes:e.visitedNodes,inspected_edges:e.inspectedEdges}}}function Oc(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 h(`Item ${t} not found`,g.NOT_FOUND)}function Wp(e,t,n){let r={ancestors:Va,descendants:Wa,predecessors:Xa,successors:Ya}[e],i;try{i=r(n.assembly.graph,t,{...n.kinds===void 0?{}:{kinds:n.kinds},...n.maxDepth===void 0?{}:{maxDepth:n.maxDepth},limit:n.limit,...n.after===void 0?{}:{after:n.after}})}catch(s){Ti(s)}let o=Ri(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 Xp(e,t,n){let r=Ja(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,...Ri(r.meta),...n.summary?{}:{paths:r.value.map(i=>({nodes:i.nodes,kinds:i.edges.map(o=>o.kind),length:i.length}))}}}function Yp(e,t){let n;try{n=Dn(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},...t.after===void 0?{}:{after:t.after}})}catch(r){Ti(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 Jp(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 Qp(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 Zp(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 eh(e){let t=e.assembly.graph,n=e.limit,r=An(t,{registry:t.registry()}),i=Ks(t);return{subcommand:"analyze",node_count:t.nodes().length,edge_count:t.edges().length,edge_basis:"deduplicated_directed",sample_limit:n,execution:Jp(r,e.summary,n),knowledge:Qp(i,e.summary,n),hierarchy:Zp(Pn(e.assembly),e.summary,n)}}function th(e,t){let n=Zn(e.assembly,{isTerminal:t,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",truncated:n.findings.length>e.limit,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.slice(0,e.limit)}}}function nh(e){let t=e.limit,n={};e.kinds!==void 0&&(n.kinds=e.kinds);let r=Za(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 rh(e){let t;try{t=it(e.assembly.graph,{...e.kinds===void 0?{}:{kinds:e.kinds},...e.maxDepth===void 0?{}:{maxDepth:e.maxDepth},limit:e.limit})}catch(n){Ti(n)}return{subcommand:"redundancy",redundant_count:t.value.length,...Ri(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 ih(e,t){let n=t.limit,r=ec(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 oh(e){let t=e.limit,n=oc(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.slice(0,t),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 sh(e){let t=e.limit,n=ic(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 ah(e){let t=e.limit,n=Xn(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 ch(e,t){let n=e.limit,r=xc(e.assembly,{isTerminal:t,redundancyLimit:n,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 Mc(e,t,n,r){return JSON.stringify({projection_version:2,subcommand:e,root:t??null,target:n??null,kinds:r.kinds??null,maxDepth:r.maxDepth??null,limit:r.limit,after:r.after??null,direction:r.direction,maxPaths:r.maxPaths??null,sample:r.sample,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 Nc(e,t,n,r,i){return e==="analyze"?eh(r):e==="audit"?th(r,i):e==="plan"?ch(r,i):e==="communities"?nh(r):e==="redundancy"?rh(r):e==="dominators"?ih(t,r):e==="slack"?oh(r):e==="centrality"?sh(r):e==="articulation"?ah(r):e==="paths"?Xp(t,n,r):e==="impact"?Yp(t,r):Wp(e,t,r)}function dh(e,t){if(e!=="index"&&(t.rebuild===!0||t.clear===!0))throw new h("--rebuild and --clear apply only to graph index.",g.USAGE);if(e!=="audit"&&t.saveBaseline===!0)throw new h("--save-baseline applies only to graph audit.",g.USAGE);if(e==="slack"&&t.kind!==void 0)throw new h("graph slack analyzes every ordering kind; --kind is not supported.",g.USAGE);if(t.rebuild===!0&&t.clear===!0)throw new h("graph index accepts either --rebuild or --clear, not both.",g.USAGE);if(t.full===!0&&t.limit!==void 0)throw new h(`graph ${e} accepts either --full or --limit, not both.`,g.USAGE)}async function lh(e,t,n,r,i,o){let s="status";if(o.clear===!0&&(await Ci(e),s="cleared"),o.rebuild===!0){await Ci(e);let c=await Ei(e,t),d={assembly:n.assembly,direction:"both",exemptIsolates:[],exemptIsolateTypes:[],saveBaseline:!1,summary:!0,limit:Ie.rows,sample:Ie.samples,unbounded:!1};for(let l of["analyze","audit"])await Ii(e,t,c,Mc(l,void 0,void 0,d),Nc(l,void 0,void 0,d,i));s="rebuilt"}let a=await Ic(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:wi,persist_enabled:Si(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 uh(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(st.map(s=>[s,n.affected_subjects_by_code[s]??0]))}},o=await Sc(e);return r&&await Tc(e,i),o===void 0?n:{...n,baseline:vc(o,i)}}async function fh(e,t,n,r,i){try{await Ii(e,t,n,r,i)}catch{}}function mh(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=sc(s,n.filter(f=>!i.has(f.id)),{now:D(),limit:t.limit}),{rows:c,residuals:d,overcommitted:l,...u}=a;e.deadline_schedule={population:"active",...u,...t.summary?{}:{rows:c,residuals:d,overcommitted:l}}}async function VE(e,t,n,r,i){let o=Vp(e,t,n);pt(r.summary===!0,r.full===!0,"--summary");let s=O(process.cwd(),i.path);await U(s);let a=await N(s),c=M(a,x()),d=await pe(s,a.item_format,c.type_to_folder,void 0,a.schema),l=J(a.schema),u=$=>P($,l);dh(o,r);let f=z(),m=mi(r.kind,f),p=Un().lookup(s,jn(d,u,f),()=>St(d,u,f)),_=qp(o,p.assembly,m,r);if(o==="index")return Dc(await lh(s,p.fingerprint,_,d.length,u,r),!1);let y=Lc.has(o)?Oc(_.assembly,t):void 0,b=o==="paths"?Oc(_.assembly,n):void 0,v=Mc(o,y,b,_),w=await Ei(s,p.fingerprint),k=w.results[v],S=p.memoize(v,()=>k!==void 0?structuredClone(k):Nc(o,y,b,_,u)),L=Si(d.length,w.exists);!S.reused&&k===void 0&&L&&await fh(s,p.fingerprint,w,v,S.value);let B=S.value.subcommand==="audit"?await uh(s,p.fingerprint,S.value,_.saveBaseline):S.value;return B.cache={fingerprint:p.fingerprint.slice(0,12),assembly:p.assemblyReused?"hit":"miss",result:S.reused?"hit":"miss",durable:k!==void 0?"hit":L?"miss":"off"},mh(B,_,d,u),Dc(B,_.summary,"result_rows")}import xi from"node:fs/promises";import Di 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]="069e2e60-11d9-5a37-a966-9073944d32a2")}catch{}})();var Fc=8388608,ph=new Set(["resolved","failed"]),hh=[{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 ye(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ai(e){return hh.find(t=>t.matches(e))?.kind}function $c(e){let t=new Map,n=0,r=0;return{entries:e.map(i=>{let o=ye(i.agent_provenance)?i.agent_provenance:void 0;if(o===void 0||!_s(i).ok)return i;let s={},a=!1;for(let[d,l]of Object.entries(o)){let u=ye(l)?Ai(l.value):void 0;if(u===void 0){s[d]=l;continue}a=!0,r+=1;let f=i.agent_harness??"unknown",m=`${f}\0${d}\0${u}`,p=t.get(m)??{harness:f,dimension:d,kind:u,count:0};p.count+=1,t.set(m,p)}if(!a)return i;n+=1;let c={...i};return Object.keys(s).length===0?delete c.agent_provenance:c.agent_provenance=s,ys(i,c,{retainPriorRecord:!0,retainPriorRecordHash:!1})}),receipt:{changed:n>0,events_changed:n,observations_removed:r,invalid_values:[...t.values()].sort((i,o)=>i.harness.localeCompare(o.harness)||i.dimension.localeCompare(o.dimension)||i.kind.localeCompare(o.kind))}}}async function Pc(e){let t=[];for(let n of await jc(e)??[])try{let r=await xi.readFile(Di.join(e,"history",n),"utf8");for(let i of r.split(`
|
|
2
|
+
`)){if(i.trim().length===0)continue;let o=Uc(i);if(!(o===null||!ye(o.agent_provenance))&&Object.values(o.agent_provenance).some(s=>ye(s)&&Ai(s.value)!==void 0)){t.push(n.slice(0,-6));break}}}catch{}return t}async function jc(e){try{return(await xi.readdir(Di.join(e,"history"))).filter(t=>t.endsWith(".jsonl")).sort()}catch{return null}}async function gh(e,t,n){let r;try{r=await xi.open(Di.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
|
+
`),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 Uc(e){try{let t=JSON.parse(e);return ye(t)?t:null}catch{return null}}function _h(e,t,n){let r=typeof e.agent_harness=="string"?e.agent_harness:void 0;if(r===void 0)return;let i=ye(e.agent_provenance)?e.agent_provenance:{};if(Object.entries(i).forEach(([s,a])=>{if(!ye(a))return;let c=Ai(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)}),!ye(e.context))return;let o=e.context.agent_provenance_outcomes;ye(o)&&Object.entries(o).forEach(([s,a])=>{if(!ye(a)||typeof a.resolver!="string"||!ph.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 yh(e,t,n,r,i,o){let s=i;for(let a of e.split(`
|
|
4
|
+
`)){if(a.trim().length===0)continue;if(s>=r)return{eventsRead:s,truncated:!0};s+=1;let c=Uc(a);if(c===null){o.malformed_events+=1;continue}if(typeof c.ts=="string"&&cn(c.ts)){let d=new Date(c.ts).toISOString();(o.earliest_event_at===null||d<o.earliest_event_at)&&(o.earliest_event_at=d),(o.latest_event_at===null||d>o.latest_event_at)&&(o.latest_event_at=d)}_h(c,t,n)}return{eventsRead:s,truncated:!1}}function vh(e,t,n){return n?[...e.filter(r=>r.attempts>0&&r.successes===0).map(r=>`provenance_resolver_zero_success:${r.harness}:${r.dimension}:${r.resolver}:${String(r.attempts)}`),...t.map(r=>`provenance_value_domain_invalid:${r.harness}:${r.dimension}:${r.kind}:${String(r.count)}`)]:[]}async function ZE(e,t=1e4){if(!Number.isSafeInteger(t)||t<0)throw new RangeError("Provenance event limit must be a non-negative safe integer.");let n={scope:"history_prefix",event_limit:t,byte_limit:Fc,bytes_read:0,events_read:0,truncated:!1,unreadable_sources:0,malformed_events:0,earliest_event_at:null,latest_event_at:null,complete:!1},r=new Map,i=new Map,o=0,s=0,a=!1,c=await jc(e);c===null&&(n.unreadable_sources+=1);for(let u of c??[]){let f=await gh(e,u,Math.max(0,Fc-s));if(f===null){n.unreadable_sources+=1;continue}s+=f.bytesRead;let m=yh(f.content,r,i,t,o,n);if(o=m.eventsRead,m.truncated){a=!0;break}if(!f.complete){a=!0;break}}let d=[...r.values()].sort((u,f)=>u.harness.localeCompare(f.harness)||u.dimension.localeCompare(f.dimension)||u.resolver.localeCompare(f.resolver)),l=[...i.values()].sort((u,f)=>u.harness.localeCompare(f.harness)||u.dimension.localeCompare(f.dimension)||u.kind.localeCompare(f.kind));return n.bytes_read=s,n.events_read=o,n.truncated=a,n.complete=!a&&n.unreadable_sources===0&&n.malformed_events===0,{outcomes:d,sample:n,invalid_values:l,warnings:vh(d,l,n.complete),events_read:o,truncated:a}}import bh from"fast-json-patch";(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]="b3ef9db1-1d20-5d88-927e-a08edf563cd5")}catch{}})();function Bc(e,t,n){let r=gt(e,t);if(r.ok)return r.document;let i=structuredClone(e);for(let[o,s]of t.entries()){let a=/^\/metadata\/([^/]*)$/u.exec(s.path)?.[1],c=a!==void 0&&!Object.hasOwn(i.metadata,a.replaceAll("~1","/").replaceAll("~0","~"));if(c&&s.op==="remove")continue;let d=c&&s.op==="replace"?{...s,op:"add"}:s,l=gt(i,[d]);if(!l.ok)throw new h(`History union cannot rebase a scalar patch at ${n.branch} line ${n.line} (${n.op}), operation ${o+1} ${s.op} ${s.path}; preserve the source histories for manual recovery.`,g.CONFLICT,{code:"history_union_rebase_conflict",field:s.path,history_merge:{...n,patch_index:o,patch_path:s.path},nextSteps:["Preserve all three history inputs and both item snapshots. Review the named branch event against the merged replay state; do not drop the event or concatenate unchecked patches. After resolving the history and item deliberately, run pm history <id> --verify and pm merge reconcile --dry-run before committing."]});i=l.document}return i}(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]="425ef2aa-56fa-5d06-b8d0-316373ad2433")}catch{}})();var wh=Object.freeze({pm_item_scalar_missing:!0});function dt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.keys(e).length===1&&e.pm_item_scalar_missing===!0}function R(e){return e===void 0?wh:e}function Ae(e){return ie(E(e===void 0?{pm_item_scalar_presence:"missing"}:{pm_item_scalar_presence:"present",value:e}))}function Oi(e,t){let n=Ve(e);if(n)throw new h(`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 h(`History merge input (${t}) contains invalid JSON at line ${i+1}.`,g.GENERIC_FAILURE)}}return r}function se(e){return E({ts:e.ts,author:e.author,op:e.op,patch:e.patch,message:e.message??null})}function kh(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&se(e[r])===se(t[r]);)r+=1;return r}function Eh(e,t,n,r){let i=[...e,...n],o=new Map(i.map((u,f)=>[u,f])),s=new Map(i.map((u,f)=>[se(u),f])),a=i.map(()=>new Set);for(let u of[e,t]){let f=u.map(m=>o.get(m)??s.get(se(m)));for(let m=1;m<f.length;m+=1)f[m-1]!==f[m]&&a[f[m-1]].add(f[m])}let c=i.map(()=>0);for(let u of a)for(let f of u)c[f]+=1;let d=i.map((u,f)=>f).filter(u=>c[u]===0),l=[];for(;d.length>0;){d.sort((f,m)=>{let p=i[f],_=i[m],y=C(p.ts,_.ts),b=se(p),v=se(_);return y||Number(r.has(v))-Number(r.has(b))});let u=d.shift();l.push(i[u]);for(let f of a[u])c[f]-=1,c[f]===0&&d.push(f)}if(l.length!==i.length)throw new h("History union cannot preserve contradictory original branch event orders; leave the file unresolved for manual recovery.",g.GENERIC_FAILURE);return l}function Hc(e){return{entries:e,positions:new Map(e.map((t,n)=>[se(t),n])),index:-1,document:cs()}}function Pi(e,t){let n=t??e.index;for(;e.index<n;){let r=gt(e.document,e.entries[e.index+1].patch);if(!r.ok)throw new h("History union cannot preserve a patch that does not apply in its original branch.",g.GENERIC_FAILURE);e.document=r.document,e.index+=1}return e.document}function Gc(e,t){if(t!==void 0&&t>e.index+1)throw new h("History union cannot attribute multiple original branch events to one semantic identity; preserve the source histories for manual recovery.",g.GENERIC_FAILURE);return Pi(e,t)}function Ih(e,t,n){if(n===0)return;let r=Hc(e),i=Hc(t),o=Pi(r,n-1);Pi(i,n-1);let s=0,a=new Set([...zc,...qc]);return(c,d)=>{if(s++<n)return c.patch;let l=se(c),u=Gc(r,r.positions.get(l)),f=Gc(i,i.positions.get(l)),m=hn(c.patch).filter(v=>{let[w,k]=v.path.slice(1).split("/");return w!=="metadata"||!a.has(k)}),p=r.positions.get(l),_=Bc(d,m,{branch:p===void 0?"theirs":"ours",line:(p??i.positions.get(l))+1,op:c.op}),y=Xc(o.metadata,u.metadata,f.metadata,"ours","latest_document_update",String(u.metadata.updated_at),String(f.metadata.updated_at));for(let v of a)Object.hasOwn(y.merged,v)?_.metadata[v]=y.merged[v]:delete _.metadata[v];let b=pn({metadata:_.metadata,body:_.body});return bh.compare(d,b)}}function gI(e,t,n){let r=Oi(e,"base"),i=Oi(t,"ours"),o=Oi(n,"theirs"),s=[r,i,o].map(m=>m.filter(p=>p.op==="create"));if(s[0].length===0&&s.slice(1).every(m=>m.length>0)||s.some(m=>m.length>1)||new Set(s.flat().map(se)).size>1)throw new h("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=kh(i,o);if(a===i.length&&a===o.length)return{merged:Me(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:Me(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:Me(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(se)),l=o.slice(a).filter(m=>!d.has(se(m))),u=Eh(c,o.slice(a),l,d),f=gn([...i.slice(0,a),...u],void 0,{continuousHashSurface:!0,projectPatch:Ih(i,o,a)});if(f.skippedOps>0)throw new h(`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:Me(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 Li(e,t){let n=Ve(e);if(n)throw new h(`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 h(`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 h(`Relationship merge input (${t}) line ${i+1} is not a relationship event (eventId + sequence required).`,g.GENERIC_FAILURE);r.push(a)}return r}function tr(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
|
|
5
|
+
`)}
|
|
6
|
+
`}function Ch(e){return e.map((t,n)=>({...t,sequence:n+1}))}function _I(e,t,n){Li(e,"base");let r=Li(t,"ours"),i=Li(n,"theirs"),o=Math.min(r.length,i.length),s=0;for(;s<o&&r[s].eventId===i[s].eventId;)s+=1;if(s===r.length&&s===i.length)return{merged:tr(r),strategy:"identical",common_entries:s,entries_from_ours:0,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(s===i.length)return{merged:tr(r),strategy:"fast_forward_ours",common_entries:s,entries_from_ours:r.length-s,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(s===r.length)return{merged:tr(i),strategy:"fast_forward_theirs",common_entries:s,entries_from_ours:0,entries_from_theirs:i.length-s,entries_total:i.length,reanchored:!1};let a=r.slice(s),c=new Set(a.map(f=>f.eventId)),d=i.slice(s).filter(f=>!c.has(f.eventId)),l=[...a,...d].sort((f,m)=>{if(f.timestamp!==void 0&&m.timestamp!==void 0){let y=C(f.timestamp,m.timestamp);if(y!==0)return y}else{if(f.timestamp===void 0&&m.timestamp!==void 0)return 1;if(f.timestamp!==void 0)return-1}let p=c.has(f.eventId),_=c.has(m.eventId);return p!==_?Number(_)-Number(p):0}),u=Ch([...r.slice(0,s),...l]);return{merged:tr(u),strategy:"union_reanchor",common_entries:s,entries_from_ours:a.length,entries_from_theirs:d.length,entries_total:u.length,reanchored:!0}}var zc=["tags","dependencies","comments","notes","learnings","files","tests","test_runs","docs","reminders","events"],qc=["acceptance_criteria"],Sh=["updated_at"];function je(e,t){return e===void 0||t===void 0?e===void 0&&t===void 0:E(e)===E(t)}function Kc(e,t,n){let r=l=>Array.isArray(l)?l:[],i=new Set(r(e).map(l=>E(l))),o=r(t),s=new Set(o.map(l=>E(l))),a=r(n),c=new Set(a.map(l=>E(l))),d=o.filter(l=>{let u=E(l);return!i.has(u)||c.has(u)});for(let l of a){let u=E(l);!s.has(u)&&!i.has(u)&&d.push(l)}return d}function Nt(e){if(typeof e!="object"||e===null||Array.isArray(e))return E(e);let{provenance:t,...n}=e;return E(n)}function Th(e){if(typeof e!="object"||e===null||Array.isArray(e))return e;let t=e;return t.provenance?{...t,provenance:{...t.provenance,source_kind:"merge_union"}}:{...t,provenance:{source_kind:"merge_union"}}}function Rh(e,t,n){let r=l=>Array.isArray(l)?l:[],i=new Set(r(e).map(Nt)),o=r(t),s=new Set(o.map(Nt)),a=r(n),c=new Set(a.map(Nt)),d=o.filter(l=>{let u=Nt(l);return!i.has(u)||c.has(u)});for(let l of a){let u=Nt(l);!s.has(u)&&!i.has(u)&&d.push(Th(l))}return d}function xh(e,t){return C(String(e),String(t))>=0?e:t}function Vc(e,t,n,r){return je(t,n)?{value:t,from_theirs:!1,conflict:!1}:je(e,t)?{value:n,from_theirs:!0,conflict:!1}:je(e,n)?{value:t,from_theirs:!1,conflict:!1}:{value:r==="theirs"?n:t,from_theirs:r==="theirs",conflict:!0}}function Wc(e,t,n,r,i,o,s){let a=Vc(e,t,n,r);if(!a.conflict)return{...a,conflict:!1};if(i==="preferred_side")return{...a,resolution_basis:"requested_preference",retained_side:a.from_theirs?"theirs":"ours"};let c=C(o,s);if(i==="latest_document_update"&&c!==0){let l=c<0;return{value:l?n:t,from_theirs:l,conflict:!0,resolution_basis:"document_updated_at",retained_side:l?"theirs":"ours"}}let d=E(R(n)).localeCompare(E(R(t)))<0;return{value:d?n:t,from_theirs:d,conflict:!0,resolution_basis:"stable_value_tiebreak",retained_side:d?"theirs":"ours"}}function Mi(e){return{...e.metadata}}function Ni(e,t,n){try{let r=es(Qo(e,{...n,requireSupportedFormat:!0}),n),i=Object.entries(r.metadata).find(([,o])=>dt(o))?.[0];if(i!==void 0)throw new TypeError(`metadata field ${i} uses the reserved missing-scalar evidence marker`);return r}catch(r){throw r instanceof h&&r.context?.code==="item_format_version_unsupported"?r:new h(`Item merge input (${t}) is not a readable item document: ${String(r)}`,g.GENERIC_FAILURE)}}function Dh(e){if(!e.unionFieldSet.has(e.field))return!1;let t=e.field==="tests"?Rh(e.baseValue,e.oursValue,e.theirsValue):e.field==="acceptance_criteria"?Kc(En(e.baseValue),En(e.oursValue),En(e.theirsValue)).join("; "):Kc(e.baseValue,e.oursValue,e.theirsValue);return e.accumulator.merged[e.field]=t,je(t,e.oursValue)||e.accumulator.unionFields.push(e.field),!0}function Ah(e){let t=Wc(e.baseValue,e.oursValue,e.theirsValue,e.preferred,e.conflictResolution,e.oursUpdatedAt,e.theirsUpdatedAt);t.value!==void 0&&(e.accumulator.merged[e.field]=t.value),t.conflict?(e.accumulator.conflictFields.push(e.field),e.accumulator.conflictDecisions.push({field:e.field,base:R(e.baseValue),ours:R(e.oursValue),theirs:R(e.theirsValue),retained:R(t.value),discarded:R(t.from_theirs?e.oursValue:e.theirsValue),retained_side:t.retained_side,resolution_basis:t.resolution_basis})):t.from_theirs&&e.accumulator.fieldsFromTheirs.push(e.field)}function Xc(e,t,n,r,i,o,s){let a=new Set([...zc,...qc]),c=new Set(Sh),d=[...new Set([...Object.keys(t),...Object.keys(n)])].sort((u,f)=>u.localeCompare(f)),l={merged:{},conflictFields:[],fieldsFromTheirs:[],unionFields:[],conflictDecisions:[]};for(let u of d){let f=e[u],m=t[u],p=n[u];if(!Dh({field:u,baseValue:f,oursValue:m,theirsValue:p,unionFieldSet:a,accumulator:l})){if(c.has(u)){l.merged[u]=xh(m,p);continue}Ah({field:u,baseValue:f,oursValue:m,theirsValue:p,preferred:r,conflictResolution:i,oursUpdatedAt:o,theirsUpdatedAt:s,accumulator:l})}}return l}function yI(e,t,n,r={}){let i=r.preferred??"ours",o=r.conflictResolution??"preferred_side",s=Ni(t,"ours",r),a=Ni(n,"theirs",r);if(e.trim().length===0)throw new h("Duplicate item identity: add/add item documents have no common ancestor. Preserve both branches and assign distinct item ids before merging.",g.CONFLICT,{code:"item_identity_conflict",item_id:s.metadata.id});let c=Ni(e,"base",r);if(c.metadata.id!==s.metadata.id||c.metadata.id!==a.metadata.id)throw new h("Duplicate or mismatched item identity: all merge sides must address the common ancestor's item id.",g.CONFLICT,{code:"item_identity_conflict",item_id:c.metadata.id});let d=Mi(c),l=Mi(s),u=Mi(a),{merged:f,conflictFields:m,fieldsFromTheirs:p,unionFields:_,conflictDecisions:y}=Xc(d,l,u,i,o,s.metadata.updated_at,a.metadata.updated_at),b=Wc(c.body,s.body,a.body,i,o,s.metadata.updated_at,a.metadata.updated_at);b.conflict?(m.push("body"),y.push({field:"body",base:R(c.body),ours:R(s.body),theirs:R(a.body),retained:R(b.value),discarded:R(b.from_theirs?s.body:a.body),retained_side:b.retained_side,resolution_basis:b.resolution_basis})):b.from_theirs&&p.push("body");let v=f;return v.pm_format_version=Jo(Math.max(...[c.metadata,s.metadata,a.metadata,v].map(Yo))),{merged:Zo({metadata:v,body:b.value},r),conflict_fields:m,fields_from_theirs:p,union_fields:_,conflict_decisions:y,requested_preference:i,requested_preference_applied:o==="preferred_side",conflict_resolution:o}}function Fi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function $i(e,t){let n=Ve(e);if(n)throw new h(`JSON merge input (${t}) contains unresolved conflict markers at line ${n.line}.`,g.GENERIC_FAILURE);if(e.trim().length!==0)try{return JSON.parse(e)}catch{throw new h(`JSON merge input (${t}) is not valid JSON.`,g.GENERIC_FAILURE)}}function Oh(e,t,n){if(!Array.isArray(e)||!Array.isArray(t)||!Array.isArray(n))return null;let r=d=>{let l=new Map;for(let u of d){let f=E(u);l.set(f,(l.get(f)??0)+1)}return l},i=r(e),o=r(t),s=r(n);for(let[d,l]of i)if((o.get(d)??0)<l||(s.get(d)??0)<l)return null;let a=new Map(o),c=[];for(let d of n){let l=E(d),u=a.get(l)??0;u>0?a.set(l,u-1):c.push(d)}return{merged:[...t,...c],acceptedTheirs:c.length>0}}function Lh(e,t,n,r,i,o,s){if(!Fi(t)||!Fi(n))return null;let a=Fi(e)?e:{},c={},d=[...new Set([...Object.keys(t),...Object.keys(n)])].sort((l,u)=>l.localeCompare(u));for(let l of d){let u=i.length>0?`${i}.${l}`:l,f=Mh(a,t,n,l,r,u,o,s);f!==void 0&&(c[l]=f)}return c}function Yc(e,t,n,r,i,o,s){if(je(t,n))return t;let a=Oh(e,t,n);if(a!==null)return a.acceptedTheirs&&s.push(i),a.merged;let c=Lh(e,t,n,r,i,o,s);if(c!==null)return c;let d=Vc(e,t,n,r);return d.conflict?o.push(i):d.from_theirs&&s.push(i),d.value}function Mh(e,t,n,r,i,o,s,a){let c=Object.prototype.hasOwnProperty.call(t,r),d=Object.prototype.hasOwnProperty.call(n,r),l=Object.prototype.hasOwnProperty.call(e,r);if(c&&d)return Yc(e[r],t[r],n[r],i,o,s,a);if(c){if(l&&je(e[r],t[r])){a.push(o);return}return l?(s.push(o),i==="theirs"?void 0:t[r]):t[r]}if(!(l&&je(e[r],n[r])))return l?(s.push(o),i==="theirs"?n[r]:void 0):(a.push(o),n[r])}function vI(e,t,n,r={}){let i=r.preferred??"ours",o=$i(e,"base"),s=$i(t,"ours"),a=$i(n,"theirs"),c=[],d=[],l=Yc(o,s,a,i,"",c,d);return{merged:`${JSON.stringify(l??null,null,2)}
|
|
7
|
+
`,conflict_paths:c,paths_from_theirs:d,preferred:i}}import{execFile as ng}from"node:child_process";import{randomUUID as rg}from"node:crypto";import{readdir as ig,realpath as Oe,stat as og}from"node:fs/promises";import F from"node:path";import{promisify as sg}from"node:util";import rr from"node:path";import{execFile as Nh}from"node:child_process";import{createHash as Jc}from"node:crypto";import{readdir as Fh}from"node:fs/promises";import $h from"node:path";import{promisify as Ph}from"node:util";(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]="af5442e7-c8af-5d81-8c89-7f1a98159cec")}catch{}})();var Ce=Ph(Nh),nr=/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u;async function TI(e,t,n){let r=t.trim(),i=/^(['"])(.*)\1$/su.exec(r)?.[2]??r;for(let o of["rebase-merge","rebase-apply"])try{let{stdout:s}=await Ce("git",["rev-parse","--path-format=absolute","--git-path",`${o}/orig-head`],{cwd:e,timeout:1e4}),a=(await _t(s.trim(),128))?.trim();if(a===void 0||!nr.test(a))continue;let{stdout:c}=await Ce("git",["rev-parse","--verify",`${a}:${i}`],{cwd:e,timeout:1e4}),d=c.trim();return{kind:"rebase",original_head:a,original_blob:d}}catch{}if(n!==void 0&&Object.keys(process.env).some(o=>/^GITHEAD_[a-f0-9]{40}(?:[a-f0-9]{24})?$/u.test(o)))try{let{stdout:o}=await Ce("git",["rev-parse","HEAD","ORIG_HEAD"],{cwd:e,timeout:1e4}),[s,a]=o.trim().split(/\r?\n/u);if(s!==a||!nr.test(s))return;let{stdout:c}=await Ce("git",["rev-parse","--verify",`${s}:${i}`],{cwd:e,timeout:1e4}),d=c.trim(),l=Jc(d.length===40?"sha1":"sha256").update(`blob ${Buffer.byteLength(n)}\0`).update(n).digest("hex");return d!==l?void 0:{kind:"merge",original_head:s,original_blob:d}}catch{}}function Qc(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;return Object.keys(t).length===3&&(t.kind==="rebase"||t.kind==="merge")&&typeof t.original_head=="string"&&nr.test(t.original_head)&&typeof t.original_blob=="string"&&nr.test(t.original_blob)}async function Zc(e,t,n,r){if(r!==void 0&&Jc(n.original_blob.length===40?"sha1":"sha256").update(`blob ${Buffer.byteLength(r)}\0`).update(r).digest("hex")!==n.original_blob)return!1;try{let{stdout:i}=await Ce("git",["rev-parse","--absolute-git-dir"],{cwd:e,timeout:1e4}),o=new Set(["rebase-merge","rebase-apply","MERGE_HEAD","CHERRY_PICK_HEAD","REVERT_HEAD"]);if((await Fh(i.trim())).some(d=>o.has(d)))return!1;let{stdout:s}=await Ce("git",["rev-parse","HEAD"],{cwd:e,timeout:1e4});if(s.trim()!==n.original_head)return!1;let{stdout:a}=await Ce("git",["rev-parse","--verify",`HEAD:${t}`],{cwd:e,timeout:1e4});if(a.trim()!==n.original_blob)return!1;let{stdout:c}=await Ce("git",["hash-object","--",$h.resolve(e,t)],{cwd:e,timeout:1e4});return c.trim()!==n.original_blob?!1:(await Ce("git",["diff","--cached","--quiet","HEAD","--",t],{cwd:e,timeout:1e4}),!0)}catch{return!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]="35c5d9a8-5ae0-5e97-9ea3-f8a70a5fd7d0")}catch{}})();var jh=/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/u,Uh=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u,or=2048,Bh=64,Hh=1e5,Gh=new Set(["version","id","item_path","item_id","requested_preference","requested_preference_applied","preferred","conflict_resolution","fields_from_theirs","union_fields","merged_field_hashes","decisions","state","created_at","reconciled_at","value_availability","value_policy","evidence_source","operation","settlement"]);function sr(e){return jh.test(e)}var Kh=new Set(["field","base","ours","theirs","retained","discarded","retained_side","resolution_basis"]),ar="bounded_non_sensitive_scalars_v1",zh=new Set(["open","in_progress","blocked","closed","canceled"]),qh=new Set(["risk","confidence","severity"]),Vh=new Set(["low","medium","high","critical"]),td=new Map([["priority",new Set([0,1,2,3,4].map(E))],["status",new Set([...zh].map(E))],...[...qh].map(e=>[e,new Set([...Vh].map(E))])]);function ve(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function nd(e,t){return Object.keys(e).every(n=>t.has(n))}function ir(e){return Array.isArray(e)&&e.length<=or&&e.every(t=>typeof t=="string"&&t.length>0&&t.length<=256)}function Ft(e){let t=[{value:e,depth:0}],n=0;for(;t.length>0;){let r=t.pop();if(n+=1,n>Hh||r.depth>Bh)return!1;if(Array.isArray(r.value))for(let i of r.value)t.push({value:i,depth:r.depth+1});else if(ve(r.value))for(let i of Object.values(r.value))t.push({value:i,depth:r.depth+1})}return!0}function rd(e){if(!ve(e))return!1;let t=[void 0,"ours","theirs"],n=[void 0,"requested_preference","document_updated_at","stable_value_tiebreak"];return[nd(e,Kh),typeof e.field=="string",typeof e.field=="string"&&e.field.length>0,typeof e.field=="string"&&e.field.length<=256,Object.hasOwn(e,"base"),Object.hasOwn(e,"ours"),Object.hasOwn(e,"theirs"),Object.hasOwn(e,"retained"),Object.hasOwn(e,"discarded"),Ft(e.base),Ft(e.ours),Ft(e.theirs),Ft(e.retained),Ft(e.discarded),t.includes(e.retained_side),n.includes(e.resolution_basis)].every(Boolean)}function Wh(e){if(!ve(e))return!1;let t=Object.entries(e);return t.length<=or&&t.every(([n,r])=>n.length>0&&n.length<=256&&typeof r=="string"&&/^[a-f0-9]{64}$/u.test(r))}function Xh(e,t){if(typeof e!="string"||e.length===0||e.length>4096||e.includes("\0")||e.includes("\\")||rr.posix.isAbsolute(e))return!1;let n=rr.posix.normalize(e);return n!==".."&&!n.startsWith("../")&&rr.posix.basename(n,rr.posix.extname(n))===t}function Yh(e){return!ir(e.fields_from_theirs)||!ir(e.union_fields)||!Array.isArray(e.decisions)||e.decisions.length>or||!e.decisions.every(rd)?!1:e.merged_field_hashes===void 0||Wh(e.merged_field_hashes)}function Jh(e){let t=[void 0,"ours","theirs"],n=[void 0,"preferred_side","stable_value_order","latest_document_update"],r=[void 0,"clone_local","hash_only","bounded_inline","mixed"],i=[void 0,"clone_local","durable"];return t.includes(e.requested_preference)&&t.includes(e.preferred)&&(e.requested_preference_applied===void 0||typeof e.requested_preference_applied=="boolean")&&n.includes(e.conflict_resolution)&&(e.state==="pending"||e.state==="reconciled")&&r.includes(e.value_availability)&&(e.value_policy===void 0||e.value_policy===ar)&&i.includes(e.evidence_source)}function Qh(e){return typeof e.created_at=="string"&&Pr(e.created_at)&&(e.reconciled_at===void 0||typeof e.reconciled_at=="string"&&Pr(e.reconciled_at))}function ed(e,t){if(!ve(t)||lr(t)===void 0)return!1;let n=Object.keys(t);if(!n.every(i=>i==="pm_value_hash"||i==="pm_value"))return!1;if(!Object.hasOwn(t,"pm_value"))return n.length===1;let r=t.pm_value;return(r===null||td.get(e)?.has(E(r))===!0)&&Ae(r)===t.pm_value_hash}function Zh(e){if(!e.decisions.every(r=>r.base===null&&r.ours===null&&r.theirs===null&&ed(r.field,r.retained)&&ed(r.field,r.discarded)))return!1;let t=e.decisions.reduce((r,i)=>r+(ve(i.retained)&&Object.hasOwn(i.retained,"pm_value")?1:0)+(ve(i.discarded)&&Object.hasOwn(i.discarded,"pm_value")?1:0),0),n=t===0?"hash_only":t===e.decisions.length*2?"bounded_inline":"mixed";return e.value_availability===n&&(t===0||e.value_policy===ar)}function eg(e){return e.operation!==void 0&&!Qc(e.operation)?!1:e.settlement===void 0||e.settlement==="original_git_state_restored"&&e.state==="reconciled"&&e.operation!==void 0}function tg(e){for(let t of["version","id","item_path","item_id","fields_from_theirs","union_fields","decisions","state","created_at"])if(!Object.hasOwn(e,t))return"required_fields";return e.version!==1||!nd(e,Gh)?"required_fields":typeof e.id!="string"||!sr(e.id)?"receipt_id":typeof e.item_id!="string"||!Uh.test(e.item_id)?"item_id":Xh(e.item_path,e.item_id)?null:"item_path"}function cr(e,t){if(!ve(e))return"required_fields";let n=tg(e);return n!==null?n:eg(e)?Yh(e)?Jh(e)?Qh(e)?t==="durable"&&!Zh(e)?"durable_decisions":null:"timestamps":"enums":"collections":"operation"}function dr(e){if(!ve(e)||e.version!==1||e.value_policy!==void 0||!Array.isArray(e.decisions))return e;let t=(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0,n=(e.requested_preference==="ours"||e.requested_preference==="theirs")&&e.value_availability==="clone_local";return!t&&!n?e:{...e,decisions:e.decisions.map(r=>!ve(r)||!Object.hasOwn(r,"retained")||!Object.hasOwn(r,"discarded")?r:{base:R(void 0),ours:R(void 0),theirs:R(void 0),...r})}}function id(e){if(!ve(e))return;if(!ir(e.fields_from_theirs))return"fields_from_theirs";if(!ir(e.union_fields))return"union_fields";if(!Array.isArray(e.decisions)||e.decisions.length>or)return"decisions";let t=e.decisions.findIndex(n=>!rd(n));return t>=0?`decisions[${t}]`:"merged_field_hashes"}function ji(e,t){return cr(e,t)===null}function lr(e){if(typeof e!="object"||e===null||Array.isArray(e)||!("pm_value_hash"in e))return;let t=e.pm_value_hash;return typeof t=="string"&&/^[a-f0-9]{64}$/u.test(t)?t:void 0}function Ui(e,t){let n=dt(t),r=Ae(n?void 0:t);return!n&&(t===null||td.get(e)?.has(E(t))===!0)?{pm_value_hash:r,pm_value:t}:{pm_value_hash: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]="7bab0a8e-842c-5588-a0b2-22ef261ddb06")}catch{}})();var ag=sg(ng),ur=100;async function Bi(e){try{let{stdout:t}=await ag("git",["rev-parse","--path-format=absolute","--git-path","pm-merge-receipts"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return t.trim()}catch{return null}}async function ad(e,t){let n=F.dirname(F.resolve(e,t));for(let r=0;r<12;r+=1){if(await en(F.join(n,"settings.json")))return n;let i=F.dirname(n);if(i===n)break;n=i}return null}function lt(e){return F.join(e,"merge-receipts")}function Le(e){return`${e}.json`}async function od(e){let t;try{t=e.readReceipt?await e.readReceipt(e.receiptPath):await _t(e.receiptPath,Tn)}catch(o){if(Be(o))return null;throw o}if(t===null)throw new Error(`Receipt ${e.receiptId} settlement source is not a bounded regular file.`);let n;try{n=dr(JSON.parse(t))}catch{throw new Error(`Receipt ${e.receiptId} settlement source is not valid JSON.`)}if(!ji(n,e.evidenceSource)||n.id!==e.receiptId||e.settlement!==void 0&&n.operation===void 0||F.basename(e.receiptPath)!==Le(n.id))throw new Error(`Receipt ${e.receiptId} settlement source failed schema or identity validation.`);let{evidence_source:r,...i}=n;return{path:e.receiptPath,fingerprints:Pt(n),modern:n.value_policy!==void 0,content:`${JSON.stringify({...i,state:"reconciled",reconciled_at:e.reconciledAt,...e.settlement?{settlement:e.settlement}:{}},null,2)}
|
|
8
|
+
`}}function $t(e,t=!1){return ie(E({id:e.id,item_id:e.item_id,item_path:e.item_path,created_at:e.created_at,requested_preference:e.requested_preference??e.preferred??"ours",requested_preference_applied:e.requested_preference_applied??(e.conflict_resolution??"preferred_side")==="preferred_side",conflict_resolution:e.conflict_resolution??"preferred_side",fields_from_theirs:e.fields_from_theirs,union_fields:e.union_fields,merged_field_hashes:e.merged_field_hashes??null,operation:e.operation??null,decisions:t?e.decisions.map(n=>({field:n.field,retained_hash:ie(E(R(n.retained))),discarded_hash:ie(E(R(n.discarded)))})):fr(e).decisions}))}function Pt(e){let t=[$t(e)];return e.value_policy===void 0&&(e.value_availability===void 0||e.value_availability==="clone_local")&&t.push($t(e,!0)),t}function cg(e,t){let{reconciled_at:n,settlement:r,...i}=e;return t.state==="reconciled"?{...i,state:"reconciled",reconciled_at:t.reconciled_at,...t.settlement===void 0?{}:{settlement:t.settlement}}:{...i,state:"pending"}}async function dg(e,t,n){let r=new Map;for(let i of t){let o=e.get(i.id);if(i.state!=="reconciled"||o===void 0)continue;let s=r.get(o.item_id);if(s===void 0){try{s=await Xe(F.join(n,"history",`${o.item_id}.jsonl`),o.item_id),fe(s).ok||(s=[])}catch{s=[]}r.set(o.item_id,s)}let a=o.settlement==="original_git_state_restored",c=E({...fr(o),...a?{reason:o.settlement,operation:o.operation}:{}});if(!s.some(d=>{if(d.op!=="merge_reconcile"||d.record_hash_version===void 0)return!1;let l=d.context?.merge;if(typeof l!="object"||l===null||Array.isArray(l))return!1;let u=l[a?"abandoned_receipts":"receipts"];return Array.isArray(u)&&u.some(f=>E(f)===c)})){let{reconciled_at:d,settlement:l,...u}=o;e.set(o.id,{...u,state:"pending"})}}}function fr(e){return{receipt_id:e.id,item_id:e.item_id,item_path:e.item_path,conflict_fields:e.decisions.map(t=>t.field),fields_from_theirs:e.fields_from_theirs,union_fields:e.union_fields,requested_preference:e.requested_preference??e.preferred??"ours",requested_preference_applied:e.requested_preference_applied??(e.conflict_resolution??"preferred_side")==="preferred_side",conflict_resolution:e.conflict_resolution,decisions:e.decisions.map(t=>({field:t.field,retained_hash:lr(t.retained)??Ae(dt(t.retained)?void 0:t.retained),discarded_hash:lr(t.discarded)??Ae(dt(t.discarded)?void 0:t.discarded)}))}}async function JI(e){let t=await Bi(e.cwd);if(t===null)return null;let n=e.itemPath.trim(),r=/^(['"])(.*)\1$/su.exec(n)?.[2]??n,i=F.basename(r,F.extname(r)),o={version:1,id:rg(),item_path:r.replaceAll("\\","/"),item_id:i,requested_preference:e.preferred,requested_preference_applied:(e.conflictResolution??"preferred_side")==="preferred_side",conflict_resolution:e.conflictResolution??"preferred_side",fields_from_theirs:[...e.fieldsFromTheirs],union_fields:[...e.unionFields],...e.mergedFieldHashes?{merged_field_hashes:{...e.mergedFieldHashes}}:{},decisions:structuredClone(e.decisions).map(a=>({...a,base:R(a.base),ours:R(a.ours),theirs:R(a.theirs),retained:R(a.retained),discarded:R(a.discarded)})),...e.operation?{operation:e.operation}:{},state:"pending",created_at:D(),value_availability:"clone_local"};await Mr(t),await X(F.join(t,Le(o.id)),`${JSON.stringify(o,null,2)}
|
|
9
|
+
`);let s=await ad(e.cwd,o.item_path);if(s!==null){let a=lt(s),c=o.decisions.map(u=>({field:u.field,base:null,ours:null,theirs:null,retained:Ui(u.field,u.retained),discarded:Ui(u.field,u.discarded),retained_side:u.retained_side,resolution_basis:u.resolution_basis})),d=c.reduce((u,f)=>u+(Object.hasOwn(f.retained,"pm_value")?1:0)+(Object.hasOwn(f.discarded,"pm_value")?1:0),0),l={...o,decisions:c,value_availability:d===0?"hash_only":d===c.length*2?"bounded_inline":"mixed",value_policy:ar};await Mr(a),await X(F.join(a,Le(o.id)),`${JSON.stringify(l,null,2)}
|
|
10
|
+
`)}return o}async function sd(e,t){let n;try{n=await ig(e)}catch(a){let c=await lg(e,a);return{receipts:[],invalid_evidence_count:c?0:1,invalid_evidence:c?[]:[{evidence_source:t,reason:"directory_unreadable"}],invalid_evidence_truncated:!1}}let r=[],i=0,o=[],s=(a,c)=>{if(i+=1,o.length>=ur)return;let d=a.slice(0,-5);o.push({evidence_source:t,reason:c.reason,...c.validation_path?{validation_path:c.validation_path}:{},...c.validation_error===void 0?{}:{validation_error:c.validation_error},...sr(d)?{receipt_id:d}:{candidate_name_hash:ie(a)}})};for(let a of n.sort((c,d)=>c.localeCompare(d))){if(!a.endsWith(".json"))continue;let c=await ug(e,a,t);c.receipt!==void 0?r.push(c.receipt):s(a,c)}return{receipts:r,invalid_evidence_count:i,invalid_evidence:o,invalid_evidence_truncated:i>o.length}}async function lg(e,t,n=og){if(!de(t))return!1;let r=e;for(;;)try{return(await n(r)).isDirectory()}catch(i){if(!de(i))return!1;let o=F.dirname(r);if(o===r)return!0;r=o}}async function ug(e,t,n){let r;try{r=await _t(F.join(e,t),Tn)}catch{return{reason:"candidate_unreadable"}}if(r===null)return{reason:"candidate_not_bounded_regular_file"};let i;try{i=dr(JSON.parse(r))}catch{return{reason:"candidate_invalid_json"}}let o=cr(i,n);if(o!==null)return{reason:new Set(["receipt_id","item_id","item_path"]).has(o)?"identity_invalid":"schema_invalid",validation_error:o,...o==="collections"?{validation_path:id(i)}:{}};let s=i;if(t!==Le(s.id))return{reason:"identity_invalid",validation_error:"filename"};let{preferred:a,evidence_source:c,...d}=s;return{receipt:{...d,requested_preference:s.requested_preference??a??"ours",requested_preference_applied:s.requested_preference_applied??(s.conflict_resolution??"preferred_side")==="preferred_side",conflict_resolution:s.conflict_resolution??"preferred_side",evidence_source:n}}}async function fg(e,t,n){if(n.length===0)return[];let{readIndexedReceiptBlobs:r}=await import("./indexed-receipt-blobs-LHLE7PSG.js"),i=await mg(t),o=await r(i?.workspace??e,lt(t),n.map(s=>Le(s.id)),Tn,i?.directory);return n.flatMap(s=>{try{let a=dr(JSON.parse(o.get(Le(s.id))??""));if(cr(a,"durable")!==null)return[];let c=a,d=Pt(s);return c.id===s.id&&Pt(c).some(l=>d.includes(l))?[s.id]:[]}catch{return[]}})}async function mg(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT,n=process.env.PM_SOURCE_PM_PATH,r=process.env.PM_PATH;if(!(process.env.PM_SOURCE_CONTEXT_ACCESS!=="read_only"||!t||!n||!r))try{if(await Oe(e)!==await Oe(r))return;let i=F.relative(await Oe(t),await Oe(n)),o=i===".."||i.startsWith(`..${F.sep}`)||F.isAbsolute(i),s=lt(o?F.join(await Oe(t),".agents","pm"):await Oe(n)),[a,c]=await Promise.all([Oe(s),Oe(lt(n))]);return a!==c?void 0:{workspace:t,directory:s}}catch{return}}async function mr(e,t={}){let n=await Bi(e),r=n===null?{receipts:[],invalid_evidence_count:0,invalid_evidence:[],invalid_evidence_truncated:!1}:await sd(n,"clone_local"),i=t.pmRoot??F.join(e,".agents","pm"),o=await sd(lt(i),"durable"),s=new Map(o.receipts.map(u=>[u.id,u])),a=0,c=[];for(let u of r.receipts){let f=s.get(u.id);if(f!==void 0&&!(f.value_policy===void 0?Pt(u):[$t(u)]).includes($t(f))){s.delete(u.id),a+=1,r.invalid_evidence.length+o.invalid_evidence.length+c.length<ur&&c.push({evidence_source:"clone_local_and_durable",reason:"copy_provenance_mismatch",receipt_id:u.id});continue}s.set(u.id,f===void 0?u:cg(u,f))}await dg(s,o.receipts,i);let d=o.receipts.filter(u=>s.has(u.id)),l=new Set(await fg(e,i,d));return{durable_receipt_ids:[...l],unstaged_durable_receipt_ids:d.filter(u=>!l.has(u.id)).map(u=>u.id),receipts:[...s.values()].filter(u=>(t.includeReconciled||u.state==="pending")&&(t.includeLossless!==!1||u.decisions.length>0)).sort((u,f)=>u.created_at.localeCompare(f.created_at)),invalid_evidence_count:r.invalid_evidence_count+o.invalid_evidence_count+a,invalid_evidence:[...r.invalid_evidence,...o.invalid_evidence,...c].slice(0,ur),invalid_evidence_truncated:r.invalid_evidence_truncated||o.invalid_evidence_truncated||r.invalid_evidence_count+o.invalid_evidence_count+a>ur,clone_local_evidence_resolved:n!==null}}async function pg(e,t={}){return(await mr(e,t)).receipts}function cd(e,t,n){let r=new Set([...t?.durable_receipt_ids??[],...n?t?.unstaged_durable_receipt_ids??[]:[]]),i=[...e].filter(o=>!r.has(o));if(i.length!==0)throw new h(`Merge reconciliation refused ${i.length} receipt(s) without validated tracked evidence; no audit history was written.`,g.CONFLICT,{code:"merge_receipt_not_portable",required:"Every receipt cited by tracked history must have matching validated evidence in the Git index before any audit write.",recovery:{suggested_retry:"pm merge report --include-reconciled"},nextSteps:["Stage valid project sidecars after reviewing git diff, or use pm merge reconcile --stage for guarded lossless settlement. Restore missing original counterparts or preserve unrelated stale receipts outside the active store. Never copy private clone-local values into tracked evidence. Then rerun pm merge reconcile --dry-run."]})}function QI(e){let t=[],n=[];for(let r of e)(Array.isArray(r.decisions)&&r.decisions.length>0?t:n).push(r);return{pendingDecisions:t,lossless:n}}async function ZI(e,t,n={}){let r=await Bi(e);if(r===null){if(n.requireExisting===!0)throw new Error(`Receipt ${t.id} disappeared before settlement.`);return}let i=t.evidence_source??"clone_local";if(!ji(t,i))throw new Error("Merge receipt trusted settlement input failed schema validation.");let o=D(),s=F.join(r,Le(t.id)),a=await ad(e,t.item_path),c=a===null?null:F.join(lt(a),Le(t.id)),d=(await Promise.all([od({receiptPath:s,receiptId:t.id,evidenceSource:"clone_local",reconciledAt:o,settlement:n.settlement}),...c===null?[]:[od({receiptPath:c,receiptId:t.id,evidenceSource:"durable",reconciledAt:o,settlement:n.settlement})]])).filter(l=>l!==null);if(d.length===0){if(n.requireExisting===!0)throw new Error(`Receipt ${t.id} disappeared before settlement.`);return}if(!(d.some(l=>l.modern)?[$t(t)]:Pt(t)).some(l=>d.every(u=>u.fingerprints.includes(l))))throw new Error(`Receipt ${t.id} settlement copies disagree on immutable merge provenance.`);for(let l of d)await X(l.path,l.content)}async function eC(e){let t=await pg(e.cwd??process.cwd(),{...e,includeLossless:!0});return{ok:!0,count:t.length,receipts:t,generated_at:D()}}async function tC(e){let t=await mr(e.cwd??process.cwd(),{...e,includeLossless:!0}),n=t.clone_local_evidence_resolved===!0&&t.invalid_evidence_count===0;return{ok:n,complete:n,count:t.receipts.length,invalid_evidence_count:t.invalid_evidence_count,invalid_evidence:t.invalid_evidence,invalid_evidence_truncated:t.invalid_evidence_truncated,clone_local_evidence_resolved:t.clone_local_evidence_resolved,receipts:t.receipts,generated_at:D()}}import hg from"node:fs/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]="eeaf2318-5964-5d98-ad90-9faa7fc69975")}catch{}})();function Hi(e){if(!e.itemDocument)return[];let t=e.itemDocument.metadata?.assignee?.trim();if(!t||t===e.author||e.force)return[];let n=Is(e.settings);if(n.ownership_enforcement==="strict")throw new h(`Item ${e.subjectId} is assigned to ${t}. Use --force to override.`,g.CONFLICT);return n.ownership_enforcement==="warn"?[`ownership_warning:assignee_conflict:${e.subjectId}:${t}`]:[]}async function gg(e){let t=await be(e.subject.historyPath);if(t!==e.historyRawBeforeLock)throw new h(`History for ${e.subject.id} changed while waiting for lock; retry ${e.operation}.`,g.CONFLICT);let n=await me(e.pmRoot,e.subject.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder),r=n?e.readItem?await e.readItem(n):await Re(n,{schema:e.settings.schema}):null;if((r?.raw??null)!==(e.currentItemRawBeforeLock??null))throw new h(`Item ${e.subject.id} changed while waiting for lock; retry ${e.operation}.`,g.CONFLICT);return{historyRawUnderLock:t,locatedUnderLock:n,loadedItemUnderLock:r}}async function pr(e){let t=e.writeHistoryRaw??X;try{await t(e.historyPath,e.nextHistoryRaw),await zr(e.historyPath)}catch(n){try{e.historyRawUnderLock===null?await hg.rm(e.historyPath,{force:!0}):await t(e.historyPath,e.historyRawUnderLock),await zr(e.historyPath)}catch(r){throw new AggregateError([n,r],`History rewrite failed and rollback also failed: ${String(n)}`)}throw n}}async function dd(e){let t=[...Hi({itemDocument:e.itemDocument,subjectId:e.subject.id,author:e.author,force:e.force,settings:e.settings})],n=await qe(e.pmRoot,e.subject.id,e.settings.locks.ttl_seconds,e.author,!!e.force,e.settings.governance.force_required_for_stale_lock,e.settings.locks.wait_ms);try{let r=await gg({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:e.operation});return await e.applyRewrite(r),e.applyPostRewrite&&t.push(...await e.applyPostRewrite(r)),t}finally{await n()}}(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]="6283ef18-f75e-5e8c-a65f-0ba05858bc2b")}catch{}})();async function ld(e){let{subject:t,settings:n,operation:r,options:i}=e,o=await as(t.historyPath,t.id);if(o.raw===null)throw new h(`No history stream exists for ${t.id}.`,g.NOT_FOUND);if(o.entries.length===0)throw new h(`No history entries exist for ${t.id}; nothing to ${r.slice(8)}.`,g.USAGE);let s=t.located?await Re(t.located,{schema:n.schema}):null,a=Ee(i.author,n.author_default),c=await e.transform({raw:o.raw,entries:o.entries,verification:Gr(o.entries),loadedItem:s,author:a}),d=Gr(c.rewrittenEntries);if(!d.ok)throw new h(`${r} produced an invalid rewritten chain (${d.errors.join(", ")}).`,g.GENERIC_FAILURE);let l=c.changed&&!i.dryRun?await dd({pmRoot:e.pmRoot,subject:t,settings:n,typeRegistry:e.typeRegistry,historyRawBeforeLock:o.raw,currentItemRawBeforeLock:s?.raw??null,operation:r,author:a,force:i.force,itemDocument:s?.document??null,applyRewrite:async u=>{await c.beforeWrite?.(),c.applyRewrite?await c.applyRewrite(u):await pr({historyPath:t.historyPath,nextHistoryRaw:Me(c.rewrittenEntries),historyRawUnderLock:u.historyRawUnderLock})},applyPostRewrite:c.afterWrite??(async()=>rn({path:t.historyPath,scope:"project",op:`${r.replace("-","_")}:history`}))}):[];return c.report({verification:d,warnings:l})}import{isUtf8 as _g}from"node:buffer";import{readFile as yg}from"node:fs/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]="cca38e64-dd53-5086-8825-dc1c8f1cc587")}catch{}})();function vg(e){let t;try{t=JSON.parse(e)}catch{if(e.trimStart().startsWith("{")&&e.includes("}"))throw new h("History salvage cannot discard a potentially complete record with trailing corruption.",g.CONFLICT,{code:"history_salvage_refused"});return null}if(typeof t!="object"||t===null||Array.isArray(t))throw new h("History salvage would conceal interior corruption or a malformed record.",g.CONFLICT,{code:"history_salvage_refused"});let n=t;if(!Array.isArray(n.patch)||![n.ts,n.author,n.op,n.before_hash,n.after_hash].every(r=>typeof r=="string"))throw new h("History salvage requires complete history records before the invalid tail.",g.CONFLICT,{code:"history_salvage_refused"});return n}function bg(e){if(Ve(e))throw new h("Resolve history merge conflicts before salvage.",g.CONFLICT,{code:"history_salvage_refused"});let t=[],n=0,r,i=0;for(let[s,a]of e.split(`
|
|
11
|
+
`).entries()){if(!a.trim()){n+=a.length+1;continue}let c=vg(a);if(c===null){r===void 0&&(r=n,i=s+1),n+=a.length+1;continue}if(r!==void 0)throw new h("History salvage would discard a record or conceal interior corruption.",g.CONFLICT,{code:"history_salvage_refused",required:"Recover the damaged record from version control or a backup; no bytes were changed."});t.push(c),n+=a.length+1}let o=fe(t);if(!o.ok||o.item_hash_version===void 0)throw new h("History salvage requires a nonempty verified prefix.",g.CONFLICT,{code:"history_salvage_refused",verification_errors:o.errors,required:"Recover an intact history prefix from version control or a backup."});return{entries:t,itemHashVersion:o.item_hash_version,prefix:r===void 0?e:e.slice(0,r),receipt:r===void 0?null:{first_invalid_line:i,discarded_bytes:Buffer.byteLength(e.slice(r)),discarded_sha256:ie(e.slice(r)),retained_entries:t.length}}}async function wg(e,t,n){if(!e.located)return{itemRaw:null,document:n};let r=await Os(e.located,{schema:t.schema});return{itemRaw:r.raw,document:r.document??n}}async function ud(e){let t;try{t=await yg(e)}catch(n){if(de(n))return null;throw n}if(!_g(t))throw new h("History salvage requires UTF-8 input; recover binary corruption from a byte-preserving backup.",g.CONFLICT,{code:"history_salvage_refused"});return t.toString("utf8")}async function fd(e){let{subject:t,settings:n,options:r,author:i}=e;if([r.normalizeProvenance,r.auditOperation,r.auditContext,r.auditContextById,r.forceAuditEntry,r.mergeReceiptProof,r.mergeReceiptProofById].some(Boolean))throw new h("Tail salvage cannot be combined with other repair modes.",g.USAGE);let o=await ud(t.historyPath);if(o===null)throw new h(`No history stream exists for ${t.id}.`,g.NOT_FOUND);await on({path:t.historyPath,scope:"project"});let s=bg(o),a=bn(s.entries,s.entries.length-1),c=ds(a);if(typeof a.metadata.id=="string"&&a.metadata.id!==t.id)throw new h("History belongs to another item; salvage refused.",g.CONFLICT,{code:"history_salvage_refused"});let d=await wg(t,n,c),l=Hi({itemDocument:d.document,subjectId:t.id,author:i,force:r.force,settings:n}),u=s.itemHashVersion,f=r.dryRun===!0,m=s.receipt!==null;if(m&&!f){let p=await qe(e.pmRoot,t.id,n.locks.ttl_seconds,i,!!r.force,n.governance.force_required_for_stale_lock,n.locks.wait_ms);try{let _=await ud(t.historyPath),y=await me(e.pmRoot,t.id,n.id_prefix,n.item_format,e.typeRegistry.type_to_folder),b=y?await be(y.itemPath):null;if(_!==o||b!==d.itemRaw)throw new h("History or item changed while waiting for salvage lock; retry.",g.CONFLICT);let v=yn({...ws({hashAlgorithm:ke(s.entries.at(-1).hash_algorithm),nowIso:D(),author:i,op:"history_salvage",before:c,after:c,message:r.message,context:{history_salvage:s.receipt}}),before_hash:s.entries.at(-1).after_hash,after_hash:s.entries.at(-1).after_hash,item_hash_version:u});await pr({historyPath:t.historyPath,historyRawUnderLock:o,nextHistoryRaw:`${s.prefix}${JSON.stringify(v)}
|
|
12
|
+
`}),l.push(...await rn({path:t.historyPath,scope:"project",op:"history_salvage:history"}))}finally{await p()}}return{id:t.id,dry_run:f,changed:m,history:{path:t.historyPath,entries_scanned:s.entries.length,chain_drift_before:!1,entries_rehashed:0,entries_patch_repaired:0,converted_replace_to_add:0,skipped_ops:0,reconciled_with_item:!1,audit_entry_added:m&&!f,verify_ok:!0,verify_errors:[],item_hash_version_before:u,item_hash_version_after:u,version_disposition:"preserved"},item:{exists:t.located!==null,path:t.located?.itemPath??null,matched_chain_before:null},provenance_normalization:{requested:!1,changed:!1,events_changed:0,observations_removed:0,invalid_values:[]},...s.receipt?{salvage:s.receipt}:{},warnings:l,generated_at:D()}}import{realpath as Sd}from"node:fs/promises";import Ki from"node:path";import Td from"fast-json-patch";import jt from"node:fs/promises";import{createHash as kg}from"node:crypto";import pd 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]="97537e2a-b8cb-559e-82bc-3c98b0c51db1")}catch{}})();var Gi=new Set([void 0,...Xo]),hd=11,Eg="history-drift-cache.json";function gd(e){return pd.join(e,"runtime",Eg)}async function Ig(e){try{let t=await jt.readFile(gd(e),"utf8"),n=JSON.parse(t);return n.version!==hd||n.history_item_hash_version!==_n||typeof n.entries!="object"||n.entries===null||Object.values(n.entries).some(r=>typeof r.chain_ok!="boolean"||typeof r.latest_hash_comparable!="boolean"||!Gi.has(r.hash_algorithm)||!Je.includes(r.item_hash_version)&&r.version_skew!==!0||r.chain_ok&&r.version_skew!==!0&&Je.includes(r.item_hash_version)&&!r.latest_hash_comparable)?null:n}catch{return null}}function _d(){return{missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[],versionSkews:[],workspaceStateMismatches:[],workspaceStateMissing:[],workspaceStateUnreadable:[]}}function yd(e){let t=[...new Set([...e.missingStreams,...e.unreadableStreams,...e.hashMismatches,...e.chainMismatches,...e.versionSkews,...e.workspaceStateMismatches.length>0||e.workspaceStateMissing.length>0||e.workspaceStateUnreadable.length>0?[Z]:[]])].sort((n,r)=>n.localeCompare(r));return{...e,driftedItems:t}}async function Cg(e,t,n,r,i){let o=ks(e),s;try{s=await jt.stat(o)}catch(d){return de(d)||i.unreadableStreams.push(Z),!1}let a=i.missingStreams.length,c=await vd({itemId:Z,historyPath:o,stat:s,cached:t[Z],verifyCacheHitByContent:r,accumulator:i});return c.verification?(c.verification.versionSkew&&i.versionSkews.push(Z),c.verification.chainOk||i.chainMismatches.push(Z),n[Z]={mtime_ms:s.mtimeMs,ctime_ms:s.ctimeMs,size:s.size,content_hash:c.verification.contentHash,latest_after_hash:c.verification.latestAfterHash,chain_ok:c.verification.chainOk,version_skew:c.verification.versionSkew,latest_hash_comparable:c.verification.latestHashComparable,item_hash_version:c.verification.itemHashVersion,hash_algorithm:c.verification.hashAlgorithm},c.cacheDirty):(i.missingStreams.splice(a),c.cacheDirty)}function Sg(e){return!Gi.has(e.hash_algorithm)||e.item_hash_version!==void 0&&!Je.includes(e.item_hash_version)}async function Tg(e){let t=await jt.readFile(e,"utf8"),n=kg("sha256").update(t).digest("hex");if(t.trim().length===0)return null;let r=[],i=null;for(let f of t.split(/\r?\n/)){let m=f.trim();if(m.length===0)continue;let p=JSON.parse(m);if(typeof p.after_hash!="string"||p.after_hash.trim().length===0)throw new Error("missing after_hash");r.push(p),i=p.after_hash}if(!i)return null;let o=fe(r),s=r.some(Sg),a=r[r.length-1],c=Gi.has(a.hash_algorithm),d=a.item_hash_version,l=d!==void 0&&Je.includes(d),u=l?d:o.item_hash_version;return{latestAfterHash:i,hashAlgorithm:c?ke(a.hash_algorithm):void 0,identityDiscontinuities:Hr(r),chainOk:o.ok,versionSkew:s,latestHashComparable:c&&u!==void 0&&(!s||l||d===void 0),contentHash:n,itemHashVersion:u??_n}}function Rg(e,t){return e!==void 0&&e.mtime_ms===t.mtimeMs&&e.ctime_ms===t.ctimeMs&&e.size===t.size}async function md(e,t,n){try{return await Tg(t)||(n.missingStreams.push(e),null)}catch{return n.unreadableStreams.push(e),null}}function xg(e,t){return e!==null&&e.contentHash===t.content_hash&&e.latestAfterHash===t.latest_after_hash&&e.chainOk===t.chain_ok&&e.versionSkew===(t.version_skew===!0)&&e.latestHashComparable===t.latest_hash_comparable&&e.itemHashVersion===t.item_hash_version&&e.hashAlgorithm===t.hash_algorithm}async function vd(e){let t=typeof e.cached?.content_hash=="string"&&e.cached.content_hash.length>0?e.cached.content_hash:void 0;if(!(Rg(e.cached,e.stat)&&t!==void 0)||!e.cached||!e.cached.chain_ok)return{verification:await md(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0};if(e.verifyCacheHitByContent){let n=await md(e.itemId,e.historyPath,e.accumulator);return{verification:n,cacheDirty:!xg(n,e.cached)}}return{verification:{identityDiscontinuities:[],latestAfterHash:e.cached.latest_after_hash,chainOk:e.cached.chain_ok,versionSkew:e.cached.version_skew===!0,latestHashComparable:e.cached.latest_hash_comparable&&Je.includes(e.cached.item_hash_version),contentHash:t,itemHashVersion:e.cached.item_hash_version,hashAlgorithm:e.cached.hash_algorithm},cacheDirty:!1}}async function bd(e,t,n,r){let i,o;try{i=Ge(e,t.id),o=await jt.stat(i)}catch(d){return(de(d)?r.missingStreams:r.unreadableStreams).push(t.id),!1}let s=await vd({itemId:t.id,historyPath:i,stat:o,cached:n.previousEntries[t.id],verifyCacheHitByContent:n.verifyCacheHitByContent,accumulator:r});if(!s.verification)return s.cacheDirty;s.verification.identityDiscontinuities.length>0&&(r.identityDiscontinuities??=[]).push(...s.verification.identityDiscontinuities.map(d=>({...d,item_id:t.id}))),s.verification.versionSkew&&r.versionSkews.push(t.id),s.verification.chainOk||r.chainMismatches.push(t.id),n.nextEntries[t.id]={mtime_ms:o.mtimeMs,ctime_ms:o.ctimeMs,size:o.size,content_hash:s.verification.contentHash,latest_after_hash:s.verification.latestAfterHash,chain_ok:s.verification.chainOk,version_skew:s.verification.versionSkew,latest_hash_comparable:s.verification.latestHashComparable,item_hash_version:s.verification.itemHashVersion,hash_algorithm:s.verification.hashAlgorithm};let{body:a,...c}=t;return s.verification.latestHashComparable&&(vn({metadata:c,body:a},s.verification.itemHashVersion,s.verification.hashAlgorithm).includes(s.verification.latestAfterHash)||r.hashMismatches.push(t.id)),s.cacheDirty}async function Dg(e,t){if(!(t.unreadableStreams.includes(Z)||t.chainMismatches.includes(Z)||t.versionSkews.includes(Z)))try{let n=await Es(e);t.workspaceStateMismatches.push(...n.mismatched_documents),t.workspaceStateMissing.push(...n.missing_documents),t.workspaceStateUnreadable.push(...n.unreadable_documents)}catch{t.unreadableStreams.push(Z)}}async function WC(e,t){let n=_d();return await bd(e,t,{previousEntries:{},nextEntries:{},verifyCacheHitByContent:!0},n),yd(n)}async function wd(e,t,n={}){let r=_d(),i=(await Ig(e))?.entries??{},o={},s=!1,a=n.cacheHitVerification!=="metadata",c={previousEntries:i,nextEntries:o,verifyCacheHitByContent:a};for(let l of t)await bd(e,l,c,r)&&(s=!0);let d=await Cg(e,i,o,a,r);if(s||=d,await Dg(e,r),s||Object.keys(i).length!==Object.keys(o).length){let l=gd(e);try{await jt.mkdir(pd.dirname(l),{recursive:!0}),await X(l,JSON.stringify({version:hd,history_item_hash_version:_n,entries:o}))}catch{}}return yd(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]="a6d2870f-ebba-580a-85e9-3eb44e533d08")}catch{}})();function kd(e,t){return t==="body"?e.body:e.metadata[t]}function Ag(e,t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;let n=t;return e==="comments"?typeof n.created_at=="string"&&typeof n.author=="string"&&typeof n.text=="string":typeof n.path=="string"||e==="tests"&&typeof n.command=="string"}function Og(e){let t={...e};if(t.source_kind==="merge_union"&&(t.source_kind="local_mutation"),t.provenance!==null&&typeof t.provenance=="object"&&!Array.isArray(t.provenance)){let n={...t.provenance};n.source_kind==="merge_union"&&(n.source_kind="local_mutation"),t.provenance=n}return t}function Ed(e,t){if(!Array.isArray(t)||!["comments","docs","tests"].includes(e)||!t.every(r=>Ag(e,r)))return t;let n=t.map(r=>e==="comments"?r:Og(r));return[...new Map(n.map(r=>[E(r),r])).values()]}function zi(e,t){if(e===void 0||Object.is(e,t))return!0;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let r=new Set;return e.every(i=>{let o=t.findIndex((s,a)=>!r.has(a)&&zi(i,s));return o<0?!1:(r.add(o),!0)})}if(e===null||t===null||typeof e!="object"||typeof t!="object"||Array.isArray(t))return!1;let n=t;return Object.entries(e).every(([r,i])=>Object.hasOwn(n,r)&&zi(i,n[r]))}function Id(e,t){let n=new Set(t),r=[];for(let i=e.length-1;i>=0&&n.size>0;i-=1){let o=e[i],s=new Set;for(let c of hn(o.patch))s.add(In(c.path)),c.from&&s.add(In(c.from));let a=[...n].filter(c=>s.has(c));if(a.length!==0){for(let c of a)n.delete(c);r.push({index:i+1,ts:o.ts,author:o.author,op:o.op,fields:a.sort((c,d)=>c.localeCompare(d))})}}return r.reverse()}function Lg(e,t,n){let r=Td.compare(t,n);if(r.length===0)return;let i=new Set;for(let p of r)i.add(In(p.path));let o=new Set([...i].filter(p=>zi(Ed(p,kd(t,p)),Ed(p,kd(n,p))))),s=new Set([...i].filter(p=>!o.has(p))),a=Id(e,s),c=Id(e,o),d=[...i].sort((p,_)=>p.localeCompare(_)),l=[...s].sort((p,_)=>p.localeCompare(_)),u=[...o].sort((p,_)=>p.localeCompare(_)),f=[...new Set(a.map(p=>p.author))].sort((p,_)=>p.localeCompare(_)),m=[...new Set(c.map(p=>p.author))].sort((p,_)=>p.localeCompare(_));return{reconciled_field_count:i.size,reconciled_fields:d,reverted_field_count:s.size,reverted_fields:l,discarded_events:a,discarded_authors:f,preserved_field_count:o.size,preserved_fields:u,preserved_events:c,preserved_authors:m,recovery_hint:a.length>0?"Reconciliation keeps the on-disk item and overwrites these replayed mutations. To recover one, inspect it with pm history <id> --diff --field <field>, then re-apply the lost value with pm update.":null}}async function Mg(e){try{return await Sd(e)}catch{return null}}async function Ng(e){if(await Mg(Ki.resolve(e.gitWorkspaceRoot,e.receipt.item_path))!==e.currentPath)return null;let t=[...new Set([...e.receipt.fields_from_theirs,...e.receipt.union_fields,...e.receipt.decisions.map(o=>o.field)])].sort(),n=e.receipt.merged_field_hashes;if(!n||t.length===0)return null;let r=Object.keys(n).sort();if(t.length!==r.length||t.some((o,s)=>o!==r[s]))return null;let i=e.currentItemReplay.metadata;return t.every(o=>{let s=o==="body"?e.currentItemReplay.body:i[o];return[Ae(s),ie(E(R(s)))].includes(n[o])})?{receipt:e.receipt,declaredFields:t}:null}async function Fg(e){if(e.proof.gitWorkspaceRoot===null)return{trusted:!1,reason:"git_workspace_unavailable",receipt_ids:[]};if(e.itemPath===null||e.currentItemReplay===null)return{trusted:!1,reason:"item_path_unavailable",receipt_ids:[]};let t=e.proof.receipts.filter(s=>s.item_id===e.id);if(t.length===0)return{trusted:!1,reason:"no_item_receipts",receipt_ids:[]};let n=await Sd(e.itemPath),r=[];for(let s of t){let a=await Ng({receipt:s,gitWorkspaceRoot:e.proof.gitWorkspaceRoot,currentPath:n,currentItemReplay:e.currentItemReplay});a&&r.push(a)}let i=new Set(r.flatMap(({declaredFields:s})=>s)),o=e.reconciliation?.reconciled_fields;return r.length>0&&(o===void 0||o.length>0&&o.every(s=>i.has(s)))?{trusted:!0,reason:"trusted_merge_driver_hash_evidence",receipt_ids:r.map(({receipt:s})=>s.id)}:{trusted:!1,reason:"no_receipt_set_proves_snapshot",receipt_ids:[]}}async function Cd(e,t,n,r){if(e===void 0)return;let{receipt:i,gitWorkspaceRoot:o}=e,s=t.currentItemPath===null?null:Ki.relative(o,t.currentItemPath).split(Ki.sep).join("/");if(!n||r.entriesRehashed!==0||r.entriesPatchRepaired!==0||t.matchedChainBefore!==!0||t.currentItemRawBeforeLock===null||s!==i.item_path||i.operation===void 0||!await Zc(o,i.item_path,i.operation,t.currentItemRawBeforeLock))throw new h("Restored-origin receipt evidence no longer proves the exact clean item snapshot.",g.CONFLICT,{code:"merge_reconcile_receipt_evidence_untrusted",recovery:{suggested_retry:"pm merge reconcile --dry-run"}})}async function $g(e){let t=new Set(e.options.mergeReceiptProof?.receipts.filter(s=>s.item_id===e.subjectId).map(s=>s.id)??[]),n=e.options.mergeReceiptProof?await mr(e.options.mergeReceiptProof.gitWorkspaceRoot??process.cwd(),{includeReconciled:!0,includeLossless:!0,pmRoot:e.pmRoot}):void 0,r=n?.receipts.filter(s=>s.item_id===e.subjectId&&t.has(s.id))??[];cd(t,n,e.options.dryRun===!0);let i=e.options.mergeReceiptProof?await Fg({proof:{...e.options.mergeReceiptProof,receipts:r},id:e.subjectId,itemPath:e.itemReplayContext.currentItemPath,currentItemReplay:e.itemReplayContext.currentItemReplay,reconciliation:e.reconciliation}):void 0;if(i&&!i.trusted&&e.options.force!==!0)throw new h(`Merge receipt evidence for ${e.subjectId} does not prove the exact item snapshot (${i.reason}).`,g.CONFLICT,{code:"merge_reconcile_receipt_evidence_untrusted",required:"Use authoritative clone-local or durable receipt evidence whose canonical path, declared fields, and merged-value hashes match the current item, or review the mismatch and rerun with --force.",recovery:{suggested_retry:"pm merge reconcile --dry-run"}});let o=i?.trusted?r.filter(s=>i.receipt_ids.includes(s.id)):[];return{mergeReceiptProof:i,effectiveAuditContext:o.length>0&&e.options.force!==!0?{...e.options.auditContext,merge:{receipts:o.map(fr)}}:e.options.auditContext}}function Pg(e,t,n){let r=e.located?.itemPath??null,i=t.loadedItem,o=t.entries;if(!i)return{currentItemReplay:null,currentItemPath:r,matchedChainBefore:null,currentItemRawBeforeLock:null,loadedItem:null};let s=pn(i.document),a=o[o.length-1].after_hash;return{currentItemReplay:s,currentItemPath:r,matchedChainBefore:Ye(s,n,ke(o.at(-1)?.hash_algorithm)).includes(a),currentItemRawBeforeLock:i.raw,loadedItem:i}}function jg(e){return typeof e.message=="string"&&e.message.trim().length>0?e.message:`history-repair re-anchored ${e.entriesRehashed} entr${e.entriesRehashed===1?"y":"ies"}${e.entriesPatchRepaired>0?`, repaired ${e.entriesPatchRepaired} patch(es)`:""}${e.reconcileNeeded?", reconciled chain with on-disk item":""}.`}function Ug(e){let t=[...e.reanchorEntries];if(!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let n=e.reconcileNeeded&&e.currentItemReplay?e.currentItemReplay:e.finalReplay,r=ke(e.reanchorEntries.at(-1)?.hash_algorithm),i=Ye(e.finalReplay,e.itemHashVersion,r),o=e.reanchorEntries[e.reanchorEntries.length-1].after_hash,s=i.indexOf(o),a=Ye(n,e.itemHashVersion,r),c={hash_algorithm:r,ts:D(),author:e.author,op:e.auditOperation,patch:e.reconcileNeeded&&e.currentItemReplay?Td.compare(e.finalReplay,e.currentItemReplay):[],before_hash:i[s],after_hash:a[s],message:e.message,...e.explicitItemHashVersion?{item_hash_version:e.itemHashVersion}:{},...e.auditContext===void 0?{}:{context:e.auditContext}};return t.push(yn({...c,event_class:fs(c)})),{rewrittenEntries:t,auditEntryAdded:!0}}function Bg(e,t,n){let r=[];return e||r.push("history_repair_no_changes"),t>0&&r.push(`history_repair_skipped_unresolvable_ops:${t}`),n&&n.discarded_events.length>0&&r.push(`history_repair_reconcile_discards_events:${n.discarded_events.length}`,`history_repair_discarded_authors:${n.discarded_authors.join(",")}`),r}async function Hg(e,t,n){let{pmRoot:r,settings:i,typeRegistry:o}=await Xr(n.path),s=await Rn(r,e,i,o.type_to_folder);return t.salvageTail===!0?fd({pmRoot:r,subject:s,settings:i,typeRegistry:o,options:t,author:Ee(t.author,i.author_default)}):ld({pmRoot:r,subject:s,settings:i,typeRegistry:o,operation:"history-repair",options:t,transform:a=>Kg({pmRoot:r,subject:s,options:t},a)})}function Gg(e,t,n){let r=(e.mergeAbandonmentProof!==void 0||e.mergeReceiptProof!==void 0&&e.force!==!0)&&n!==void 0&&t.some(i=>i.record_hash_version!==void 0&&i.op==="merge_reconcile"&&E(i.context)===E(n));return e.forceAuditEntry===!0&&!r}async function Kg(e,t){let{pmRoot:n,subject:r,options:i}=e,o=t.entries,s=t.verification,a=fe(o),c=i.normalizeProvenance?$c(o):{entries:o,receipt:{changed:!1,events_changed:0,observations_removed:0,invalid_values:[]}},d=us(c.entries),l=new Set(c.entries.map(H=>H.item_hash_version).filter(H=>H!==void 0)),u=gn(c.entries,d),f=Pg(r,t,d);await Cd(i.mergeAbandonmentProof,f,s.ok,u);let m=u.finalDocument,p=Ye(m,d),_=!1;if(f.currentItemReplay!==null){let H=Ye(f.currentItemReplay,d);_=!p.some((j,q)=>j===H[q])}let y=_&&f.currentItemReplay?Lg(u.entries,m,f.currentItemReplay):void 0,{mergeReceiptProof:b,effectiveAuditContext:v}=await $g({options:i,pmRoot:n,subjectId:r.id,itemReplayContext:f,reconciliation:y}),w=[u.entriesRehashed>0,u.entriesPatchRepaired>0,_,Gg(i,u.entries,v),c.receipt.changed].some(Boolean),k=t.author,S=!!i.dryRun,L=jg({message:i.message,entriesRehashed:u.entriesRehashed,entriesPatchRepaired:u.entriesPatchRepaired,reconcileNeeded:_}),{rewrittenEntries:B,auditEntryAdded:$}=Ug({reanchorEntries:u.entries,changed:w,reconcileNeeded:_,currentItemReplay:f.currentItemReplay,finalReplay:m,author:k,message:L,auditOperation:i.auditOperation??"history_repair",auditContext:c.receipt.changed?{...v,provenance_normalization:c.receipt}:v,itemHashVersion:d,explicitItemHashVersion:u.explicitItemHashVersion}),ce=Bg(w,u.skippedOps,y);return{changed:w,rewrittenEntries:B,beforeWrite:async()=>Cd(i.mergeAbandonmentProof,f,s.ok,u),report:({verification:H,warnings:j})=>({id:r.id,dry_run:S,changed:w,history:{path:r.historyPath,entries_scanned:o.length,chain_drift_before:!s.ok,entries_rehashed:u.entriesRehashed,entries_patch_repaired:u.entriesPatchRepaired,converted_replace_to_add:u.convertedReplaceToAdd,skipped_ops:u.skippedOps,reconciled_with_item:_,audit_entry_added:$,verify_ok:H.ok,verify_errors:H.errors,item_hash_version_before:a.item_hash_version??null,item_hash_version_after:d,version_disposition:l.size>1?"selected_for_ambiguous_stream":"preserved"},item:{exists:f.currentItemPath!==null,path:f.currentItemPath,matched_chain_before:f.matchedChainBefore},provenance_normalization:{requested:i.normalizeProvenance===!0,...c.receipt},...y?{reconciliation:y}:{},...b?{merge_receipt_proof:b}:{},warnings:[...new Set([...ce,...j])].sort((q,te)=>q.localeCompare(te)),generated_at:D()})}}function vS(e,t){if(t&&e!==void 0)throw new h("history-repair: <id> and --all are mutually exclusive; pass an item id to repair one stream or --all to repair every drifted stream.",g.USAGE);if(!t&&e===void 0)throw new h("history-repair: provide an item <id> or pass --all to repair every drifted stream.",g.USAGE)}async function bS(e,t){if(e.salvageTail===!0)throw new h("Tail salvage requires one explicit item ID; --all is not supported.",g.USAGE);let{pmRoot:n,settings:r,typeRegistry:i}=await Xr(t.path),o=[],s=await kn(n,r.item_format,i.type_to_folder,o,r.schema,{forceSourceScan:!0}),a=await wd(n,s),c=e.normalizeProvenance?await Pc(n):[],d=[...new Set([...a.driftedItems,...c])].sort((m,p)=>m.localeCompare(p)),l=[],u=[],f={repaired:0,skipped_clean:0,failed:0};for(let m of d)try{let p=await Hg(m,{...e,auditContext:e.auditContextById?.[m],auditContextById:void 0,mergeReceiptProof:e.mergeReceiptProofById?.[m]??e.mergeReceiptProof,mergeReceiptProofById:void 0},t),_=p.changed?"repaired":"skipped_clean";f[_]+=1,u.push(...p.warnings.map(y=>`${m}:${y}`)),l.push({id:m,outcome:_,entries_rehashed:p.history.entries_rehashed,entries_patch_repaired:p.history.entries_patch_repaired,reconciled_with_item:p.history.reconciled_with_item,...p.reconciliation?{reconciliation:p.reconciliation}:{},...p.merge_receipt_proof?{merge_receipt_proof:p.merge_receipt_proof}:{},warnings:p.warnings})}catch(p){f.failed+=1,l.push({id:m,outcome:"failed",error:p instanceof Error?p.message:String(p)})}return e.dryRun||await gs(n),{all:!0,dry_run:!!e.dryRun,scanned_streams:s.length,drifted_streams:a.driftedItems.length,provenance_invalid_streams:c.length,streams:l,totals:f,warnings:[...new Set([...o,...u])].sort((m,p)=>m.localeCompare(p)),generated_at:D()}}(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]="1433b417-e41f-5963-a551-094132afd717")}catch{}})();var Rd=16;async function xd(e,t,n){let r=M(t,x()).type_to_folder,i=[],o=new Set,s=n;for(;s&&i.length<Rd;){let a=s.trim().toLowerCase();if(!a||o.has(a))break;o.add(a);let c=await me(e,s,t.id_prefix,t.item_format,r);if(!c)break;let d=await Re(c,{schema:t.schema});i.push(d.document.metadata.id),s=d.document.metadata.parent}return i}async function SS(e){await rs({pmRoot:e.pmRoot,principal:e.principal,itemId:e.itemId,lineageIds:await xd(e.pmRoot,e.settings,e.itemId)})}async function TS(e){await is(e)}async function RS(e){await os({pmRoot:e.pmRoot,principal:e.principal,...e.itemId?{itemId:e.itemId,lineageIds:await xd(e.pmRoot,e.settings,e.itemId)}:{}})}var xS={lineage_depth:Rd,active_items:64,evidence_rows:32};function Dd(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}import{encode as qg}from"@toon-format/toon";import{createHash as zg}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]="66022e7d-1594-5b88-a283-c64830ff0dfd")}catch{}})();function qi(e){let t=zg("sha256").update("[");for(let n of e)t.update(E(n)).update("\0");return t.update("]").digest("hex")}function hr(e,t){if(t===void 0)return D();let n=Bo(t).snapshot,r=`${e}:`,i=n?.slice(r.length);if(!n?.startsWith(r)||!i||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/u.test(i)||!Number.isFinite(Date.parse(i)))throw new h("Query cursor has no supported fixed-window clock.",g.USAGE,{code:"invalid_query_cursor",nextSteps:["Repeat the original query without --after to obtain a fresh cursor."]});return i}function Ut(e,t){let n=e.map((a,c)=>({row:a,index:c})),r=le(t.command,{query:t.query,rows_digest:qi(e)}),i=t.after===void 0?void 0:Ho(t.after,r);if(i&&(i.after_index===void 0||i.after_id!==String(i.after_index)||i.after_index>=e.length))throw new h("Query cursor position is outside the matching window.",g.USAGE,{code:"invalid_query_cursor",nextSteps:["Repeat the original query without --after to obtain a fresh cursor."]});let o=Ko(n,{cursor:t.after,fingerprint:r,snapshot:`${t.command}:${t.clock}`,limit:t.limit??e.length,readId:({index:a})=>String(a)}),s=i?.after_index===void 0?0:i.after_index+1;return{...o,rows:o.rows.map(({row:a})=>a),count:o.rows.length,total_count:e.length,page_start:s,omitted_count:e.length-s-o.rows.length,has_more:s+o.rows.length<e.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]="351df2b3-3a1a-528c-96b9-72bb3e2f27fc")}catch{}})();var Vi=["agenda","day","week","month"],Wi=["markdown","toon","json"],Vg=["sun","mon","tue","wed","thu","fri","sat"],Wg=365,Xg=365,Fd=28,Yg=1e3;function Xi(e,t){if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw new h(`${t} must be a non-negative integer`,g.USAGE);return n}function Jg(e){if(!e)return new Set(["deadlines","reminders","events"]);let t=e.trim().toLowerCase();if(t==="all")return new Set(["deadlines","reminders","events"]);let n=t.split(/[|,]/).map(i=>i.trim()).filter(i=>i.length>0);if(n.length===0)throw new h("Calendar include filter must not be empty",g.USAGE);let r=new Set;for(let i of n){if(i==="deadlines"||i==="deadline"){r.add("deadlines");continue}if(i==="reminders"||i==="reminder"){r.add("reminders");continue}if(i==="events"||i==="event"||i==="scheduled"){r.add("events");continue}throw new h("Calendar include filter must be deadlines|reminders|events|scheduled|all",g.USAGE)}return r}function $d(e,t){let n;for(let r of t){let i=Do(e,r,2);i!==null&&(n===void 0||i<n.distance)&&(n={choice:r,distance:i})}return n?.choice}function Qg(e){if(!e)return"agenda";let t=e.trim().toLowerCase();if(!Vi.includes(t)){let n=$d(t,Vi);throw new h(`Calendar view must be one of ${Vi.join("|")}${n?`. Did you mean "${n}"?`:"."}`,g.USAGE)}return t}function Zg(e){if(!e)return;let t=e.trim().toLowerCase();if(!Wi.includes(t)){let n=$d(t,Wi);throw new h(`Calendar format must be one of ${Wi.join("|")}${n?`. Did you mean "${n}"?`:"."}`,g.USAGE)}return t}function BS(e,t){let n=Zg(e.format);if(t.json&&n&&n!=="json")throw new h("Cannot combine --json with --format markdown|toon",g.USAGE);return t.json?"json":n??"markdown"}function e_(e,t){if(e===void 0)return;let n=Q(e,t);if(!n){let r=t.definitions.map(i=>i.id);throw new h(`Calendar status filter must be one of ${r.join("|")}`,g.USAGE)}return n}function t_(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(!t)throw new h("Calendar assignee filter must be one of assigned|unassigned",g.USAGE);if(t!=="assigned"&&t!=="unassigned")throw new h(`Invalid calendar assignee filter "${e}". Allowed: assigned|unassigned`,g.USAGE);return t}function gr(e){return new Date(e).toISOString().slice(0,10)}function Pd(e,t){if(!t||t==="UTC")return gr(e);try{let n=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(e)),r=n.find(s=>s.type==="year")?.value,i=n.find(s=>s.type==="month")?.value,o=n.find(s=>s.type==="day")?.value;if(r&&i&&o)return`${r}-${i}-${o}`}catch{}return gr(e)}function Zi(e){let t=new Date(e);return new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate(),0,0,0,0)).toISOString()}function Se(e,t){let n=new Date(e);return new Date(n.getTime()+t*24*60*60*1e3).toISOString()}function jd(e){let t=new Date(Zi(e)),n=t.getUTCDay(),r=n===0?-6:1-n;return Se(t.toISOString(),r)}function n_(e){let t=new Date(e);return new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),1,0,0,0,0)).toISOString()}function r_(e){let t=new Date(e);return new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth()+1,1,0,0,0,0)).toISOString()}function i_(e,t){return C(e,t)>=0?e:t}function Ad(e){return Object.fromEntries([...e.entries()].sort(([t],[n])=>t.localeCompare(n)))}function Od(e,t){e.set(t,(e.get(t)??0)+1)}function o_(e){if(!e)return null;let t=[`freq=${e.freq}`];if(e.interval!==void 0&&t.push(`interval=${e.interval}`),e.count!==void 0&&t.push(`count=${e.count}`),e.until&&t.push(`until=${e.until}`),e.by_weekday&&e.by_weekday.length>0){let n=[...e.by_weekday].sort((r,i)=>He(r)-He(i));t.push(`by_weekday=${n.join("|")}`)}if(e.by_month_day&&e.by_month_day.length>0){let n=[...e.by_month_day].sort((r,i)=>r-i);t.push(`by_month_day=${n.join("|")}`)}if(e.exdates&&e.exdates.length>0){let n=[...e.exdates].sort((r,i)=>r.localeCompare(i));t.push(`exdates=${n.join("|")}`)}return t.join(",")}function Ud(e,t,n,r){let i=new Date(Date.UTC(e,t,n,r.getUTCHours(),r.getUTCMinutes(),r.getUTCSeconds(),r.getUTCMilliseconds()));if(!(i.getUTCFullYear()!==e||i.getUTCMonth()!==t||i.getUTCDate()!==n))return i.toISOString()}function Bd(e){return Vg[new Date(e).getUTCDay()]}function s_(e){let t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():null}function a_(e){let t=new Set;for(let n of e??[]){let r=s_(n);r&&t.add(r)}return t}function c_(e,t,n,r,i){let o=e??Se(n,-(r??Xg)),s=t??Se(e??n,i??Wg);return{start:o,end:C(s,o)>0?s:Se(o,1)}}function d_(e,t,n,r){let i=t.by_weekday!==void 0?[...t.by_weekday]:[Bd(e)],o=t.by_month_day!==void 0?[...t.by_month_day]:[new Date(e).getUTCDate()];return{startAt:e,startDate:new Date(e),window:n,maxOccurrences:r??Yg,interval:t.interval??1,countLimit:t.count??Number.POSITIVE_INFINITY,until:t.until,excluded:a_(t.exdates),weekdayFilter:t.by_weekday!==void 0?new Set(t.by_weekday):void 0,monthDayFilter:t.by_month_day!==void 0?new Set(t.by_month_day):void 0,sortedWeekdays:[...new Set(i)].sort((s,a)=>He(s)-He(a)),sortedMonthDays:[...new Set(o)].sort((s,a)=>s-a),occurrences:[],produced:0}}function _r(e,t){return C(t,e.startAt)<0?"continue":e.until&&C(t,e.until)>0||C(t,e.window.end)>=0?"stop":e.excluded.has(t)?"continue":(e.produced+=1,C(t,e.window.start)>=0&&e.occurrences.push(t),e.produced>=e.countLimit||e.occurrences.length>=e.maxOccurrences?"stop":"continue")}function yr(e,t){let n=Bd(t),r=new Date(t).getUTCDate(),i=!e.weekdayFilter||e.weekdayFilter.has(n),o=!e.monthDayFilter||e.monthDayFilter.has(r);return i&&o}function l_(e){let t=e.startAt;for(let n=0;n<e.maxOccurrences&&!(yr(e,t)&&_r(e,t)==="stop");n+=1)t=Se(t,e.interval);return e.occurrences}function u_(e,t,n){let r=He(n),i=Se(t,r),o=new Date(i);return new Date(Date.UTC(o.getUTCFullYear(),o.getUTCMonth(),o.getUTCDate(),e.startDate.getUTCHours(),e.startDate.getUTCMinutes(),e.startDate.getUTCSeconds(),e.startDate.getUTCMilliseconds())).toISOString()}function f_(e){let t=jd(e.startAt);for(let n=0;n<e.maxOccurrences;n+=1){let r=Se(t,n*e.interval*7);for(let i of e.sortedWeekdays){let o=u_(e,r,i);if(yr(e,o)&&_r(e,o)==="stop")return e.occurrences}}return e.occurrences}function m_(e){let t=e.startDate.getUTCFullYear(),n=e.startDate.getUTCMonth();for(let r=0;r<e.maxOccurrences;r+=1){let i=new Date(Date.UTC(t,n+r*e.interval,1,0,0,0,0));for(let o of e.sortedMonthDays){let s=Ud(i.getUTCFullYear(),i.getUTCMonth(),o,e.startDate);if(!(!s||!yr(e,s))&&_r(e,s)==="stop")return e.occurrences}}return e.occurrences}function p_(e){let t=e.startDate.getUTCFullYear(),n=e.startDate.getUTCMonth();for(let r=0;r<e.maxOccurrences;r+=1){let i=t+r*e.interval;for(let o of e.sortedMonthDays){let s=Ud(i,n,o,e.startDate);if(!(!s||!yr(e,s))&&_r(e,s)==="stop")return e.occurrences}}return e.occurrences}function h_(e,t,n,r){let i=d_(e,t,n,r);return t.freq==="daily"?l_(i):t.freq==="weekly"?f_(i):t.freq==="monthly"?m_(i):p_(i)}function Hd(e){return[...e].sort((t,n)=>{let r=C(t.at,n.at);if(r!==0)return r;let i=t.item_priority-n.item_priority;if(i!==0)return i;let o=t.item_id.localeCompare(n.item_id);if(o!==0)return o;let s=t.kind.localeCompare(n.kind);if(s!==0)return s;let a=String(t.event_title).localeCompare(String(n.event_title));return a!==0?a:String(t.reminder_text).localeCompare(String(n.reminder_text))})}function eo(e){return{item_id:e.id,item_title:e.title,item_type:e.type,item_status:e.status,item_priority:e.priority,item_assignee:e.assignee??null,item_deadline:e.deadline??null,item_tags:e.tags}}function g_(e){return e.deadline?{at:e.deadline,date:gr(e.deadline),kind:"deadline",reminder_text:null,event_title:null,event_end:null,event_location:null,event_all_day:null,event_timezone:null,event_recurring:null,event_recurrence_rule:null,...eo(e),item_deadline:e.deadline}:null}function __(e){return(e.reminders??[]).map(t=>({at:t.at,date:gr(t.at),kind:"reminder",reminder_text:t.text,event_title:null,event_end:null,event_location:null,event_all_day:null,event_timezone:null,event_recurring:null,event_recurrence_rule:null,...eo(e)}))}function y_(e,t){if(!t)return null;let n=Date.parse(t)-Date.parse(e);return Number.isFinite(n)&&n>0?n:null}function v_(e,t,n){return t.recurrence&&n!==null?new Date(new Date(e).getTime()+n).toISOString():t.end_at??null}function b_(e,t,n,r){let i=o_(t.recurrence),o=y_(t.start_at,t.end_at);return(t.recurrence?h_(t.start_at,t.recurrence,n,r):[t.start_at]).map(s=>({at:s,date:t.all_day===!0?s.slice(0,10):Pd(s,t.timezone),kind:"event",reminder_text:t.description??null,event_title:t.title??e.title,event_end:v_(s,t,o),event_location:t.location??null,event_all_day:t.all_day??null,event_timezone:t.timezone??null,event_recurring:!!t.recurrence,event_recurrence_rule:i,...eo(e)}))}function w_(e,t,n,r){let i=[];for(let o of e){let s=n.has("deadlines")?g_(o):null;s&&i.push(s),n.has("reminders")&&i.push(...__(o));for(let a of n.has("events")?o.events??[]:[])i.push(...b_(o,a,t,r))}return Hd(i)}function k_(e,t,n,r,i){let o=Ws(t.type,n),s=t.tag?.trim().toLowerCase(),a=Nn(t.priority),c=e_(t.status,r),d=t.assignee?.trim(),l=t_(t.assigneeFilter),u=t.sprint?.trim(),f=t.release?.trim();if(d&&(d.toLowerCase()==="none"||d.toLowerCase()==="null"))throw new h('--assignee no longer accepts "none" or "null". Use --assignee-filter unassigned.',g.USAGE);if(d!==void 0&&l==="unassigned")throw new h("Cannot combine --assignee with --assignee-filter unassigned",g.USAGE);return e.filter(m=>E_(m,{typeFilter:o,tagFilter:s,priorityFilter:a,statusFilter:c,assigneeFilter:d,assigneeModeFilter:l,sprintFilter:u,releaseFilter:f,runtimeFieldFilters:i}))}function E_(e,t){return I_(e,t)&&C_(e,t)&&Sn(e,t.runtimeFieldFilters)}function I_(e,t){return!(t.typeFilter&&e.type!==t.typeFilter||t.tagFilter&&!e.tags.some(n=>n.trim().toLowerCase()===t.tagFilter)||t.priorityFilter!==void 0&&e.priority!==t.priorityFilter||t.statusFilter&&e.status!==t.statusFilter)}function C_(e,t){return!(t.assigneeModeFilter==="assigned"&&!e.assignee||t.assigneeModeFilter==="unassigned"&&e.assignee||t.assigneeFilter!==void 0&&e.assignee!==t.assigneeFilter||t.sprintFilter!==void 0&&e.sprint!==t.sprintFilter||t.releaseFilter!==void 0&&e.release!==t.releaseFilter)}function S_(e,t,n){return!(t&&C(e.at,t)<0||n&&C(e.at,n)>=0)}function Yi(e,t,n){return e.trim().toLowerCase()==="today"?Zi(t):we(e,new Date(t),n)}function T_(e,t,n){let r=t.date?Yi(t.date,n,"--date"):n,i=t.past===!0,o=t.fullPeriod===!0,s=t.from?Yi(t.from,n,"--from"):void 0,a=t.to?Yi(t.to,n,"--to"):void 0;if(s&&a&&C(s,a)>=0)throw new h("Calendar --from must be before --to",g.USAGE);if(e!=="agenda"&&(t.from!==void 0||t.to!==void 0))throw new h("--from and --to are only supported for --view agenda",g.USAGE);if(e==="agenda")return R_(r,t,n,i,o,s,a);if(e==="day"){let d=Zi(r);return Ji(r,n,i,o,d,Se(d,1))}if(e==="week"){let d=jd(r);return Ji(r,n,i,o,d,Se(d,7))}let c=n_(r);return Ji(r,n,i,o,c,r_(r))}function R_(e,t,n,r,i,o,s){if(i)throw new h("--full-period is only supported for --view day|week|month. For agenda windows, use --from and --to.",g.USAGE);return{anchor:e,start:o??(t.date?e:r?void 0:n),end:s,fullPeriod:!1}}function Ji(e,t,n,r,i,o){let s=n||r;return{anchor:e,start:s?i:i_(i,t),end:o,periodStart:i,periodEnd:o,fullPeriod:s}}function x_(e){let t=new Map;for(let n of e){let r=t.get(n.date)??[];r.push(n),t.set(n.date,r)}return[...t.entries()].sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>({date:n,count:r.length,events:Hd(r)}))}function D_(e){let t=new Set,n=new Map,r=new Map,i=0,o=0,s=0,a=0;for(let c of e)t.add(c.item_id),Od(n,c.item_type),Od(r,c.item_status),c.kind==="deadline"?i+=1:c.kind==="reminder"?o+=1:(s+=1,c.event_recurring===!0&&(a+=1));return{events:e.length,items:t.size,deadlines:i,reminders:o,scheduled:s,by_kind:{deadline:i,reminder:o,event:s},by_type:Ad(n),by_status:Ad(r),recurring_events:a}}function A_(e){let t=e.start??"unbounded",n=e.end??"unbounded";return`${t} -> ${n}`}function Gd(e,t){if(t&&t!=="UTC")try{let n=new Intl.DateTimeFormat("en-GB",{timeZone:t,hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).formatToParts(new Date(e)),r=n.find(o=>o.type==="hour")?.value,i=n.find(o=>o.type==="minute")?.value;if(r&&i)return`${r}:${i}`}catch{}return`${new Date(e).toISOString().slice(11,16)}Z`}function Qi(e){let t=Object.entries(e);return t.length===0?"empty":t.map(([n,r])=>`${n}=${r}`).join(", ")}function O_(e){return e.event_end?e.event_all_day===!0?e.event_end.slice(0,10):e.date===Pd(e.event_end,e.event_timezone)?Gd(e.event_end,e.event_timezone):e.event_end:null}function L_(e){let t=`${Gd(e.at,e.event_timezone)} [${e.kind}] ${e.item_id} type=${e.item_type} p${e.item_priority} ${e.item_status} ${e.item_title}`;if(e.kind==="reminder"){let n=e.reminder_text??"";return`${t} \u2014 ${n} reminder=${JSON.stringify(n)}`}if(e.kind==="event"){let n=[],r=e.event_title??e.item_title;e.event_title!==null&&e.event_title!==e.item_title&&(n.push(r),n.push(`title=${JSON.stringify(r)}`)),e.event_recurring&&(n.push("(recurring)"),n.push("recurring=true"));let i=O_(e);return i&&n.push(`end=${i}`),e.event_all_day!==null&&n.push(`all_day=${e.event_all_day?"true":"false"}`),e.event_timezone&&n.push(`timezone=${e.event_timezone}`),e.event_location&&(n.push(`@ ${e.event_location}`),n.push(`location=${JSON.stringify(e.event_location)}`)),e.event_recurrence_rule&&n.push(`recurrence=${e.event_recurrence_rule}`),e.reminder_text&&n.push(`description=${JSON.stringify(e.reminder_text)}`),`${t} \u2014 ${n.join(" ")}`}return t}function Ld(e,t){if(t&&t.length>0){e.push("### warnings");for(let n of t)e.push(`- ${n}`);e.push("")}}function HS(e){let t=[];if(t.push(`# pm calendar (${e.view})`),t.push(""),t.push(`- now: ${e.now}`),t.push(`- window: ${A_(e.range)}`),e.range.period_start&&e.range.period_end&&(t.push(`- period: ${e.range.period_start} -> ${e.range.period_end}`),t.push(`- period-mode: ${e.range.full_period?"full-period":"active-window"}`)),t.push(`- events: ${e.summary.events} (deadlines: ${e.summary.deadlines}, reminders: ${e.summary.reminders}, scheduled: ${e.summary.scheduled})`),t.push(`- items: ${e.summary.items}`),t.push(`- matching-events: ${e.total_count}; returned: ${e.count}; remaining: ${e.omitted_count} (summary: ${e.summary_scope})`),e.next_cursor&&t.push(`- continue: repeat the same query with --after ${e.next_cursor}`),t.push(`- by-kind: ${Qi(e.summary.by_kind)}`),t.push(`- by-type: ${Qi(e.summary.by_type)}`),t.push(`- by-status: ${Qi(e.summary.by_status)}`),t.push(`- recurring-events: ${e.summary.recurring_events}`),t.push(""),e.events.length===0)return t.push(e.total_count===0?"No calendar events matched the selected filters.":"No calendar events returned on this page. Repeat the same query with --limit 1 or greater to retrieve matching events."),t.push(""),Ld(t,e.warnings),Md(t.join(`
|
|
13
|
+
`));for(let n of e.days){t.push(`## ${n.date} (${n.count})`);for(let r of n.events)t.push(`- ${L_(r)}`);t.push("")}return Ld(t,e.warnings),Md(t.join(`
|
|
14
|
+
`))}function GS(e){return qg(e)}function Md(e){let t=e.length;for(;t>0&&e[t-1]===`
|
|
15
|
+
`;)t-=1;return e.slice(0,t)}function M_(e){let t=hr("calendar",e.after),n=Qg(e.view),r=T_(n,e,t),i=oe(e.limit),o=Jg(e.include),s=Xi(e.recurrenceLookaheadDays,"Calendar recurrence lookahead days"),a=Xi(e.recurrenceLookbackDays,"Calendar recurrence lookback days"),c=Xi(e.occurrenceLimit,"Calendar occurrence limit");if(c!==void 0&&c<1)throw new h("Calendar occurrence limit must be >= 1",g.USAGE);let d=o.has("events")&&!o.has("deadlines")&&!o.has("reminders"),l=e.to!==void 0||s!==void 0||a!==void 0||c!==void 0,u=d&&!l;return{nowValue:t,view:n,rangeBounds:r,limit:i,includeSources:o,occurrenceLimit:c,recurrenceLookaheadDays:u?Fd:s,recurrenceLookbackWindowDays:u&&a===void 0?0:a,eventsOnlyCapApplied:u}}function N_(e,t){t&&e.push(`recurring_events_default_cap_applied:lookback=0d,lookahead=${Fd}d -- use --recurrence-lookback-days/--recurrence-lookahead-days or --to for wider range`)}function Nd(e,t){return{type:e.type??null,tag:e.tag??null,priority:e.priority??null,status:e.status??null,assignee:e.assignee??null,assignee_filter:e.assigneeFilter??null,sprint:e.sprint??null,release:e.release??null,runtime_filters:t,limit:e.limit??null,include:e.include??null,full_period:e.fullPeriod===!0?"true":null,recurrence_lookahead_days:e.recurrenceLookaheadDays??null,recurrence_lookback_days:e.recurrenceLookbackDays??null,occurrence_limit:e.occurrenceLimit??null}}function F_(e,t){return{start:t.start??null,end:t.end??null,period_start:t.periodStart??null,period_end:t.periodEnd??null,full_period:t.fullPeriod,past:e.past===!0,from:e.from??null,to:e.to??null}}async function Kd(e,t){let n=O(process.cwd(),t.path);await U(n);let r=M_(e),i=await N(n),o=J(i.schema),s=mn(i.schema),a=Cn(e,s,"calendar"),c=M(i,x()),d=[];N_(d,r.eventsOnlyCapApplied);let l=await pe(n,i.item_format,c.type_to_folder,d,i.schema),u=k_(l,e,c,o,a),f=c_(r.rangeBounds.start,r.rangeBounds.end,r.nowValue,r.recurrenceLookbackWindowDays,r.recurrenceLookaheadDays),m=w_(u,f,r.includeSources,r.occurrenceLimit).filter(v=>S_(v,r.rangeBounds.start,r.rangeBounds.end)),{rows:p,..._}=Ut(m,{command:"calendar",after:e.after,clock:r.nowValue,limit:r.limit,query:{pmRoot:n,view:r.view,range:r.rangeBounds,filters:{...Nd(e,a),limit:void 0},recurringWindow:f,occurrenceLimit:r.occurrenceLimit}}),y=x_(p),b=[...new Set(d)].sort((v,w)=>v.localeCompare(w));return{view:r.view,output_default:"markdown",now:r.nowValue,anchor:r.rangeBounds.anchor,range:F_(e,r.rangeBounds),filters:Nd(e,a),..._,summary_scope:"returned_rows",summary:D_(p),events:p,days:y,...b.length>0?{warnings:b}:{}}}(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]="2e0c4f91-ea56-5bec-b071-448eff719fec")}catch{}})();var vr={version:1,aliases:{}};function br(e=[]){let t=new Set(We),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 zd(e){if(e===void 0)return;let t=(typeof e=="string"?[e]:e).flatMap(n=>n.split(",")).map(n=>n.trim()).filter(n=>n.length>0);return t.length===0?void 0:new Set(t)}function to(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 no(e,t=We){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 h(`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 h(`Unknown provenance dimension "${a||o.trim()}". Declared dimensions: ${[...n].sort().join(", ")}.`,g.USAGE,{code:"unknown_provenance_dimension"});if(c.length===0)throw new h(`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 wr(e,t=vr,n={}){let r=to(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 WS(e,t,n=vr,r=We){return ro(t,n,r)(e)}function ro(e,t=vr,n=We){let r=zd(e.harness),i=zd(e.agentInstance),o=no(e,n);return s=>{let a=to(s,t).agent_harness;if(r&&(!a||!r.has(a))||i&&!i.has(s.agent_instance??""))return!1;for(let[c,d]of o){let l=s.agent_provenance?.[c];if(!l||!d.has(l.value))return!1}return!0}}function kr(e,t=vr,n=We){let r=new Set(n),i=new Map,o=0;for(let s of e){for(let a of Object.keys(s.agent_provenance??{}))r.add(a);to(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 $_ from"node:fs/promises";import Vd 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]="aa1ede64-e578-57da-9194-1cd646cee915")}catch{}})();var P_=20,j_=5,U_=15,B_="-24h";function sT(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 H_={digest:"activity_digest",compact:"compact_activity",provenance:"provenance_activity",full:"activity"};function io(e,t){if(e===void 0)return;let n=e.trim();if(n.length===0)throw new h(`${t} must not be empty`,g.USAGE);return n}function qd(e,t,n){if(e===void 0)return;let r=e.trim();if(r.length===0)throw new h("Activity time bounds must not be empty",g.USAGE);let i=n==="--from"&&/^\d+[hdwm]$/iu.test(r)?`-${r}`:r;return we(i,new Date(t),n)}function G_(e,t,n){return!(e.ts.length===0&&(t||n)||t&&C(e.ts,t)<0||n&&C(e.ts,n)>=0)}function Bt(e,t=""){return typeof e=="string"?e:t}function K_(e,t){return{...t,id:e,ts:Bt(t.ts),author:Bt(t.author,"unknown"),op:Bt(t.op,"unknown"),patch:Array.isArray(t.patch)?t.patch:[],before_hash:Bt(t.before_hash),after_hash:Bt(t.after_hash)}}function z_(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 q_(e){try{return(await $_.readdir(e)).filter(t=>t.endsWith(".jsonl")).sort((t,n)=>t.localeCompare(n))}catch(t){if(de(t))return[];throw t}}function V_(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 W_(e,t,n){if(e.unbounded!==!0)return t!==void 0?t:n==="digest"?U_:n==="compact"?P_:j_}function X_(e,t,n){let r=t==="digest",i=qd(e.to??(r||e.unbounded!==!0?n:void 0),n,"--to"),o=qd(e.from??(r?B_:void 0),e.from===void 0&&r?i:n,"--from");if(o&&i&&C(o,i)>=0)throw new h("Activity --from must be before --to",g.USAGE);let s=Vr(e.limit);if(e.unbounded===!0&&s!==void 0)throw new h("Activity --unbounded cannot be combined with --limit",g.USAGE);return{id:io(e.id,"Activity --id"),op:io(e.op,"Activity --op"),author:io(e.author,"Activity --author"),from:o,to:i,limit:W_(e,s,t),limitSource:e.unbounded===!0||s!==void 0?"explicit":"default",harness:e.harness,agentInstance:e.agentInstance,provenance:e.provenanceFilter}}async function Y_(e){let t=O(process.cwd(),e.path);return await U(t),{pmRoot:t,settings:await N(t)}}async function J_(e){let t=M(e.settings,x()),n=await pe(e.pmRoot,e.settings.item_format,t.type_to_folder,void 0,e.settings.schema);await xs({pmRoot:e.pmRoot,settings:e.settings,itemIds:n.map(i=>i.id),commandLabel:"activity"});let r=Vd.join(e.pmRoot,"history");return await on({path:r,scope:"project"}),{historyDir:r,itemsById:new Map(n.map(i=>[i.id,{title:i.title,type:i.type,status:i.status}]))}}function Q_(e,t,n){return n.op&&e.op!==n.op||n.author&&e.author!==n.author?!1:G_(t,n.from,n.to)}async function Z_(e,t){let n=[];for(let r of await q_(e)){let i=r.slice(0,-6);if(t.id&&i!==t.id)continue;let o=await Xe(Vd.join(e,r),i);for(let s of o){let a=K_(i,s);Q_(s,a,t)&&n.push(a)}}return n}function ey(e){return e.map(t=>({id:t.id,op:t.op,ts:t.ts,author:t.author,...t.message?{msg:t.message}:{}}))}function ty(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 ny(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,C(r.ts,i.firstTs)<0&&(i.firstTs=r.ts),C(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:ty(i.operations)}}).sort((r,i)=>C(i.last_ts,r.last_ts)||r.id.localeCompare(i.id))}function ry(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 iy(e,t,n,r,i){if(e==="digest"){let{rows:a,...c}=Ut(ny(t,r),n);return{rows:{activity_digest:a},compact:!1,page:c}}let{rows:o,...s}=Ut(t,n);return e==="compact"?{rows:{compact_activity:ey(o)},compact:!0,page:s}:e==="provenance"?{rows:{provenance_activity:o.map(i)},compact:!1,page:s}:{rows:{activity:o},compact:!1,page:s}}async function Wd(e,t){let n=await Y_(t),r=V_(e),i=hr("activity",e.after),o=X_(e,r,i),s=await J_(n),a=br(n.settings.agent_identity.harness_signals),c=n.settings.agent_identity.identity_vocabulary,d=ro({harness:o.harness,agentInstance:o.agentInstance,provenance:o.provenance},c,a),l=z_(await Z_(s.historyDir,o)).filter(d),u=iy(r,l,{command:"activity",after:e.after,clock:i,limit:o.limit,query:{pmRoot:n.pmRoot,projectionMode:r,filters:{...o,limit:void 0,limitSource:void 0},matching_activity_digest:r==="digest"?qi(l):void 0,vocabulary:c,provenanceDimensions:a}},s.itemsById,f=>wr(f,c,{itemId:f.id}));return{...u.rows,compact:u.compact,projection:{mode:r,row_key:H_[r]},omission_receipt:No("activity",r),...u.page,window:{anchor:i,from:o.from??null,to:o.to??null},limit:o.limit??null,...r==="digest"?{activity_summary:{window:{from:o.from,to:o.to},event_count:l.length,item_count:u.page.total_count,author_count:new Set(l.map(f=>f.author)).size,operation_counts:ry(l)}}:{},...e.provenanceSummary===!0?{provenance_summary:kr(l,c,a)}:{},applied_bound:{kind:o.limit===void 0?"unbounded":"limit",source:o.limitSource,value:o.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]="9cdfc765-7370-57bb-a4dc-be2df8aa1e6f")}catch{}})();var Xd="1970-01-01T00:00:00.000Z";function Ht(e){if(typeof e!="string")return null;let t=e.trim();if(!cn(t)&&!/^\d{4}-\d{2}-\d{2}$/u.test(t))return null;try{return we(t,new Date(Number.NaN),"context signal recency coordinate")}catch{return 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]="74b476d9-5f30-5135-9539-5fe3e864c60f")}catch{}})();var oo=["structural","recency","activity_density","graph_proximity","claim_focus","priority_pressure","risk_pressure","deadline_pressure","knowledge_density","author_affinity","usage_affinity","semantic_similarity"],oy=Symbol("no-context-author"),sy=Symbol("no-item-assignee");function Yd(e,t){if(typeof e!="string")return t;let n=e.trim().toLowerCase();return n.length>0?n:t}function ay(e){if(typeof e!="string")return;let t=/^v?(\d{4})\.(\d{1,2})\.(\d{1,2})(?:$|[-+])/u.exec(e.trim());if(!t)return;let n=Number(t[1]),r=Number(t[2]),i=Number(t[3]),o=new Date(Date.UTC(n,r-1,i));return o.getUTCFullYear()===n&&o.getUTCMonth()===r-1&&o.getUTCDate()===i?o.toISOString():void 0}function cy(e){let t=ay(e.release);return t!==void 0?{source:"release_cohort",coordinate:t}:{source:"created_at",coordinate:Ht(e.created_at)??Xd}}function dy(e){if(!["substantive_history","release_cohort","created_at"].includes(e.source)||(e.source==="substantive_history"?e.history_op!==void 0&&typeof e.history_op!="string"||e.event_class!==void 0&&e.event_class!=="substantive":e.history_op!==void 0||e.event_class!==void 0))throw new TypeError("Context signal recency provenance must match its source");let t=Ht(e.coordinate);if(t===null)throw new TypeError("Context signal recency coordinate must be a valid absolute timestamp with millisecond precision");return{...e,coordinate:t}}function ly(e,t){let n=typeof e=="number"?e:typeof e=="string"?Number.parseFloat(e):Number.NaN;return Number.isFinite(n)?1-Math.min(Math.max(n,0),t)/t:0}function uy(e,t){let n=typeof e=="string"?Date.parse(e):e instanceof Date?e.getTime():typeof e=="number"?e:Number.NaN;if(!Number.isFinite(n)||!Number.isFinite(t))return 0;let r=(n-t)/864e5;return r<=0?1:1/(1+r/30)}function fy(e){let t=typeof e=="string"?e.trim().toLowerCase():void 0;return t==="critical"||t==="high"?1:t==="medium"?.5:t==="low"?.1:0}function Er(e,t,n){return e?.[t]??n}function Ir(e,t){let n=new Map(e.map(d=>{let l=t.recencyEvidence?.[d.id];return[d.id,l===void 0?cy(d):dy(l)]})),r=[...e].sort((d,l)=>{let u=n.get(d.id).coordinate,f=n.get(l.id).coordinate;return C(f,u)||d.id.localeCompare(l.id)}),i=new Map(r.map((d,l)=>[d.id,l])),o=Math.max(e.length-1,1),s=Yd(t.author,oy),a=Q("in_progress",t.statusRegistry),c=Date.parse(t.now);return e.map(d=>{let l=Yd(d.assignee,sy)===s,u=(d.comments?.length??0)+(d.notes?.length??0)+(d.learnings?.length??0);return{id:d.id,item:d,signal_provenance:{recency:n.get(d.id)},signals:{recency:e.length===1?1:1-i.get(d.id)/o,activity_density:t.activityDensity?.[d.id],graph_proximity:Er(t.graphProximity,d.id,d.parent?.3:0),claim_focus:Er(t.claimFocus,d.id,T(d.status,t.statusRegistry)===a?1:l?.75:0),priority_pressure:ly(d.priority,4),risk_pressure:fy(d.risk),deadline_pressure:uy(d.deadline,c),knowledge_density:Er(t.knowledgeDensity,d.id,Math.min(u/5,1)),author_affinity:Er(t.authorAffinity,d.id,l?1:0),usage_affinity:t.usageAffinity?.[d.id],semantic_similarity:t.semanticSimilarity?.[d.id]}}})}var my="context_relevance",py={structural:.4,recency:.35,activity_density:.25,graph_proximity:.15,claim_focus:.6,priority_pressure:.35,risk_pressure:.2,deadline_pressure:.45,knowledge_density:.25,author_affinity:.2,usage_affinity:.3,semantic_similarity:.5},hy=new TextEncoder;function gy(e){let t=new Set;for(let n of e){if(typeof n.id!="string"||n.id.trim().length===0||t.has(n.id))throw new TypeError("Context relevance candidates require unique non-empty ids");t.add(n.id);for(let[r,i]of Object.entries(n.signals??{})){if(r==="structural"||!oo.includes(r))throw new TypeError(`Unknown context relevance signal: ${r}`);if(i!==void 0&&(!Number.isFinite(i)||i<0||i>1))throw new TypeError(`Context relevance signal ${r} must be a finite number from 0 to 1`)}}}function _y(e){let t={...py};for(let[n,r]of Object.entries(e??{}))r!==void 0&&oo.includes(n)&&(t[n]=r);for(let[n,r]of Object.entries(t))if(!Number.isFinite(r)||r<0)throw new TypeError(`Context relevance weight ${n} must be a finite non-negative number`);return t}function Qd(e,t={}){gy(e);let n=_y(t.weights),r=Math.max(e.length-1,1),i=new Set(["structural"]);for(let a of e)for(let[c,d]of Object.entries(a.signals??{}))d!==void 0&&i.add(c);let o=oo.filter(a=>i.has(a)),s=e.map((a,c)=>{let d={structural:e.length===1?1:1-c/r,...a.signals},l={},u=0,f=0;for(let m of o){let p=d[m];if(p===void 0)continue;let _=p*n[m];l[m]=_,u+=_,f+=n[m]}return{...a,baseline_rank:c+1,rank:0,score:f===0?0:u/f,contributions:l}});return s.sort((a,c)=>c.score-a.score||a.baseline_rank-c.baseline_rank),s.forEach((a,c)=>{a.rank=c+1}),{model:"default-weighted-v1",available_signals:o,ranked:s}}async function yy(e,t={}){let n=Qd(e,t);if(!t.scorer)return n;let r=await t.scorer({candidates:e,default_report:n}),i=new Map;for(let s of r){if(i.has(s.id)||!Number.isFinite(s.score))throw new TypeError("Context relevance scorer must return one finite score for every candidate");i.set(s.id,s.score)}if(i.size!==e.length||e.some(s=>!i.has(s.id)))throw new TypeError("Context relevance scorer must return one finite score for every candidate");let o=n.ranked.map(s=>{let a=i.get(s.id);return{...s,score:a,contributions:{custom:a}}});return o.sort((s,a)=>a.score-s.score||s.baseline_rank-a.baseline_rank),o.forEach((s,a)=>{s.rank=a+1}),{model:"custom",available_signals:n.available_signals,ranked:o}}async function Cr(e,t,n={}){let r=Qd(t,n),i=await Mo(my,{surface:e,candidates:t,default_report:r});if(!i.handled)return i.warnings.length>0?{...r,warnings:i.warnings}:r;if(!Array.isArray(i.result)||!i.result.every(o=>typeof o=="object"&&o!==null&&typeof o.id=="string"&&typeof o.score=="number"&&Number.isFinite(o.score)))return{...r,warnings:[...i.warnings,"extension_context_relevance_invalid_result"]};try{let o=await yy(t,{...n,scorer:()=>i.result});return i.warnings.length>0?{...o,warnings:i.warnings}:o}catch{return{...r,warnings:[...i.warnings,"extension_context_relevance_invalid_result"]}}}var vy=["ndcg","reciprocal_rank","required_recall","continuity_coverage","token_budget_adherence"];function Jd(e,t){return e.length===0?1:e.filter(n=>t.has(n)).length/e.length}function by(e){if(!Number.isFinite(e.actual_tokens)||e.actual_tokens<0||!Number.isFinite(e.token_budget)||e.token_budget<=0)throw new TypeError("Context ranking token counts require actual_tokens >= 0 and token_budget > 0");let t=e.judgments??{},n=e.ranked_ids.map(d=>Math.max(0,t[d]??0)),r=Object.values(t).map(d=>Math.max(0,d)).sort((d,l)=>l-d).slice(0,n.length||1),i=d=>d.reduce((l,u,f)=>l+(2**u-1)/Math.log2(f+2),0),o=i(r),s=n.findIndex(d=>d>0),a=new Set(e.ranked_ids),c=e.actual_tokens<=e.token_budget;return{ndcg:o===0?1:i(n)/o,reciprocal_rank:s<0?0:1/(s+1),required_recall:Jd(e.required_ids??[],a),continuity_coverage:Jd(e.continuity_ids??[],a),token_budget_adherence:c?1:e.token_budget/e.actual_tokens,within_token_budget:c}}function wy(e){return Math.ceil(hy.encode(JSON.stringify(e)).byteLength/4)}function ky(e){return Math.round(e*1e4)/1e4}function Ey(e,t){let n=t==="context"?[...e.high_level??[],...e.low_level??[],...e.blocked_fallback??[]].map(o=>o.id):[...e.recommended?[e.recommended]:[],...e.ready??[]].map(o=>o.id),r=new Set(n),i=(e.ranking?.items??[]).filter(o=>r.has(o.id)).map(o=>({id:o.id,contributions:o.contributions}));return{rankedIds:n,attribution:i}}async function Iy(e,t){if(e.id.trim().length===0||e.rationale.trim().length===0)throw new TypeError("Context evaluation scenarios require non-empty id and rationale values");let n=e.surface==="context"?await t.context({...e.options,explainRanking:!0,outputBudget:e.options?.outputBudget??"unbounded"}):await t.next({...e.options,explainRanking:!0,outputBudget:e.options?.outputBudget??"unbounded"});if(sn(n)||n.read_output?.result_omitted===!0||n.context_intent?.result_omitted===!0)throw new h(`Cannot evaluate ${e.surface} scenario "${e.id}": the read omitted its useful result.`,g.USAGE,{code:"context_evaluation_read_incomplete",nextSteps:["Increase the read output budget or start a new shared output session, then rerun the scenario."]});let{rankedIds:r,attribution:i}=Ey(n,e.surface),o={...n,ranking:void 0},s=wy(o);return{id:e.id,surface:e.surface,rationale:e.rationale,ranked_ids:r,actual_tokens:s,metrics:by({ranked_ids:r,judgments:e.judgments,required_ids:e.required_ids,continuity_ids:e.continuity_ids,actual_tokens:s,token_budget:e.token_budget}),attribution:i}}function Cy(e,t){if(e.length===0)throw new TypeError("Context evaluation requires at least one scenario report");let n=vy;for(let o of n)if(!Number.isFinite(t[o]))throw new TypeError(`Context evaluation threshold ${o} must be a finite number`);let r=Object.fromEntries(n.map(o=>[o,ky(e.reduce((s,a)=>s+a.metrics[o],0)/e.length)])),i=n.filter(o=>r[o]<t[o]).map(o=>`${o}:${r[o]}<${t[o]}`);return{scenario_count:e.length,aggregate:r,scenarios:[...e],passed:i.length===0,failures:i}}async function _T(e,t,n){let r=[];for(let i of e)r.push(await Iy(i,t));return Cy(r,n)}(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]="d07ec2dc-762a-58ab-83ee-734ca1bf76a7")}catch{}})();var Sy={balanced:{redundancyPenalty:.35,uncertaintyPenalty:.2},context:{redundancyPenalty:.45,uncertaintyPenalty:.15},next:{redundancyPenalty:.25,uncertaintyPenalty:.3}},Ty=["identity","summary","full"];function Ry(e){if(!e.id.trim()||!Number.isInteger(e.rank)||e.rank<1)throw new TypeError("Context packing candidates require a non-empty id and positive integer rank");if(!Number.isFinite(e.score)||e.score<0)throw new TypeError("Context packing candidate scores must be finite and non-negative");let t=Ty.map(n=>e.token_costs[n]);if(t.some(n=>!Number.isInteger(n)||n<1)||t[0]>t[1]||t[1]>t[2])throw new TypeError("Context projection costs must be positive monotone integers");if(e.uncertainty!==void 0&&(!Number.isFinite(e.uncertainty)||e.uncertainty<0))throw new TypeError("Context packing uncertainty must be finite and non-negative")}function xy(e){if(!Number.isInteger(e.tokenBudget)||e.tokenBudget<1)throw new TypeError("Context packing tokenBudget must be a positive integer");let t=e.profile??"balanced",n=Sy[t];if(!n)throw new TypeError("Unknown context packing profile");let r=e.redundancyPenalty??n.redundancyPenalty,i=e.uncertaintyPenalty??n.uncertaintyPenalty;if(!Number.isFinite(r)||r<0||r>1||!Number.isFinite(i)||i<0)throw new TypeError("Context packing penalties must be finite and within their supported ranges");if(e.latencyBudgetMs!==void 0&&(!Number.isFinite(e.latencyBudgetMs)||e.latencyBudgetMs<=0))throw new TypeError("Context packing latencyBudgetMs must be positive");return{redundancy:r,uncertainty:i,profile:t}}function Dy(e){let t=new Set;for(let n of e){if(Ry(n),t.has(n.id))throw new TypeError("Context packing candidates require unique ids");t.add(n.id)}return[...e].sort((n,r)=>n.rank-r.rank||n.id.localeCompare(r.id))}function Ay(e,t,n,r,i){let o=-1,s=0;for(let a=0;a<e.length;a+=1){if(a%128===0&&i()>=r)return{index:o,evaluated:s,timedOut:!0};let c=e[a];if(c.token_costs.identity>t)continue;s+=1;let d=o<0?void 0:e[o],l=n(c)/c.token_costs.identity,u=d===void 0?Number.NEGATIVE_INFINITY:n(d)/d.token_costs.identity;(l>u||l===u&&d!==void 0&&(c.rank<d.rank||c.rank===d.rank&&c.id.localeCompare(d.id)<0))&&(o=a)}return{index:o,evaluated:s,timedOut:!1}}function Oy(e){let t=new Set,n=[],r=e.tokenBudget,i=d=>{let l=d.lineage??d.cluster,u=l&&t.has(l)?1-e.redundancyPenalty:1;return Math.max(0,(d.score-e.uncertaintyPenalty*(d.uncertainty??0))*u)},o=d=>{let l=d.token_costs.identity;n.push({...d,projection:"identity",tokens:l,marginal_value:i(d)}),r-=l;let u=d.lineage??d.cluster;u&&t.add(u)};for(let d of e.ordered.filter(l=>l.required))d.token_costs.identity<=r&&o(d);let s=e.ordered.filter(d=>!d.required),a=!0,c=0;for(;s.length>0;){let d=Ay(s,r,i,e.deadline,e.readClock);if(c+=d.evaluated,d.timedOut&&(a=!1),d.index<0||d.timedOut)break;o(s.splice(d.index,1)[0])}return{included:n,remaining:r,selectionComplete:a,evaluatedCandidates:c}}function Ly(e,t){let n=t;for(let r of["summary","full"]){let i=r==="summary"?"identity":"summary",o=[...e].sort((s,a)=>{let c=s.token_costs[r]-s.token_costs[i],d=a.token_costs[r]-a.token_costs[i];return a.marginal_value/Math.max(d,1)-s.marginal_value/Math.max(c,1)||s.rank-a.rank||s.id.localeCompare(a.id)});for(let s of o){if(s.projection!==i)continue;let a=s.token_costs[r]-s.tokens;a>n||(s.projection=r,s.tokens+=a,n-=a)}}return n}function Zd(e,t){let n=xy(t),r=Dy(e),i=t.readClock??performance.now.bind(performance),o=t.latencyBudgetMs===void 0?Number.POSITIVE_INFINITY:i()+t.latencyBudgetMs,s=Oy({ordered:r,tokenBudget:t.tokenBudget,redundancyPenalty:n.redundancy,uncertaintyPenalty:n.uncertainty,deadline:o,readClock:i}),{included:a}=s,c=Ly(a,s.remaining);a.sort((l,u)=>l.rank-u.rank||l.id.localeCompare(u.id));let d=new Set(a.map(l=>l.id));return{included:a,omitted_ids:r.filter(l=>!d.has(l.id)).map(l=>l.id),token_budget:t.tokenBudget,used_tokens:t.tokenBudget-c,remaining_tokens:c,complete:s.selectionComplete&&a.length===e.length&&a.every(l=>l.projection==="full"),selection_complete:s.selectionComplete,termination_reason:s.selectionComplete?"exhausted":"latency_budget",evaluated_candidates:s.evaluatedCandidates,latency_budget_ms:t.latencyBudgetMs??null,profile:n.profile,degradation_ladder:["full","summary","identity"]}}import Gt from"node:fs/promises";import Kt from"node:path";import{createHash as el,randomUUID as My}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]="179e487f-baf9-59d1-a438-3ae0c12b00eb")}catch{}})();var so=3,ao=2,tl=["recency","activity_density","graph_proximity","priority_pressure","risk_pressure","knowledge_density"],Ny=new Set(["substantive_history","release_cohort","created_at"]),Fy={context_signal_store_invalid:{code:"context_signal_store_invalid",meaning:"The persisted context-signal snapshot was unreadable or invalid and was rebuilt from authoritative items.",recovery_command:"pm context",recovery_effect:"Re-read context and confirm the rebuilt snapshot can be loaded without the warning."},context_signal_store_stale:{code:"context_signal_store_stale",meaning:"The persisted context-signal snapshot did not match the authoritative cursor or item corpus and was rebuilt.",recovery_command:"pm context",recovery_effect:"Re-read context and confirm the rebuilt snapshot is now fresh."},context_signal_store_write_failed:{code:"context_signal_store_write_failed",meaning:"Context signals were rebuilt in memory, but the derived snapshot could not be persisted.",recovery_command:"pm context",recovery_effect:"Retry the derived snapshot write and confirm the warning clears after storage access is restored."}};function ut(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function nl(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=1}function $y(e){let t={};for(let n of tl){let r=e[n];if(r!==void 0){if(!nl(r))throw new TypeError(`Context relevance signal ${n} must be a finite number from 0 to 1`);t[n]=r}}return t}function Py(e,t){let n=e.map(i=>[i.id,t(i)]),r=Math.max(0,...n.map(([,i])=>i));return Object.fromEntries(n.map(([i,o])=>[i,r===0?0:o/r]))}function jy(e){let t=new Map(e.map(i=>[i.id,0])),n=i=>{t.set(i,(t.get(i)??0)+1)};for(let i of e){typeof i.parent=="string"&&i.parent.trim()&&(n(i.id),n(i.parent.trim()));for(let o of i.dependencies??[])typeof o.id!="string"||!o.id.trim()||(n(i.id),n(o.id.trim()))}let r=Math.max(0,...t.values());return Object.fromEntries(e.map(i=>[i.id,r===0?0:t.get(i.id)/r]))}function rl(e,t){return{...t,activityDensity:t.activityDensity??Py(e,n=>(n.comments?.length??0)+(n.notes?.length??0)+(n.learnings?.length??0)+(n.test_runs?.length??0)),graphProximity:t.graphProximity??jy(e)}}function uo(e){let t=el("sha256");for(let{id:n,signal_provenance:{recency:r}}of[...e].sort((i,o)=>i.id.localeCompare(o.id)))t.update(JSON.stringify([n,r.source,r.coordinate,r.history_op??null,r.event_class??null]));return`sha256:${t.digest("hex")}`}function Uy(e){if(!ut(e))return null;let t=e.signal_provenance;if(![typeof e.id=="string",ut(e.signals),ut(t)].every(Boolean))return null;let n=t.recency;if(!ut(n))return null;let r=Ht(n.coordinate);if(r===null)return null;let i=new Set(tl),o=Object.entries(e.signals);return!o.every(([s,a])=>i.has(s)&&nl(a))||![typeof n.source=="string"&&Ny.has(n.source),["undefined","string"].includes(typeof n.history_op),[void 0,"substantive","maintenance"].includes(n.event_class),n.source==="substantive_history"?n.event_class===void 0||n.event_class==="substantive":n.history_op===void 0&&n.event_class===void 0].every(Boolean)?null:{id:e.id,signals:Object.fromEntries(o),signal_provenance:{recency:{source:n.source,coordinate:r,history_op:n.history_op,event_class:n.event_class}}}}function By(e,t){let n=Array.from(e,Uy);if(n.some(i=>i===null))return null;let r=n;return new Set(r.map(i=>i.id)).size!==r.length||r.some(i=>i.id.trim().length===0)||t!==uo(r)?null:r.sort((i,o)=>i.id.localeCompare(o.id))}function Hy(e){if(!ut(e)||e.format_version!==so||e.signal_set_version!==ao||typeof e.source_cursor!="string"||e.source_cursor.trim().length===0||typeof e.recency_evidence_fingerprint!="string"||!/^sha256:[a-f0-9]{64}$/u.test(e.recency_evidence_fingerprint)||typeof e.generated_at!="string"||!Number.isFinite(Date.parse(e.generated_at))||e.source!=="derived_index"&&e.source!=="scan_fallback"||!Array.isArray(e.items))return null;let t=By(e.items,e.recency_evidence_fingerprint);return t===null?null:{format_version:so,signal_set_version:ao,source_cursor:e.source_cursor,recency_evidence_fingerprint:e.recency_evidence_fingerprint,generated_at:e.generated_at,source:e.source,items:t}}function il(e){if(typeof e.sourceCursor!="string"||e.sourceCursor.trim().length===0)throw new TypeError("Context signal source cursor must be non-empty");if(!Number.isFinite(Date.parse(e.now)))throw new TypeError("Context signal snapshot clock must be a valid timestamp");if(e.source!=="derived_index"&&e.source!=="scan_fallback")throw new TypeError("Context signal snapshot source must be derived_index or scan_fallback")}function ol(e,t,n=uo(e)){let r=e.map(({id:o})=>o);if(new Set(r).size!==r.length||r.some(o=>o.trim().length===0))throw new TypeError("Context signal snapshot item IDs must be unique and non-empty");let i=e.map(({id:o,signals:s,signal_provenance:a})=>({id:o,signals:$y(s),signal_provenance:a})).sort((o,s)=>o.id.localeCompare(s.id));return Object.freeze({format_version:so,signal_set_version:ao,source_cursor:t.sourceCursor,recency_evidence_fingerprint:n,generated_at:t.now,source:t.source,items:Object.freeze(i.map(o=>Object.freeze(o)))})}function RT(e,t){return il(t),ol(Ir(e,rl(e,t)),t)}var co=class{filePath;constructor(t){if(typeof t!="string"||t.trim().length===0)throw new TypeError("Context signal store path must be non-empty");this.filePath=Kt.resolve(t)}async read(){try{return JSON.parse(await Gt.readFile(this.filePath,"utf8"))}catch(t){if(ut(t)&&Be(t))return null;throw t}}async write(t){let n=Kt.dirname(this.filePath);await Gt.mkdir(n,{recursive:!0});let r=Kt.join(n,`.${Kt.basename(this.filePath)}.${My()}.tmp`);try{await Gt.writeFile(r,`${JSON.stringify(t)}
|
|
16
|
+
`,{encoding:"utf8",flag:"wx"}),await Gt.rename(r,this.filePath)}finally{try{await Gt.rm(r,{force:!0})}catch{}}}},lo=class{adapter;constructor(t){this.adapter=t}async readOrRebuild(t,n){il(n);let r=[],i=null;try{let f=await this.adapter.read();i=Hy(f),f!==null&&i===null&&r.push("context_signal_store_invalid")}catch{r.push("context_signal_store_invalid")}let o=t.map(f=>f.id).sort((f,m)=>f.localeCompare(m)),s=i?.items.map(f=>f.id)??[],a=Ir(t,rl(t,n)),c=uo(a),d=i!==null&&i.source_cursor===n.sourceCursor&&i.recency_evidence_fingerprint===c&&i.source===n.source&&s.length===o.length&&s.every((f,m)=>f===o[m]),l;if(d&&i!==null)l=i;else{l=ol(a,n,c);try{await this.adapter.write(l)}catch{r.push("context_signal_store_write_failed")}}let u=new Map(l.items.map(f=>[f.id,f]));return{snapshot:l,candidates:a.map(f=>({...f,signals:{...f.signals,...u.get(f.id)?.signals},signal_provenance:u.get(f.id).signal_provenance})),cache_status:d?"fresh":"rebuilt",warnings:r,warning_details:r.map(f=>Fy[f])}}};function Gy(e){let t=el("sha256");for(let n of[...e].sort((r,i)=>r.id.localeCompare(i.id)))t.update(JSON.stringify([n.id,n.updated_at,n.status,n.parent??null,n.priority??null,n.risk??null,(n.dependencies??[]).map(r=>r.id).sort(),n.comments?.length??0,n.notes?.length??0,n.learnings?.length??0,n.test_runs?.length??0]));return`scan:${t.digest("hex")}`}async function Sr(e,t){let n=t.sourceCursor!==void 0,r=t.source!==void 0;if(n!==r)throw new TypeError("Context signal source and source cursor must be provided together");if(t.storeKey!==void 0&&!/^[a-z0-9](?:[a-z0-9_-]*[a-z0-9])?$/u.test(t.storeKey))throw new TypeError("Context signal store key must be a filesystem-safe identifier");let i=n?null:await Qe(t.pmRoot),o=t.sourceCursor??i?.source_cursor??Gy(e),s=t.source??(i===null?"scan_fallback":"derived_index"),a=new lo(new co(Kt.join(t.pmRoot,"runtime",t.storeKey?`context-signals-${t.storeKey}.json`:"context-signals.json"))),c=t.recencyEvidence??Object.fromEntries(Object.entries(await hs(t.pmRoot,e.map(d=>d.id))).map(([d,l])=>[d,{source:"substantive_history",coordinate:l.entry.ts,history_op:l.entry.op,event_class:"substantive"}]));return a.readOrRebuild(e,{...t,recencyEvidence:c,sourceCursor:o,source: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]="61e27cd0-a444-5b66-a8e3-d81c76e4f8ae")}catch{}})();function Ky(e){for(let t of e.patch){if(t.path==="/metadata/status"||t.path==="/front_matter/status"){if(typeof t.value=="string")return t.value.trim().toLowerCase();continue}if(t.path!==""||typeof t.value!="object")continue;let n=t.value,r=n.metadata??n.front_matter;if(typeof r?.status=="string")return r.status.trim().toLowerCase()}}function zy(e,t,n){let r,i;for(let o of t){let s=Ky(o);if(s===void 0)continue;let a=n.has(s)&&(r!==void 0&&!n.has(r)||r===void 0&&o.op==="create");r=s,a&&Number.isFinite(Date.parse(o.ts))&&(i={id:e,completed_at:o.ts,history_op:o.op})}return i}function sl(e){return e.completed_at!==void 0?{resolved:!0,timestamp:e.completed_at,source:"completed_at",fallback:!1}:e.closed_at!==void 0?{resolved:!0,timestamp:e.closed_at,source:"closed_at",fallback:!0}:e.updated_at!==void 0?{resolved:!0,timestamp:e.updated_at,source:"updated_at",fallback:!0}:{resolved:!1}}function DT(e,t,n){let r=[];for(let i of e){if(i.completed_at!==void 0||!n.has(i.status.trim().toLowerCase()))continue;let o=zy(i.id,t.get(i.id)??[],n);o!==void 0&&r.push(o)}return r.sort((i,o)=>i.id.localeCompare(o.id))}import qy from"node:path";import{createHash as Vy}from"node:crypto";import Wy from"node:fs/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]="df753f1d-cfc1-555e-a411-e1417eab0b53")}catch{}})();var al=1,Xy=1e4,cl=12;function Yy(e){let t=new Date(e);return`${t.getUTCFullYear()}-Q${Math.floor(t.getUTCMonth()/3)+1}`}function Jy(e,t){let n=new Set,r=e.parent;for(;r&&!n.has(r);){n.add(r);let i=t.get(r);if(!i)return;if(i.type.toLowerCase()==="epic")return i;r=i.parent}}function Qy(e){let t=[...e.items].sort((i,o)=>o.completion.timestamp.localeCompare(i.completion.timestamp)||i.item.id.localeCompare(o.item.id)),n=new Set,r=0;for(let{item:i}of t){let o=i.resolution??i.close_reason;o?.trim()&&n.add(o.trim()),r+=(i.notes?.length??0)+(i.learnings?.length??0)}return{kind:e.kind,key:e.key,label:e.label,item_count:t.length,first_closed_at:t.at(-1).completion.timestamp,last_closed_at:t[0].completion.timestamp,representative_items:t.slice(0,5).map(({item:{id:i,title:o}})=>({id:i,title:o})),outcomes:[...n].sort().slice(0,5),knowledge_entries:r}}function Zy(e,t){if(!t.sourceCursor.trim())throw new TypeError("Workspace memory source cursor must be non-empty");if(!Number.isFinite(Date.parse(t.now)))throw new TypeError("Workspace memory clock must be a valid timestamp");let n=e.filter(o=>t.statusRegistry.terminal_done_statuses.has(T(o.status,t.statusRegistry))).map(o=>{let s=sl(o);if(!s.resolved)throw new TypeError(`Completed item ${o.id} has no reporting timestamp`);return{item:o,completion:s}}),r=new Map(e.map(o=>[o.id,o])),i=new Map;for(let o of n){let{item:s,completion:a}=o,c=Yy(a.timestamp),d=`epoch:${c}`,l=i.get(d)??{kind:"epoch",key:c,label:c,items:[]};l.items.push(o),i.set(d,l);let u=Jy(s,r);if(u){let f=`epic:${u.id}`,m=i.get(f)??{kind:"epic",key:u.id,label:u.title,items:[]};m.items.push(o),i.set(f,m)}}return{format_version:al,source_cursor:t.sourceCursor,source_item_count:e.length,generated_at:t.now,completion_time_sources:n.reduce((o,{completion:s})=>(o[s.source]+=1,o),{completed_at:0,closed_at:0,updated_at:0}),rollups:[...i.values()].map(Qy).sort((o,s)=>s.last_closed_at.localeCompare(o.last_closed_at)||o.kind.localeCompare(s.kind)||o.key.localeCompare(s.key))}}function ev(e){return typeof e=="object"&&e!==null&&"id"in e&&typeof e.id=="string"&&e.id.length>0&&"title"in e&&typeof e.title=="string"}function tv(e){if(typeof e!="object"||e===null)return!1;let t=e,n=[t.key,t.label].every(i=>typeof i=="string"&&i.length>0),r=[t.first_closed_at,t.last_closed_at].every(i=>typeof i=="string"&&Number.isFinite(Date.parse(i)));return(t.kind==="epoch"||t.kind==="epic")&&n&&Number.isSafeInteger(t.item_count)&&t.item_count>0&&r&&Array.isArray(t.representative_items)&&t.representative_items.every(ev)&&Array.isArray(t.outcomes)&&t.outcomes.every(i=>typeof i=="string")&&Number.isSafeInteger(t.knowledge_entries)&&t.knowledge_entries>=0}function nv(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;let t=e;return t.format_version!==al||typeof t.source_cursor!="string"||!t.source_cursor.trim()||!Number.isSafeInteger(t.source_item_count)||t.source_item_count<0||typeof t.generated_at!="string"||!Number.isFinite(Date.parse(t.generated_at))||!Array.isArray(t.rollups)?null:t.rollups.every(tv)?t:null}function rv(e){return`scan:${Vy("sha256").update(E(e.map(t=>[t.id,t.updated_at,t.status,t.parent]).sort(([t],[n])=>String(t).localeCompare(String(n))))).digest("hex")}`}async function iv(e,t,n){return n!==void 0?n:(await Qe(t))?.source_cursor??rv(e)}async function ov(e){try{let t=nv(JSON.parse(await Wy.readFile(e,"utf8")));return{snapshot:t,invalid:t===null}}catch(t){return{snapshot:null,invalid:!(typeof t=="object"&&t!==null&&"code"in t&&Be(t))}}}async function dl(e,t){let n=Math.max(1,Math.floor(t.minimumItems??Xy));if(e.length<n)return{snapshot:null,cache_status:"skipped",warnings:[]};let r=await iv(e,t.pmRoot,t.sourceCursor),i=qy.join(t.pmRoot,"runtime","workspace-memory.json"),o=[],s=await ov(i),a=s.snapshot;if(s.invalid&&o.push("workspace_memory_invalid"),a?.source_cursor===r&&a.source_item_count===e.length)return{snapshot:a,cache_status:"fresh",warnings:o};a&&o.push("workspace_memory_stale");let c=Zy(e,{statusRegistry:t.statusRegistry,sourceCursor:r,now:t.now});try{await X(i,`${JSON.stringify(c)}
|
|
17
|
+
`)}catch{o.push("workspace_memory_write_failed")}return{snapshot:c,cache_status:"rebuilt",warnings:o}}function sv(e,t,n=cl){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 ll(e,t,n=cl){if(e.snapshot===null)return;let r=sv(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 av(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 UT(e,t,n=5){let r=av(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]="2355a6b7-2a17-586c-8dd3-182980a708d0")}catch{}})();var cv=["markdown","toon","json","ndjson"],xr=new Set(["Epic","Feature"]),mo=10,hl=1e4,gl=["hierarchy","activity","progress","recently_created","unparented","workload"],dv=[...gl,"blockers","files","staleness","tests"],lv=/^(\d{4})-(\d{2})-(\d{2})/,uv=/^(\d{4})(\d{2})(\d{2})(?:[T ]?\d{2}|$)/,fv=/^(\d{4})(\d{2})(\d{2})$/,mv=/^(\d{4})(\d{2})(\d{2})(?:[T\s]?)(\d{2})(\d{2})(\d{2})?(Z|[+-]\d{2}:?\d{2})?$/i;function pv(e){if(!e)return;let t=e.trim().toLowerCase();if(!cv.includes(t))throw new h("Context format must be one of markdown|toon|json|ndjson",g.USAGE);return t}var ul=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 hv(e){if(e===void 0)return;let t=[];for(let n of e.split(",")){let r=n.trim().toLowerCase();if(r.length!==0){if(!ul.has(r))throw new h(`Context --fields value not projectable: ${r} (valid: ${[...ul].join(", ")})`,g.USAGE);t.includes(r)||t.push(r)}}if(t.length===0)throw new h("Context --fields requires at least one field name",g.USAGE);return t}function zt(e,t){return e.map(n=>{let r={},i=n;for(let o of t)r[o]=i[o]??null;return r})}function cR(e,t){let n=pv(e.format);if(t.json&&n&&n!=="json"&&n!=="ndjson")throw new h("Cannot combine --json with --format markdown|toon",g.USAGE);return t.json?n==="ndjson"?"ndjson":"json":n??"toon"}function gv(e,t){return oe(e,"--limit")??(t==="full"?Number.MAX_SAFE_INTEGER:mo)}function po(e,t){if(e===void 0)return t;let n=typeof e=="number"?e:Number(e);if(!Number.isInteger(n)||n<1)throw new h("--token-budget must be a positive integer",g.USAGE);return n}function _v(e,t){return t>=hl&&e===Number.MAX_SAFE_INTEGER?mo:e}function yv(e,t){if(!e)return t.default_depth;let n=e.trim().toLowerCase();if(!Nr.includes(n))throw new h(`Context --depth must be one of ${Nr.join("|")}`,g.USAGE);return n}function vv(e,t,n){if(e&&e.length>0){let r=[];for(let i of e){let o=i.trim().toLowerCase();if(!tn.includes(o))throw new h(`Context --section must be one of ${tn.join("|")}`,g.USAGE);r.includes(o)||r.push(o)}return r}return t==="brief"?[]:t==="full"?[...tn]:(t==="deep"?dv:gl).filter(r=>n.sections[r])}function bv(e,t){return e?oe(e,"--activity-limit")??t.activity_limit:t.activity_limit}function wv(e,t){if(!e)return t.stale_threshold_days;let n=e.trim().toLowerCase(),r=/^(\d+)d?$/.exec(n);if(!r)throw new h("--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 h("--stale-threshold must be positive",g.USAGE);return i}function fl(e,t){let n=T(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 qt(e,t){let n=Q("closed",t);return T(e,t)===n}function ho(e,t){return T(e,t)===t.in_progress_status}function _l(e,t){let n=T(e,t);return n!==t.in_progress_status&&t.active_statuses.has(n)}function kv(e,t){return t.blocked_statuses.has(T(e,t))}var Ev=["compact","brief","fields","includeBody","include_body","parent"];function Iv(e){let t={...e};for(let n of Ev)delete t[n];return t}function go(e,t){let n=t.trim().toLowerCase(),r=e.find(s=>s.id.trim().toLowerCase()===n);if(!r)return{ids:new Set,found:!1};let i=ft(e),o=Vt(r.id,i);return{ids:new Set([r.id,...o.map(s=>s.id)].map(s=>s.trim().toLowerCase())),found:!0}}function Cv(e){if(e===void 0)return;let t=e.trim();if(t.length===0)throw new h("Context --parent requires an item id",g.USAGE);return t}function Sv(e,t){let n=e??null,r=t??null;return n===null&&r===null?0:n===null?1:r===null?-1:n-r}function Tv(e,t){let n=e??null,r=t??null;return n===null&&r===null?0:n===null?1:r===null?-1:C(n,r)}function Rv(e,t){return new Date(Date.UTC(e,t+1,0)).getUTCDate()}function xv(e){let t=lv.exec(e)??uv.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<=Rv(n,r-1)}function Dv(e){let t=fv.exec(e);if(t)return`${t[1]}-${t[2]}-${t[3]}`;let n=mv.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 yl(e){if(typeof e!="string")return Number.NaN;let t=e.trim();if(t.length===0||!xv(t))return Number.NaN;let n=Date.parse(Dv(t));return Number.isFinite(n)?n:Number.NaN}function fo(e){let t=yl(e);return Number.isFinite(t)?new Date(t).toISOString():""}function Av(e){let t=yl(e);return Number.isFinite(t)?new Date(t).toISOString().slice(0,10):"unknown"}function _o(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function Ue(e,t,n){let r=fl(e.status,n)-fl(t.status,n);if(r!==0)return r;let i=e.priority-t.priority;if(i!==0)return i;let o=Sv(e.order,t.order);if(o!==0)return o;let s=Tv(e.deadline,t.deadline);if(s!==0)return s;let a=C(fo(t.updated_at),fo(e.updated_at)),c=e.id.localeCompare(t.id);return a!==0?a:c}function Tr(e){return Math.max(1,Math.ceil(Buffer.byteLength(JSON.stringify(e),"utf8")/4))}function yo(e,t,n=new Set,r="context"){return Zd(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:Tr({id:i.id,title:i.item.title}),summary:Tr({id:i.id,title:i.item.title,type:i.item.type,status:i.item.status,priority:i.item.priority,parent:i.item.parent}),full:Tr(i.item)}})),{tokenBudget:t,profile:r,latencyBudgetMs:25})}function vo(e){return{...e,included:e.included.map(t=>({id:t.id,projection:t.projection,tokens:t.tokens}))}}function bo(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 Rr(e,t){return t>0?Math.round(e*100/t):0}function ft(e){let t=new Map;for(let n of e){let r=_o(n.parent);if(!r)continue;let i=t.get(r)??[];i.push(n),t.set(r,i)}return t}function Wt(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:_o(e.parent)};if(t&&n){let i=Vt(e.id,n),o=i.length;if(o>0){let s=i.filter(a=>qt(a.status,t)).length;r.children_total=o,r.children_closed=s,r.completion_pct=Rr(s,o)}}return r}function Ov(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 Dr(...e){return[...new Set(e.flatMap(t=>t??[]))].sort((t,n)=>t.localeCompare(n))}function Lv(e,t){return e.filter(n=>!t.terminal_statuses.has(T(n.item_status,t)))}function Mv(e,t,n,r){let i=new Map;for(let c of e)i.set(c.id,c);let o=ft(e),s=new Set(t.filter(c=>xr.has(c.type)).map(c=>c.id)),a=[];for(let c of s){let d=i.get(c);if(!d)continue;let l=Vt(c,o),u=o.get(c)??[],f=0,m=0,p=0,_=0;for(let b of l)qt(b.status,n)?f++:ho(b.status,n)?p++:kv(b.status,n)?_++:_l(b.status,n)&&m++;let y=u.sort((b,v)=>Ue(b,v,n)).slice(0,r).map(b=>{let v=Vt(b.id,o),w=v.filter(k=>qt(k.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:m,children_in_progress:p,children_blocked:_,children:y})}return a.sort((c,d)=>{let l=i.get(c.id),u=i.get(d.id);return Ue(l,u,n)}).slice(0,r)}function Vt(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 Nv(e,t){return(await Wd({compact:!0,limit:String(e)},t)).compact_activity??[]}function Fv(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=>xr.has(c.type)),a=[];for(let c of s){let d=Vt(c.id,o),l=d.length;if(l===0)continue;let u=0,f=0,m=0,p=0;for(let _ of d)qt(_.status,r)?u++:n.has(_.id.trim().toLowerCase())?p++:ho(_.status,r)?m++:_l(_.status,r)&&f++;a.push({id:c.id,title:c.title,type:c.type,total:l,closed:u,open:f,in_progress:m,blocked:p,completion_pct:Rr(u,l)})}return a.sort((c,d)=>c.completion_pct-d.completion_pct).slice(0,i)}function $v(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=Mn(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 Pv(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 jv(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=>ho(s.status,t)).length,items:o.map(s=>s.id).sort()})).sort((i,o)=>o.active-i.active).slice(0,n)}function Uv(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 Bv(e,t,n,r){return e.map(i=>({item:i,sortKey:fo(i.created_at)})).sort((i,o)=>{let s=C(o.sortKey,i.sortKey);return s!==0?s:i.item.id.localeCompare(o.item.id)}).slice(0,r).map(({item:i})=>({...Wt(i,t,n),created_at:i.created_at}))}function Hv(e,t,n,r){return e.filter(i=>!_o(i.parent)&&!xr.has(i.type)).sort((i,o)=>Ue(i,o,t)).slice(0,r).map(i=>Wt(i,t,n))}function Gv(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{scope:"matching_active_items",total_items:e.length,items_with_tests:t,items_with_recent_runs:n,recent_runs:{passed:r,failed:i,skipped:o},items_failing:s.sort()}}function ml(e){return`${new Date(e).toISOString().slice(11,16)}Z`}function vl(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 Kv(e,t){let n=e;return t.map(r=>{let i=n[r];return Array.isArray(i)?`${r}:${i.join(",")}`:`${r}:${i??"-"}`}).join(" ")}function zv(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`${ml(e.at)} [${e.kind}] ${e.item_id} (see focus item)${n}`}let t=`${ml(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 pl(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 qv(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 Vv(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(`- ${zv(n)}`);e.push("")}function Wv(e,t){if(!(!t.hierarchy||t.hierarchy.length===0)){e.push("## Hierarchy");for(let n of t.hierarchy){let r=Rr(n.children_closed,n.children_total);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=Rr(i.children_closed,i.children_total);e.push(` - ${i.id} ${i.type} ${i.status} "${i.title}" [${i.children_closed}/${i.children_total} done ${o}%]`)}}e.push("")}}function Xv(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 Yv(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)}`:`- ${Av(i.created_at)} ${vl(i)}`);e.push("")}}function Jv(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 Qv(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 Zv(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 eb(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 tb(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 nb(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 rb(e,t,n){let r=[],i=0;for(let o of e.items_failing){if(r.length>=t)break;let s=Tr(o);if(i+s>n)break;r.push(o),i+=s}return r}function ib(e,t){if(!t.tests)return;e.push("## Test health"),e.push(`- ${t.tests.scope}: ${t.tests.total_items}`),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}`);let n=rb(t.tests,t.applied_limit??mo,t.filters.token_budget);n.length>0&&e.push(`- items_failing: [${n.join(",")}]`);let r=t.tests.items_failing.length-n.length;r>0&&e.push(`- items_failing_omitted: ${r}`),e.push("")}function ob(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 dR(e){let t=[],n=e.focus_fields,r=o=>n?Kv(o,n):vl(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(""),pl(t,"High-level focus",e.high_level,"No high-level active items.",r),pl(t,"Low-level focus",e.low_level,"No low-level active items.",r),qv(t,e,r),Vv(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 Wv(t,e),Xv(t,e),Yv(t,e,n,r),Jv(t,e,r),Qv(t,e),Zv(t,e),eb(t,e),tb(t,e),nb(t,e),ib(t,e),ob(t,e),t.join(`
|
|
18
|
+
`)}async function sb(e,t){let n=O(process.cwd(),t.path),r=await N(n),i=r.context??Co.context,o=J(r.schema),s=yv(e.depth,i),a=gv(e.limit??e.maxItems,s);return{settings:r,contextSettings:i,statusRegistry:o,depth:s,limit:a,sectionsIncluded:vv(e.section,s,i),activityLimit:bv(e.activityLimit,i),staleThresholdDays:wv(e.staleThreshold,i),parentScope:Cv(e.parent),focusFields:hv(e.fields),baseListOptions:Iv(e)}}function ab(e){return e.some(t=>["hierarchy","progress","blockers","staleness","recently_created","unparented"].includes(t))}function cb(e,t){return{...e,...t,noTruncate:!0,limit:void 0,offset:void 0,after:void 0}}async function db(e,t){let n=await xt(void 0,cb(t.baseListOptions,{excludeTerminal:!1}),e),r=n.items,i=r.filter(a=>!P(a.status,t.statusRegistry)),o=r,s=lb(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 lb(e,t){if(e===void 0)return;let n=go(t,e);if(!n.found)throw new h(`Context --parent item not found: ${e}`,g.NOT_FOUND);return n.ids}function ub(e,t,n,r){let i=new Set(bt(e,t,n,r).containers.map(o=>o.item.id));return new Set(e.filter(o=>xr.has(o.type)||i.has(o.id)||xe(o.type,r)!=="agent").map(o=>o.id))}async function fb(e,t,n,r,i,o,s,a,c,d,l,u,f,m,p,_){let y=[...e].sort((I,mt)=>Ue(I,mt,i)),b=await fn({pmRoot:f,author:c,enabled:process.env.PM_CONTEXT_USAGE_DISABLED!=="1"}),v=await Sr(y,{pmRoot:f,storeKey:"context",statusRegistry:i,now:a,author:c,usageAffinity:b.affinity,claimFocus:p}),w=await Cr("context",v.candidates),k=w.ranked.map(I=>I.item),S=i.active_statuses,L=k.filter(I=>S.has(T(I.status,i))),B=u?ze(L,d,l,I=>I.id):0,$=u?L.slice(B,B+s):L,ce=u&&$.length>0&&B+$.length<L.length,H=ce&&$.length>0?ue(l,$[$.length-1].id,B+$.length-1):void 0,j=k.filter(I=>r.has(I.id.trim().toLowerCase())),q=new Set([...$.map(I=>I.id),...j.filter(I=>!S.has(T(I.status,i))).slice(0,s).map(I=>I.id)]),te=yo({...w,ranked:w.ranked.filter(I=>q.has(I.id))},m,new Set(Object.entries(p??{}).filter(([,I])=>I>=1).map(([I])=>I))),Y=te.included.map(I=>I.item),ne=Y.filter(I=>S.has(T(I.status,i))),Te=Y.filter(I=>r.has(I.id.trim().toLowerCase())),V=ft(t),Or=ab(o)?V:void 0,W=new Map(n.map(I=>[I.id.trim().toLowerCase(),I])),G=I=>{let mt=Wt(I,i,Or);return r.has(I.id.trim().toLowerCase())&&(mt.blocked=!0,mt.blocker_ids=Mn(I,W,i).filter(Lr=>!Lr.resolved).map(Lr=>Lr.id)),mt},Eo=ub(ne,n,i,_),Nl=ne.filter(I=>Eo.has(I.id)).slice(0,u?$.length:s).map(G),Fl=ne.filter(I=>!Eo.has(I.id)).slice(0,u?$.length:s).map(G),Io=L.length===0;return{activeItems:ne,blockedItems:Te,highLevel:Nl,lowLevel:Fl,blockedFallback:Io?Te.slice(0,s).map(G):[],blockedFallbackUsed:Io,ranking:w,packing:te,featureStore:v,pageExtras:{...u?{applied_limit:s}:{},...ce?{has_more:!0,truncated:!0}:{},...H?{next_cursor:H}:{}}}}function mb(e,t){return le("context",{pmRoot:t,options:an(e,Ns)})}function pb(e,t){return e.limit!==void 0||e.maxItems!==void 0||e.after!==void 0||t>=hl}async function hb(e,t,n,r){let i={...t.baseListOptions,after:void 0,view:"agenda",include:"all",limit:t.parentScope===void 0?String(t.limit):void 0},o=await Kd(i,e),s=n===void 0?o.events:o.events.filter(d=>n.has(d.item_id.trim().toLowerCase())),a=Lv(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:Ov(a)}}function bl(e,t,n){let r=String(t);return e.filter(i=>T(i.status,n)===r).length}async function gb(e){let{runtime:t,allItems:n,fullCorpus:r,blockedIds:i,focusGroups:o,now:s,global:a}=e,c=ft(n),d=n.filter(u=>!P(u.status,t.statusRegistry)),l=u=>t.sectionsIncluded.includes(u);return{hierarchy:l("hierarchy")?Mv(n,o.activeItems,t.statusRegistry,t.limit):void 0,activity:l("activity")?await Nv(t.activityLimit,a):void 0,progress:l("progress")?Fv(n,o.activeItems,i,t.statusRegistry,t.limit):void 0,blockersSection:l("blockers")?$v(o.blockedItems,r,t.statusRegistry,t.limit):void 0,recentlyCreated:l("recently_created")?Bv(d,t.statusRegistry,c,t.limit):void 0,unparented:l("unparented")?Hv(d,t.statusRegistry,c,t.limit):void 0,filesSection:l("files")?Pv(o.activeItems,t.limit):void 0,workload:l("workload")?jv(o.activeItems,t.statusRegistry,t.limit):void 0,staleness:l("staleness")?Uv(d,t.staleThresholdDays,s,t.limit):void 0,tests:l("tests")?Gv(n.filter(u=>t.statusRegistry.active_statuses.has(T(u.status,t.statusRegistry)))):void 0}}function _b(e,t,n){let r=Q("canceled",t),i=e.filter(s=>t.active_statuses.has(T(s.status,t))),o=bl(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=>qt(s.status,t)).length,canceled:e.filter(s=>T(s.status,t)===r).length}}function yb(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 vb(e,t){t&&(e.focus_fields=t,e.high_level=zt(e.high_level,t),e.low_level=zt(e.low_level,t),e.blocked_fallback=zt(e.blocked_fallback,t),e.recently_created&&(e.recently_created=zt(e.recently_created,t)),e.unparented&&(e.unparented=zt(e.unparented,t)))}function bb(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 wb(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 kb(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 ln(e,"context"))s.has(c)||(o.push({id:c,rank:o.length+1,included:!1}),s.add(c));let a=await un({pmRoot:n,author:r,surface:"context",profile:t.packing.profile,rows:o,enabled:process.env.PM_CONTEXT_USAGE_DISABLED!=="1"});dn(e,a)}catch{e.warnings=Dr(e.warnings,["context_usage_feedback_write_failed"])}}async function Eb(e,t,n){if(e)return{};let r=(await Ao({pmRoot:t,settings:n,cwd:process.cwd(),noExtensions:!1})).discovered.map(o=>({name:o.name??o.directory,status:o.status==="ok"?"ok":"degraded"})).sort((o,s)=>o.name.localeCompare(s.name)),i=r.filter(o=>o.status==="degraded").length;return r.length===0?{}:{extension_health:{total:r.length,ok:r.length-i,degraded:i,packages:r.slice(0,20),...r.length>20?{truncated:!0}:{}}}}async function Ib(e,t){let n=ss(),r=await ts(e),i=n.instance||ns(t);return Dd(r.semantic_attribution?.[i])}async function lR(e,t){let n=O(process.cwd(),t.path),r=await sb(e,t),i=await db(t,r),o=_v(r.limit,i.fullCorpus.length),s={...r,limit:o,tokenBudget:po(e.tokenBudget,Math.max(256,o*160))},a=Ee(void 0,s.settings.author_default),c=await Ib(n,a),d=Eb(e.noExtensionHealth===!0,n,s.settings),l=vt(i.fullCorpus,s.statusRegistry),u=await fb(i.listedItemMetadata,i.allItems,i.fullCorpus,l,s.statusRegistry,s.sectionsIncluded,s.limit,D(),a,e.after,mb(e,n),pb(e,i.fullCorpus.length),n,s.tokenBudget,c,M(s.settings,x())),f=await hb(t,s,i.subtreeIds,new Set([...u.highLevel,...u.lowLevel,...u.blockedFallback].map(k=>k.id))),m=await dl(i.fullCorpus,{pmRoot:n,statusRegistry:s.statusRegistry,now:f.agenda.now}),p=Dr(i.listed.warnings,f.agenda.warnings,u.ranking.warnings,[...u.featureStore.warnings],m.warnings),_=bl(u.activeItems,s.statusRegistry.in_progress_status,s.statusRegistry),y=u.activeItems.length-_,b=await gb({runtime:s,allItems:i.allItems,fullCorpus:i.fullCorpus,blockedIds:l,focusGroups:u,now:f.agenda.now,global:t}),v=_b(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:_,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=ll(m,Math.min(800,Math.floor(s.tokenBudget*.2))),Object.assign(w,await d),yb(w,b,u.featureStore.warning_details),bb(w,e.noTags===!0),e.explainRanking===!0&&(w.ranking=bo(u.ranking,u.featureStore,new Set([...u.highLevel,...u.lowLevel,...u.blockedFallback].map(k=>k.id))),w.packing=vo(u.packing)),Fo(w,[...u.highLevel,...u.lowLevel,...u.blockedFallback].map(k=>({id:k.id,status:T(k.status,s.statusRegistry)===s.statusRegistry.in_progress_status?"in_progress":"open",blocked:k.blocked}))),vb(w,s.focusFields),$o(w),p.length>0&&(w.warnings=p),wb(w,u.activeItems,u.blockedItems),await kb(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]="7328ddd0-a555-56d2-9f7d-3496dad501f5")}catch{}})();function wl(e,t,n){let r={recommended:e.recommended,ready:e.ready},i=()=>Math.max($r(r,"json"),$r(r,"toon")),o=r.ready.length+ +(r.recommended!==null),s=i(),a=s,c=r.ready;if(a>t&&(r.ready=[],a=i()),s>t&&a<=t){let u=0,f=c.length;for(;u<f;){let m=Math.ceil((u+f)/2);r.ready=c.slice(0,m),i()<=t?u=m:f=m-1}r.ready=c.slice(0,u),a=i()}let d=a>t&&r.recommended!==null;d&&(r.recommended=null,a=i()),e.recommended=r.recommended,e.ready=r.ready,e.summary.recommended=r.recommended!==null;let l=o-r.ready.length-+(r.recommended!==null);n&&l===0&&a<=t||(e.truncation={...e.truncation,...l>0?{ready_total:e.summary.ready}:{},ready_budget:{scope:"recommended_and_ready",budget_tokens:t,estimated_tokens:a,within_budget:a<=t,omitted_count:l,recommendation_omitted:d,restore_budget_tokens:s}},d&&(e.suggestions=[`Ready work exists but the selection budget omitted the recommendation. Retry pm next --token-budget ${s}; use --output-budget to bound the entire response.`]))}(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]="f610c3be-8212-56de-86d4-2b5b9752b87c")}catch{}})();var Cb=["markdown","toon","json"],Sb=5,Tb=1440*60*1e3;function Rb(e){if(!e)return;let t=e.trim().toLowerCase();if(!Cb.includes(t))throw new h("Next format must be one of markdown|toon|json",g.USAGE);return t}function IR(e,t){let n=Rb(e.format);if(t.json&&n&&n!=="json")throw new h("Cannot combine --json with --format markdown|toon",g.USAGE);return t.json?"json":n??"toon"}function kl(e,t,n){let r=oe(e,t);return r===void 0||r<=0?n:r}function Xt(e,t,n,r){return{...Wt(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 xb(e,t,n,r){let i=e.item,o=[],s=Q("in_progress",t);return o.push(T(i.status,t)===s?"resume work":"ready"),r&&o.push("completed container \u2014 governance closeout"),o.push(`p${i.priority}${i.priority===0?" (highest)":""}`),typeof i.deadline=="string"&&i.deadline.trim().length>0&&o.push(Db(i.deadline,n)),o.push(Ne(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 El(e,t,n){let r=Ee(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 CR={partitionCallerOwnedReady:El,resolveNextCallerAuthor:(e,t)=>Il(e,t)};function SR(e,t,n){let r=e.filter(i=>xe(i.item.type,n)==="human");return{agent:t?e:e.filter(i=>xe(i.item.type,n)!=="human"),decisions:t?[]:r}}function Db(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))/Tb);return o<0?`deadline ${r} (overdue ${-o}d)`:o===0?`deadline ${r} (due today)`:`deadline ${r} (in ${o}d)`}function Ab(e,t){let n=Q("in_progress",t);return e.filter(r=>T(r.status,t)===n).length}function wo(e,t){return(t.get(e.id.trim().toLowerCase())??[]).length>0}function Ob(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 Ar(e,t,n){return[...e].sort((r,i)=>{let o=wo(r.item,t),s=wo(i.item,t);return o!==s?Number(o)-Number(s):Ue(r.item,i.item,n)})}function Lb(e){return e.projectedReady.length===0?null:{...e.readyRows[0],reasons:xb(e.projectedReady[0],e.statusRegistry,e.now,e.completedContainer)}}function Mb(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 Nb(e,t,n,r){let i={};return e>r&&(i.decision_needed_total=e),t>r&&(i.held_by_others_total=t),n>r+1&&(i.ready_total=n),Object.keys(i).length>0?i:void 0}async function Fb(e){try{let t=new Set([...e.result.recommended?[e.result.recommended.id]:[],...e.result.ready.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 ln(e.result,"next"))r.has(o)||(n.push({id:o,rank:n.length+1,included:!1}),r.add(o));let i=await un({pmRoot:e.pmRoot,author:e.author,surface:"next",profile:"next",rows:n,enabled:process.env.PM_CONTEXT_USAGE_DISABLED!=="1"});dn(e.result,i)}catch{e.result.warnings=Dr(e.result.warnings,["context_usage_feedback_write_failed"])}}async function $b(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.result.suggestions=Mb(e.recommended,e.blockedRows,e.gateCount),e.tokenBudget!==void 0&&wl(e.result,e.tokenBudget,e.hasIntentBudget),e.explainRanking&&(e.result.ranking=bo(e.readyRanking,e.featureStore,new Set([...e.result.recommended?[e.result.recommended.id]:[],...e.result.ready.map(n=>n.id)])),e.result.packing=vo(yo(e.readyRanking,e.packingBudget,new Set,"next"))),await Fb({result:e.result,pmRoot:e.pmRoot,author:e.author,ranking:e.readyRanking}),e.result}function Pb(e,t,n){if(!n)return e;let r=go(t,n);if(!r.found)throw new h(`Next --parent item not found: ${n}`,g.NOT_FOUND);return e.filter(i=>r.ids.has(i.id.trim().toLowerCase()))}async function jb(e,t,n,r,i,o,s){let a=e.filter(m=>!wo(m.item,t)),c=s||a.length===0?e:a,d=await fn({pmRoot:o,author:i,enabled:process.env.PM_CONTEXT_USAGE_DISABLED!=="1"}),l=await Sr(c.map(m=>m.item),{pmRoot:o,storeKey:"next",statusRegistry:n,now:r,author:i,usageAffinity:d.affinity}),u=await Cr("next",l.candidates),f=new Map(c.map(m=>[m.item.id,m]));return{projectedReady:u.ranked.map(m=>f.get(m.id)).filter(m=>m!==void 0),ranking:u,completedContainer:a.length===0&&!s,featureStore:l}}function Il(e,t){let n=e.assignee?.trim();return Ee(e.callerAuthor??(n&&n.length>0?n:void 0),t)}async function TR(e,t){let n=O(process.cwd(),t.path),r=await N(n),i=Il(e,r.author_default),o=J(r.schema),s=M(r,x()),a=D(),c=kl(e.limit,"--limit",Sb),d=po(e.tokenBudget,Math.max(192,c*128)),l=kl(e.blockedLimit,"--blocked-limit",c),u=e.readyOnly===!0,f=typeof e.parent=="string"?e.parent.trim():"",m=await xt(void 0,Ob(e,{excludeTerminal:!0}),t),p=await xt(void 0,{excludeTerminal:!1,noTruncate:!0},t),_=Pb(m.items,p.items,f),y=p.items,b=bt(_,y,o,s),v=ft(y),w=Zr(b,o,e,s),k=El(w.ready,r.author_default,i),S=Ar(k.available,v,o),L=[...b.blocked].sort((W,G)=>Ue(W.item,G.item,o)),{projectedReady:B,ranking:$,completedContainer:ce,featureStore:H}=await jb(S,v,o,a,i,n,e.includeContainers===!0),j=B.map((W,G)=>Xt(W,o,v,G+1)),q=L.map((W,G)=>Xt(W,o,v,G+1)),te=Ar(w.decisions,v,o).map((W,G)=>Xt(W,o,v,G+1)),Y=Ar(w.gates,v,o).map((W,G)=>Xt(W,o,v,G+1)),ne=Ar(b.containers,v,o).map((W,G)=>Xt(W,o,v,G+1)),Te=Lb({projectedReady:B,readyRows:j,statusRegistry:o,now:a,completedContainer:ce}),V=Nb(te.length,k.held.length,j.length,c)??{};Y.length>c&&(V.gate_needed_total=Y.length),ne.length>c&&(V.containers_total=ne.length);let Or={output_default:"toon",now:a,recommended:Te,ready:j.slice(1,c+1),decision_needed:te.slice(0,c),gate_needed:Y.slice(0,c),containers:ne.slice(0,c),blocked:u?[]:q.slice(0,l),held_by_others:k.held.slice(0,c),summary:{recommended:Te!==null,ready:j.length,blocked:q.length,in_progress:Ab(j,o),candidates:b.active_count,containers:b.container_count,decision_needed:te.length,gate_needed:Y.length,held_by_others:k.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(V).length>0?V:void 0};return $b({result:Or,recommended:Te,blockedRows:q,gateCount:Y.length,candidatesWarnings:m.warnings,corpusWarnings:p.warnings,readyRanking:$,explainRanking:e.explainRanking===!0,pmRoot:n,author:i,packingBudget:d,featureStore:H,tokenBudget:e.tokenBudget===void 0?void 0:d,hasIntentBudget:typeof e.for=="string"})}function RR(e){let t=["# pm next","",...Ub(e)];for(let[n,r]of[["Gate verification needed",e.gate_needed],["Containers",e.containers]])r&&r.length>0&&t.push(...Yt(n,r.map(i=>`- ${Jt(i)}`),""));if(t.push(...Yt("Recommended",Bb(e.recommended),e.truncation?.ready_budget?.recommendation_omitted?"Recommendation omitted by the selection budget; ready work still exists.":"No ready work.")),t.push(...Yt("Decision needed",(e.decision_needed??[]).map(n=>`- ${Jt(n)}`),"No human-gated decisions.")),t.push(...Yt("Ready",e.ready.map(n=>`- ${Jt(n)}`),"No ready items.")),e.filters.ready_only||t.push(...Yt("Blocked",e.blocked.map(n=>`- ${Hb(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
|
+
`).trimEnd()}function Ub(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 Bb(e){return e?[`- ${Jt(e)}`,` why: ${e.reasons.join("; ")}`]:[]}function Yt(e,t,n){return[`## ${e}`,...t.length===0?[n]:t,""]}function Hb(e){let t=e.blockers.map(n=>`${n.id}(${n.status??"?"})`).join(", ");return`${Jt(e)} blocked_by:${t}`}function Jt(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 Gb}from"node:crypto";import{setTimeout as Kb}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]="c583f859-9204-565b-b143-59aba53c3e9c")}catch{}})();var Tl=1,Rl=/^[A-Za-z0-9_-]+$/,zb=100,Cl=1e3,qb=250,BR=Object.freeze({batch_to_row_ratio:.6,fixture_events:200});function ae(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 xl(e){return Gb("sha256").update(E({type:ae(e.type),author:ae(e.author),item:ae(e.item),harness:ae(e.harness),agent_instance:ae(e.agentInstance),provenance:ae(e.provenanceFilter)})).digest("hex").slice(0,24)}function ko(e,t){let n={version:Tl,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 Dl(e,t){if(typeof e!="object"||e===null)return!1;let n=e;return[n.version===Tl,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 Al(e,t){let n=e.trim();if(n.length===0||n.length>4096||!Rl.test(n))throw new h("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 h("Invalid mutation event cursor.",g.USAGE,{code:"invalid_event_cursor"})}if(!Dl(r,t))throw new h("Mutation event cursor does not match this query.",g.USAGE,{code:"event_cursor_query_mismatch"});return r}function Ol(e){let t=e??zb;if(!Number.isSafeInteger(t)||t<0||t>Cl)throw new h(`Mutation event limit must be an integer from 0 to ${Cl}.`,g.USAGE,{code:"invalid_event_limit"});return t}function Ll(e){return e instanceof Error&&e.name==="AbortError"}function Ml(e,t){let n=e?.trim();if(!n)return{};if(Rl.test(n))return{cursor:Al(n,t)};let r=Date.parse(n);if(!Number.isFinite(r))throw new h("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 Vb(e,t){if(t.verify)return Sl(e,t);let n=await Kr(e,t),r=n.result;if(r===null&&n.repair_needed)try{await ms(e,{lockWaitMs:0})&&(r=(await Kr(e,t)).result)}catch{}return r===null?Sl(e,t):{...r,source:"derived_index"}}async function Sl(e,t){try{return{...await ps(e,t),source:"authoritative_history"}}catch(n){throw n instanceof h?n:new h("Mutation events are unavailable because authoritative history could not be read.",g.GENERIC_FAILURE,{code:"event_index_unavailable",why:To(n)})}}function Wb(e){let t=e??"batch";if(t!=="batch"&&t!=="row")throw new h("Mutation event cursor mode must be batch or row.",g.USAGE,{code:"invalid_event_cursor_mode"});return t}async function Xb(e={}){let t=O(e.cwd??process.cwd(),e.pmRoot);await U(t);let n=Ol(e.limit),r=Wb(e.cursorMode);if(e.full===!0&&e.provenance===!0)throw new h("Mutation event projections are mutually exclusive. Use --provenance or --full.",g.USAGE);let i=await N(t),o=i.agent_identity.identity_vocabulary,s=br(i.agent_identity.harness_signals),a=no({provenance:e.provenanceFilter},s),c=ae(e.harness),d=xl(e),{cursor:l,sinceTimestamp:u}=Ml(e.since,d),f={verify:e.verify===!0,...l?{after_ts:l.ts,after_stream_id:l.stream_id,after_stream_offset:l.stream_offset}:u?{since_ts:u}:{},ops:ae(e.type),authors:ae(e.author),harnesses:c,harness_alias_authors:c?Object.entries(o.aliases).filter(([,_])=>c.includes(_)).map(([_])=>_):void 0,agent_instances:ae(e.agentInstance),provenance:[...a].map(([_,y])=>({dimension:_,values:[...y]})),stream_ids:ae(e.item),limit:n},m=await Vb(t,f),p=m.events.map(_=>({...r==="row"?{cursor:ko(_,d)}:{},item_id:_.stream_id,version:_.stream_offset+1,ts:_.entry.ts,author:_.entry.author,type:_.entry.op,..._.entry.message===void 0?{}:{message:_.entry.message},patch_count:_.entry.patch.length,...e.full===!0?{entry:structuredClone(_.recorded_entry??_.entry)}:{},...e.provenance===!0?{provenance:wr(_.entry,o,{itemId:_.stream_id,version:_.stream_offset+1})}:{}}));return{integrity:e.verify===!0?"verified":"unverified",...m.verified_streams===void 0?{}:{verified_streams:m.verified_streams},events:p,count:p.length,has_more:m.has_more,cursor_mode:r,...m.events.length===0?{}:{next_cursor:ko(m.events[m.events.length-1],d)},source:m.source,...e.provenanceSummary===!0?{provenance_summary:kr(m.events.map(_=>_.entry),o,s)}:{}}}async function*Yb(e={}){let t=e.intervalMs??qb;if(!Number.isSafeInteger(t)||t<10)throw new h("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 Xb({...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 Kb(t,void 0,{signal:e.signal})}catch(i){if(Ll(i))return;throw i}}}async function*HR(e={}){for await(let t of Yb({...e,cursorMode:"row"}))for(let n of t.events)yield n}var GR={decodeMutationEventCursor:Al,encodeMutationEventCursor:ko,eventQueryFingerprint:xl,isAbortError:Ll,isMutationEventCursorEnvelope:Dl,parseMutationEventLimit:Ol,resolveMutationEventStart:Ml};(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]="f091d0c3-f2a7-5d76-8656-4aebe82e9798")}catch{}})();function zR(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{Zb as a,$l as b,ew as c,js as d,jl as e,Xr as f,Rn as g,Aw as h,Ow as i,An as j,Dn as k,Ks as l,Fw as m,xe as n,Jl as o,Ne as p,Ln as q,qs as r,Mn as s,vt as t,Zr as u,bt as v,oe as w,Nn as x,Ws as y,ei as z,wt as A,Xs as B,Ys as C,aa as D,ai as E,da as F,S0 as G,T0 as H,fa as I,ma as J,x0 as K,eu as L,i0 as M,tu as N,o0 as O,s0 as P,a0 as Q,c0 as R,ou as S,z as T,ea as U,$n as V,g0 as W,ni as X,_0 as Y,It as Z,hu as _,_u as $,ii as aa,yu as ba,St as ca,Pu as da,ka as ea,_a as fa,ya as ga,Gu as ha,Ku as ia,zu as ja,xt as ka,jn as la,di as ma,Un as na,fk as oa,At as pa,Fa as qa,_e as ra,Uk as sa,Va as ta,Wa as ua,Xa as va,Ya as wa,Ja as xa,qn as ya,Za as za,it as Aa,ec as Ba,ic as Ca,Xn as Da,oc as Ea,sc as Fa,wp as Ga,yc as Ha,Qn as Ia,bi as Ja,Zn as Ka,vc as La,wc as Ma,wi as Na,Mt as Oa,Ec as Pa,Ei as Qa,Ii as Ra,Ci as Sa,Ic as Ta,Si as Ua,Sc as Va,Tc as Wa,xc as Xa,Vp as Ya,VE as Za,WC as _a,wd as $a,zR as ab,$c as bb,Pc as cb,ZE as db,wh as eb,dt as fb,R as gb,Ae as hb,gI as ib,_I as jb,zc as kb,Sh as lb,yI as mb,vI as nb,TI as ob,Zc as pb,sr as qb,fr as rb,JI as sb,mr as tb,pg as ub,cd as vb,QI as wb,ZI as xb,eC as yb,tC as zb,gg as Ab,ld as Bb,Lg as Cb,Hg as Db,vS as Eb,bS as Fb,xd as Gb,SS as Hb,TS as Ib,RS as Jb,xS as Kb,Dd as Lb,BS as Mb,HS as Nb,GS as Ob,Kd as Pb,vr as Qb,br as Rb,no as Sb,wr as Tb,WS as Ub,ro as Vb,kr as Wb,sT as Xb,Wd as Yb,Xd as Zb,Ht as _b,oo as $b,Ir as ac,my as bc,Qd as cc,yy as dc,Cr as ec,vy as fc,by as gc,Iy as hc,Cy as ic,_T as jc,Sy as kc,Zd as lc,so as mc,ao as nc,Fy as oc,Hy as pc,RT as qc,co as rc,lo as sc,Sr as tc,sl as uc,DT as vc,Xy as wc,Zy as xc,dl as yc,sv as zc,ll as Ac,av as Bc,UT as Cc,cv as Dc,hv as Ec,zt as Fc,cR as Gc,po as Hc,yv as Ic,vv as Jc,go as Kc,Ue as Lc,yo as Mc,vo as Nc,bo as Oc,ft as Pc,Wt as Qc,Dr as Rc,dR as Sc,bb as Tc,lR as Uc,Cb as Vc,IR as Wc,CR as Xc,SR as Yc,TR as Zc,RR as _c,BR as $c,Xb as ad,Yb as bd,HR as cd,GR as dd};
|
|
20
|
+
//# sourceMappingURL=chunk-PQLRKFPZ.js.map
|