@unbrained/pm-cli 2026.8.10 → 2026.8.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +2 -2
- package/CHANGELOG.md +102 -80
- package/dist/cli/commander-usage.js +79 -7
- package/dist/cli/error-guidance.d.ts +10 -0
- package/dist/cli/error-guidance.js +76 -25
- package/dist/cli/main.js +6 -2
- package/dist/cli/register-assurance.d.ts +8 -0
- package/dist/cli/register-assurance.js +52 -0
- package/dist/cli/register-files-lookup.js +14 -3
- package/dist/cli/register-mutation.js +30 -9
- package/dist/cli/register-operations.js +16 -11
- package/dist/cli-bundle/bundle-manifest.json +159 -159
- package/dist/cli-bundle/chunks/{chunk-TRWXF476.js → chunk-2OOU2AFH.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-2RA2YTHJ.js +33 -0
- package/dist/cli-bundle/chunks/chunk-A2SJGHSI.js +3 -0
- package/dist/cli-bundle/chunks/chunk-DSKYD4LG.js +13 -0
- package/dist/cli-bundle/chunks/chunk-HC3GM6YY.js +194 -0
- package/dist/cli-bundle/chunks/chunk-IUNRVDAI.js +2 -0
- package/dist/cli-bundle/chunks/chunk-W7CPZGSB.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-EBO7OUUE.js → chunk-WMEZHCFI.js} +59 -53
- package/dist/cli-bundle/chunks/{chunk-ETML5C6H.js → chunk-ZU34C3LH.js} +47 -47
- package/dist/cli-bundle/chunks/chunk-ZXOC6HG5.js +5 -0
- package/dist/cli-bundle/chunks/{register-list-query-OJ6ZXKV4.js → register-list-query-HAUXVUPY.js} +8 -8
- package/dist/cli-bundle/chunks/register-mutation-7Y5U7ABT.js +20 -0
- package/dist/cli-bundle/chunks/register-operations-EQX3DLAZ.js +2 -0
- package/dist/cli-bundle/chunks/{register-setup-S3KT2LTH.js → register-setup-NOCOOWQY.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-34SX654S.js → chunk-23FTGO3W.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-2COZ67XT.js → chunk-2DL3MRTD.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-3AYKXMYX.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-4AHEC74N.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-7UN6BHHO.js → chunk-4H5IA6AV.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-4SV3ZKG3.js +16 -0
- package/dist/cli-bundle/focused-chunks/chunk-55BIB6DV.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-6JW6Z2P5.js +8 -0
- package/dist/cli-bundle/focused-chunks/{chunk-IW43E4XL.js → chunk-BKPIY34S.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-D4PIWE6D.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-KR5RVXLQ.js → chunk-DPO7TEFX.js} +29 -29
- package/dist/cli-bundle/focused-chunks/{chunk-JMVA4HKR.js → chunk-E3KCL7AY.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-ERAAFLPS.js +153 -0
- package/dist/cli-bundle/focused-chunks/{chunk-RIIN5V4N.js → chunk-F6E4JZKG.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-FPSYO5ZG.js +18 -0
- package/dist/cli-bundle/focused-chunks/{chunk-M6RPIXKC.js → chunk-J5EKAIVD.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-2EXI2DKR.js → chunk-KDH5OX3D.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-OJ3LVVIS.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-DZGAHZZV.js → chunk-TL5M2PAY.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-75774JWP.js → chunk-UDAZWT25.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-VABB4L5Y.js +17 -0
- package/dist/cli-bundle/main.js +13 -13
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +1 -1
- package/dist/cli-bundle/sdk-core.js +41 -39
- 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 +1 -1
- 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 +2 -2
- package/dist/core/session/session-state.d.ts +47 -0
- package/dist/core/session/session-state.js +207 -6
- package/dist/core/shared/author.d.ts +7 -1
- package/dist/core/shared/author.js +66 -46
- package/dist/core/shared/errors.d.ts +8 -0
- package/dist/core/shared/errors.js +2 -2
- package/dist/sdk/agent/refusal-reachability.d.ts +40 -0
- package/dist/sdk/agent/refusal-reachability.js +72 -0
- package/dist/sdk/agent/subcommand-recovery.d.ts +40 -0
- package/dist/sdk/agent/subcommand-recovery.js +84 -0
- package/dist/sdk/cli-bootstrap.d.ts +8 -0
- package/dist/sdk/cli-bootstrap.js +7 -7
- package/dist/sdk/cli-contracts/completeness.js +13 -3
- package/dist/sdk/cli-contracts/enum-contracts.d.ts +1 -1
- package/dist/sdk/cli-contracts/enum-contracts.js +3 -2
- package/dist/sdk/cli-contracts/flag-contracts.d.ts +2 -0
- package/dist/sdk/cli-contracts/flag-contracts.js +17 -2
- package/dist/sdk/cli-contracts/runtime-contracts.js +4 -3
- package/dist/sdk/cli-contracts/schemas/assurance-definition.d.ts +513 -0
- package/dist/sdk/cli-contracts/schemas/assurance-definition.js +251 -0
- package/dist/sdk/cli-contracts/tool-parameter-tables.js +79 -2
- package/dist/sdk/cli-contracts/tool-schema.d.ts +2 -2
- package/dist/sdk/cli-contracts/tool-schema.js +34 -4
- package/dist/sdk/cli-contracts.d.ts +1 -1
- package/dist/sdk/cli-contracts.js +3 -3
- package/dist/sdk/completion.js +9 -3
- package/dist/sdk/config.js +9 -3
- package/dist/sdk/context/semantic-session-attribution.d.ts +32 -0
- package/dist/sdk/context/semantic-session-attribution.js +83 -0
- package/dist/sdk/core-governance.d.ts +3 -1
- package/dist/sdk/core-governance.js +5 -3
- package/dist/sdk/core.d.ts +1 -1
- package/dist/sdk/core.js +2 -2
- package/dist/sdk/error-code-catalog.d.ts +13 -0
- package/dist/sdk/error-code-catalog.js +35 -2
- package/dist/sdk/extension.js +18 -17
- package/dist/sdk/files.d.ts +11 -0
- package/dist/sdk/files.js +82 -24
- package/dist/sdk/generated-error-code-catalog.js +32 -13
- package/dist/sdk/governance/assurance-action-contracts.d.ts +7 -0
- package/dist/sdk/governance/assurance-action-contracts.js +5 -0
- package/dist/sdk/governance/assurance-action.d.ts +70 -0
- package/dist/sdk/governance/assurance-action.js +198 -0
- package/dist/sdk/governance/assurance-limits.d.ts +7 -0
- package/dist/sdk/governance/assurance-limits.js +11 -0
- package/dist/sdk/governance/assurance-runtime.d.ts +20 -0
- package/dist/sdk/governance/assurance-runtime.js +131 -0
- package/dist/sdk/governance/assurance.d.ts +432 -0
- package/dist/sdk/governance/assurance.js +689 -0
- package/dist/sdk/graph/run.js +8 -3
- package/dist/sdk/index.d.ts +6 -1
- package/dist/sdk/index.js +8 -3
- package/dist/sdk/lifecycle/claim.js +18 -3
- package/dist/sdk/lifecycle/focus.js +13 -3
- package/dist/sdk/lifecycle/plan.js +8 -3
- package/dist/sdk/provenance.d.ts +38 -0
- package/dist/sdk/provenance.js +64 -2
- package/dist/sdk/query/context.js +19 -8
- package/dist/sdk/runtime-extended-actions.js +22 -5
- package/dist/sdk/runtime-primitives.d.ts +2 -0
- package/dist/sdk/runtime-primitives.js +4 -2
- package/dist/sdk/runtime.d.ts +4 -0
- package/dist/sdk/runtime.js +31 -27
- package/dist/sdk/telemetry.js +7 -4
- package/dist/sdk/traceability/runtime-files-lookup.d.ts +8 -0
- package/dist/sdk/traceability/runtime-files-lookup.js +33 -0
- package/dist/sdk/traceability/source-traceability.d.ts +102 -0
- package/dist/sdk/traceability/source-traceability.js +293 -0
- package/dist/types.d.ts +8 -2
- package/dist/types.js +2 -2
- package/docs/ASSURANCE.md +132 -0
- package/docs/README.md +1 -0
- package/docs/RELEASING.md +9 -5
- package/docs/SDK.md +12 -1
- package/docs/SDK_AGENT_SESSION_CONTEXT.md +40 -4
- package/docs/SDK_EVIDENCE_TRACEABILITY.md +39 -1
- package/docs/SDK_RUNTIME_BOUNDARIES.md +36 -1
- package/docs/TESTING.md +12 -9
- package/docs/generated/AGENT_COMMAND_SURFACE.md +1 -0
- package/marketplace.json +2 -2
- package/package.json +3 -3
- 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/extensions/templates/index.ts +9 -3
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/sdk/public-surface.json +840 -28
- package/dist/cli-bundle/chunks/chunk-2QYH4QMI.js +0 -30
- package/dist/cli-bundle/chunks/chunk-JUDU4RO4.js +0 -194
- package/dist/cli-bundle/chunks/chunk-JZSNADRR.js +0 -5
- package/dist/cli-bundle/chunks/chunk-MENWVGJW.js +0 -2
- package/dist/cli-bundle/chunks/chunk-S4EITGLA.js +0 -3
- package/dist/cli-bundle/chunks/chunk-TIGKWVLA.js +0 -13
- package/dist/cli-bundle/chunks/chunk-TSLDTJLQ.js +0 -2
- package/dist/cli-bundle/chunks/register-mutation-DKI7QC7O.js +0 -20
- package/dist/cli-bundle/chunks/register-operations-P5OGMT6I.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-36FTZ2NT.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-3CQECMKR.js +0 -16
- package/dist/cli-bundle/focused-chunks/chunk-CHIBMEZR.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-FF4MNAYB.js +0 -153
- package/dist/cli-bundle/focused-chunks/chunk-GHTN2ILR.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-I4YM2I7S.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-IMDTEN7K.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-KSNJG4KI.js +0 -16
- package/dist/cli-bundle/focused-chunks/chunk-MXYSIQ56.js +0 -18
- package/dist/cli-bundle/focused-chunks/chunk-RKWSCYYN.js +0 -2
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import{A as br,B as p,Ba as Jt,Bc as Sr,Bf as Le,Ca as Ze,Cc as Tr,D as g,Dd as ve,Df as ue,Ef as on,F as j,Ff as zr,Gb as ke,Hc as Dr,Ia as $,Id as Or,If as Hr,Ja as et,Jf as ot,Kg as at,Lf as qr,Lg as ct,P as G,Pd as pe,Pf as Wr,Qa as S,Qd as xe,Qf as Ce,Qg as Jr,R as x,Rd as Pr,S as kr,Sd as en,T as oe,Ta as O,Tg as T,Ua as Er,Wa as Qt,Wc as z,Yc as tt,Zb as Cr,Zf as Vr,Zg as Qr,_ as vr,_d as nt,_e as nn,_f as st,aa as xr,ae as jr,bh as Zr,c as A,ch as ei,dh as Se,e as ie,ee as tn,eh as ti,f as K,fe as rt,g as _r,ge as de,gh as le,hd as N,he as se,hh as fe,hj as ii,id as C,ih as ni,jd as L,je as Ur,jh as Q,ke as Ee,kh as ri,mb as q,od as Rr,pd as Ar,pf as it,qc as F,rb as Ir,sf as rn,tg as Xr,ug as Yr,vd as Fr,w as wr,wa as be,wd as Nr,wf as Ie,xd as Lr,xf as Br,yd as Mr,yf as Gr,yg as sn,zc as Zt,zd as $r,zf as Kr,zk as oi}from"./chunk-HC3GM6YY.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]="47c087c2-124a-58b7-a5c9-09403235f4a2")}catch{}})();function aa(e,t){let n=-1;return e.forEach((r,i)=>{let o=Date.parse(r.ts);if(!Number.isFinite(o))throw new g(`History for this item contains invalid timestamp at entry ${i+1}.`,p.GENERIC_FAILURE);o<=t&&(n=i)}),n}function ca(e){let t=e[0]?.ts??null,n=e.at(-1)?.ts??null,r={code:"history_target_out_of_range",required:"Choose a target within the available item history.",why:"Point-in-time reads and restores can only reconstruct recorded versions.",examples:[],nextSteps:["Run pm history <id> to inspect available versions and timestamps."],valid_range:{first_version:null,last_version:null,first_timestamp:t,last_timestamp:n}};return n!==null&&(r.examples=["1",String(e.length),n],r.valid_range.first_version=1,r.valid_range.last_version=e.length),{guidance:r,lastTimestamp:n}}function si(e,t){let n={};if(t instanceof Error&&t.message.trim().length>0&&(n.reason=t.message.trim()),typeof t!="object"||t===null)return n;let r=t;if(typeof r.index=="number"&&Number.isInteger(r.index)&&r.index>=0&&(n.patchIndex=r.index),typeof r.operation=="object"&&r.operation!==null){let i=r.operation;Object.assign(n,Object.fromEntries(["op","path","from"].flatMap(o=>{let s=i[o];return typeof s=="string"?[[o,s]]:[]})))}if(n.patchIndex!==void 0){let i=e[n.patchIndex];i&&(n.op??=i.op,n.path??=i.path,n.from??=i.from)}return n}function ai(e,t,n={}){let r=e.trim(),i=n.errorSubject??"history",o=i==="restore"?"Restore":"History",{guidance:s,lastTimestamp:a}=ca(t);if(!r)throw new g(`Missing ${i} target. Use a timestamp or version number.`,p.USAGE,s);if(/^\d+$/.test(r)){let u=Number(r);if(!Number.isSafeInteger(u)||u<1||u>t.length)throw new g(`${o} version must be between 1 and ${t.length} for this item.`,p.USAGE,s);return{kind:"version",raw:r,historyIndex:u-1}}let c=Date.parse(r);if(!Number.isFinite(c))throw new g(`Invalid ${i} target "${e}". Use a positive version number or ISO timestamp.`,p.USAGE,s);let d=aa(t,c);if(d<0||n.allowFutureTimestamp!==!0&&c>Date.parse(a))throw new g(i==="restore"?`No history entries exist at or before timestamp ${r}.`:`No history entry exists at timestamp ${r}.`,p.USAGE,s);return{kind:"timestamp",raw:r,historyIndex:d}}function Me(e,t,n,r){let i=Hr(e,t);if(i.ok)return i.document;let o=si(t,i.error),s=[`history_op=${r}`,o.patchIndex===void 0?null:`patch_index=${o.patchIndex}`,o.op?`op=${o.op}`:null,o.path?`path=${o.path}`:null,o.from?`from=${o.from}`:null].filter(a=>a!==null);throw new g(`Failed to apply history patch at entry ${n} (${s.join(", ")}). ${o.reason??String(i.error)}`,p.GENERIC_FAILURE)}function ci(e,t){let n=structuredClone(Le);for(let r=0;r<=t;r+=1){let i=e[r];if(!i)throw new g(`History target entry ${r+1} does not exist.`,p.USAGE);if(ue(n)!==i.before_hash)throw new g(`History hash mismatch before replay at entry ${r+1}.`,p.GENERIC_FAILURE);if(n=Me(n,i.patch,r+1,i.op),ue(n)!==i.after_hash)throw new g(`History hash mismatch after replay at entry ${r+1}.`,p.GENERIC_FAILURE)}return n}function di(e,t){if(Object.keys(e.metadata).length>0)return e;throw new g(`History target ${t.raw} resolves to a deleted state; choose a version or timestamp where the item exists.`,p.USAGE)}import an from"node:fs/promises";import da 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]="a2ec9f1a-aae2-59d5-8c9a-7acd8bf5a7a2")}catch{}})();function ua(e){if(!e.itemDocument)return[];let t=e.itemDocument.metadata?.assignee?.trim();if(!t||t===e.author||e.force)return[];let n=Jr(e.settings);if(n.ownership_enforcement==="strict")throw new g(`Item ${e.subjectId} is assigned to ${t}. Use --force to override.`,p.CONFLICT);return n.ownership_enforcement==="warn"?[`ownership_warning:assignee_conflict:${e.subjectId}:${t}`]:[]}async function la(e){let t=await ie(e.subject.historyPath);if(t!==e.historyRawBeforeLock)throw new g(`History for ${e.subject.id} changed while waiting for lock; retry ${e.operation}.`,p.CONFLICT);let n=await le(e.pmRoot,e.subject.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder),r=n?await fe(n,{schema:e.settings.schema}):null;if((r?.raw??null)!==(e.currentItemRawBeforeLock??null))throw new g(`Item ${e.subject.id} changed while waiting for lock; retry ${e.operation}.`,p.CONFLICT);return{historyRawUnderLock:t,locatedUnderLock:n,loadedItemUnderLock:r}}async function xg(e){let t=e.writeHistoryRaw??K;try{await t(e.historyPath,e.nextHistoryRaw),await Ie(e.historyPath)}catch(n){try{e.historyRawUnderLock===null?await da.rm(e.historyPath,{force:!0}):await t(e.historyPath,e.historyRawUnderLock),await Ie(e.historyPath)}catch(r){throw new AggregateError([n,r],`History rewrite failed and rollback also failed: ${String(n)}`)}throw n}}async function ui(e){let t=[...ua({itemDocument:e.itemDocument,subjectId:e.subject.id,author:e.author,force:e.force,settings:e.settings})],n=await Ce(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 la({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]="cd2a27ec-0f12-591d-ab34-529ddda05063")}catch{}})();function cn(e){return Array.isArray(e)?e:typeof e=="string"?[e]:[]}function li(e){let t=[];for(let n of e)t.includes(n)||t.push(n);return t.includes("g")||t.push("g"),t.join("")}function fi(e){let t=e.trim();if(t.length===0)throw new g("history-redact --regex requires a non-empty pattern.",p.USAGE);let n=t,r="g";if(t.startsWith("/")&&t.length>1){let i=t.lastIndexOf("/");i>0&&(n=t.slice(1,i),r=li(t.slice(i+1)))}if(n.length===0)throw new g("history-redact --regex cannot use an empty pattern.",p.USAGE);try{new RegExp(n,r)}catch{throw new g("Invalid --regex value; provide a valid JavaScript regular expression.",p.USAGE)}return{kind:"regex",source:n,flags:r}}function mi(e,t){let n=[...new Set(cn(e).map(o=>o.trim()))].filter(o=>o.length>0).map(o=>({kind:"literal",value:o})),r=[...new Set(cn(t).map(o=>o.trim()))].filter(o=>o.length>0).map(fi),i=[...n,...r];if(i.length===0)throw new g("history-redact requires at least one matcher via --literal or --regex.",p.USAGE,{code:"missing_required_argument",required:"Provide --literal <value> and/or --regex <pattern>.",examples:['pm history-redact pm-a1b2 --literal "[redacted_path_prefix]/private"','pm history-redact pm-a1b2 --regex "/192\\\\.168\\\\.[0-9.]+/g" --replacement "[scrubbed_ip]"']});return i}function pi(e,t,n){if(t.length===0)return{value:e,replacements:0};let r=0,i=0;for(;r<=e.length;){let o=e.indexOf(t,r);if(o===-1)break;i+=1,r=o+Math.max(1,t.length)}return i===0?{value:e,replacements:0}:{value:e.split(t).join(n),replacements:i}}function gi(e,t,n){let r=new RegExp(t.source,t.flags),i=[...e.matchAll(r)];return i.length===0?{value:e,replacements:0}:{value:e.replace(r,n),replacements:i.length}}function dn(e,t,n){let r=e,i=0;for(let o of t){let s=o.kind==="literal"?pi(r,o.value,n):gi(r,o,n);r=s.value,i+=s.replacements}return{value:r,replacements:i}}function dt(e,t,n){if(typeof e=="string")return dn(e,t,n);if(Array.isArray(e)){let r=0;return{value:e.map(o=>{let s=dt(o,t,n);return r+=s.replacements,s.value}),replacements:r}}if(typeof e=="object"&&e!==null){let r=0,i={};for(let[o,s]of Object.entries(e)){let a=dt(s,t,n);r+=a.replacements,i[o]=a.value}return{value:i,replacements:r}}return{value:e,replacements:0}}function fa(e){let t=structuredClone(Le),n=0,r=0;for(let i=0;i<e.length;i+=1){let o=e[i];ue(t)!==o.before_hash&&(n+=1),t=Me(t,o.patch,i+1,o.op),ue(t)!==o.after_hash&&(r+=1)}return{hashMismatchesBefore:n,hashMismatchesAfter:r,finalDocument:t}}function ma(e,t,n){let r=0,i=!1,o=e.message;if(typeof e.message=="string"){let a=dn(e.message,t,n);o=a.value,r+=a.replacements,a.replacements>0&&(i=!0)}let s=e.patch.map(a=>{if(!Object.prototype.hasOwnProperty.call(a,"value"))return a;let c=dt(a.value,t,n);return r+=c.replacements,c.replacements>0?(i=!0,{...a,value:c.value}):a});return{entry:{...e,message:o,patch:s},replacements:r,changed:i}}function pa(e,t,n){let r=structuredClone(Le),i=0,o=0,s=[];for(let a=0;a<e.length;a+=1){let c=ma(e[a],t,n);o+=c.replacements,c.changed&&(i+=1);let d=ue(r);r=Me(r,c.entry.patch,a+1,c.entry.op);let u=ue(r);s.push({...c.entry,before_hash:d,after_hash:u})}return{entries:s,finalDocument:r,entriesChanged:i,replacements:o}}function hi(e){return Object.keys(e.metadata).length>0}async function ga(e,t){let n=e.located?.itemPath??null;if(!e.located)return{raw:null,path:n,document:null};let r=await fe(e.located,{schema:t.schema});return{raw:r.raw,path:n,document:r.document}}function ha(e){if(!hi(e.finalDocument))return{raw:null,path:null,document:null};let t=Ar(on(e.finalDocument),{schema:e.settings.schema});if(t.metadata.id!==e.subject.id)throw new g("history-redact would change the item id; narrow your patterns.",p.USAGE);return{document:t,path:Er(e.pmRoot,t.metadata.type,e.subject.id,"toon",e.typeToFolder),raw:Rr(t,{format:"toon",schema:e.settings.schema})}}function ya(e,t){return typeof e.message=="string"&&e.message.trim().length>0?e.message:`history-redact replaced ${t.replacements} match(es) across ${t.entriesChanged} entr${t.entriesChanged===1?"y":"ies"}.`}function _a(e){let t=[...e.rewritten.entries];if(e.dryRun||!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let n=e.nextItemDocument??on(e.rewritten.finalDocument);return t.push(Kr({nowIso:G(),author:e.author,op:"history_redact",before:n,after:n,message:e.message})),{rewrittenEntries:t,auditEntryAdded:!0}}async function wa(e){let t=[];return ui({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItem.raw,operation:"history-redact",author:e.author,force:e.force,itemDocument:e.currentItem.document,applyRewrite:async({historyRawUnderLock:n})=>{let r=await ei(e.pmRoot,e.author),i=new Set;e.currentItem.path&&i.add(e.currentItem.path),e.nextItem.path&&i.add(e.nextItem.path);let o=new Map;e.currentItem.path&&e.currentItem.raw!==null&&o.set(e.currentItem.path,e.currentItem.raw);let s=()=>{};try{try{e.nextItem.path&&e.nextItem.raw!==null&&e.nextItem.raw!==e.currentItem.raw&&await K(e.nextItem.path,e.nextItem.raw),e.currentItem.path&&(!e.nextItem.path||e.nextItem.path!==e.currentItem.path)&&await an.rm(e.currentItem.path,{force:!0}),await K(e.subject.historyPath,qr(e.rewrittenEntries))}catch(c){try{await ba(e.subject.historyPath,n,i,o)}finally{await Ie(e.subject.historyPath)}throw c}await Ie(e.subject.historyPath);let a=e.nextItem.path??e.currentItem.path;a&&(t=await ti({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:e.typeRegistry.type_to_folder,schema:e.settings.schema,itemPath:a,...e.currentItem.path?{previousItemPath:e.currentItem.path}:{},document:e.nextItem.document}))}finally{await r().catch(a=>{s=()=>{throw a}})}s()},applyPostRewrite:async()=>[...t,...await ka(e.subject.historyPath,[e.nextItem.path,e.currentItem.path])]})}async function ba(e,t,n,r){t===null?await an.rm(e,{force:!0}):await K(e,t);for(let i of n){let o=r.get(i);o===void 0?await an.rm(i,{force:!0}):await K(i,o)}}async function ka(e,t){let n=[],r=new Set(t.filter(i=>i!==null));for(let i of r)n.push(...await Zt({path:i,scope:"project",op:"history_redact"}));return n.push(...await Zt({path:e,scope:"project",op:"history_redact:history"})),n}async function un(e,t,n,r){let i=await le(e,t,n.id_prefix,n.item_format,r);if(i)return{id:i.id,historyPath:Qt(e,i.id),located:i};let o=st(t,n.id_prefix),s=Vr(t),a=o===s?[o]:[o,s];for(let c of a){let d=Qt(e,c);if(await A(d))return{id:c,historyPath:d,located:null}}throw new g(`Item ${t} not found`,p.NOT_FOUND)}async function Hg(e,t,n){let r=S(process.cwd(),n.path);if(!await A(O(r)))throw new g(`Tracker is not initialized at ${r}. Run pm init first.`,p.NOT_FOUND);let i=await T(r),o=$(i,F()),s=t.replacement??"",a=s.length===0,c=a?"[redacted]":s,d=mi(t.literal,t.regex),u=await un(r,e,i,o.type_to_folder);if(!await A(u.historyPath))throw new g(`No history stream exists for ${u.id}.`,p.NOT_FOUND);let l=await ie(u.historyPath),f=await xe(u.historyPath,u.id);if(f.length===0)throw new g(`No history entries exist for ${u.id}; nothing to redact.`,p.USAGE);let m=fa(f),h=pa(f,d,c),y=m.hashMismatchesBefore+m.hashMismatchesAfter,w=!!t.dryRun,_=h.replacements>0,b=[];y>0&&b.push(`history_redact_preexisting_hash_mismatches:${y}`),_||b.push("history_redact_no_matches");let k=await ga(u,i),E=ha({pmRoot:r,subject:u,settings:i,typeToFolder:o.type_to_folder,finalDocument:h.finalDocument}),I=(k.path??null)!==(E.path??null)||(k.raw??null)!==(E.raw??null),P=pe(t.author,i.author_default),D=ya(t,h),{rewrittenEntries:U,auditEntryAdded:ce}=_a({rewritten:h,dryRun:w,changed:_,nextItemDocument:E.document,author:P,message:D}),B=ot(U);if(!B.ok)throw new g(`history-redact produced an invalid rewritten chain (${B.errors.join(", ")}).`,p.GENERIC_FAILURE);return!w&&_&&b.push(...await wa({pmRoot:r,subject:u,settings:i,typeRegistry:o,historyRawBeforeLock:l,currentItem:k,nextItem:E,author:P,force:t.force,rewrittenEntries:U})),{id:u.id,dry_run:w,changed:_,patterns:{literal_count:d.filter(M=>M.kind==="literal").length,regex_count:d.filter(M=>M.kind==="regex").length,total_count:d.length,replacement_is_default:a},history:{path:u.historyPath,entries_scanned:f.length,entries_changed:h.entriesChanged,replacements:h.replacements,hash_mismatches_before:m.hashMismatchesBefore,hash_mismatches_after:m.hashMismatchesAfter,preexisting_hash_mismatches:y,audit_entry_added:ce,verify_ok:B.ok,verify_errors:B.errors},item:{existed_before:k.path!==null,exists_after:E.path!==null,path_before:k.path,path_after:E.path,changed:I},warnings:[...new Set(b)].sort((M,H)=>M.localeCompare(H)),generated_at:G()}}var qg={applyLiteralRule:pi,applyRegexRule:gi,buildRedactionRules:mi,hasItemMetadata:hi,normalizeRegexFlags:li,normalizeStringArrayInput:cn,parseRegexRule:fi,redactStringValue:dn,redactUnknownValue:dt};(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]="bccbd81b-988f-569d-8dbf-c0998d813953")}catch{}})();function sh(e,t){let n=ot(e),r=e.length>0?e[e.length-1].after_hash:Gr(),i=t===void 0?void 0:Br(t),o=i===void 0?void 0:i===r,s=[...n.errors];return o===!1&&s.push("verify_failed:current_item_hash_mismatch"),{ok:s.length===0,entries:e.length,errors:s,latest_after_hash:e.length>0?e[e.length-1].after_hash:void 0,current_item_hash:i,current_matches_latest:o}}async function ah(e,t,n={}){let r=S(n.cwd??process.cwd(),n.pmRoot);if(!await A(O(r)))throw new g(`Tracker is not initialized at ${r}. Run pm init first.`,p.NOT_FOUND);let i=await T(r),o=$(i,F()),s=await un(r,e,i,o.type_to_folder),a=await xe(s.historyPath,s.id);if(a.length===0)throw new g(`No history exists for ${s.id}; point-in-time reads are unavailable.`,p.NOT_FOUND);let c=ai(t,a),d=di(ci(a,c.historyIndex),c),u=zr(d,{schema:i.schema});if(u.metadata.id!==s.id)throw new g(`History target resolved to item ${u.metadata.id}, expected ${s.id}.`,p.GENERIC_FAILURE);let l=a[c.historyIndex];return{document:u,reconstructed:!0,as_of_version:c.historyIndex+1,as_of_timestamp:l.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]="3a33af50-3d2c-57bb-884a-4d5394599ba2")}catch{}})();function va(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:Ra(r,t,e.parents)}),"continue"):(e.cursorFound=t===i,"skip")}function xa(e,t,n,r){let i=de("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:Ur(t.after,i)}}function $e(e,t,n){e.get(t).add(n)}function lt(e){return new Map(e.map(t=>[t,new Set]))}function _i(e){for(let t of e)t.sort();return e.sort((t,n)=>n.length-t.length||t[0].localeCompare(n[0]))}function ut(e){if(Array.isArray(e))return e.map(n=>ut(n));if(e===null||typeof e!="object")return e;let t=e.toJSON;return typeof t=="function"?ut(t.call(e)):Object.fromEntries(Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,ut(r)]))}function yi(e){return JSON.stringify(ut(e))}function Ea(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 Ia(e,t){let n=new Set,r=[];for(let i of e)n.has(i)||Ea(i,t,n,r);return r}function Ca(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 _i(r)}function wi(e,t){let n=lt(e);for(let[r,i]of t)for(let o of i)$e(n,o,r);return Ca(Ia(e,t),n)}function Sa(e,t){let n=lt(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";$e(n,o?r.source:r.target,o?r.target:r.source)}return n}function Ta(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 Da(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 Ra(e,t,n){let r=[t],i=t;for(;i!==e;)i=n.get(i),r.push(i);return r.reverse()}function ft(e,t={}){let n=t.registry??q(),r=[...e.nodes()],i=Sa(e,n),o=Ta(r,i),s=o.flat(),a=s.length===r.length,c=a?[]:wi(r,i).filter(u=>u.length>1||i.get(u[0]).has(u[0])),d=Da(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 bi(e,t,n={}){let r=n.direction??"outgoing",i=n.maxDepth??Number.POSITIVE_INFINITY,o=n.limit??Number.POSITIVE_INFINITY,{fingerprint:s,after:a}=xa(t,n,r,i),c={queue:[{id:t,depth:0}],seen:new Set([t]),parents:new Map,affected:[],cursorFound:a===void 0||a===t},d=0,u=0,l=!1,f=!1;e:for(let m=0;m<c.queue.length;m+=1){n.signal?.throwIfAborted();let h=c.queue[m];d+=1;let y=e.adjacency(h.id,{direction:r,kinds:n.kinds,signal:n.signal});if(u+=y.meta.inspectedEdges,h.depth>=i){y.value.some(w=>!c.seen.has(w))&&(l=!0);continue}for(let w of y.value)if(va(c,w,h,t,a,o)==="truncate"){l=!0,f=!0;break e}}if(!c.cursorFound)throw new TypeError(`Unknown impact cursor item: ${a}`);return{root:t,affected:c.affected,exact:!0,truncated:l,...f?{nextCursor:se(s,c.affected.at(-1)?.id??t)}:{},cost:{visitedNodes:d,inspectedEdges:u}}}function ki(e){let t=[...e.nodes()],n=lt(t),r=lt(t);for(let c of e.edges())$e(n,c.source,c.target),$e(n,c.target,c.source),$e(r,c.source,c.target);let i=[],o=new Set;for(let c of t){if(o.has(c))continue;let d=[],u=[c];for(o.add(c);u.length>0;){let l=u.pop();d.push(l);for(let f of n.get(l))o.has(f)||(o.add(f),u.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:_i(i),stronglyConnected:wi(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 lh(e,t){let n=new Map(e.edges.map(i=>[yi(i),i])),r=new Map(t.edges.map(i=>[yi(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]="eb044a23-d43b-5e9c-9ae7-4ac91b5e587a")}catch{}})();function W(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 g(`${t} must be a non-negative integer`,p.USAGE);return r}function mt(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 g(`${t} filter must be 0..4`,p.USAGE);return r}function vi(e,t,n="--type"){if(e===void 0)return;let r=et(e,t);if(!r)throw new g(`${n} filter must be one of ${t.types.join("|")}`,p.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]="8b010e79-a73a-5760-ac05-8dc88484cd69")}catch{}})();var pt={version:1,aliases:{}};function gt(e=[]){let t=new Set(ve),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 xi(e){if(e===void 0)return;let n=(typeof e=="string"?[e]:e).flatMap(r=>r.split(",")).map(r=>r.trim()).filter(r=>r.length>0);return n.length===0?void 0:new Set(n)}function ln(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 fn(e,t=ve){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 g(`Provenance predicate must use dimension=value; received "${o.trim()}".`,p.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 g(`Unknown provenance dimension "${a||o.trim()}". Declared dimensions: ${[...n].sort().join(", ")}.`,p.USAGE,{code:"unknown_provenance_dimension"});if(c.length===0)throw new g(`Provenance predicate must use dimension=value; received "${o.trim()}".`,p.USAGE,{code:"invalid_provenance_predicate"});let d=r.get(a)??new Set;d.add(c),r.set(a,d)}return r}function ht(e,t=pt,n={}){let r=ln(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 kh(e,t,n=pt,r=ve){return mn(t,n,r)(e)}function mn(e,t=pt,n=ve){let r=xi(e.harness),i=xi(e.agentInstance),o=fn(e,n);return s=>{let c=ln(s,t).agent_harness;if(r&&(!c||!r.has(c))||i&&!i.has(s.agent_instance??""))return!1;for(let[d,u]of o){let l=s.agent_provenance?.[d];if(!l||!u.has(l.value))return!1}return!0}}function yt(e,t=pt,n=ve){let r=new Set(n),i=new Map,o=0;for(let s of e){for(let c of Object.keys(s.agent_provenance??{}))r.add(c);ln(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 u=d.agent_provenance?.[s];u===null?c+=1:u!==void 0&&(a+=1)}return{dimension:s,observed:a,unavailable:c,legacy_missing:e.length-a-c}})}}import Aa from"node:fs/promises";import Ii 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]="a7efa5e0-5610-51ca-8288-4f5410dbcf51")}catch{}})();var Fa=20,Na=5;function pn(e,t){if(e===void 0)return;let n=e.trim();if(n.length===0)throw new g(`${t} must not be empty`,p.USAGE);return n}function Ei(e,t,n){if(e===void 0)return;let r=e.trim();if(r.length===0)throw new g("Activity time bounds must not be empty",p.USAGE);let i=n==="--from"&&/^\d+[hdwm]$/iu.test(r)?`-${r}`:r;return oe(i,new Date(t),n)}function La(e,t,n){return!(e.ts.length===0&&(t||n)||t&&x(e.ts,t)<0||n&&x(e.ts,n)>=0)}function Ma(e,t){return t===void 0?e:e.slice(0,t)}function Oe(e,t=""){return typeof e=="string"?e:t}function $a(e,t){return{...t,id:e,ts:Oe(t.ts),author:Oe(t.author,"unknown"),op:Oe(t.op,"unknown"),patch:Array.isArray(t.patch)?t.patch:[],before_hash:Oe(t.before_hash),after_hash:Oe(t.after_hash)}}function Oa(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 Pa(e){try{return(await Aa.readdir(e)).filter(t=>t.endsWith(".jsonl")).sort((t,n)=>t.localeCompare(n))}catch(t){if(t.code==="ENOENT")return[];throw t}}function ja(e){let t=G(),n=Ei(e.from,t,"--from"),r=Ei(e.to,t,"--to");if(n&&r&&x(n,r)>=0)throw new g("Activity --from must be before --to",p.USAGE);let i=sn(e.limit);if(e.unbounded===!0&&i!==void 0)throw new g("Activity --unbounded cannot be combined with --limit",p.USAGE);return{id:pn(e.id,"Activity --id"),op:pn(e.op,"Activity --op"),author:pn(e.author,"Activity --author"),from:n,to:r,limit:e.unbounded===!0?void 0:i??(e.compact===!0?Fa:Na),limitSource:e.unbounded===!0||i!==void 0?"explicit":"default",harness:e.harness,agentInstance:e.agentInstance,provenance:e.provenanceFilter}}async function Ua(e){let t=S(process.cwd(),e.path);if(!await A(O(t)))throw new g(`Tracker is not initialized at ${t}. Run pm init first.`,p.NOT_FOUND);return{pmRoot:t,settings:await T(t)}}async function Ba(e){let t=$(e.settings,F()),n=await Q(e.pmRoot,e.settings.item_format,t.type_to_folder,void 0,e.settings.schema);await Wr({pmRoot:e.pmRoot,settings:e.settings,itemIds:n.map(i=>i.id),commandLabel:"activity"});let r=Ii.join(e.pmRoot,"history");return await Sr({path:r,scope:"project"}),r}function Ga(e,t,n){return n.op&&e.op!==n.op||n.author&&e.author!==n.author?!1:La(t,n.from,n.to)}async function Ka(e,t){let n=[];for(let r of await Pa(e)){let i=r.slice(0,-6);if(t.id&&i!==t.id)continue;let o=await xe(Ii.join(e,r),i);for(let s of o){let a=$a(i,s);Ga(s,a,t)&&n.push(a)}}return n}function za(e){return e.map(t=>({id:t.id,op:t.op,ts:t.ts,author:t.author,...t.message?{msg:t.message}:{}}))}async function Ci(e,t){let n=await Ua(t),r=ja(e),i=await Ba(n),o=gt(n.settings.agent_identity.harness_signals),s=n.settings.agent_identity.identity_vocabulary,a=mn({harness:r.harness,agentInstance:r.agentInstance,provenance:r.provenance},s,o),c=Oa(await Ka(i,r)).filter(a),d=Ma(c,r.limit),u=e.compact===!0,l=u?za(d):void 0,f=e.provenance===!0?d.map(w=>ht(w,s,{itemId:w.id})):void 0,m=c.length-d.length,h=e.provenance===!0?"provenance":u?"compact":"full";return{...{compact:{compact_activity:l},provenance:{provenance_activity:f},full:{activity:d}}[h],compact:u,projection:{mode:h,row_key:h==="compact"?"compact_activity":h==="provenance"?"provenance_activity":"activity"},omission_receipt:jr("activity",h),count:d.length,total_count:c.length,limit:r.limit??null,omitted_count:m,has_more:m>0,...e.provenanceSummary===!0?{provenance_summary:yt(c,s,o)}:{},applied_bound:{kind:r.limit===void 0?"unbounded":"limit",source:r.limitSource,value:r.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]="1b2f1ac3-82b3-58a2-9f40-2dd95ab1b2bc")}catch{}})();var Si="global",Ha="external";function Te(e){let t=e?.trim().toLowerCase();return t===Si||t===Ha}function Fh(e){let t=e?.trim();if(t)return Te(t)?Si:t}function Nh(e,t,n){let r=e.trim();return Te(n)?r:st(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]="62ec8e0e-658e-5a32-b458-439d5ffd1229")}catch{}})();function _t(e){if(typeof e!="string")return;let t=e.trim();if(!(!t||["none","null","n/a","na"].includes(t.toLowerCase())))return t}function gn(e){let t=_t(e);return t?.toLowerCase()==="no-active-blocker"?void 0:t}function De(){let e=q();for(let t of F()?.relationship_kinds??[])for(let n of t.definitions)e.register(n);return e}function hn(e,t){let n=e.toLowerCase(),r=t.toLowerCase();return n!==r?n<r?-1:1:e!==t?e<t?-1:1:0}function qa(e){let t=new Map;for(let n of e.dependencies??[]){if(typeof n!="object"||n===null)continue;let r=n,i=_t(r.id);if(!i)continue;let o=typeof r.kind=="string"?r.kind:"related",s=`${o}\0${i.toLowerCase()}`,a=t.get(s);a?a.count+=1:t.set(s,{target_id:i,kind:o,count:1})}return t}function Wa(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 qa(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=hn(r.holder_id,i.holder_id);if(o!==0)return o;let s=hn(r.target_id,i.target_id);return s!==0?s:hn(r.kind,i.kind)})}function yn(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,u,l)=>{let f=_t(d);if(!f||r.has(f.toLowerCase()))return;let m={holder_id:c.id.trim(),target_id:f,kind:u,source:l,holder_status:c.status,legacy_terminal:t(c.status),no_active_blocker_sentinel:f.toLowerCase()==="no-active-blocker"};i.set(`${m.holder_id}::${m.target_id}::${m.kind}::${m.source}`,m)};for(let c of n){o(c,c.parent,"parent","parent"),o(c,c.blocked_by,"blocked_by","blocked_by");for(let d of c.dependencies??[]){if(typeof d!="object"||d===null)continue;let u=d;Te(u.source_kind)||o(c,u.id,typeof u.kind=="string"?u.kind:"related","dependency")}}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 Va(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 Xa(e){let t=new Map;for(let n of e)for(let r of n.dependencies??[]){if(typeof r!="object"||r===null||!Te(r.source_kind))continue;let i=_t(r.id);i&&!t.has(i.toLowerCase())&&t.set(i.toLowerCase(),i)}return[...t.values()].sort((n,r)=>n.localeCompare(r))}function Ya(e,t=De()){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 Re(e,t,n){let r=n??De(),i=e.filter(f=>typeof f?.id=="string"&&f.id.trim().length>0),o=new Map(i.map(f=>[f.id.trim().toLowerCase(),f.id.trim()])),s=yn(i,t),a=Va(s);for(let f of a)o.set(f.toLowerCase(),f);let c=Xa(i),d=new Set(o.keys()),u=new Map;for(let f of c){let m=f;for(;d.has(m.toLowerCase());)m=`external:${m}`;u.set(f.toLowerCase(),m),d.add(m.toLowerCase())}let l=i.map(f=>{let m=gn(f.parent),h=gn(f.blocked_by),y=(f.dependencies??[]).flatMap(w=>{if(typeof w!="object"||w===null)return[];let _=w,b=gn(_.id);return b?[{id:Te(_.source_kind)?u.get(b.toLowerCase()):o.get(b.toLowerCase()),kind:typeof _.kind=="string"?_.kind:"related"}]:[]});return{id:f.id.trim(),...m?{parent:o.get(m.toLowerCase())}:{},...h?{blocked_by:o.get(h.toLowerCase())}:{},dependencies:y}});return{graph:Ir.fromItems([...l,...a.map(f=>({id:f})),...c.map(f=>({id:u.get(f.toLowerCase())}))],r),details:[...i.map(f=>({id:f.id.trim(),title:f.title,status:f.status,...typeof f.type=="string"&&f.type.trim().length>0?{type:f.type.trim()}:{}})),...a.map(f=>({id:f,title:`[missing] ${f}`,status:"missing"})),...c.map(f=>({id:u.get(f.toLowerCase()),title:`[external] ${f}`,status:"external"}))],missingIdSet:new Set(a.map(f=>f.toLowerCase())),dangling:s,duplicateRows:Wa(i,t),legacyAliasCounts:Ya(i,r)}}import{createHash as Ja}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]="dea35fb9-9f9f-56ce-afc0-f4dc993012c3")}catch{}})();var Qa=64,Za=8;function ec(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 wt(e,t=r=>r==="closed"||r==="canceled",n=q()){let r=e.filter(o=>typeof o?.id=="string"&&o.id.trim().length>0).map(o=>ec(o,t)).sort(),i=n.list().map(o=>ke(o)).sort();return Ja("sha256").update(r.join("")).update("").update(i.join("")).digest("hex")}function Ti(e,t,n){let r=t??n;if(!Number.isInteger(r)||r<1)throw new TypeError(`Invalid ${e} bound: ${String(t)}`);return r}var _n=class{#e=new Map;#t;#n;constructor(t={}){this.#t=Ti("maxResultsPerWorkspace",t.maxResultsPerWorkspace,Qa),this.#n=Ti("maxWorkspaces",t.maxWorkspaces,Za)}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 u=s.results.get(c);if(u!==void 0||s.results.has(c))return s.results.delete(c),s.results.set(c,u),{value:structuredClone(u),reused:!0};let l=d();return s.results.size>=a&&s.results.delete(s.results.keys().next().value),s.results.set(c,structuredClone(l)),{value:l,reused:!1}}}}clear(){this.#e.clear()}},Di=new _n;function bt(){return Di}function Gh(){Di.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]="31a800f7-1374-5e7c-ad23-ae3d8ebcebe0")}catch{}})();var tc=["prerequisite","dependent","ancestor","descendant","provenance","related"],nc=new TextEncoder;function wn(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 kt(e){return Math.max(1,Math.ceil(nc.encode(JSON.stringify(e)).byteLength/4))}function bn(e,t,n){let r=n.resolve(e.kind);if(r?.ordering){let o=(r.precedence??"source_before_target")==="source_before_target"?e.source:e.target;return t===o?"prerequisite":"dependent"}if(r?.hierarchy){let o=(r.hierarchyDirection??"source_parent")==="source_parent"?e.source:e.target;return t===o?"ancestor":"descendant"}return e.kind==="discovered_from"||e.kind==="incident_from"?"provenance":"related"}function rc(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 ic(e){return tc.find(t=>e.includes(t))}function oc(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,u=!1;for(let l=0;l<a.length;l+=1){r.signal?.throwIfAborted();let f=a[l];if(f.distance>=o&&u)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(h=>!s.has(h.id))&&(u=!0);continue}for(let{id:h,edge:y}of m.value){if(s.has(h))continue;s.add(h);let w={id:h,distance:f.distance+1,via:f.id,role:bn(y,h,n)};c.push(w),a.push(w)}}return c.sort((l,f)=>l.distance-f.distance||l.id.localeCompare(f.id)),{rows:c,visitedNodes:a.length,inspectedEdges:d,depthTruncated:u}}function sc(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 ac(e){let t=[],n=e.initialTokens;for(let r of e.candidates){if(t.length>=e.nodeLimit)break;let i=r.distance===1?rc(e.rootEdges,e.rootId,r.id,e.registry):[],o={...e.details.get(r.id)??{id:r.id},distance:r.distance,role:i.length>0?ic(i):r.role,via:r.via,reasons:i.length>0?i:[`${r.role} via ${r.via} (depth ${r.distance})`]},s=kt(o);if(n+s>e.tokenBudget)break;t.push(o),n+=s}if(e.candidates.length>0&&t.length===0)throw new TypeError("Relationship context tokenBudget cannot fit one node");return{nodes:t,usedTokens:n}}function cc(e){let t=e.options.kinds?new Set(e.options.kinds.map(o=>e.registry.require(o).kind)):void 0,n=e.graph.edges().filter(o=>{if(!e.included.has(o.source)||!e.included.has(o.target))return!1;if(t===void 0||t.has(o.kind))return!0;let s=e.registry.resolve(o.kind)?.inverse;return s!==void 0&&t.has(s)}),r=[],i=e.initialTokens;for(let o of n){if(r.length>=e.edgeLimit)break;let s=kt(o);if(i+s>e.tokenBudget)break;r.push(o),i+=s}return{edges:r,usedTokens:i,candidateCount:n.length}}function Ri(e,t,n,r={}){if(!e.nodes().includes(t))throw new TypeError(`Relationship node not found: ${t}`);let i=wn(r.nodeLimit,20,"nodeLimit"),o=wn(r.edgeLimit,40,"edgeLimit"),s=wn(r.tokenBudget,1200,"tokenBudget"),a=r.registry??q(),c=new Map(n.map(J=>[J.id,J])),d=c.get(t)??{id:t},{evidence:u=[],...l}=d,f=[...u],m=oc(e,t,a,r),{rootEdges:h,...y}=sc(e,t,a,r),w=de("relationship-context",{rootId:t,direction:r.direction??"both",kinds:[...r.kinds??[]].sort(),maxDepth:r.maxDepth??3}),_=Ee(m.rows,r.cursor,w,({id:J})=>J),b=m.rows.slice(_),k=kt(l)+kt(f);if(k>s)throw new TypeError("Relationship context tokenBudget cannot fit root and evidence");let E=ac({candidates:b,details:c,rootEdges:h,rootId:t,registry:a,nodeLimit:i,tokenBudget:s,initialTokens:k}),{nodes:I}=E,P=new Set([t,...I.map(({id:J})=>J)]),D=cc({graph:e,included:P,options:r,registry:a,edgeLimit:o,tokenBudget:s,initialTokens:E.usedTokens}),{edges:U,usedTokens:ce}=D,B=_+I.length,M=B<m.rows.length,H=I.at(-1),X=D.candidateCount-U.length,Y=m.depthTruncated||M||X>0,_e={rootId:t,...l.status===void 0?{}:{rootStatus:l.status},...y,discoveredNodes:m.rows.length,returnedNodes:I.length,returnedEdges:U.length,omittedNodes:m.rows.length-B,omittedEdges:X,evidenceCount:f.length,hasMore:M};return{root:l,summary:_e,nodes:I,edges:U,evidence:f,meta:{exact:!0,truncated:Y,completeness:Y?"truncated":"complete",nodeLimit:i,edgeLimit:o,tokenBudget:s,usedTokens:ce,visitedNodes:m.visitedNodes,inspectedEdges:m.inspectedEdges,omittedNodes:m.rows.length-B,omittedEdges:X,...M&&H?{nextCursor:se(w,H.id,B-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]="ee0547d9-ae0f-5762-8bff-e25f0a3cd4d5")}catch{}})();var dc=["tree","graph","context"],uc=["none","repeated"],lc=["outgoing","incoming","both"],fc=32,mc=200,pc=400,gc=16e3;function hc(e){let t=e?.trim().toLowerCase()??"tree";if(dc.includes(t))return t;throw new g(`Invalid --format value "${e}". Use "tree", "graph", or "context".`,p.USAGE)}function Z(e,t){if(e===void 0)return;let n=typeof e=="number"?e:Number(e.trim());if(!Number.isInteger(n)||n<1)throw new g(`Invalid --${t} value "${e}". Use a positive integer.`,p.USAGE);return n}function vt(e){if(e===void 0)return;let t=typeof e=="number"?e:Number(e.trim());if(!Number.isInteger(t)||t<0)throw new g(`Invalid --max-depth value "${e}". Use a non-negative integer.`,p.USAGE);return t}function yc(e){let t=e?.trim().toLowerCase()??"none";if(uc.includes(t))return t;throw new g(`Invalid --collapse value "${e}". Use "none" or "repeated".`,p.USAGE)}function vn(e){let t=e?.trim().toLowerCase()??"both";if(lc.includes(t))return t;throw new g(`Invalid --direction value "${e}". Use "outgoing", "incoming", or "both".`,p.USAGE)}function xn(e,t=q()){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 g(`Invalid --kind value "${i}". Registered kinds: ${s}.`,p.USAGE)}r.add(o.kind)}return[...r].sort()}function _c(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 wc(e){return{id:e.id,title:e.title,type:e.type,status:e.status,dependencies:_c(e.dependencies)}}function bc(e){return it(new TextEncoder().encode(JSON.stringify({...e,dependencies:void 0})).byteLength)}function kc(e,t,n,r,i,o,s,a,c){for(let d of t.dependencies){let u=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+u>=a.tokenBudget){e.truncated=!0,a.reasons.add("token_budget");break}a.edges+=1,a.estimatedTokens+=u,e.dependencies.push(Fi(d.id,n,r,i,o,s,a,c+1,d.kind))}}function vc(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 Fi(e,t,n,r,i,o,s,a=0,c){let d=e.trim().toLowerCase(),u=t.get(d),l={id:u?.id??e,title:u?.title,type:u?.type,status:u?.status,via:c,missing:!u,cycle:n.has(d),dependencies:[]};if(s.nodes+=1,s.estimatedTokens+=bc(l),vc(l,u,d,r,i,o,s,a))return l;i==="repeated"&&o.add(d);let f=new Set(n);return f.add(d),kc(l,u,t,f,r,i,o,s,a),l}function Ai(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 xc(e){let t=new Map,n=new Map,r=[e];for(;r.length>0;){let a=r.pop();t.set(a.id,Ai(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,Ai(t.get(c.id),{id:c.id,title:c.title,type:c.type,status:c.status,missing:c.missing}));let d=c.via??"related",u=`${a.id}::${c.id}::${d}`;n.has(u)||n.set(u,{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 u=a.to.localeCompare(c.to);return u!==0?u: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 Ni(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++],u=d.id.trim().toLowerCase();r.add(u);let l=t.get(u);if(!l){o.add(u);continue}if(!(n!==void 0&&d.depth>=n)&&!s.has(u)){s.add(u);for(let f of l.dependencies)i.add(`${u}::${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 Ec(e,t=q()){let n=vt(e.maxDepth),r=Z(e.nodeLimit,"node-limit"),i=Z(e.edgeLimit,"edge-limit"),o=Z(e.tokenBudget,"token-budget"),s=xn(e.kind,t);return{direction:vn(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 Ic(e,t,n,r){return Ri(e.graph,t,e.details.map(i=>i.id===t&&r.length>0?{...i,evidence:r}:i),n)}function kn(e,t,n,r){for(let i of n.slice(0,r)){let o=i?.trim();o&&e.push(`${t}:${o}`)}}async function Cc(e,t,n,r){let i=await le(e,t,n.id_prefix,n.item_format,r);if(!i)return[];let{document:o}=await fe(i,{schema:n.schema}),s=o.metadata,a=s.files??[],c=s.tests??[],d=s.docs??[],u=[["files",a.length],["tests",c.length],["docs",d.length],["comments",(s.comments??[]).length],["notes",(s.notes??[]).length],["learnings",(s.learnings??[]).length]];if(u.every(([,f])=>f===0))return[];let l=[`linked:${u.map(([f,m])=>`${f}=${m}`).join(",")}`];return kn(l,"file",a.map(f=>f.path),3),kn(l,"test",c.map(f=>f.command??f.path),2),kn(l,"doc",d.map(f=>f.path),2),l}function Sc(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 Tc(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 Li(e,t,n){let r;for(;;){let i=it(new TextEncoder().encode(rn(tn("deps",e),t)).byteLength);if(i===r)return i;n(i),r=i}}function Dc(e){return e instanceof TypeError&&e.message.startsWith("Relationship context tokenBudget cannot fit ")}function Rc(e){try{return Ic(e.assembly,e.canonicalId,{...e.contextOptions,...e.internalTokenBudget===void 0?{}:{tokenBudget:e.internalTokenBudget}},e.rootEvidence)}catch(t){if(e.smallestResult!==void 0&&Dc(t))return e.smallestResult;throw t}}function Ac(e){let{assembly:t,canonicalId:n,contextOptions:r,rootEvidence:i,summaryOnly:o,outputFormat:s,missingCount:a,missingReferences:c}=e,u=r.edgeLimit??40,l=r.tokenBudget,f,m;for(;;){let h=Rc({assembly:t,canonicalId:n,contextOptions:r,internalTokenBudget:l,rootEvidence:i,smallestResult:m});if("format"in h)return h;let y=h;f??=y.meta.tokenBudget,l??=f;let w=Sc({canonicalId:n,context:y,missingCount:a,missingReferences:c,referenceLimit:u,summaryOnly:o});if(m=w,o||(y.meta.tokenBudget=f,y.meta.usedTokens=Li(Ae(w,!1),s,k=>{y.meta.usedTokens=k}),y.meta.usedTokens<=f))return w;if(u>0){u-=1;continue}let _=l,b=_*f/y.meta.usedTokens;l=Math.min(_-1,Math.max(1,Math.floor(b*.9)))}}function Fc(e){let{assembly:t,canonicalId:n,options:r,rootEvidence:i,summaryOnly:o,outputFormat:s}=e,a=Ec(r,t.graph.registry()),c=t.graph.closure(n,{direction:a.direction,...a.kinds===void 0?{}:{kinds:a.kinds},maxDepth:a.maxDepth??3}),d=c.value.filter(y=>t.missingIdSet.has(y.toLowerCase())),u=new Set(d.map(y=>y.toLowerCase())),l=t.graph.registry(),f=a.kinds?new Set(a.kinds.map(y=>l.require(y).kind)):void 0,m=new Set([n,...c.value]),h=[...t.dangling.active,...t.dangling.legacy_terminal].filter(y=>Tc({row:y,missingReachableSet:u,packetIds:m,filteredKinds:f,registry:l}));return Ac({assembly:t,canonicalId:n,contextOptions:a,rootEvidence:i,summaryOnly:o,outputFormat:s,missingCount:d.length,missingReferences:h})}function Nc(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 Lc(e,t,n,r,i,o,s){let a=i??fc,c=Z(n.nodeLimit,"node-limit")??mc,d=Z(n.edgeLimit,"edge-limit")??pc,u=Z(n.tokenBudget,"token-budget")??gc,l={nodeLimit:c,edgeLimit:d,tokenBudget:u,nodes:0,edges:0,estimatedTokens:0,reasons:new Set},f=Fi(e,r,new Set,a,t==="graph"?"repeated":o,new Set,l),m=Ni(e,r,void 0),h;for(;;){let y=xc(f),w=l.reasons.size===0?void 0:{reasons:[...l.reasons].sort(),limits:{max_depth:a,node_limit:c,edge_limit:d,token_budget:u},estimated_tokens:0,total_node_count:m.node_count,total_edge_count:m.edge_count,omitted_node_count:Math.max(0,m.node_count-y.nodes.length),omitted_edge_count:Math.max(0,m.edge_count-y.edges.length)},_={id:e,format:t,node_count:y.nodes.length,edge_count:y.edges.length,edge_basis:"deduplicated_directed",missing_count:y.missing_ids.length,...w?{truncation:w}:{}};if(h=t==="tree"?{..._,tree:f}:{..._,graph:y},(h.truncation===void 0?it(new TextEncoder().encode(rn(tn("deps",Ae(h,!1)),s)).byteLength):Li(Ae(h,!1),s,k=>{h.truncation.estimated_tokens=k}))<=u)return h;if(!Nc(f))return l.reasons.add("token_budget"),h;l.reasons.add("token_budget")}}function Ae(e,t,n={}){let r={name:e.format==="tree"?"dependency_tree":e.format==="graph"?"dependency_graph":"relationship_context",restore_with:"--full"};return{...e,legacy_alias_counts:n,projection:{mode:t?"summary":"full",declared_field_groups:[r],included_field_groups:t?[]:[r.name]}}}async function uy(e,t,n){let r=S(process.cwd(),n.path);if(!await A(O(r)))throw new g(`Tracker is not initialized at ${r}. Run pm init first.`,p.NOT_FOUND);let i=hc(t.format),o=vt(t.maxDepth),s=yc(t.collapse);nt(t.summary===!0,t.full===!0,"--summary");let a=t.summary===!0,c=await T(r),d=$(c,F()),u=await Q(r,c.item_format,d.type_to_folder,void 0,c.schema),l=z(c.schema),f=new Map(u.map(h=>[h.id.trim().toLowerCase(),wc(h)])),m=yn(u,h=>L(h,l));for(let h of[...m.active,...m.legacy_terminal]){let y=f.get(h.holder_id.trim().toLowerCase()),w=h.kind.trim().toLowerCase();y&&!y.dependencies.some(_=>_.id.trim().toLowerCase()===h.target_id.trim().toLowerCase()&&_.kind===w)&&y.dependencies.push({id:h.target_id,kind:w})}if(!f.has(e.trim().toLowerCase()))throw new g(`Item ${e} not found`,p.NOT_FOUND);if(i==="context"){let h=f.get(e.trim().toLowerCase()).id,y=a?[]:await Cc(r,h,c,d.type_to_folder),w=k=>L(k,l),_=De(),b=bt().lookup(r,wt(u,w,_),()=>Re(u,w,_));return Ae(Fc({assembly:b.assembly,canonicalId:h,options:t,rootEvidence:y,summaryOnly:a,outputFormat:n.json===!0?"json":"toon"}),a,b.assembly.legacyAliasCounts)}return a?Ae({id:e,format:i,...Ni(e,f,o)},!0,Object.fromEntries(Object.entries(Re(u,h=>L(h,l)).legacyAliasCounts))):Ae(Lc(e,i,t,f,o,s,n.json===!0?"json":"toon"),!1,Object.fromEntries(Object.entries(Re(u,h=>L(h,l)).legacyAliasCounts)))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c0fb747e-1f9f-55c4-808b-b77d3a881f87")}catch{}})();var Mc=5,$c=1e4,Oc=8;function En(e,t){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new TypeError(`Invalid path ${e} bound: ${String(t)}`)}function xt(e,t){return t.hierarchyDirection==="target_parent"?e.target:e.source}function Pe(e,t){return(t.precedence??"source_before_target")==="target_before_source"?e.target:e.source}function Et(e,t){let n=Pe(e,t);return{predecessor:n,successor:n===e.source?e.target:e.source}}function Pc(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);if(!s[n])throw new TypeError(`Relationship kind ${s.kind} is not a ${n} kind`);i.add(s.kind)}return i}function jc(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 u=o.require(d.edge.kind);u[r]&&i(d,u,t)&&(c.has(d.id)||(c.add(d.id),a.push(d.id)))}return{neighbors:a,inspectedEdges:s.meta.inspectedEdges}}function Uc(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 It(e,t,n,r,i){if(!e.hasNode(t))throw new TypeError(`Relationship node not found: ${t}`);let o=Pc(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},u=0,l=0;for(let f=0;f<d.queue.length;f+=1){n.signal?.throwIfAborted();let m=d.queue[f];u+=1;let h=jc(e,m.id,o,r,i);if(l+=h.inspectedEdges,Uc(h,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:u,inspectedEdges:l,truncated:d.truncated,nextCursor:d.value.at(-1)}}}function Mi(e,t){if(!e.hasNode(t))throw new TypeError(`Relationship node not found: ${t}`)}function $i(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 Bc(e,t,n,r,i,o,s){for(let a of $i(e,t,r,i,s)){let c=[...t.nodes,a.id],d=new Set(t.nodeSet).add(a.id),u=[...t.edges,a.edge];if(a.id===n){if(s.value.push({nodes:c,edges:u,length:u.length}),s.value.length>=o)return!0}else s.queue.push({nodes:c,nodeSet:d,edges:u})}return!1}function Oi(e,t,n={}){return It(e,t,n,"hierarchy",(r,i)=>xt(r.edge,i)===r.id)}function Pi(e,t,n={}){return It(e,t,n,"hierarchy",(r,i,o)=>xt(r.edge,i)===o)}function ji(e,t,n={}){return It(e,t,n,"ordering",(r,i)=>Pe(r.edge,i)===r.id)}function Ui(e,t,n={}){return It(e,t,n,"ordering",(r,i,o)=>Pe(r.edge,i)===o)}function Gc(e,t,n,r,i,o,s,a){let c={value:[],queue:[{nodes:[t],nodeSet:new Set([t]),edges:[]}],inspectedEdges:0},d=0,u=!1,l=i+1;for(let f=0;f<c.queue.length;f+=1){if(r.signal?.throwIfAborted(),c.value.length>=l||d>=o){u=!0;break}let m=c.queue[f];if(d+=1,m.edges.length>=s){$i(e,m,r,a,c).length>0&&(u=!0);continue}if(Bc(e,m,n,r,a,l,c)){u=!0;break}}return{value:c.value.slice(0,i),meta:{visitedNodes:d,inspectedEdges:c.inspectedEdges,truncated:u}}}function Bi(e,t,n,r={}){Mi(e,t),Mi(e,n);let i=r.maxPaths??Mc,o=r.maxVisitedPaths??$c,s=r.maxDepth??Oc;En("maxPaths",i),En("maxVisitedPaths",o),En("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}}:Gc(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]="24898402-1568-5b05-9072-f89dd91f25a6")}catch{}})();var Kc=16,zc=2,Hc=8;function Ct(e,t){if(!Number.isInteger(t)||t<1)throw new TypeError(`Invalid ${e} bound: ${String(t)}`)}function St(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 qc(e,t){let n=new Map;St(e,t,r=>{Gi(n,r.source,r.target),Gi(n,r.target,r.source)});for(let r of n.values())r.sort();return n}function Gi(e,t,n){let r=e.get(t);r===void 0?e.set(t,[n]):r.push(n)}function Wc(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 Vc(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 Ki(e,t={}){let n=t.maxIterations??Kc,r=t.minSize??zc;Ct("maxIterations",n),Ct("minSize",r);let i=qc(e,t.kinds),o=e.nodes(),s=new Map(o.map(l=>[l,l])),a=0,c=!1,d=0,u=0;for(;a<n&&!c;){t.signal?.throwIfAborted(),a+=1,c=!0;for(let l of o){d+=1;let f=i.get(l);if(f===void 0)continue;u+=f.length;let m=Wc(f,s);m!==s.get(l)&&(s.set(l,m),c=!1)}}return{value:{communities:Vc(s,r),iterations:a,converged:c},meta:{visitedNodes:d,inspectedEdges:u,truncated:!c}}}function Tt(e){return e.direction==="directed"&&(e.ordering||e.hierarchy)}function Dt(e){return e.inverse!==void 0&&e.inverse<e.kind?e.inverse:e.kind}function In(e,t){return(t.hierarchy?xt(e,t):e.source===Pe(e,t)?e.target:e.source)===e.target?{from:e.source,to:e.target}:{from:e.target,to:e.source}}function Xc(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(!Tt(o))throw new TypeError(`Relationship kind ${o.kind} is not a directed ordering or hierarchy kind`);r.add(Dt(o))}return r}function Yc(e,t){let n=e.registry(),r=new Map;for(let i of e.edges()){let o=n.require(i.kind);if(!Tt(o))continue;let s=Dt(o);if(t!==void 0&&!t.has(s))continue;let a=In(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 Jc(e){let t=new Map;for(let[n,r]of e.adjacency)t.set(n,[...r].sort());return t}function Qc(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 Zc(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 Qc(r,t.from,n.id,s);i.push({id:s,depth:n.depth+1})}}function ed(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=Zc(e,t,a,i,o,r);if(c!==void 0)return c}}function Rt(e,t={}){let n=t.maxDepth??Hc;Ct("maxDepth",n),t.limit!==void 0&&Ct("limit",t.limit);let r=t.limit??Number.POSITIVE_INFINITY,i=Xc(e,t.kinds),o=Yc(e,i),s=[],a={visitedNodes:0,inspectedEdges:0},c=!1;e:for(let d of[...o.keys()].sort()){let u=o.get(d),l=Jc(u);for(let f of u.records){t.signal?.throwIfAborted();let m=ed(l,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 td(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 nd(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:u,depth:l}=a.queue[d];o.push(u);let f=e.neighborEdges(u,{direction:r,...n.kinds===void 0?{}:{kinds:n.kinds}});c+=f.meta.inspectedEdges,s.set(u,td(u,l,f.value,i,a))}return{order:o,successors:s,predecessors:a.predecessors,inspectedEdges:c,truncated:a.truncated}}function rd(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 id(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 od(e,t,n){let r;for(let i of[...e].sort())t.has(i)&&(r=r===void 0?i:id(r,i,t,n));return r}function sd(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=od(e.predecessors.get(a),o,r);c!==void 0&&o.get(a)!==c&&(o.set(a,c),s=!0)}}return o}function zi(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=nd(e,t,n),i=rd(r,t),o=new Map(i.map((d,u)=>[d,u])),s=sd(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 u=i[d];if(u===t)continue;let l=s.get(u);a.set(l,a.get(l)+a.get(u))}let c=i.filter(d=>d!==t).map(d=>({id:d,idom:s.get(d),dominatedCount:a.get(d)-1})).sort((d,u)=>u.dominatedCount-d.dominatedCount||d.id.localeCompare(u.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]="348c9246-2fb9-529e-b627-f60c901a6cf2")}catch{}})();function Hi(e){return Math.round(e*1e6)/1e6}function qi(e,t,n){let r=e.get(t);r===void 0?e.set(t,new Set([n])):r.add(n)}function Wi(e,t){let n=new Map(e.nodes().map(i=>[i,new Set]));St(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 ad(e,t){let n=new Map,r=new Map;return St(e,t,(i,o)=>{if(!o.ordering)return;let{predecessor:s,successor:a}=Et(i,o);qi(r,s,a),qi(n,a,s)}),{incoming:n,outgoing:r}}function cd(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 u=0;u<a.length;u+=1){let l=a[u];n.visitedNodes+=1,s.push(l);let f=r.get(l);l!==e&&(c+=1,d+=f);for(let m of t.get(l))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(l));let h=o.get(m);h===void 0?o.set(m,[l]):h.push(l)}}return{stack:s,sigma:i,predecessors:o,reachableCount:c,distanceSum:d}}function dd(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 ud(e,t){return t<=1||e.reachableCount===0?0:e.reachableCount/(t-1)*(e.reachableCount/e.distanceSum)}function ld(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:Hi((r.get(e)??0)/2),closeness:Hi(i.get(e))}}function Vi(e,t={}){let n=Wi(e,t.kinds),r=ad(e,t.kinds),i=e.nodes(),o=new Map,s=new Map,a={visitedNodes:0,inspectedEdges:0};for(let u of i){t.signal?.throwIfAborted();let l=cd(u,n,a);s.set(u,ud(l,i.length)),dd(l,u,o)}let c=0;for(let u of n.values())c+=u.length;let d=i.map(u=>ld(u,n,r,o,s)).sort((u,l)=>l.betweenness-u.betweenness||l.degree-u.degree||u.id.localeCompare(l.id));return{value:{nodeCount:i.length,edgeCount:c/2,rows:d},meta:{visitedNodes:a.visitedNodes,inspectedEdges:a.inspectedEdges,truncated:!1}}}function fd(e,t){return e<=t?{source:e,target:t}:{source:t,target:e}}function md(e,t,n){let i=t.get(e.node)[e.neighborIndex];if(e.neighborIndex+=1,n.inspectedEdges+=1,i!==e.parent){if(n.discovery.has(i)){n.low.set(e.node,Math.min(n.low.get(e.node),n.discovery.get(i)));return}return e.children+=1,n.discovery.set(i,n.timer),n.low.set(i,n.timer),n.timer+=1,{node:i,parent:e.node,neighborIndex:0,children:0}}}function pd(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(fd(r,e.node))}function gd(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=md(o,t,n);s!==void 0&&i.push(s)}else pd(o,e,n),i.pop()}}function Xi(e,t={}){let n=Wi(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)||gd(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]="f155ac72-64eb-5316-b016-954abd48c0e7")}catch{}})();function hd(e){let t=e.registry(),n=new Map,r=new Set;for(let i of e.edges()){let o=t.require(i.kind);if(!o.ordering)continue;let{predecessor:s,successor:a}=Et(i,o);if(r.add(s),r.add(a),s===a)continue;let c=n.get(s);c===void 0?n.set(s,new Set([a])):c.add(a)}return{forward:n,participants:r}}function yd(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 _d(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 wd(e,t,n,r,i){let o=new Map;for(let s=e.length-1;s>=0;s-=1){let a=e[s],c=yd(t.forward.get(a),r,o,i);o.set(a,c-1)}return e.map(s=>_d(s,n[s],o.get(s))).sort((s,a)=>s.slack-a.slack||s.earliestStart-a.earliestStart||s.id.localeCompare(a.id))}function Yi(e,t={}){t.signal?.throwIfAborted();let n=ft(e,{registry:e.registry()}),r=hd(e),i=new Set(n.order),o=n.order.filter(d=>r.participants.has(d)),s=o.reduce((d,u)=>Math.max(d,n.depth[u]+1),0),a=wd(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"}}}import Qi 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]="ee260dcf-f4df-5997-a8d7-691c19c66a41")}catch{}})();var Zi=1,Cn=500,bd=64,kd="graph-durable-cache";function eo(e){return Ce(e,kd,30,`graph-cache:${process.pid}`,!1,!1,3e3)}function je(e){return Qi.join(e,"runtime","graph-cache.json")}function to(e){return Qi.join(e,"runtime","graph-audit-baseline.json")}function Sn(e){if(e!==null)try{let t=JSON.parse(e);return typeof t!="object"||t===null||t.version!==Zi||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 Tn(e,t){let n=await ie(je(e)),r=Sn(n),i=r?.fingerprint===t;return{exists:n!==null,fresh:i,results:i?r.results:{}}}async function Dn(e,t,n,r,i){let o=await eo(e);try{let s=Sn(await ie(je(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-bd)))delete a[d];await K(je(e),JSON.stringify({version:Zi,fingerprint:t,saved_at:new Date().toISOString(),results:a})),n.results=a}finally{await o()}}async function Rn(e){let t=await eo(e);try{await _r(je(e))}finally{await t()}}async function no(e,t){let n=je(e),r=await ie(n),i=Sn(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 An(e,t){return t||e>=Cn}function Ji(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.values(e).every(t=>Number.isInteger(t)&&t>=0)}function vd(e){return typeof e!="object"||e===null||Array.isArray(e)?!1:Object.values(e).every(t=>typeof t=="object"&&t!==null&&!Array.isArray(t)&&[t.active,t.isolated,t.degree_leq_one].every(n=>Number.isInteger(n)&&n>=0))}function xd(e){if(e!==null)try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return;let n=t,r=n.profile;return typeof n.saved_at!="string"||typeof n.fingerprint!="string"||!Ji(n.affected_subjects_by_code)||typeof r!="object"||r===null||![r.nodes,r.edges,r.active_nodes,r.missing_nodes,r.isolated_active_nodes,r.degree_leq_one_active_nodes].every(i=>Number.isInteger(i)&&i>=0)||!Ji(r.edges_by_kind)||r.coverage_by_type!==void 0&&!vd(r.coverage_by_type)?void 0:{...n,profile:{...r,coverage_by_type:r.coverage_by_type??{}}}}catch{return}}async function ro(e){return xd(await ie(to(e)))}async function io(e,t){await K(to(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]="76fa19c7-a421-5026-8de8-450285987c4e")}catch{}})();var Ed=25,oo={error:0,warning:1,info:2};function Nn(e,t,n,r,i,o,s){let a=[...i].sort((c,d)=>c.localeCompare(d));return{code:e,severity:t,policy:n,message:r(a.length),count:a.length,sample:a.slice(0,o),sample_truncated:a.length>o,remediation:s}}function Id(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 co(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 Cd(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))):(co(o,r),t.push({node:o,neighborIndex:0})),!0}function Sd(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 Td(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(co(r,t);i.length>0;){let o=i.at(-1);Cd(o,i,e,t)||Sd(o,i,e,t)}}return t.components.sort((r,i)=>r[0].localeCompare(i[0]))}function Fn(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(Nn(r,i,o,s,t,n,a))}function Dd(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(Fn),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(Fn),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(Fn),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 Ln(e,t){let n=t.get(e);return n?!n.terminal:!0}function Rd(e,t,n,r){let i=[],o=Id(e);for(let c of Td(o)){let d=c.some(u=>Ln(u,t));i.push(d?Nn("ordering_cycle","error","Order-bearing relationship kinds must stay acyclic; a cycle makes every member unschedulable.",u=>`execution-order cycle across ${u} item(s)`,c,r,"Remove or retype one ordering edge inside the cycle, or split the work so precedence is linear."):Nn("legacy_ordering_cycle","info","Ordering cycles between exclusively terminal items are historical contradictions with no scheduling effect.",u=>`terminal-only execution-order cycle across ${u} 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."))}let s=new Map;for(let[c,d]of o)for(let u of d){let l=s.get(u);l?l.push(c):s.set(u,[c])}let a=[...t.values()].filter(c=>!c.missing&&!c.terminal&&n(c.status)&&!(s.get(c.id)??[]).some(d=>{let u=t.get(d);return u===void 0||!u.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 At(e){let t=e.edges.map(n=>n.kind).sort((n,r)=>n.localeCompare(r));return`${e.from} -> ${e.to} (${t.join(" + ")})`}function Mn(e){let t=e.graph.registry(),n=new Map;for(let i of e.graph.edges()){let o=t.require(i.kind);if(!Tt(o))continue;let s=In(i,o);if(s.from===s.to)continue;let a=`${Dt(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 Ad(e,t,n){let r=[],i=[];for(let s of Mn(e))(Ln(s.from,t)||Ln(s.to,t)?r:i).push(At(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 Fd(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 Nd(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 Ld(e,t,n,r,i,o){let s={active:0,missing:0,isolated:0,degreeLeqOne:0,isolates:[],sparse:[],byType:new Map};for(let u of e.graph.nodes()){let l=t.get(u);if(l){if(l.missing){s.missing+=1;continue}l.terminal||Nd(s,l,e.graph.incidentEdges(u).length,n,r)}}let{isolates:a,sparse:c}=s,d=[];return ee(d,a,i,"isolated_active_node","warning","Active work should be reachable from the graph unless explicitly declared a valid isolate.",u=>`${u} active item(s) with no relationships`,"Link the item to its parent, prerequisite, or origin \u2014 or register it as an exempt isolate."),ee(d,c,i,"sparse_active_node","info","Active items with a single edge often miss an honest semantic partner; sparse is not automatically defective.",u=>`${u} active item(s) with exactly one relationship`,"Investigate for an honest second edge (story->task, defect family, cross-epic complement); do not fabricate one."),{findings:d,profile:{nodes:e.graph.nodes().length,edges:e.graph.edges().length,edge_basis:"deduplicated_directed",edges_by_kind:Object.fromEntries(Object.entries(o).sort(([u],[l])=>u.localeCompare(l))),active_nodes:s.active,missing_nodes:s.missing,isolated_active_nodes:s.isolated,degree_leq_one_active_nodes:s.degreeLeqOne,coverage_by_type:Object.fromEntries([...s.byType.entries()].sort(([u],[l])=>u<l?-1:1))}}}function Ft(e,t={}){let n=t.isTerminal??(l=>l==="closed"||l==="canceled"),r=t.isBlocked??(l=>l==="blocked"),i=t.maxSampleSize??Ed;if(!Number.isInteger(i)||i<1)throw new TypeError(`Invalid audit sample bound: ${String(t.maxSampleSize)}`);let o=new Set((t.exemptIsolates??[]).filter(l=>typeof l=="string").map(l=>l.trim().toLowerCase())),s=new Set((t.isolateExemptTypes??[]).filter(l=>typeof l=="string").map(l=>l.trim().toLowerCase())),a=new Map(e.details.map(l=>[l.id,{id:l.id,status:l.status,missing:e.missingIdSet.has(l.id.toLowerCase()),terminal:n(l.status),...l.type===void 0?{}:{type:l.type}}]));t.signal?.throwIfAborted();let c={};for(let l of e.graph.edges())c[l.kind]=(c[l.kind]??0)+1;let d=Dd(e,n,i);t.signal?.throwIfAborted(),d.push(...Rd(e,a,r,i)),t.signal?.throwIfAborted(),d.push(...Ad(e,a,i),...Fd(e,i)),t.signal?.throwIfAborted();let u=Ld(e,a,o,s,i,c);return d.push(...u.findings),d.sort((l,f)=>oo[l.severity]-oo[f.severity]||l.code.localeCompare(f.code)||l.sample[0].localeCompare(f.sample[0])),{findings:d,profile:u.profile}}function so(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 ao(e){return e.profile.coverage_by_type??{}}function uo(e,t){let n={},r=ao(e),i=ao(t),o=[...new Set([...Object.keys(r),...Object.keys(i)])].sort();for(let s of o){let a=r[s],c=i[s],d={active:(c?.active??0)-(a?.active??0),isolated:(c?.isolated??0)-(a?.isolated??0),degree_leq_one:(c?.degree_leq_one??0)-(a?.degree_leq_one??0)};Object.values(d).some(u=>u!==0)&&(n[s]=d)}return{baseline_saved_at:e.saved_at,same_snapshot:e.fingerprint===t.fingerprint,affected_subjects_by_code:so(e.affected_subjects_by_code,t.affected_subjects_by_code),profile:{nodes:t.profile.nodes-e.profile.nodes,edges:t.profile.edges-e.profile.edges,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:so(e.profile.edges_by_kind,t.profile.edges_by_kind),coverage_by_type: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]="9b8e22ad-6268-515d-994e-6b98a062ba93")}catch{}})();var Md={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)."},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 lo(e){return`${e.source} -${e.kind}-> ${e.target}`}function $d(e){let[t,...n]=e.edges;return n.map(r=>({op:"remove",code:"duplicate_edge",subject:lo(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: ${lo(t)}`,`group: ${At(e)}`],confidence:"high"}))}function Od(e,t){if(e.code==="duplicate_edge")return e.sample.flatMap(r=>$d(t.get(r)));let n=Md[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 fo(e,t={}){let{redundancyLimit:n,...r}=t,i=Ft(e,r),o=new Map(Mn(e).map(d=>[At(d),d])),s=i.findings.flatMap(d=>Od(d,o)),a=i.findings.some(d=>d.sample_truncated);t.signal?.throwIfAborted();let c=Rt(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]="6c8bfb7a-687a-5fbb-b408-ffdbab1187a9")}catch{}})();var ho=new Set(["ancestors","descendants","predecessors","successors","paths","impact","dominators"]),me=10;function mo(e,t,n){return{...e,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 po(e){return e===void 0?[]:(Array.isArray(e)?e:[e]).flatMap(t=>t.split(",")).map(t=>t.trim()).filter(t=>t.length>0)}function Pd(e,t,n){let r=e.trim().toLowerCase();if(!nn.includes(r))throw xr({command_path:"graph",token:r||"<empty>",allowed:nn});let i=r;if(ho.has(i)&&!t?.trim())throw new g(`graph ${i} requires an item id.`,p.USAGE);if(i==="paths"&&!n?.trim())throw new g("graph paths requires a source and a target item id.",p.USAGE);return i}function $n(e){throw e instanceof TypeError?new g(e.message,p.USAGE):e}function On(e){return{truncated:e.truncated,cost:{visited_nodes:e.visitedNodes,inspected_edges:e.inspectedEdges}}}function go(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 g(`Item ${t} not found`,p.NOT_FOUND)}function jd(e,t,n){let r={ancestors:Oi,descendants:Pi,predecessors:ji,successors:Ui}[e],i;try{i=r(n.assembly.graph,t,{...n.kinds===void 0?{}:{kinds:n.kinds},...n.maxDepth===void 0?{}:{maxDepth:n.maxDepth},...n.limit===void 0?{}:{limit:n.limit},...n.after===void 0?{}:{after:n.after}})}catch(s){$n(s)}let o=On(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 Ud(e,t,n){let r=Bi(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,...On(r.meta),...n.summary?{}:{paths:r.value.map(i=>({nodes:i.nodes,kinds:i.edges.map(o=>o.kind),length:i.length}))}}}function Bd(e,t){let n;try{n=bi(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??me},...t.after===void 0?{}:{after:t.after}})}catch(r){$n(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 Gd(e){let t=e.assembly.graph,n=e.limit??me,r=ft(t,{registry:t.registry()}),i=ki(t);return{subcommand:"analyze",node_count:t.nodes().length,edge_count:t.edges().length,edge_basis:"deduplicated_directed",sample_limit:n,execution:{acyclic:r.acyclic,ordered_node_count:r.order.length,layer_count:r.layers.length,frontier_count:r.frontier.length,critical_path_length:r.criticalPathLength,cycle_count:r.cycles.length,...e.summary?{}:{frontier:r.frontier.slice(0,n),critical_path:r.criticalPath.slice(0,n),cycles:r.cycles.slice(0,n)}},knowledge:{component_count:i.components.length,largest_component_size:i.components[0]?.length??0,orphan_count:i.orphans.length,...e.summary?{}:{orphans:i.orphans.slice(0,n),hubs:i.hubs.slice(0,n)}}}}function Kd(e,t){let n=Ft(e.assembly,{isTerminal:t,...e.sample===void 0?{}:{maxSampleSize:e.sample},...e.exemptIsolates.length===0?{}:{exemptIsolates:e.exemptIsolates},...e.exemptIsolateTypes.length===0?{}:{isolateExemptTypes:e.exemptIsolateTypes}}),r={},i={},o={},s={};for(let a of n.findings)r[a.severity]=(r[a.severity]??0)+1,i[a.code]=(i[a.code]??0)+1,o[a.severity]=(o[a.severity]??0)+a.count,s[a.code]=(s[a.code]??0)+a.count;return{subcommand:"audit",finding_count:n.findings.length,findings_by_severity:r,findings_by_code:i,affected_subjects_by_severity:o,affected_subjects_by_code:s,profile:n.profile,legacy_alias_counts:e.assembly.legacyAliasCounts,...e.summary?{}:{findings:n.findings}}}function zd(e){let t=e.limit??me,n={};e.kinds!==void 0&&(n.kinds=e.kinds);let r=Ki(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 Hd(e){let t;try{t=Rt(e.assembly.graph,{...e.kinds===void 0?{}:{kinds:e.kinds},...e.maxDepth===void 0?{}:{maxDepth:e.maxDepth},...e.limit===void 0?{}:{limit:e.limit}})}catch(n){$n(n)}return{subcommand:"redundancy",redundant_count:t.value.length,...On(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 qd(e,t){let n=t.limit??me,r=zi(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 Wd(e){let t=e.limit??me,n=Yi(e.assembly.graph),r=n.rows.filter(i=>i.critical).length;return{subcommand:"slack",acyclic:n.acyclic,makespan:n.makespan,scheduled_count:n.scheduledCount,critical_count:r,critical_path_length:n.criticalPathLength,cycle_count:n.cycles.length,truncated:n.rows.length>t,...e.summary?{}:{critical_path:n.criticalPath,rows:n.rows.slice(0,t).map(i=>({id:i.id,earliest_start:i.earliestStart,latest_start:i.latestStart,slack:i.slack,critical:i.critical}))}}}function Vd(e){let t=e.limit??me,n=Vi(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 Xd(e){let t=e.limit??me,n=Xi(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 Yd(e,t){let n=e.limit??me,r=fo(e.assembly,{isTerminal:t,redundancyLimit:n,...e.sample===void 0?{}:{maxSampleSize:e.sample},...e.exemptIsolates.length===0?{}:{exemptIsolates:e.exemptIsolates},...e.exemptIsolateTypes.length===0?{}:{isolateExemptTypes:e.exemptIsolateTypes}}),i={},o={};for(let s of r.steps)i[s.op]=(i[s.op]??0)+1,o[s.code]=(o[s.code]??0)+1;return{subcommand:"plan",step_count:r.steps.length,steps_by_op:i,steps_by_code:o,finding_count:r.report.findings.length,truncated:r.truncated||r.steps.length>n,cost:{visited_nodes:r.cost.visitedNodes,inspected_edges:r.cost.inspectedEdges},...e.summary?{}:{steps:r.steps.slice(0,n)}}}function yo(e,t,n,r){return JSON.stringify({subcommand:e,root:t??null,target:n??null,kinds:r.kinds??null,maxDepth:r.maxDepth??null,limit:r.limit??null,after:r.after??null,direction:r.direction,maxPaths:r.maxPaths??null,sample:r.sample??null,exemptIsolates:[...new Set(r.exemptIsolates.map(i=>i.toLowerCase()))].sort(),exemptIsolateTypes:[...new Set(r.exemptIsolateTypes.map(i=>i.toLowerCase()))].sort(),summary:r.summary,unbounded:r.unbounded})}function _o(e,t,n,r,i){return e==="analyze"?Gd(r):e==="audit"?Kd(r,i):e==="plan"?Yd(r,i):e==="communities"?zd(r):e==="redundancy"?Hd(r):e==="dominators"?qd(t,r):e==="slack"?Wd(r):e==="centrality"?Vd(r):e==="articulation"?Xd(r):e==="paths"?Ud(t,n,r):e==="impact"?Bd(t,r):jd(e,t,r)}function Jd(e,t){if(e!=="index"&&(t.rebuild===!0||t.clear===!0))throw new g("--rebuild and --clear apply only to graph index.",p.USAGE);if(e!=="audit"&&t.saveBaseline===!0)throw new g("--save-baseline applies only to graph audit.",p.USAGE);if(e==="slack"&&t.kind!==void 0)throw new g("graph slack analyzes every ordering kind; --kind is not supported.",p.USAGE);if(t.rebuild===!0&&t.clear===!0)throw new g("graph index accepts either --rebuild or --clear, not both.",p.USAGE);if(e==="impact"&&t.full===!0&&t.limit!==void 0)throw new g("graph impact accepts either --full or --limit, not both.",p.USAGE)}async function Qd(e,t,n,r,i,o){let s="status";if(o.clear===!0&&(await Rn(e),s="cleared"),o.rebuild===!0){await Rn(e);let c=await Tn(e,t),d={assembly:n.assembly,direction:"both",exemptIsolates:[],exemptIsolateTypes:[],saveBaseline:!1,summary:!0,unbounded:!1};for(let u of["analyze","audit"])await Dn(e,t,c,yo(u,void 0,void 0,d),_o(u,void 0,void 0,d,i));s="rebuilt"}let a=await no(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:Cn,persist_enabled:An(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 Zd(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},o=await ro(e);return r&&await io(e,i),o===void 0?n:{...n,baseline:uo(o,i)}}async function eu(e,t,n,r,i){try{await Dn(e,t,n,r,i)}catch{}}async function e_(e,t,n,r,i){let o=Pd(e,t,n);nt(r.summary===!0,r.full===!0,"--summary");let s=S(process.cwd(),i.path);if(!await A(O(s)))throw new g(`Tracker is not initialized at ${s}. Run pm init first.`,p.NOT_FOUND);let a=await T(s),c=$(a,F()),d=await Q(s,a.item_format,c.type_to_folder,void 0,a.schema),u=z(a.schema),l=U=>L(U,u);Jd(o,r);let f=De(),m=xn(r.kind,f),h=bt().lookup(s,wt(d,l,f),()=>Re(d,l,f)),y={assembly:h.assembly,...m===void 0?{}:{kinds:m},maxDepth:vt(r.maxDepth),limit:Z(r.limit,"limit"),after:r.after?.trim()||void 0,direction:vn(r.direction),maxPaths:Z(r.maxPaths,"max-paths"),sample:Z(r.sample,"sample"),exemptIsolates:po(r.exemptIsolate),exemptIsolateTypes:po(r.exemptIsolateType),saveBaseline:r.saveBaseline===!0,summary:r.summary===!0,unbounded:r.full===!0};if(o==="index")return mo(await Qd(s,h.fingerprint,y,d.length,l,r),!1);let w=ho.has(o)?go(y.assembly,t):void 0,_=o==="paths"?go(y.assembly,n):void 0,b=yo(o,w,_,y),k=await Tn(s,h.fingerprint),E=k.results[b],I=h.memoize(b,()=>E!==void 0?structuredClone(E):_o(o,w,_,y,l)),P=An(d.length,k.exists);!I.reused&&E===void 0&&P&&await eu(s,h.fingerprint,k,b,I.value);let D=I.value.subcommand==="audit"?await Zd(s,h.fingerprint,I.value,y.saveBaseline):I.value;return D.cache={fingerprint:h.fingerprint.slice(0,12),assembly:h.assemblyReused?"hit":"miss",result:I.reused?"hit":"miss",durable:E!==void 0?"hit":P?"miss":"off"},mo(D,y.summary,"result_rows")}(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]="de8a82e1-0b02-5d5a-9086-686529a1ccab")}catch{}})();var wo="blocked_by",bo="blocks",tu=Object.freeze([wo,bo]),Pn="no-active-blocker";function R(e){return e.trim().toLowerCase()}function ge(e){let t=new Set,n=typeof e.blocked_by=="string"?R(e.blocked_by):"";n.length>0&&n!==Pn&&t.add(n);for(let r of e.dependencies??[]){let i=typeof r.id=="string"?R(r.id):"";r.kind===wo&&i.length>0&&i!==Pn&&t.add(i)}return[...t].sort((r,i)=>r.localeCompare(i))}function Nt(e){let t=new Map;for(let n of e){let r=R(n.id);r.length!==0&&t.set(r,new Set(ge(n)))}for(let n of e){let r=R(n.id);if(r.length!==0)for(let i of n.dependencies??[]){let o=i.kind===bo&&typeof i.id=="string"?R(i.id):"";if(o.length===0||o===Pn)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 ko(e,t){let n=R(e.id);return n.length>0?Nt(t).get(n)??ge(e):ge(e)}function jn(e,t,n,r){let i=e;return(typeof i.id=="string"?r?.get(R(i.id))??ko(i,[...t.values()]):ge(e)).map(s=>{let a=t.get(R(s));return a?{id:s,title:a.title,status:a.status,resolved:L(a.status,n)}:{id:s,title:null,status:null,resolved:!1}})}function Lt(e,t,n){return jn(e,t,n)}function Ue(e,t){let n=new Map(e.map(s=>[R(s.id),s])),r=Nt(e),i=new Set([...vo(t),...t.blocked_statuses]),o=new Set;for(let s of e){let a=C(s.status,t);if(!i.has(a))continue;(t.blocked_statuses.has(a)||jn(s,n,t,r).some(d=>!d.resolved))&&o.add(R(s.id))}return o}function vo(e){return e.active_statuses.size>0?e.active_statuses:new Set([e.open_status])}function nu(e,t,n){let r=[R(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(!L(s.status,n))return!0;r.push(R(s.id))}}}return!1}function ru(e){let t=new Map,n=new Map,r=new Map,i=Nt(e);for(let o of e){t.set(R(o.id),o);let s=typeof o.parent=="string"?o.parent.trim():"";if(s.length>0){let a=R(s),c=n.get(a)??[];c.push(o),n.set(a,c)}for(let a of i.get(R(o.id))){let c=R(a),d=r.get(c)??[];d.push(o.id),r.set(c,d)}}return{itemsById:t,childrenByParent:n,blockedByReverse:r,blockerIdsByItem:i}}function Un(e,t,n){let{itemsById:r,childrenByParent:i,blockedByReverse:o,blockerIdsByItem:s}=ru(t),a=new Set([...vo(n),...n.blocked_statuses]),c=new Set(t.filter(m=>!L(m.status,n)).map(m=>R(m.id))),d=[],u=[],l=0,f=0;for(let m of e){if(!a.has(C(m.status,n)))continue;if(l+=1,nu(m.id,i,n)){f+=1;continue}let h=jn(m,r,n,s).filter(b=>!b.resolved),y=(o.get(R(m.id))??[]).filter(b=>c.has(R(b))).sort((b,k)=>b.localeCompare(k)),w={item:m,open_blockers:h,unblocks:y},_=n.blocked_statuses.has(C(m.status,n));h.length===0&&!_?d.push(w):u.push(w)}return{ready:d,blocked:u,active_count:l,container_count:f}}(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]="cc271a73-9767-54bb-a142-d4d4569e3c6a")}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]="1035bd62-b012-5249-bd53-31b39f21b2d3")}catch{}})();function Bn(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 g(`${t.label} requires at least one non-empty value`,p.USAGE);let o=i.map(s=>t.normalize?.(s)??s);return[...new Set(o)]}function Be(e,t){let n=Bn(e,t);return n===void 0?void 0:new Set(n)}function xo(e,t,n="--type"){let r=Bn(e,{label:n});if(r===void 0)return;let i=r.map(o=>{let s=et(o,t);if(!s)throw new g(`${n} filter token "${o}" must be one of ${t.types.join("|")}`,p.USAGE);return s});return new Set(i)}function Eo(e,t="--priority"){let n=Bn(e,{label:t});if(n!==void 0)return new Set(n.map(r=>mt(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]="5b7b3eaf-a792-5f44-9981-8c82ce511070")}catch{}})();function Io(e,t){let n=e.trim().toLowerCase();return t.alias_to_id.get(n)??n}function Do(e){return{isTerminal(t){return e.terminal_statuses.has(Io(t,e))},classify(t){let n=Io(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 Gn(e){return j(e.acceptance_criteria)===void 0}function Kn(e){return!Number.isFinite(e.estimated_minutes)}function Ro(e,t){return t.isTerminal(e.status)?j(e.resolution)===void 0:!1}function iu(e){return j(e.reviewer)===void 0}function ou(e){return j(e.risk)===void 0}function su(e){return typeof e.confidence=="number"?!Number.isFinite(e.confidence):j(e.confidence)===void 0}function au(e){return j(e.sprint)===void 0}function cu(e){return j(e.release)===void 0}function zn(e){return!!(e.acMissing||e.estimatesMissing||e.resolutionMissing||e.reviewerMissing||e.riskMissing||e.confidenceMissing||e.sprintMissing||e.releaseMissing||e.metadataMissing)}function du(e,t,n){return[[t.acMissing,Gn(e)],[t.estimatesMissing,Kn(e)],[t.resolutionMissing,Ro(e,n)],[t.reviewerMissing,iu(e)],[t.riskMissing,ou(e)],[t.confidenceMissing,su(e)],[t.sprintMissing,au(e)],[t.releaseMissing,cu(e)]].every(([i,o])=>i!==!0||o)}function uu(e,t){return Gn(e)||Kn(e)||Ro(e,t)}function Ao(e,t,n){return zn(t)?!(!du(e,t,n)||t.metadataMissing&&!uu(e,n)):!0}var Hn=["acceptance_criteria","estimated_minutes","resolution","tags","parent"];function lu(e,t){switch(t){case"acceptance_criteria":return!Gn(e);case"estimated_minutes":return!Kn(e);case"resolution":return j(e.resolution)!==void 0;case"tags":return Array.isArray(e.tags)&&e.tags.length>0;default:return j(e.parent)!==void 0}}function fu(e,t,n){return t==="resolution"?n.isTerminal(e.status):!0}function mu(e,t){return t===0?100:Math.round(e/t*1e3)/10}function Co(){let e={};for(let t of Hn)e[t]={present:0,applicable:0,percent:100};return e}function So(e,t,n){for(let r of Hn){if(!fu(t,r,n))continue;let i=e[r];i.applicable+=1,lu(t,r)&&(i.present+=1)}}function To(e){for(let t of Hn){let n=e[t];n.percent=mu(n.present,n.applicable)}}function f_(e,t){let n=Co(),r={};for(let i of e){So(n,i,t);let o=r[i.type]??(r[i.type]=Co());So(o,i,t)}To(n);for(let i of Object.values(r))To(i);return{overall:n,by_type:r}}var pu={assignee:"(unassigned)",priority:"(no priority)",tag:"(untagged)",parent:"(unparented)",type:"(untyped)",status:"(no status)"};function gu(e){return pu[e]}function hu(){return{open:0,in_progress:0,blocked:0,draft:0,closed:0,canceled:0,other:0}}function yu(e,t,n){switch(t){case"assignee":return[j(e.assignee)??null];case"parent":return[j(e.parent)??null];case"type":return[j(e.type)??null];case"status":return[j(e.status)??null];case"priority":return[typeof e.priority=="number"?`P${e.priority}`:null];default:{let r=n.tagPrefix?.trim(),o=(Array.isArray(e.tags)?e.tags:[]).filter(s=>typeof s=="string"&&s.length>0&&(!r||s.startsWith(r)));return o.length>0?o:[null]}}}function m_(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 yu(a,t,r)){let u=d??"\0empty",l=i.get(u);l||(l={label:d??gu(t),key:d,buckets:hu(),total:0},i.set(u,l)),l.buckets[c]+=1,l.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]="03824e4b-562b-5e12-a89a-9dd091ae7fd3")}catch{}})();var Fe=["notes","learnings","files","docs","tests","comments","deps","body","linked_command"];function he(e){return Array.isArray(e)&&e.length>0}function _u(e){return typeof e=="string"&&e.trim().length>0}function wu(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 No(e,t){switch(t){case"notes":return he(e.notes);case"learnings":return he(e.learnings);case"files":return he(e.files);case"docs":return he(e.docs);case"tests":return he(e.tests);case"comments":return he(e.comments);case"deps":return he(e.dependencies);case"body":return _u(e.body);case"linked_command":return wu(e.tests)}}function Lo(e){return Fe.some(t=>e[t]!==void 0)}function Mo(e,t){for(let n of Fe){let r=t[n];if(r===void 0)continue;let i=No(e,n);if(r==="present"&&!i||r==="absent"&&i)return!1}return!0}function $o(e){return Fe.some(t=>t!=="body"&&e[t]!==void 0)}function Oo(e){return e.body!==void 0}function Fo(e,t){return t===0?100:Math.round(e/t*1e3)/10}function bu(){let e={};for(let t of Fe)e[t]={present:0,total:0,percent:100};return e}function g_(e){let t=bu(),n=e.length;for(let s of e)for(let a of Fe)No(s,a)&&(t[a].present+=1);for(let s of Fe)t[s].total=n,t[s].percent=Fo(t[s].present,n);let r=t.body,i=n-r.present,o={present:i,total:n,percent:Fo(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]="ec0c4c57-e3c2-54b3-bcf4-b4ab3b1d964e")}catch{}})();var ku=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}),Po=[{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"}],Ko=e=>{let t=Po.find(n=>e[n.presentKey]===!0&&e[n.absentKey]===!0);if(t)throw new g(`Cannot combine ${t.presentFlag} with ${t.absentFlag} for the same field.`,p.USAGE);return Object.fromEntries(Po.flatMap(n=>e[n.presentKey]===!0?[[n.field,"present"]]:e[n.absentKey]===!0?[[n.field,"absent"]]:[]))},jo=["priority","deadline","updated_at","created_at","title","parent"],Uo=["asc","desc"],vu=["id","title","status","type","priority","parent","updated_at"],xu=["id","status","type","title"],B_={list:"brief","list-all":"full","list-draft":"full","list-open":"brief","list-in-progress":"brief","list-blocked":"brief","list-closed":"full","list-canceled":"full"},Eu=["tree_depth","tree_parent","tree_children","tree_title"],zo=new Set(Zr);function Iu(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 g(`List source is incomplete: ${r} item document(s) and ${i} item directory/directories could not be read.`,p.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 Cu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.keys(e).length>0}var Su=[{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"}],Tu=[{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 Ho(e,t){for(let n of Su)t[n.key]===!0&&(e[n.summaryKey]=!0)}function qo(e,t){for(let n of Tu)t[n.key]===!0&&(e[n.summaryKey]=!0)}function Du(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 Ru(e){let t={};return Ho(t,e),t}function Au(e){let t={};return qo(t,e),t}var Fu=[{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"}],Nu=[{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"}],Lu=[{key:"filterAcMissing",summaryKey:"filter_ac_missing"},{key:"filterEstimatesMissing",summaryKey:"filter_estimates_missing"},{key:"filterResolutionMissing",summaryKey:"filter_resolution_missing"},{key:"filterMetadataMissing",summaryKey:"filter_metadata_missing"}],Mu="-7d";function $u(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"),Du(c,n,Fu),Vo(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),qo(c,n),Ho(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),Cu(a)&&(c.runtime_filters=a),c}function Wo(e,t,n){let r=L(e.status,n),i=L(t.status,n);if(r!==i)return r?1:-1;let o=e.priority-t.priority;if(o!==0)return o;let s=x(t.updated_at,e.updated_at);return s!==0?s:(e.id??"").localeCompare(t.id??"")}function Ou(e,t){return[...e].sort((n,r)=>Wo(n,r,t))}function Bo(e,t){if(e!==void 0)return oe(e,new Date,t)}function Ge(e,t){if(e==null)return;let n=String(e).trim();if(n.length!==0)return oe(n,new Date,t)}function Pu(e){let t=e.updatedAfter!=null&&String(e.updatedAfter).trim().length>0;if([e.today===!0,e.recent===!0,t].filter(r=>r).length>1)throw new g("Choose only one updated_at window: --today, --recent, or --updated-after.",p.USAGE);if(e.today===!0){let r=new Date;return r.setHours(0,0,0,0),r.toISOString()}return e.recent===!0?Ge(Mu,"recent"):Ge(e.updatedAfter,"updated-after")}function Vo(e,t){t.today===!0&&(e.today=!0),t.recent===!0&&(e.recent=!0)}function ju(e){if(e==null)return;let t=String(e).trim();if(t.length===0)throw new g("--ids requires at least one non-empty item ID",p.USAGE);let n=t.split(",").map(r=>r.trim()).filter(r=>r.length>0);if(n.length===0)throw new g("--ids requires at least one non-empty item ID",p.USAGE);return new Set(n)}function Xo(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 g("Offset filter must be a non-negative integer",p.USAGE);return n}function Uu(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 g("List --fields requires a comma-separated list of field names",p.USAGE);return[...new Set(t)]}function Bu(e){let t=e.compact===!0,n=e.brief===!0,r=e.full===!0,i=Uu(e.fields);if(Number(t)+Number(n)+Number(r)+ +(i!==void 0)>1)throw new g("List projection options are mutually exclusive. Use one of --compact, --brief, --full, or --fields.",p.USAGE);return r?{mode:"full",fields:[]}:n?{mode:"brief",fields:[...xu]}:t?{mode:"compact",fields:[...vu]}:i?{mode:"fields",fields:i}:{mode:"full",fields:[]}}function Ke(e){return e.startsWith("item.")?e.slice(5):e}function Gu(e,t){if(e.mode!=="fields")return;let n=new Set([...wr,"body",...Eu,...t]),r=e.fields.filter(i=>!n.has(Ke(i)));if(r.length>0)throw new g(`Unknown list --fields value(s): ${r.join(", ")}`,p.USAGE,{code:"unknown_field_projection",examples:["pm list-open --fields id,title,status,type,updated_at","pm list --fields id,title,parent,priority --limit 10","pm list-all --fields id,title,body --limit 5"]})}var Ku=new Map([["updated","updated_at"],["update","updated_at"],["modified","updated_at"],["created","created_at"],["create","created_at"]]);function zu(e){if(e===void 0)return;let t=e.trim().toLowerCase(),n=Ku.get(t);if(n)return n;if(!jo.includes(t))throw new g(`Sort field must be one of ${jo.join("|")} (aliases: updated->updated_at, created->created_at)`,p.USAGE);return t}function Hu(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(!Uo.includes(t))throw new g(`Sort order must be one of ${Uo.join("|")}`,p.USAGE);return t}function qu(e){return W(e,"--tree-depth")}function Wu(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(!t)throw new g("Assignee filter must be one of assigned|unassigned",p.USAGE);if(t!=="assigned"&&t!=="unassigned")throw new g(`Invalid assignee filter "${e}". Allowed: assigned|unassigned`,p.USAGE);return t}function Go(e,t){return Yr(e,t,{strict:!0})}function Yo(e){return Be(e,{label:"--tag",normalize:t=>t.toLowerCase()})}function Vu(e,t,n){let r=Yo(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 Xu(e,t){if(e&&[...e].some(n=>n.toLowerCase()==="none"||n.toLowerCase()==="null"))throw new g('--assignee no longer accepts "none" or "null". Use --assignee-filter unassigned.',p.USAGE);if(e!==void 0&&t==="unassigned")throw new g("Cannot combine --assignee with --assignee-filter unassigned",p.USAGE)}function Yu(e,t,n,r){let i=Be(t.assignee,{label:"--assignee"}),o=Wu(t.assigneeFilter);Xu(i,o);let s=ku(t),a=Ko(t);return{idsFilter:ju(t.ids),statusSet:e&&e.length>0?new Set(e):void 0,excludeTerminal:t.excludeTerminal===!0,typeFilter:xo(t.type,n),tagFilters:Yo(t.tag),priorityFilter:Eo(t.priority),deadlineBefore:Bo(t.deadlineBefore,"deadline-before"),deadlineAfter:Bo(t.deadlineAfter,"deadline-after"),updatedAfter:Pu(t),updatedBefore:Ge(t.updatedBefore,"updated-before"),createdAfter:Ge(t.createdAfter,"created-after"),createdBefore:Ge(t.createdBefore,"created-before"),assigneeFilter:i,assigneeModeFilter:o,parentFilter:t.parent?.trim(),treeEnabled:t.tree===!0,sprintFilter:Be(t.sprint,{label:"--sprint"}),releaseFilter:Be(t.release,{label:"--release"}),missingMetadataFilters:s,missingMetadataActive:zn(s),lifecycleClassifier:Do(r),contentFieldFilters:a,contentFiltersActive:Lo(a)}}function Ju(e,t,n){return Qu(e,t,n)&&Zu(e,t)&&el(e,t)&&tl(e,t)}function Qu(e,t,n){return t.idsFilter&&!t.idsFilter.has(e.id)||t.statusSet&&!t.statusSet.has(e.status)||t.excludeTerminal&&L(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 Zu(e,t){return kr(e,t)}function el(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 tl(e,t){return t.parentFilter!==void 0&&!t.treeEnabled&&e.parent!==t.parentFilter||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 nl(e,t,n,r){return!(!Ju(e,t,n)||t.missingMetadataActive&&!Ao(e,t.missingMetadataFilters,t.lifecycleClassifier)||t.contentFiltersActive&&!Mo(e,t.contentFieldFilters)||!ct(e,r))}function rl(e,t,n,r,i,o){let s=Yu(t,n,r,i);return e.filter(a=>nl(a,s,i,o))}function Mt(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function il(e,t,n){let r=e,i=typeof r.title=="string"?r.title:"",o=Mt(typeof r.parent=="string"?r.parent:void 0)??null;return{...e,tree_depth:t,tree_parent:o,tree_children:n,tree_title:`${" ".repeat(t)}${i}`}}function ol(e,t,n){let r=new Map,i=new Map;for(let d of e){r.set(d.id,d);let u=Mt(d.parent);if(!u)continue;let l=i.get(u);l?l.push(d):i.set(u,[d])}let o=t?[...i.get(t)??[]]:e.filter(d=>{let u=Mt(d.parent);return!u||!r.has(u)}),s=[],a=new Set,c=(d,u)=>{if(a.has(d.id))return;a.add(d.id);let l=i.get(d.id)??[];if(s.push(il(d,u,l.length)),!(n!==void 0&&u>=n))for(let f of l)c(f,u+1)};for(let d of o)c(d,0);return s}function sl(e,t){return e===t?0:e===null?1:t===null?-1:e.localeCompare(t)}function al(e,t){return e===t?0:e===null?1:t===null?-1:x(e,t)}function cl(e,t,n){switch(n){case"priority":return e.priority-t.priority;case"deadline":return al(e.deadline??null,t.deadline??null);case"updated_at":return x(e.updated_at,t.updated_at);case"created_at":return x(e.created_at,t.created_at);case"title":return(e.title??"").localeCompare(t.title??"");case"parent":return sl(e.parent??null,t.parent??null);default:return 0}}function dl(e,t,n,r){return t?[...e].sort((i,o)=>{let s=cl(i,o,t);if(s!==0)return n==="desc"?-s:s;let a=Wo(i,o,r);return n==="desc"?-a:a}):Ou(e,r)}function ul(e,t,n=!1){let r=Ke(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 Jo(e,t,n=!1){return t.mode==="full"?e:e.map(r=>{let i={};for(let o of t.fields)i[o]=ul(r,o,n);return i})}function ll(e){let t=[];for(let n of e)t.push(n.metadata_key);return t}function fl(e,t){if(e.noTruncate!==!0)return W(e.limit)??(t>=1e4?20:void 0)}function ml(e,t,n){return t.after===void 0?Xo(t.offset)??0:Ee(e,t.after,n,r=>r.id)}function Qo(e,t,n){return{...e!==void 0?{applied_limit:e}:{},has_more:t,truncated:t,next_cursor:n??null}}async function pl(e,t){let n=S(process.cwd(),t.path);if(!await A(O(n)))throw new g(`Tracker is not initialized at ${n}. Run pm init first.`,p.NOT_FOUND);let r=await T(n),i=z(r.schema),o=tt(r.schema),s=Bu(e);return Gu(s,ll(o.definitions)),{pmRoot:n,settings:r,statusRegistry:i,runtimeFieldFilters:at(e,o,"list"),typeRegistry:$(r,F()),projection:s}}async function gl(e,t,n){let r=t.projection.fields.some(c=>Ke(c)==="body"),i=t.projection.mode==="full"||t.projection.fields.some(c=>zo.has(Ke(c))),o=Ko(e),s=$o(o),a=Oo(o);return e.includeBody||r||a?await ri(t.pmRoot,t.settings.item_format,t.typeRegistry.type_to_folder,n,t.settings.schema):i||s?await ni(t.pmRoot,t.settings.item_format,t.typeRegistry.type_to_folder,n,t.settings.schema):await Q(t.pmRoot,t.settings.item_format,t.typeRegistry.type_to_folder,n,t.settings.schema)}function hl(e){let t=zu(e.sort),n=Hu(e.order)??"asc",r=e.tree===!0;if(!r&&e.treeDepth!==void 0)throw new g("List --tree-depth requires --tree",p.USAGE);if(!t&&e.order!==void 0)throw new g("List --order requires --sort",p.USAGE);return{sortField:t,sortOrder:n,treeEnabled:r,treeDepth:r?qu(e.treeDepth):void 0,parentRoot:r?Mt(e.parent):void 0}}function yl(e,t,n){let r=Go(t.status,n),i=r??Go(e,n),o=Xr(t.status),s=r||o?{...t,excludeTerminal:!1}:t,a=o?"all":i===void 0?s.excludeTerminal===!0?null:"all":i.length===1?i[0]:i;return{resolvedStatus:i,explicitAllStatuses:o,effectiveOptions:s,filtersStatus:a}}function _l(e,t,n,r,i){if(t.after!==void 0&&t.offset!==void 0)throw new g("List --after cannot be combined with --offset.",p.USAGE);let o=fl(t,e.length),s=ml(e,t,i),a=o===void 0?e.slice(s):e.slice(s,s+o),c=Jo(a,n,r),d=e.length,u=a.length>0&&s+a.length<d,l=u&&a.length>0?se(i,a[a.length-1].id,s+a.length-1):void 0;return{projected:c,totalMatched:d,pageExtras:Qo(o,u,l)}}function Zo(e,t,n){return de("list",{status:e,options:rt(t,ii),sort:n.sortField??"default",order:n.sortOrder,tree:n.treeEnabled,tree_depth:n.treeDepth??null})}async function wl(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","noTruncate"]),s=[n.projection.mode==="full",n.projection.fields.some(h=>{let y=Ke(h);return y==="body"||zo.has(y)})].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,Tr(),Object.keys(n.runtimeFieldFilters).length>0,Object.entries(t).some(([h,y])=>y!==void 0&&!o.has(h))].includes(!0))return null;let c=await Se(n.pmRoot,[...new Set(Object.values(n.typeRegistry.type_to_folder))]);if(!c)return null;let d=W(t.limit),u=Xo(t.offset)??0,l=await Qr({pmRoot:n.pmRoot,expectedSourceCursor:c.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:d,offset:u}});if(!l)return null;let f=l.items.length>0&&u+l.items.length<l.total,m=f?se(Zo(r.filtersStatus,t,i),l.items.at(-1).id,u+l.items.length-1):void 0;return{projected:Jo(l.items,n.projection,!1),totalMatched:l.total,pageExtras:Qo(d,f,m)}}function bl(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 u=n;for(let l of Nu){let f=u[l.optionKey];f!=null&&(d[l.summaryKey]=f)}for(let l of Lu)u[l.key]===!0&&(d[l.summaryKey]=!0);return Object.assign(d,Au(n),Ru(n)),Vo(d,n),r&&(d.no_truncate=!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 ze(e,t,n){let r=await pl(t,n),i=[],o=hl(t),s=yl(e,t,r.statusRegistry),a=t.noTruncate===!0,c=await wl({options:t,runtime:r,statusSelection:s,ordering:o}),d=c;if(!d){let y=await gl(t,r,i);Vu(y,t.tag,i);let w=rl(y,s.resolvedStatus,s.effectiveOptions,r.typeRegistry,r.statusRegistry,r.runtimeFieldFilters),_=t.dependencyBlocked===!0?(()=>{let E=Ue(y,r.statusRegistry);return w.filter(I=>E.has(I.id.trim().toLowerCase()))})():w,b=dl(_,o.sortField,o.sortOrder,r.statusRegistry),k=o.treeEnabled?ol(b,o.parentRoot,o.treeDepth):b;d=_l(k,t,r.projection,o.treeEnabled,Zo(s.filtersStatus,t,o))}let u=G(),l=[...new Set(i)].sort((y,w)=>y.localeCompare(w)),f=Iu(l,c!==null,t.strictRead===!0),m=r.projection.mode==="full"?null:[...r.projection.fields];if(r.projection.mode==="compact"&&t.compact===!0){let y=$u({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:y,projection:{mode:"compact",fields:m},...l.length>0?{warnings:l}:{}}}return{items:d.projected,count:d.projected.length,total:d.totalMatched,...d.pageExtras,completeness:f,filters:bl({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"},now:u,...l.length>0?{warnings:l}:{}}}import{encode as kl}from"@toon-format/toon";(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]="f1677c6e-872e-5c42-ae3d-f73f4ec73616")}catch{}})();var qn=["agenda","day","week","month"],Wn=["markdown","toon","json"],vl=["sun","mon","tue","wed","thu","fri","sat"],xl=365,El=365,ns=28,Il=1e3;function Vn(e,t){if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw new g(`${t} must be a non-negative integer`,p.USAGE);return n}function Cl(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 g("Calendar include filter must not be empty",p.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 g("Calendar include filter must be deadlines|reminders|events|scheduled|all",p.USAGE)}return r}function rs(e,t){let n;for(let r of t){let i=vr(e,r,2);i!==null&&(n===void 0||i<n.distance)&&(n={choice:r,distance:i})}return n?.choice}function Sl(e){if(!e)return"agenda";let t=e.trim().toLowerCase();if(!qn.includes(t)){let n=rs(t,qn);throw new g(`Calendar view must be one of ${qn.join("|")}${n?`. Did you mean "${n}"?`:"."}`,p.USAGE)}return t}function Tl(e){if(!e)return;let t=e.trim().toLowerCase();if(!Wn.includes(t)){let n=rs(t,Wn);throw new g(`Calendar format must be one of ${Wn.join("|")}${n?`. Did you mean "${n}"?`:"."}`,p.USAGE)}return t}function W_(e,t){let n=Tl(e.format);if(t.json&&n&&n!=="json")throw new g("Cannot combine --json with --format markdown|toon",p.USAGE);return t.json?"json":n??"markdown"}function Dl(e,t){if(e===void 0)return;let n=N(e,t);if(!n){let r=t.definitions.map(i=>i.id);throw new g(`Calendar status filter must be one of ${r.join("|")}`,p.USAGE)}return n}function Rl(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(!t)throw new g("Calendar assignee filter must be one of assigned|unassigned",p.USAGE);if(t!=="assigned"&&t!=="unassigned")throw new g(`Invalid calendar assignee filter "${e}". Allowed: assigned|unassigned`,p.USAGE);return t}function $t(e){return new Date(e).toISOString().slice(0,10)}function is(e,t){if(!t||t==="UTC")return $t(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 $t(e)}function Qn(e){let t=new Date(e);return new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate(),0,0,0,0)).toISOString()}function ae(e,t){let n=new Date(e);return new Date(n.getTime()+t*24*60*60*1e3).toISOString()}function os(e){let t=new Date(Qn(e)),n=t.getUTCDay(),r=n===0?-6:1-n;return ae(t.toISOString(),r)}function Al(e){let t=new Date(e);return new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),1,0,0,0,0)).toISOString()}function Fl(e){let t=new Date(e);return new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth()+1,1,0,0,0,0)).toISOString()}function Nl(e,t){return x(e,t)>=0?e:t}function es(e){return Object.fromEntries([...e.entries()].sort(([t],[n])=>t.localeCompare(n)))}function ts(e,t){e.set(t,(e.get(t)??0)+1)}function Ll(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)=>be(r)-be(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 ss(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 as(e){return vl[new Date(e).getUTCDay()]}function Ml(e){let t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():null}function $l(e){let t=new Set;for(let n of e??[]){let r=Ml(n);r&&t.add(r)}return t}function Ol(e,t,n,r,i){let o=e??ae(n,-(r??El)),s=t??ae(e??n,i??xl);return{start:o,end:x(s,o)>0?s:ae(o,1)}}function Pl(e,t,n,r){let i=t.by_weekday!==void 0?[...t.by_weekday]:[as(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??Il,interval:t.interval??1,countLimit:t.count??Number.POSITIVE_INFINITY,until:t.until,excluded:$l(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)=>be(s)-be(a)),sortedMonthDays:[...new Set(o)].sort((s,a)=>s-a),occurrences:[],produced:0}}function Ot(e,t){return x(t,e.startAt)<0?"continue":e.until&&x(t,e.until)>0||x(t,e.window.end)>=0?"stop":e.excluded.has(t)?"continue":(e.produced+=1,x(t,e.window.start)>=0&&e.occurrences.push(t),e.produced>=e.countLimit||e.occurrences.length>=e.maxOccurrences?"stop":"continue")}function Pt(e,t){let n=as(t),r=new Date(t).getUTCDate(),i=!e.weekdayFilter||e.weekdayFilter.has(n),o=!e.monthDayFilter||e.monthDayFilter.has(r);return i&&o}function jl(e){let t=e.startAt;for(let n=0;n<e.maxOccurrences&&!(Pt(e,t)&&Ot(e,t)==="stop");n+=1)t=ae(t,e.interval);return e.occurrences}function Ul(e,t,n){let r=be(n),i=ae(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 Bl(e){let t=os(e.startAt);for(let n=0;n<e.maxOccurrences;n+=1){let r=ae(t,n*e.interval*7);for(let i of e.sortedWeekdays){let o=Ul(e,r,i);if(Pt(e,o)&&Ot(e,o)==="stop")return e.occurrences}}return e.occurrences}function Gl(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=ss(i.getUTCFullYear(),i.getUTCMonth(),o,e.startDate);if(!(!s||!Pt(e,s))&&Ot(e,s)==="stop")return e.occurrences}}return e.occurrences}function Kl(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=ss(i,n,o,e.startDate);if(!(!s||!Pt(e,s))&&Ot(e,s)==="stop")return e.occurrences}}return e.occurrences}function zl(e,t,n,r){let i=Pl(e,t,n,r);return t.freq==="daily"?jl(i):t.freq==="weekly"?Bl(i):t.freq==="monthly"?Gl(i):Kl(i)}function cs(e){return[...e].sort((t,n)=>{let r=x(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 Zn(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 Hl(e){return e.deadline?{at:e.deadline,date:$t(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,...Zn(e),item_deadline:e.deadline}:null}function ql(e){return(e.reminders??[]).map(t=>({at:t.at,date:$t(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,...Zn(e)}))}function Wl(e,t){if(!t)return null;let n=Date.parse(t)-Date.parse(e);return Number.isFinite(n)&&n>0?n:null}function Vl(e,t,n){return t.recurrence&&n!==null?new Date(new Date(e).getTime()+n).toISOString():t.end_at??null}function Xl(e,t,n,r){let i=Ll(t.recurrence),o=Wl(t.start_at,t.end_at);return(t.recurrence?zl(t.start_at,t.recurrence,n,r):[t.start_at]).map(a=>({at:a,date:t.all_day===!0?a.slice(0,10):is(a,t.timezone),kind:"event",reminder_text:t.description??null,event_title:t.title??e.title,event_end:Vl(a,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,...Zn(e)}))}function Yl(e,t,n,r){let i=[];for(let o of e){let s=n.has("deadlines")?Hl(o):null;s&&i.push(s),n.has("reminders")&&i.push(...ql(o));for(let a of n.has("events")?o.events??[]:[])i.push(...Xl(o,a,t,r))}return cs(i)}function Jl(e,t,n,r,i){let o=vi(t.type,n),s=t.tag?.trim().toLowerCase(),a=mt(t.priority),c=Dl(t.status,r),d=t.assignee?.trim(),u=Rl(t.assigneeFilter),l=t.sprint?.trim(),f=t.release?.trim();if(d&&(d.toLowerCase()==="none"||d.toLowerCase()==="null"))throw new g('--assignee no longer accepts "none" or "null". Use --assignee-filter unassigned.',p.USAGE);if(d!==void 0&&u==="unassigned")throw new g("Cannot combine --assignee with --assignee-filter unassigned",p.USAGE);return e.filter(m=>Ql(m,{typeFilter:o,tagFilter:s,priorityFilter:a,statusFilter:c,assigneeFilter:d,assigneeModeFilter:u,sprintFilter:l,releaseFilter:f,runtimeFieldFilters:i}))}function Ql(e,t){return Zl(e,t)&&ef(e,t)&&ct(e,t.runtimeFieldFilters)}function Zl(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 ef(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 tf(e,t,n){return!(t&&x(e.at,t)<0||n&&x(e.at,n)>=0)}function Xn(e,t,n){return e.trim().toLowerCase()==="today"?Qn(t):oe(e,new Date(t),n)}function nf(e,t,n){let r=t.date?Xn(t.date,n,"--date"):n,i=t.past===!0,o=t.fullPeriod===!0,s=t.from?Xn(t.from,n,"--from"):void 0,a=t.to?Xn(t.to,n,"--to"):void 0;if(s&&a&&x(s,a)>=0)throw new g("Calendar --from must be before --to",p.USAGE);if(e!=="agenda"&&(t.from!==void 0||t.to!==void 0))throw new g("--from and --to are only supported for --view agenda",p.USAGE);if(e==="agenda")return rf(r,t,n,i,o,s,a);if(e==="day"){let d=Qn(r);return Yn(r,n,i,o,d,ae(d,1))}if(e==="week"){let d=os(r);return Yn(r,n,i,o,d,ae(d,7))}let c=Al(r);return Yn(r,n,i,o,c,Fl(r))}function rf(e,t,n,r,i,o,s){if(i)throw new g("--full-period is only supported for --view day|week|month. For agenda windows, use --from and --to.",p.USAGE);return{anchor:e,start:o??(t.date?e:r?void 0:n),end:s,fullPeriod:!1}}function Yn(e,t,n,r,i,o){let s=n||r;return{anchor:e,start:s?i:Nl(i,t),end:o,periodStart:i,periodEnd:o,fullPeriod:s}}function of(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:cs(r)}))}function sf(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),ts(n,c.item_type),ts(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:es(n),by_status:es(r),recurring_events:a}}function af(e){let t=e.start??"unbounded",n=e.end??"unbounded";return`${t} -> ${n}`}function ds(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 Jn(e){let t=Object.entries(e);return t.length===0?"empty":t.map(([n,r])=>`${n}=${r}`).join(", ")}function cf(e){return e.event_end?e.event_all_day===!0?e.event_end.slice(0,10):e.date===is(e.event_end,e.event_timezone)?ds(e.event_end,e.event_timezone):e.event_end:null}function df(e){let t=`${ds(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 o=cf(e);return o&&n.push(`end=${o}`),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 V_(e){let t=[];if(t.push(`# pm calendar (${e.view})`),t.push(""),t.push(`- now: ${e.now}`),t.push(`- window: ${af(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(`- by-kind: ${Jn(e.summary.by_kind)}`),t.push(`- by-type: ${Jn(e.summary.by_type)}`),t.push(`- by-status: ${Jn(e.summary.by_status)}`),t.push(`- recurring-events: ${e.summary.recurring_events}`),t.push(""),e.events.length===0)return t.push("No calendar events matched the selected filters."),t.join(`
|
|
2
|
+
`);for(let n of e.days){t.push(`## ${n.date} (${n.count})`);for(let r of n.events)t.push(`- ${df(r)}`);t.push("")}if(e.warnings&&e.warnings.length>0){t.push("### warnings");for(let n of e.warnings)t.push(`- ${n}`);t.push("")}return uf(t.join(`
|
|
3
|
+
`))}function X_(e){return kl(e)}function uf(e){let t=e.length;for(;t>0&&e[t-1]===`
|
|
4
|
+
`;)t-=1;return e.slice(0,t)}function lf(e){let t=G(),n=Sl(e.view),r=nf(n,e,t),i=W(e.limit),o=Cl(e.include),s=Vn(e.recurrenceLookaheadDays,"Calendar recurrence lookahead days"),a=Vn(e.recurrenceLookbackDays,"Calendar recurrence lookback days"),c=Vn(e.occurrenceLimit,"Calendar occurrence limit");if(c!==void 0&&c<1)throw new g("Calendar occurrence limit must be >= 1",p.USAGE);let d=o.has("events")&&!o.has("deadlines")&&!o.has("reminders"),u=e.to!==void 0||s!==void 0||a!==void 0||c!==void 0,l=d&&!u;return{nowValue:t,view:n,rangeBounds:r,limit:i,includeSources:o,occurrenceLimit:c,recurrenceLookaheadDays:l?ns:s,recurrenceLookbackWindowDays:l&&a===void 0?0:a,eventsOnlyCapApplied:l}}function ff(e,t){t&&e.push(`recurring_events_default_cap_applied:lookback=0d,lookahead=${ns}d -- use --recurrence-lookback-days/--recurrence-lookahead-days or --to for wider range`)}function mf(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 pf(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 us(e,t){let n=S(process.cwd(),t.path);if(!await A(O(n)))throw new g(`Tracker is not initialized at ${n}. Run pm init first.`,p.NOT_FOUND);let r=lf(e),i=await T(n),o=z(i.schema),s=tt(i.schema),a=at(e,s,"calendar"),c=$(i,F()),d=[];ff(d,r.eventsOnlyCapApplied);let u=await Q(n,i.item_format,c.type_to_folder,d,i.schema),l=Jl(u,e,c,o,a),f=Ol(r.rangeBounds.start,r.rangeBounds.end,r.nowValue,r.recurrenceLookbackWindowDays,r.recurrenceLookaheadDays),h=Yl(l,f,r.includeSources,r.occurrenceLimit).filter(b=>tf(b,r.rangeBounds.start,r.rangeBounds.end)),y=r.limit===void 0?h:h.slice(0,r.limit),w=of(y),_=[...new Set(d)].sort((b,k)=>b.localeCompare(k));return{view:r.view,output_default:"markdown",now:r.nowValue,anchor:r.rangeBounds.anchor,range:pf(e,r.rangeBounds),filters:mf(e,a),summary:sf(y),events:y,days:w,..._.length>0?{warnings:_}:{}}}(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]="1f898377-b606-5bfd-932d-6ce5f2f9c717")}catch{}})();var er=["structural","recency","activity_density","graph_proximity","claim_focus","priority_pressure","risk_pressure","deadline_pressure","knowledge_density","author_affinity","usage_affinity","semantic_similarity"],gf=Symbol("no-context-author"),hf=Symbol("no-item-assignee");function ls(e,t){if(typeof e!="string")return t;let n=e.trim().toLowerCase();return n.length>0?n:t}function yf(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 _f(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 wf(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 jt(e,t,n){return e?.[t]??n}function Ut(e,t){let n=d=>{if(typeof d!="string")return"";try{return oe(d,new Date(Number.NaN),"updated_at")}catch{return""}},r=[...e].sort((d,u)=>{let l=n(d.updated_at),f=n(u.updated_at);return x(f,l)||d.id.localeCompare(u.id)}),i=new Map(r.map((d,u)=>[d.id,u])),o=Math.max(e.length-1,1),s=ls(t.author,gf),a=N("in_progress",t.statusRegistry),c=Date.parse(t.now);return e.map(d=>{let u=ls(d.assignee,hf)===s,l=(d.comments?.length??0)+(d.notes?.length??0)+(d.learnings?.length??0);return{id:d.id,item:d,signals:{recency:e.length===1?1:1-i.get(d.id)/o,activity_density:t.activityDensity?.[d.id],graph_proximity:jt(t.graphProximity,d.id,d.parent?.3:0),claim_focus:jt(t.claimFocus,d.id,C(d.status,t.statusRegistry)===a?1:u?.75:0),priority_pressure:yf(d.priority,4),risk_pressure:wf(d.risk),deadline_pressure:_f(d.deadline,c),knowledge_density:jt(t.knowledgeDensity,d.id,Math.min(l/5,1)),author_affinity:jt(t.authorAffinity,d.id,u?1:0),usage_affinity:t.usageAffinity?.[d.id],semantic_similarity:t.semanticSimilarity?.[d.id]}}})}var bf="context_relevance",kf={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},vf=new TextEncoder;function xf(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"||!er.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 Ef(e){let t={...kf};for(let[n,r]of Object.entries(e??{}))r!==void 0&&er.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 ms(e,t={}){xf(e);let n=Ef(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=er.filter(a=>i.has(a)),s=e.map((a,c)=>{let d={structural:e.length===1?1:1-c/r,...a.signals},u={},l=0,f=0;for(let m of o){let h=d[m];if(h===void 0)continue;let y=h*n[m];u[m]=y,l+=y,f+=n[m]}return{...a,baseline_rank:c+1,rank:0,score:f===0?0:l/f,contributions:u}});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 If(e,t={}){let n=ms(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 Bt(e,t,n={}){let r=ms(t,n),i=await Dr(bf,{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 If(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 Cf=["ndcg","reciprocal_rank","required_recall","continuity_coverage","token_budget_adherence"];function fs(e,t){return e.length===0?1:e.filter(n=>t.has(n)).length/e.length}function Sf(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,u)=>u-d).slice(0,n.length||1),i=d=>d.reduce((u,l,f)=>u+(2**l-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:fs(e.required_ids??[],a),continuity_coverage:fs(e.continuity_ids??[],a),token_budget_adherence:c?1:e.token_budget/e.actual_tokens,within_token_budget:c}}function Tf(e){return Math.ceil(vf.encode(JSON.stringify(e)).byteLength/4)}function Df(e){return Math.round(e*1e4)/1e4}function Rf(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 Af(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}):await t.next({...e.options,explainRanking:!0}),{rankedIds:r,attribution:i}=Rf(n,e.surface),o={...n,ranking:void 0},s=Tf(o);return{id:e.id,surface:e.surface,rationale:e.rationale,ranked_ids:r,actual_tokens:s,metrics:Sf({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 Ff(e,t){if(e.length===0)throw new TypeError("Context evaluation requires at least one scenario report");let n=Cf;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,Df(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 ew(e,t,n){let r=[];for(let i of e)r.push(await Af(i,t));return Ff(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]="b5c90a16-c075-5dc6-a326-ad2da7a6ef6d")}catch{}})();var Nf={balanced:{redundancyPenalty:.35,uncertaintyPenalty:.2},context:{redundancyPenalty:.45,uncertaintyPenalty:.15},next:{redundancyPenalty:.25,uncertaintyPenalty:.3}},Lf=["identity","summary","full"];function Mf(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=Lf.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 $f(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=Nf[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 Of(e){let t=new Set;for(let n of e){if(Mf(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 Pf(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],u=n(c)/c.token_costs.identity,l=d===void 0?Number.NEGATIVE_INFINITY:n(d)/d.token_costs.identity;(u>l||u===l&&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 jf(e){let t=new Set,n=[],r=e.tokenBudget,i=d=>{let u=d.lineage??d.cluster,l=u&&t.has(u)?1-e.redundancyPenalty:1;return Math.max(0,(d.score-e.uncertaintyPenalty*(d.uncertainty??0))*l)},o=d=>{let u=d.token_costs.identity;n.push({...d,projection:"identity",tokens:u,marginal_value:i(d)}),r-=u;let l=d.lineage??d.cluster;l&&t.add(l)};for(let d of e.ordered.filter(u=>u.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=Pf(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 Uf(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 ps(e,t){let n=$f(t),r=Of(e),i=t.readClock??performance.now.bind(performance),o=t.latencyBudgetMs===void 0?Number.POSITIVE_INFINITY:i()+t.latencyBudgetMs,s=jf({ordered:r,tokenBudget:t.tokenBudget,redundancyPenalty:n.redundancy,uncertaintyPenalty:n.uncertainty,deadline:o,readClock:i}),{included:a}=s,c=Uf(a,s.remaining);a.sort((u,l)=>u.rank-l.rank||u.id.localeCompare(l.id));let d=new Set(a.map(u=>u.id));return{included:a,omitted_ids:r.filter(u=>!d.has(u.id)).map(u=>u.id),token_budget:t.tokenBudget,used_tokens:t.tokenBudget-c,remaining_tokens:c,complete:s.selectionComplete&&a.length===e.length&&a.every(u=>u.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{randomUUID as Bf}from"node:crypto";import{appendFile as Gf,mkdir as Kf,readFile as zf,rename as Hf,stat as qf,writeFile as Wf}from"node:fs/promises";import gs 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]="5f4ccd28-a001-54aa-8378-893025c69b96")}catch{}})();var hs=2048,ys=30,_s=864e5,Vf=262144,Xf="context-usage-ledger",te=class extends TypeError{code="context_usage_validation_failed";constructor(t){super(t),this.name="ContextUsageValidationError"}};function ws(e){return gs.join(e,"runtime","context-usage.jsonl")}function He(e){let t=e.now??new Date().toISOString(),n=Date.parse(t);if(!Number.isFinite(n))throw new te("Context usage now must be a valid timestamp");return{iso:new Date(n).toISOString(),ms:n}}async function bs(e){try{let n=(await zf(ws(e.pmRoot),"utf8")).split(`
|
|
5
|
+
`).filter(Boolean).flatMap(s=>{try{return[JSON.parse(s)]}catch{return[]}}),r=e.maxEvents??hs,i=e.retentionDays??ys,o=He(e).ms-i*_s;return n.filter(s=>Date.parse(s.at)>=o).slice(-r)}catch{return[]}}async function ks(e,t){let n=e.maxEvents??hs,r=e.retentionDays??ys;if(!Number.isInteger(n)||n<1||!Number.isFinite(r)||r<=0)throw new te("Context usage retention requires positive maxEvents and retentionDays");let i=ws(e.pmRoot),o=gs.dirname(i),s=await Ce(e.pmRoot,Xf,30,`context-usage:${process.pid}`,!1,!1,3e3);try{if(await Kf(o,{recursive:!0}),await Gf(i,t.map(u=>`${JSON.stringify(u)}
|
|
6
|
+
`).join(""),"utf8"),!(e.maxEvents!==void 0||e.retentionDays!==void 0)&&(await qf(i)).size<=Vf)return;let c=await bs(e),d=`${i}.${process.pid}.${Bf()}.tmp`;await Wf(d,`${c.map(u=>JSON.stringify(u)).join(`
|
|
7
|
+
`)}
|
|
8
|
+
`,"utf8"),await Hf(d,i)}finally{await s()}}async function vs(e,t){await ks(e,[t])}async function Gt(e){if(!(process.env.PM_CONTEXT_USAGE_DISABLED==="1"||e.enabled===!1)){if(!e.author.trim()||e.rows.some(t=>!t.id.trim()||!Number.isInteger(t.rank)||t.rank<1))throw new te("Context usage serving requires an author and valid ranked rows");await vs(e,{kind:"serve",at:He(e).iso,author:e.author.trim(),surface:e.surface,profile:e.profile.trim()||"balanced",rows:e.rows})}}async function aw(e){if(!(process.env.PM_CONTEXT_USAGE_DISABLED==="1"||e.enabled===!1)){if(!e.author.trim()||!e.itemId.trim()||!e.intent.trim())throw new te("Context usage touch requires author, itemId, and intent");await vs(e,{kind:"touch",at:He(e).iso,author:e.author.trim(),item_id:e.itemId.trim(),intent:e.intent.trim()})}}async function cw(e){if(process.env.PM_CONTEXT_USAGE_DISABLED==="1"||e.enabled===!1||e.itemIds.length===0)return;let t=e.author.trim(),n=e.intent.trim();if(!t||!n)throw new te("Context usage touch requires author and intent");let r=new Set;for(let s of e.itemIds){if(typeof s!="string")throw new te("Context usage touch requires string itemIds");let a=s.trim();if(!a)throw new te("Context usage touch requires non-empty itemId");r.add(a)}let i=He(e).iso,o=[...r].map(s=>({kind:"touch",at:i,author:t,item_id:s,intent:n}));await ks(e,o)}function Yf(e,t,n,r){return e.find(({entry:i,time:o})=>i.item_id===t&&o>=n&&o-n<=r)?.time}async function Kt(e){if(process.env.PM_CONTEXT_USAGE_DISABLED==="1"||e.enabled===!1)return{affinity:{},positive_judgments:0,serving_events:0};let t=await bs(e),n=He(e).ms,r=(e.horizonHours??24)*36e5;if(!Number.isFinite(r)||r<=0)throw new te("Context usage horizonHours must be positive");let i=e.author.trim(),o=t.filter(l=>l.kind==="touch"&&l.author===i).map(l=>({entry:l,time:Date.parse(l.at)})),s=new Map,a=0,c=0;for(let l of t){if(l.kind!=="serve"||l.author!==i)continue;a+=1;let f=Date.parse(l.at);for(let m of l.rows){if(!m.included)continue;let h=Yf(o,m.id,f,r);if(h===void 0)continue;c+=1;let y=Math.max(0,(n-h)/_s);s.set(m.id,(s.get(m.id)??0)+Math.exp(-y/14))}}let d=Math.max(0,...s.values());return{affinity:Object.fromEntries([...s.entries()].map(([l,f])=>[l,.05+.95*(d>0?f/d:0)])),positive_judgments:c,serving_events:a}}import qe from"node:fs/promises";import We from"node:path";import{createHash as Jf,randomUUID as Qf}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]="2a0f64cf-f6a4-5304-921d-c83b98d3a31f")}catch{}})();var tr=1,nr=1,xs=["recency","activity_density","graph_proximity","priority_pressure","risk_pressure","knowledge_density"],Zf={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 zt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Es(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=1}function em(e){let t={};for(let n of xs){let r=e[n];if(r!==void 0){if(!Es(r))throw new TypeError(`Context relevance signal ${n} must be a finite number from 0 to 1`);t[n]=r}}return t}function tm(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 nm(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 rm(e,t){return{...t,activityDensity:t.activityDensity??tm(e,n=>(n.comments?.length??0)+(n.notes?.length??0)+(n.learnings?.length??0)+(n.test_runs?.length??0)),graphProximity:t.graphProximity??nm(e)}}function im(e){if(!zt(e)||typeof e.id!="string"||!zt(e.signals))return null;let t={},n=new Set(xs);for(let[r,i]of Object.entries(e.signals)){if(!n.has(r)||!Es(i))return null;t[r]=i}return{id:e.id,signals:t}}function om(e){if(!zt(e)||e.format_version!==tr||e.signal_set_version!==nr||typeof e.source_cursor!="string"||e.source_cursor.trim().length===0||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=e.items.map(im);if(t.some(r=>r===null))return null;let n=t;return new Set(n.map(r=>r.id)).size!==n.length||n.some(r=>r.id.trim().length===0)?null:{format_version:tr,signal_set_version:nr,source_cursor:e.source_cursor,generated_at:e.generated_at,source:e.source,items:n.sort((r,i)=>r.id.localeCompare(i.id))}}function sm(e,t){if(typeof t.sourceCursor!="string"||t.sourceCursor.trim().length===0)throw new TypeError("Context signal source cursor must be non-empty");if(!Number.isFinite(Date.parse(t.now)))throw new TypeError("Context signal snapshot clock must be a valid timestamp");if(t.source!=="derived_index"&&t.source!=="scan_fallback")throw new TypeError("Context signal snapshot source must be derived_index or scan_fallback");let n=Ut(e,rm(e,t)).map(({id:r,signals:i})=>({id:r,signals:em(i)})).sort((r,i)=>r.id.localeCompare(i.id));return Object.freeze({format_version:tr,signal_set_version:nr,source_cursor:t.sourceCursor,generated_at:t.now,source:t.source,items:Object.freeze(n.map(r=>Object.freeze(r)))})}var rr=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=We.resolve(t)}async read(){try{return JSON.parse(await qe.readFile(this.filePath,"utf8"))}catch(t){if(zt(t)&&t.code==="ENOENT")return null;throw t}}async write(t){let n=We.dirname(this.filePath);await qe.mkdir(n,{recursive:!0});let r=We.join(n,`.${We.basename(this.filePath)}.${Qf()}.tmp`);try{await qe.writeFile(r,`${JSON.stringify(t)}
|
|
9
|
+
`,{encoding:"utf8",flag:"wx"}),await qe.rename(r,this.filePath)}finally{try{await qe.rm(r,{force:!0})}catch{}}}},ir=class{adapter;constructor(t){this.adapter=t}async readOrRebuild(t,n){let r=[],i=null;try{let l=await this.adapter.read();i=om(l),l!==null&&i===null&&r.push("context_signal_store_invalid")}catch{r.push("context_signal_store_invalid")}let o=t.map(l=>l.id).sort((l,f)=>l.localeCompare(f)),s=i?.items.map(l=>l.id)??[],a=i!==null&&i.source_cursor===n.sourceCursor&&i.source===n.source&&s.length===o.length&&s.every((l,f)=>l===o[f]),c;if(a&&i!==null)c=i;else{i!==null&&r.push("context_signal_store_stale"),c=sm(t,n);try{await this.adapter.write(c)}catch{r.push("context_signal_store_write_failed")}}let d=new Map(c.items.map(l=>[l.id,l.signals])),u=Ut(t,n);return{snapshot:c,candidates:u.map(l=>({...l,signals:{...l.signals,...d.get(l.id)}})),cache_status:a?"fresh":"rebuilt",warnings:r,warning_details:r.map(l=>Zf[l])}}};function am(e){let t=Jf("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 Ht(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 Se(t.pmRoot),o=t.sourceCursor??i?.source_cursor??am(e),s=t.source??(i===null?"scan_fallback":"derived_index");return new ir(new rr(We.join(t.pmRoot,"runtime",t.storeKey?`context-signals-${t.storeKey}.json`:"context-signals.json"))).readOrRebuild(e,{...t,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]="a19662f9-f8b3-5988-bc04-1b5a5edaaaa5")}catch{}})();function cm(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 dm(e,t,n){let r,i;for(let o of t){let s=cm(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 Is(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 hw(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=dm(i.id,t.get(i.id)??[],n);o!==void 0&&r.push(o)}return r.sort((i,o)=>i.id.localeCompare(o.id))}import um from"node:path";import{createHash as lm}from"node:crypto";import fm 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]="2e225010-1b53-59e9-8188-dcbe4a4f7eb7")}catch{}})();var Cs=1,mm=1e4,Ss=12;function pm(e){let t=new Date(e);return`${t.getUTCFullYear()}-Q${Math.floor(t.getUTCMonth()/3)+1}`}function gm(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 hm(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 ym(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(C(o.status,t.statusRegistry))).map(o=>{let s=Is(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=pm(a.timestamp),d=`epoch:${c}`,u=i.get(d)??{kind:"epoch",key:c,label:c,items:[]};u.items.push(o),i.set(d,u);let l=gm(s,r);if(l){let f=`epic:${l.id}`,m=i.get(f)??{kind:"epic",key:l.id,label:l.title,items:[]};m.items.push(o),i.set(f,m)}}return{format_version:Cs,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(hm).sort((o,s)=>s.last_closed_at.localeCompare(o.last_closed_at)||o.kind.localeCompare(s.kind)||o.key.localeCompare(s.key))}}function _m(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 wm(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(_m)&&Array.isArray(t.outcomes)&&t.outcomes.every(i=>typeof i=="string")&&Number.isSafeInteger(t.knowledge_entries)&&t.knowledge_entries>=0}function bm(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;let t=e;return t.format_version!==Cs||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(wm)?t:null}function km(e){return`scan:${lm("sha256").update(ke(e.map(t=>[t.id,t.updated_at,t.status,t.parent]).sort(([t],[n])=>String(t).localeCompare(String(n))))).digest("hex")}`}async function vm(e,t,n){return n!==void 0?n:(await Se(t))?.source_cursor??km(e)}async function xm(e){try{let t=bm(JSON.parse(await fm.readFile(e,"utf8")));return{snapshot:t,invalid:t===null}}catch(t){return{snapshot:null,invalid:!(typeof t=="object"&&t!==null&&"code"in t&&t.code==="ENOENT")}}}async function Ts(e,t){let n=Math.max(1,Math.floor(t.minimumItems??mm));if(e.length<n)return{snapshot:null,cache_status:"skipped",warnings:[]};let r=await vm(e,t.pmRoot,t.sourceCursor),i=um.join(t.pmRoot,"runtime","workspace-memory.json"),o=[],s=await xm(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=ym(e,{statusRegistry:t.statusRegistry,sourceCursor:r,now:t.now});try{await K(i,`${JSON.stringify(c)}
|
|
10
|
+
`)}catch{o.push("workspace_memory_write_failed")}return{snapshot:c,cache_status:"rebuilt",warnings:o}}function Em(e,t,n=Ss){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 Ds(e,t,n=Ss){if(e.snapshot===null)return;let r=Em(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 Im(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 Cw(e,t,n=5){let r=Im(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]="97c1e310-3cd9-5846-a54c-d019b0351541")}catch{}})();var Rs=16;async function As(e,t,n){let r=$(t,F()).type_to_folder,i=[],o=new Set,s=n;for(;s&&i.length<Rs;){let a=s.trim().toLowerCase();if(!a||o.has(a))break;o.add(a);let c=await le(e,s,t.id_prefix,t.item_format,r);if(!c)break;let d=await fe(c,{schema:t.schema});i.push(d.document.metadata.id),s=d.document.metadata.parent}return i}async function Fw(e){await Lr({pmRoot:e.pmRoot,principal:e.principal,itemId:e.itemId,lineageIds:await As(e.pmRoot,e.settings,e.itemId)})}async function Nw(e){await Mr(e)}async function Lw(e){await $r({pmRoot:e.pmRoot,principal:e.principal,...e.itemId?{itemId:e.itemId,lineageIds:await As(e.pmRoot,e.settings,e.itemId)}:{}})}var Mw={lineage_depth:Rs,active_items:64,evidence_rows:32};function Fs(e){if(!e)return;let t={};for(let n of e.active_item_ids)t[n]=1;e.focused_item_id&&(t[e.focused_item_id]=1);for(let n of e.evidence){let r=/^lineage:(.+)$/u.exec(n)?.[1];r&&t[r]===void 0&&(t[r]=.75)}return Object.keys(t).length>0?t:void 0}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="757a0349-9fb6-579d-ab29-fabaad790ce4")}catch{}})();var Cm=["markdown","toon","json","ndjson"],Xe=new Set(["Epic","Feature"]),Ps=10,js=1e4,Us=["hierarchy","activity","progress","recently_created","unparented","workload"],Sm=[...Us,"blockers","files","staleness","tests"],Tm=/^(\d{4})-(\d{2})-(\d{2})/,Dm=/^(\d{4})(\d{2})(\d{2})(?:[T ]?\d{2}|$)/,Rm=/^(\d{4})(\d{2})(\d{2})$/,Am=/^(\d{4})(\d{2})(\d{2})(?:[T\s]?)(\d{2})(\d{2})(\d{2})?(Z|[+-]\d{2}:?\d{2})?$/i;function Fm(e){if(!e)return;let t=e.trim().toLowerCase();if(!Cm.includes(t))throw new g("Context format must be one of markdown|toon|json|ndjson",p.USAGE);return t}var Ns=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 Nm(e){if(e===void 0)return;let t=[];for(let n of e.split(",")){let r=n.trim().toLowerCase();if(r.length!==0){if(!Ns.has(r))throw new g(`Context --fields value not projectable: ${r} (valid: ${[...Ns].join(", ")})`,p.USAGE);t.includes(r)||t.push(r)}}if(t.length===0)throw new g("Context --fields requires at least one field name",p.USAGE);return t}function Ve(e,t){return e.map(n=>{let r={},i=n;for(let o of t)r[o]=i[o]??null;return r})}function eb(e,t){let n=Fm(e.format);if(t.json&&n&&n!=="json"&&n!=="ndjson")throw new g("Cannot combine --json with --format markdown|toon",p.USAGE);return t.json?n==="ndjson"?"ndjson":"json":n??"toon"}function Lm(e,t){return W(e,"--limit")??(t==="full"?Number.MAX_SAFE_INTEGER:Ps)}function ar(e,t){if(e===void 0)return t;let n=typeof e=="number"?e:Number(e);if(!Number.isInteger(n)||n<1)throw new g("--token-budget must be a positive integer",p.USAGE);return n}function Mm(e,t){return t>=js&&e===Number.MAX_SAFE_INTEGER?Ps:e}function $m(e,t){if(!e)return t.default_depth;let n=e.trim().toLowerCase();if(!Jt.includes(n))throw new g(`Context --depth must be one of ${Jt.join("|")}`,p.USAGE);return n}function Om(e,t,n){if(e&&e.length>0){let i=[];for(let o of e){let s=o.trim().toLowerCase();if(!Ze.includes(s))throw new g(`Context --section must be one of ${Ze.join("|")}`,p.USAGE);i.includes(s)||i.push(s)}return i}return t==="brief"?[]:t==="full"?[...Ze]:(t==="deep"?Sm:Us).filter(i=>n.sections[i])}function Pm(e,t){return e?W(e,"--activity-limit")??t.activity_limit:t.activity_limit}function jm(e,t){if(!e)return t.stale_threshold_days;let n=e.trim().toLowerCase(),r=/^(\d+)d?$/.exec(n);if(!r)throw new g("--stale-threshold must be a number of days (e.g. 7 or 7d)",p.USAGE);let i=parseInt(r[1],10);if(i<=0)throw new g("--stale-threshold must be positive",p.USAGE);return i}function Ls(e,t){let n=C(e,t),r=N("in_progress",t),i=N("open",t),o=N("blocked",t),s=N("draft",t);return r&&n===r?0:i&&n===i?1:o&&n===o?2:s&&n===s?3:t.active_statuses.has(n)?4:t.blocked_statuses.has(n)?5:t.terminal_statuses.has(n)?7:6}function Ye(e,t){let n=N("closed",t);return C(e,t)===n}function cr(e,t){let n=N("in_progress",t);return C(e,t)===n}function Bs(e,t){let n=N("open",t);return C(e,t)===n}function Um(e,t){return t.blocked_statuses.has(C(e,t))}var Bm=["compact","brief","fields","includeBody","include_body","parent"];function Gm(e){let t={...e};for(let n of Bm)delete t[n];return t}function dr(e,t){let n=t.trim().toLowerCase(),r=e.find(a=>a.id.trim().toLowerCase()===n);if(!r)return{ids:new Set,found:!1};let i=Ne(e),o=Je(r.id,i);return{ids:new Set([r.id,...o.map(a=>a.id)].map(a=>a.trim().toLowerCase())),found:!0}}function Km(e){if(e===void 0)return;let t=e.trim();if(t.length===0)throw new g("Context --parent requires an item id",p.USAGE);return t}function zm(e,t){let n=e??null,r=t??null;return n===null&&r===null?0:n===null?1:r===null?-1:n-r}function Hm(e,t){let n=e??null,r=t??null;return n===null&&r===null?0:n===null?1:r===null?-1:x(n,r)}function qm(e,t){return new Date(Date.UTC(e,t+1,0)).getUTCDate()}function Wm(e){let t=Tm.exec(e)??Dm.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<=qm(n,r-1)}function Vm(e){let t=Rm.exec(e);if(t)return`${t[1]}-${t[2]}-${t[3]}`;let n=Am.exec(e);if(n){let[,r,i,o,s,a,c,d]=n,u=c?`:${c}`:"",l=d&&d.length===5&&d!=="Z"?`${d.slice(0,3)}:${d.slice(3)}`:d??"";return`${r}-${i}-${o}T${s}:${a}${u}${l}`}return e}function Gs(e){if(typeof e!="string")return Number.NaN;let t=e.trim();if(t.length===0||!Wm(t))return Number.NaN;let n=Date.parse(Vm(t));return Number.isFinite(n)?n:Number.NaN}function sr(e){let t=Gs(e);return Number.isFinite(t)?new Date(t).toISOString():""}function Xm(e){let t=Gs(e);return Number.isFinite(t)?new Date(t).toISOString().slice(0,10):"unknown"}function ur(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function ye(e,t,n){let r=Ls(e.status,n)-Ls(t.status,n);if(r!==0)return r;let i=e.priority-t.priority;if(i!==0)return i;let o=zm(e.order,t.order);if(o!==0)return o;let s=Hm(e.deadline,t.deadline);if(s!==0)return s;let a=x(sr(t.updated_at),sr(e.updated_at)),c=e.id.localeCompare(t.id);return a!==0?a:c}function or(e){return Math.max(1,Math.ceil(Buffer.byteLength(JSON.stringify(e),"utf8")/4))}function lr(e,t,n=new Set,r="context"){return ps(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:or({id:i.id,title:i.item.title}),summary:or({id:i.id,title:i.item.title,type:i.item.type,status:i.item.status,priority:i.item.priority,parent:i.item.parent}),full:or(i.item)}})),{tokenBudget:t,profile:r,latencyBudgetMs:25})}function fr(e){return{...e,included:e.included.map(t=>({id:t.id,projection:t.projection,tokens:t.tokens}))}}function mr(e,t){return{model:e.model,available_signals:e.available_signals,items:e.ranked.map(n=>({id:n.id,rank:n.rank,baseline_rank:n.baseline_rank,score:n.score,contributions:n.contributions})),...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 Ks(e,t){return t>0?Math.round(e/t*100):0}function Ne(e){let t=new Map;for(let n of e){let r=ur(n.parent);if(!r)continue;let i=t.get(r)??[];i.push(n),t.set(r,i)}return t}function Qe(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:ur(e.parent)};if(t&&n){let i=Je(e.id,n),o=i.length;if(o>0){let s=i.filter(a=>Ye(a.status,t)).length;r.children_total=o,r.children_closed=s,r.completion_pct=Ks(s,o)}}return r}function Ym(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 qt(...e){return[...new Set(e.flatMap(t=>t??[]))].sort((t,n)=>t.localeCompare(n))}function Jm(e,t){return e.filter(n=>!t.terminal_statuses.has(C(n.item_status,t)))}function Qm(e,t,n,r){let i=new Map;for(let c of e)i.set(c.id,c);let o=Ne(e),s=new Set(t.filter(c=>Xe.has(c.type)).map(c=>c.id)),a=[];for(let c of s){let d=i.get(c);if(!d)continue;let u=Je(c,o),l=o.get(c)??[],f=0,m=0,h=0,y=0;for(let _ of u)Ye(_.status,n)?f++:cr(_.status,n)?h++:Um(_.status,n)?y++:Bs(_.status,n)&&m++;let w=l.sort((_,b)=>ye(_,b,n)).slice(0,r).map(_=>{let b=Je(_.id,o),k=b.filter(E=>Ye(E.status,n)).length;return{id:_.id,title:_.title,type:_.type,status:_.status,children_total:b.length,children_closed:k}});a.push({id:d.id,title:d.title,type:d.type,status:d.status,children_total:u.length,children_closed:f,children_open:m,children_in_progress:h,children_blocked:y,children:w})}return a.sort((c,d)=>{let u=i.get(c.id),l=i.get(d.id);return ye(u,l,n)}).slice(0,r)}function Je(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 Zm(e,t){return(await Ci({compact:!0,limit:String(e)},t)).compact_activity??[]}function ep(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=>Xe.has(c.type)),a=[];for(let c of s){let d=Je(c.id,o),u=d.length;if(u===0)continue;let l=0,f=0,m=0,h=0;for(let y of d)Ye(y.status,r)?l++:n.has(y.id.trim().toLowerCase())?h++:cr(y.status,r)?m++:Bs(y.status,r)&&f++;a.push({id:c.id,title:c.title,type:c.type,total:u,closed:l,open:f,in_progress:m,blocked:h,completion_pct:Ks(l,u)})}return a.sort((c,d)=>c.completion_pct-d.completion_pct).slice(0,i)}function tp(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=Lt(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 np(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 rp(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=>cr(s.status,t)).length,items:o.map(s=>s.id).sort()})).sort((i,o)=>o.active-i.active).slice(0,n)}function ip(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 op(e,t,n,r){return e.map(i=>({item:i,sortKey:sr(i.created_at)})).sort((i,o)=>{let s=x(o.sortKey,i.sortKey);return s!==0?s:i.item.id.localeCompare(o.item.id)}).slice(0,r).map(({item:i})=>({...Qe(i,t,n),created_at:i.created_at}))}function sp(e,t,n,r){return e.filter(i=>!ur(i.parent)&&!Xe.has(i.type)).sort((i,o)=>ye(i,o,t)).slice(0,r).map(i=>Qe(i,t,n))}function ap(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 u of c)r+=u.passed??0,i+=u.failed??0,o+=u.skipped??0,(u.failed??0)>0&&(d=!0);d&&s.push(a.id)}}return{items_with_tests:t,items_with_recent_runs:n,recent_runs:{passed:r,failed:i,skipped:o},items_failing:s.sort()}}function Ms(e){return`${new Date(e).toISOString().slice(11,16)}Z`}function zs(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 cp(e,t){let n=e;return t.map(r=>{let i=n[r];return Array.isArray(i)?`${r}:${i.join(",")}`:`${r}:${i??"-"}`}).join(" ")}function dp(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`${Ms(e.at)} [${e.kind}] ${e.item_id} (see focus item)${n}`}let t=`${Ms(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 $s(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 up(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 lp(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(`- ${dp(n)}`);e.push("")}function fp(e,t){if(!(!t.hierarchy||t.hierarchy.length===0)){e.push("## Hierarchy");for(let n of t.hierarchy){let r=n.children_total>0?Math.round(n.children_closed/n.children_total*100):0;e.push(`- ${n.id} ${n.type} ${n.status} "${n.title}" [${n.children_closed}/${n.children_total} done ${r}%]`);for(let i of n.children){let o=i.children_total>0?Math.round(i.children_closed/i.children_total*100):0;e.push(` - ${i.id} ${i.type} ${i.status} "${i.title}" [${i.children_closed}/${i.children_total} done ${o}%]`)}}e.push("")}}function mp(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 pp(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)}`:`- ${Xm(i.created_at)} ${zs(i)}`);e.push("")}}function gp(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 hp(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 yp(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 _p(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 wp(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 bp(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 kp(e,t){t.tests&&(e.push("## Test health"),e.push(`- items_with_tests: ${t.tests.items_with_tests}`),e.push(`- items_with_recent_runs: ${t.tests.items_with_recent_runs}`),e.push(`- passed: ${t.tests.recent_runs.passed}, failed: ${t.tests.recent_runs.failed}, skipped: ${t.tests.recent_runs.skipped}`),t.tests.items_failing.length>0&&e.push(`- items_failing: [${t.tests.items_failing.join(",")}]`),e.push(""))}function vp(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 tb(e){let t=[],n=e.focus_fields,r=o=>n?cp(o,n):zs(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(""),$s(t,"High-level focus",e.high_level,"No high-level active items.",r),$s(t,"Low-level focus",e.low_level,"No low-level active items.",r),up(t,e,r),lp(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 fp(t,e),mp(t,e),pp(t,e,n,r),gp(t,e,r),hp(t,e),yp(t,e),_p(t,e),wp(t,e),bp(t,e),kp(t,e),vp(t,e),t.join(`
|
|
11
|
+
`)}async function xp(e,t){let n=S(process.cwd(),t.path),r=await T(n),i=r.context??br.context,o=z(r.schema),s=$m(e.depth,i),a=Lm(e.limit??e.maxItems,s);return{settings:r,contextSettings:i,statusRegistry:o,depth:s,limit:a,sectionsIncluded:Om(e.section,s,i),activityLimit:Pm(e.activityLimit,i),staleThresholdDays:jm(e.staleThreshold,i),parentScope:Km(e.parent),focusFields:Nm(e.fields),baseListOptions:Gm(e)}}function pr(e){return e.some(t=>["hierarchy","progress","blockers","staleness","recently_created","unparented"].includes(t))}function Ep(e,t){return{...e,...t,noTruncate:!0,limit:void 0,offset:void 0,after:void 0}}async function Ip(e,t){let n=pr(t.sectionsIncluded),r=await ze(void 0,Ep(t.baseListOptions,{excludeTerminal:!1}),e),i=r.items,o=i.filter(c=>!L(c.status,t.statusRegistry)),s=n||t.parentScope!==void 0?i:o,a=Cp(t.parentScope,i);return a&&(o=o.filter(c=>a.has(c.id.trim().toLowerCase())),s=s.filter(c=>a.has(c.id.trim().toLowerCase()))),{listed:r,listedItemMetadata:o,allItems:s,fullCorpus:i,subtreeIds:a}}function Cp(e,t){if(e===void 0)return;let n=dr(t,e);if(!n.found)throw new g(`Context --parent item not found: ${e}`,p.NOT_FOUND);return n.ids}async function Sp(e,t,n,r,i,o,s,a,c,d,u,l,f,m,h){let y=[...e].sort((v,we)=>ye(v,we,i)),w=await Kt({pmRoot:f,author:c,enabled:process.env.PM_CONTEXT_USAGE_DISABLED!=="1"}),_=await Ht(y,{pmRoot:f,storeKey:"context",statusRegistry:i,now:a,author:c,usageAffinity:w.affinity,claimFocus:h}),b=await Bt("context",_.candidates),k=b.ranked.map(v=>v.item),E=i.active_statuses,I=k.filter(v=>E.has(C(v.status,i))),P=l?Ee(I,d,u,v=>v.id):0,D=l?I.slice(P,P+s):I,U=l&&D.length>0&&P+D.length<I.length,ce=U&&D.length>0?se(u,D[D.length-1].id,P+D.length-1):void 0,B=k.filter(v=>r.has(v.id.trim().toLowerCase())),M=new Set([...D.map(v=>v.id),...B.slice(0,s).map(v=>v.id)]),H=lr({...b,ranked:b.ranked.filter(v=>M.has(v.id))},m,new Set(Object.entries(h??{}).filter(([,v])=>v>=1).map(([v])=>v))),X=H.included.map(v=>v.item),Y=X.filter(v=>E.has(C(v.status,i))),_e=X.filter(v=>r.has(v.id.trim().toLowerCase())),J=Ne(t),ne=pr(o)?J:void 0,re=new Map(n.map(v=>[v.id.trim().toLowerCase(),v])),Xt=v=>{let we=Qe(v,i,ne);return r.has(v.id.trim().toLowerCase())&&(we.blocked=!0,we.blocker_ids=Lt(v,re,i).filter(Yt=>!Yt.resolved).map(Yt=>Yt.id)),we},oa=Y.filter(v=>Xe.has(v.type)).slice(0,l?D.length:s).map(Xt),sa=Y.filter(v=>!Xe.has(v.type)).slice(0,l?D.length:s).map(Xt),yr=I.length===0;return{activeItems:Y,blockedItems:_e,highLevel:oa,lowLevel:sa,blockedFallback:yr?_e.slice(0,s).map(Xt):[],blockedFallbackUsed:yr,ranking:b,packing:H,featureStore:_,pageExtras:{...l?{applied_limit:s}:{},...U?{has_more:!0,truncated:!0}:{},...ce?{next_cursor:ce}:{}}}}function Tp(e){return de("context",rt(e,oi))}function Dp(e,t){return e.limit!==void 0||e.maxItems!==void 0||e.after!==void 0||t>=js}async function Rp(e,t,n,r){let i={...t.baseListOptions,view:"agenda",include:"all",limit:t.parentScope===void 0?String(t.limit):void 0},o=await us(i,e),s=n===void 0?o.events:o.events.filter(d=>n.has(d.item_id.trim().toLowerCase())),a=Jm(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:Ym(a)}}function Os(e,t,n){let r=String(t);return e.filter(i=>C(i.status,n)===r).length}async function Ap(e){let{runtime:t,allItems:n,fullCorpus:r,blockedIds:i,focusGroups:o,now:s,global:a}=e,c=Ne(n),d=n.filter(l=>!L(l.status,t.statusRegistry)),u=l=>t.sectionsIncluded.includes(l);return{hierarchy:u("hierarchy")?Qm(n,o.activeItems,t.statusRegistry,t.limit):void 0,activity:u("activity")?await Zm(t.activityLimit,a):void 0,progress:u("progress")?ep(n,o.activeItems,i,t.statusRegistry,t.limit):void 0,blockersSection:u("blockers")?tp(o.blockedItems,r,t.statusRegistry,t.limit):void 0,recentlyCreated:u("recently_created")?op(d,t.statusRegistry,c,t.limit):void 0,unparented:u("unparented")?sp(d,t.statusRegistry,c,t.limit):void 0,filesSection:u("files")?np(o.activeItems,t.limit):void 0,workload:u("workload")?rp(o.activeItems,t.statusRegistry,t.limit):void 0,staleness:u("staleness")?ip(d,t.staleThresholdDays,s,t.limit):void 0,tests:u("tests")?ap(o.activeItems):void 0}}function Fp(e,t,n){if(!e)return{};let r=N("canceled",n);return{total_items:t.length,closed:t.filter(i=>Ye(i.status,n)).length,canceled:t.filter(i=>C(i.status,n)===r).length}}function Np(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 Lp(e,t){t&&(e.focus_fields=t,e.high_level=Ve(e.high_level,t),e.low_level=Ve(e.low_level,t),e.blocked_fallback=Ve(e.blocked_fallback,t),e.recently_created&&(e.recently_created=Ve(e.recently_created,t)),e.unparented&&(e.unparented=Ve(e.unparented,t)))}function Mp(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 $p(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 Op(e,t,n,r){try{let i=new Set(t.packing.included.map(o=>o.id));await Gt({pmRoot:n,author:r,surface:"context",profile:t.packing.profile,rows:t.ranking.ranked.map(o=>({id:o.id,rank:o.rank,included:i.has(o.id)})),enabled:process.env.PM_CONTEXT_USAGE_DISABLED!=="1"})}catch{e.warnings=qt(e.warnings,["context_usage_feedback_write_failed"])}}async function Pp(e,t,n){if(e)return{};let i=(await Cr({pmRoot:t,settings:n,cwd:process.cwd(),noExtensions:!1})).discovered.map(s=>({name:s.name??s.directory,status:s.status==="ok"?"ok":"degraded"})).sort((s,a)=>s.name.localeCompare(a.name)),o=i.filter(s=>s.status==="degraded").length;return i.length===0?{}:{extension_health:{total:i.length,ok:i.length-o,degraded:o,packages:i.slice(0,20),...i.length>20?{truncated:!0}:{}}}}async function jp(e,t){let n=Or(),r=await Fr(e),i=n.instance||Nr(t);return Fs(r.semantic_attribution?.[i])}async function nb(e,t){let n=S(process.cwd(),t.path),r=await xp(e,t),i=await Ip(t,r),o=Mm(r.limit,i.fullCorpus.length),s={...r,limit:o,tokenBudget:ar(e.tokenBudget,Math.max(256,o*160))},a=pe(void 0,s.settings.author_default),c=await jp(n,a),d=Pp(e.noExtensionHealth===!0,n,s.settings),u=Ue(i.fullCorpus,s.statusRegistry),l=await Sp(i.listedItemMetadata,i.allItems,i.fullCorpus,u,s.statusRegistry,s.sectionsIncluded,s.limit,G(),a,e.after,Tp(e),Dp(e,i.fullCorpus.length),n,s.tokenBudget,c),f=await Rp(t,s,i.subtreeIds,new Set([...l.highLevel,...l.lowLevel,...l.blockedFallback].map(E=>E.id))),m=await Ts(i.fullCorpus,{pmRoot:n,statusRegistry:s.statusRegistry,now:f.agenda.now}),h=qt(i.listed.warnings,f.agenda.warnings,l.ranking.warnings,[...l.featureStore.warnings],m.warnings),y=Os(l.activeItems,N("in_progress",s.statusRegistry),s.statusRegistry),w=Os(l.activeItems,N("open",s.statusRegistry),s.statusRegistry),_=await Ap({runtime:s,allItems:i.allItems,fullCorpus:i.fullCorpus,blockedIds:u,focusGroups:l,now:f.agenda.now,global:t}),b=Fp(pr(s.sectionsIncluded),i.allItems,s.statusRegistry),k={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:{active_items:l.activeItems.length,in_progress:y,open:w,blocked:l.blockedItems.length,blocked_fallback_used:l.blockedFallbackUsed,high_level:l.highLevel.length,low_level:l.lowLevel.length,agenda_events:f.agendaSummary.events,...b},high_level:l.highLevel,low_level:l.lowLevel,blocked_fallback:l.blockedFallback,agenda:{summary:f.agendaSummary,events:f.agendaEvents},...l.pageExtras};return k.workspace_memory=Ds(m,Math.min(800,Math.floor(s.tokenBudget*.2))),Object.assign(k,await d),Np(k,_,l.featureStore.warning_details),Mp(k,e.noTags===!0),e.explainRanking===!0&&(k.ranking=mr(l.ranking,l.featureStore),k.packing=fr(l.packing)),Lp(k,s.focusFields),h.length>0&&(k.warnings=h),$p(k,l.activeItems,l.blockedItems),await Op(k,l,n,a),k}(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]="3431d4d4-e053-5416-b3d1-6dbfbed0142d")}catch{}})();var Up=["markdown","toon","json"],Bp=5,Gp=1440*60*1e3;function Kp(e){if(!e)return;let t=e.trim().toLowerCase();if(!Up.includes(t))throw new g("Next format must be one of markdown|toon|json",p.USAGE);return t}function mb(e,t){let n=Kp(e.format);if(t.json&&n&&n!=="json")throw new g("Cannot combine --json with --format markdown|toon",p.USAGE);return t.json?"json":n??"toon"}function Hs(e,t,n){let r=W(e,t);return r===void 0||r<=0?n:r}function gr(e,t,n,r){return{...Qe(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})),unblocks:e.unblocks,rank:r}}function zp(e,t,n,r){let i=e.item,o=[],s=N("in_progress",t);return o.push(C(i.status,t)===s?"in progress \u2014 resume to finish":"open and ready to start"),r&&o.push("completed container \u2014 governance closeout"),o.push(`priority p${i.priority}${i.priority===0?" (highest)":""}`),typeof i.deadline=="string"&&i.deadline.trim().length>0&&o.push(qp(i.deadline,n)),o.push(ge(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): ${e.unblocks.join(", ")}`),o}function Ws(e,t,n){let r=pe(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 pb={partitionCallerOwnedReady:Ws,resolveNextCallerAuthor:(e,t)=>Vs(e,t)};function Hp(e,t){let n=e.filter(r=>r.item.type.trim().toLowerCase()==="decision");return{agent:t?e:e.filter(r=>r.item.type.trim().toLowerCase()!=="decision"),decisions:t?[]:n}}function qp(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))/Gp);return o<0?`deadline ${r} (overdue ${-o}d)`:o===0?`deadline ${r} (due today)`:`deadline ${r} (in ${o}d)`}function Wp(e,t){let n=N("in_progress",t);return e.filter(r=>C(r.status,t)===n).length}function hr(e,t){return(t.get(e.id.trim().toLowerCase())??[]).length>0}function Vp(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 qs(e,t,n){return[...e].sort((r,i)=>{let o=hr(r.item,t),s=hr(i.item,t);return o!==s?Number(o)-Number(s):ye(r.item,i.item,n)})}function Xp(e){return e.projectedReady.length===0?null:{...e.readyRows[0],reasons:zp(e.projectedReady[0],e.statusRegistry,e.now,e.completedContainer)}}function Yp(e,t){if(e===null){if(t.length>0){let n=t.find(r=>r.blockers.length>0);return[n?`${t.length} item(s) are blocked; unblock the top one by closing ${n.blockers.map(r=>r.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['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 Jp(e,t,n){let r={};return e>n&&(r.decision_needed_total=e),t>n&&(r.held_by_others_total=t),Object.keys(r).length>0?r:void 0}async function Qp(e){try{let t=new Set(e.packing.included.map(n=>n.id));await Gt({pmRoot:e.pmRoot,author:e.author,surface:"next",profile:e.packing.profile,rows:e.ranking.ranked.map(n=>({id:n.id,rank:n.rank,included:t.has(n.id)})),enabled:process.env.PM_CONTEXT_USAGE_DISABLED!=="1"})}catch{e.result.warnings=qt(e.result.warnings,["context_usage_feedback_write_failed"])}}async function Zp(e){let t=[...new Set([...e.candidatesWarnings??[],...e.corpusWarnings??[],...e.readyRanking.warnings??[],...e.featureStore.warnings])].sort((n,r)=>n.localeCompare(r));return t.length>0&&(e.result.warnings=t),e.explainRanking&&(e.result.ranking=mr(e.readyRanking,e.featureStore),e.result.packing=fr(e.packing)),e.result.suggestions=Yp(e.recommended,e.blockedRows),await Qp({result:e.result,pmRoot:e.pmRoot,author:e.author,packing:e.packing,ranking:e.readyRanking}),e.result}function eg(e,t,n){if(!n)return e;let r=dr(t,n);if(!r.found)throw new g(`Next --parent item not found: ${n}`,p.NOT_FOUND);return e.filter(i=>r.ids.has(i.id.trim().toLowerCase()))}async function tg(e,t,n,r,i,o,s){let a=e.filter(y=>!hr(y.item,t)),c=a.length>0?a:e,d=await Kt({pmRoot:o,author:i,enabled:process.env.PM_CONTEXT_USAGE_DISABLED!=="1"}),u=await Ht(c.map(y=>y.item),{pmRoot:o,storeKey:"next",statusRegistry:n,now:r,author:i,usageAffinity:d.affinity}),l=await Bt("next",u.candidates),f=lr(l,s,new Set,"next"),m=new Map(c.map(y=>[y.item.id,y]));return{projectedReady:l.ranked.map(y=>m.get(y.id)).filter(y=>y!==void 0),ranking:l,completedContainer:a.length===0,packing:f,featureStore:u}}function Vs(e,t){let n=e.assignee?.trim();return pe(e.callerAuthor??(n&&n.length>0?n:void 0),t)}async function gb(e,t){let n=S(process.cwd(),t.path),r=await T(n),i=Vs(e,r.author_default),o=z(r.schema),s=G(),a=Hs(e.limit,"--limit",Bp),c=ar(e.tokenBudget,Math.max(192,a*128)),d=Hs(e.blockedLimit,"--blocked-limit",a),u=e.readyOnly===!0,l=typeof e.parent=="string"?e.parent.trim():"",f=await ze(void 0,Vp(e,{excludeTerminal:!0}),t),m=await ze(void 0,{excludeTerminal:!1,noTruncate:!0},t),h=eg(f.items,m.items,l),y=m.items,w=Un(h,y,o),_=Ne(y),b=Hp(w.ready,e.includeDecisions===!0),k=Ws(b.agent,r.author_default,i),E=qs(k.available,_,o),I=[...w.blocked].sort((ne,re)=>ye(ne.item,re.item,o)),{projectedReady:P,ranking:D,completedContainer:U,packing:ce,featureStore:B}=await tg(E,_,o,s,i,n,c),M=P.map((ne,re)=>gr(ne,o,_,re+1)),H=I.map((ne,re)=>gr(ne,o,_,re+1)),X=qs(b.decisions,_,o).map((ne,re)=>gr(ne,o,_,re+1)),Y=Xp({projectedReady:P,readyRows:M,statusRegistry:o,now:s,completedContainer:U}),_e=Jp(X.length,k.held.length,a),J={output_default:"toon",now:s,recommended:Y,ready:M.slice(1,a+1),decision_needed:X.slice(0,a),blocked:u?[]:H.slice(0,d),held_by_others:k.held.slice(0,a),summary:{recommended:Y!==null,ready:M.length,blocked:H.length,in_progress:Wp(M,o),candidates:w.active_count,containers:w.container_count,decision_needed:X.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:l.length>0?l:null,limit:a,blocked_limit:d,ready_only:u,include_decisions:e.includeDecisions===!0,token_budget:c},truncation:_e};return Zp({result:J,recommended:Y,blockedRows:H,candidatesWarnings:f.warnings,corpusWarnings:m.warnings,readyRanking:D,explainRanking:e.explainRanking===!0,pmRoot:n,author:i,packing:ce,featureStore:B})}function hb(e){let t=["# pm next","",...ng(e)];if(t.push(...Wt("Recommended",rg(e.recommended),"No ready work.")),t.push(...Wt("Decision needed",(e.decision_needed??[]).map(n=>`- ${Vt(n)}`),"No human-gated decisions.")),t.push(...Wt("Ready",e.ready.map(n=>`- ${Vt(n)}`),"No ready items.")),e.filters.ready_only||t.push(...Wt("Blocked",e.blocked.map(n=>`- ${ig(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(`
|
|
12
|
+
`).trimEnd()}function ng(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 rg(e){return e?[`- ${Vt(e)}`,` why: ${e.reasons.join("; ")}`]:[]}function Wt(e,t,n){return[`## ${e}`,...t.length===0?[n]:t,""]}function ig(e){let t=e.blockers.map(n=>`${n.id}(${n.status??"?"})`).join(", ");return`${Vt(e)} blocked_by:${t}`}function Vt(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 og}from"node:crypto";import{setTimeout as sg}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]="3f9853cc-0719-544f-8726-3cfd6063b59e")}catch{}})();var Ys=1,Js=/^[A-Za-z0-9_-]+$/,ag=100,Xs=1e3,cg=250;function V(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 Qs(e){return og("sha256").update(ke({type:V(e.type),author:V(e.author),item:V(e.item),harness:V(e.harness),agent_instance:V(e.agentInstance),provenance:V(e.provenanceFilter)})).digest("hex").slice(0,24)}function Zs(e,t){let n={version:Ys,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 ea(e,t){if(typeof e!="object"||e===null)return!1;let n=e;return[n.version===Ys,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 ta(e,t){let n=e.trim();if(n.length===0||n.length>4096||!Js.test(n))throw new g("Invalid mutation event cursor.",p.USAGE,{code:"invalid_event_cursor"});let r;try{r=JSON.parse(Buffer.from(n,"base64url").toString("utf8"))}catch{throw new g("Invalid mutation event cursor.",p.USAGE,{code:"invalid_event_cursor"})}if(!ea(r,t))throw new g("Mutation event cursor does not match this query.",p.USAGE,{code:"event_cursor_query_mismatch"});return r}function na(e){let t=e??ag;if(!Number.isSafeInteger(t)||t<0||t>Xs)throw new g(`Mutation event limit must be an integer from 0 to ${Xs}.`,p.USAGE,{code:"invalid_event_limit"});return t}function ra(e){return e instanceof Error&&e.name==="AbortError"}function ia(e,t){let n=e?.trim();if(!n)return{};if(Js.test(n))return{cursor:ta(n,t)};let r=Date.parse(n);if(!Number.isFinite(r))throw new g("Mutation event --since must be an event cursor or ISO timestamp.",p.USAGE,{code:"invalid_event_since"});return{sinceTimestamp:new Date(r).toISOString()}}async function dg(e,t){let n=await en(e,t);if(n===null){if(!await Pr(e))throw new g("Mutation events require a runtime with node:sqlite DatabaseSync support.",p.GENERIC_FAILURE,{code:"event_index_unavailable"});n=await en(e,t)}if(n===null)throw new g("Mutation event index could not be opened after rebuild.",p.GENERIC_FAILURE,{code:"event_index_unavailable"});return n}async function ug(e={}){let t=S(e.cwd??process.cwd(),e.pmRoot);if(!await A(O(t)))throw new g(`Tracker is not initialized at ${t}. Run pm init first.`,p.NOT_FOUND);let n=na(e.limit);if(e.full===!0&&e.provenance===!0)throw new g("Mutation event projections are mutually exclusive. Use --provenance or --full.",p.USAGE);let r=await T(t),i=r.agent_identity.identity_vocabulary,o=gt(r.agent_identity.harness_signals),s=fn({provenance:e.provenanceFilter},o),a=V(e.harness),c=Qs(e),{cursor:d,sinceTimestamp:u}=ia(e.since,c),l={...d?{after_ts:d.ts,after_stream_id:d.stream_id,after_stream_offset:d.stream_offset}:u?{since_ts:u}:{},ops:V(e.type),authors:V(e.author),harnesses:a,harness_alias_authors:a?Object.entries(i.aliases).filter(([,h])=>a.includes(h)).map(([h])=>h):void 0,agent_instances:V(e.agentInstance),provenance:[...s].map(([h,y])=>({dimension:h,values:[...y]})),stream_ids:V(e.item),limit:n},f=await dg(t,l),m=f.events.map(h=>({cursor:Zs(h,c),item_id:h.stream_id,version:h.stream_offset+1,ts:h.entry.ts,author:h.entry.author,type:h.entry.op,...h.entry.message===void 0?{}:{message:h.entry.message},patch_count:h.entry.patch.length,...e.full===!0?{entry:h.entry}:{},...e.provenance===!0?{provenance:ht(h.entry,i,{itemId:h.stream_id,version:h.stream_offset+1})}:{}}));return{events:m,count:m.length,has_more:f.has_more,...m.length===0?{}:{next_cursor:m[m.length-1].cursor},source:"derived_index",...e.provenanceSummary===!0?{provenance_summary:yt(f.events.map(h=>h.entry),i,o)}:{}}}async function*Tb(e={}){let t=e.intervalMs??cg;if(!Number.isSafeInteger(t)||t<10)throw new g("Mutation event follow interval must be an integer of at least 10ms.",p.USAGE,{code:"invalid_event_follow_interval"});let n=e.since;for(;e.signal?.aborted!==!0;){let r=await ug({...e,since:n});if(r.events.length>0){for(let i of r.events)yield i;n=r.next_cursor;continue}try{await sg(t,void 0,{signal:e.signal})}catch(i){if(ra(i))return;throw i}}}var Db={decodeMutationEventCursor:ta,encodeMutationEventCursor:Zs,eventQueryFingerprint:Qs,isAbortError:ra,isMutationEventCursorEnvelope:ea,parseMutationEventLimit:na,resolveMutationEventStart:ia};(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]="412fc2d2-daee-5d87-82ab-5411a1503087")}catch{}})();function Ab(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{si as a,ai as b,Me as c,ci as d,di as e,xg as f,ui as g,un as h,Hg as i,qg as j,sh as k,ah as l,ft as m,bi as n,ki as o,lh as p,W as q,mt as r,vi as s,pt as t,gt as u,fn as v,ht as w,kh as x,mn as y,yt as z,Ci as A,Si as B,Ha as C,Te as D,Fh as E,Nh as F,gn as G,De as H,Wa as I,yn as J,Va as K,Re as L,wt as M,_n as N,bt as O,Gh as P,Ri as Q,uy as R,Oi as S,Pi as T,ji as U,Ui as V,Bi as W,St as X,Ki as Y,Rt as Z,zi as _,Vi as $,Xi as aa,Yi as ba,Zi as ca,Cn as da,je as ea,to as fa,Tn as ga,Dn as ha,Rn as ia,no as ja,An as ka,ro as la,io as ma,Td as na,At as oa,Mn as pa,Ft as qa,uo as ra,fo as sa,Pd as ta,e_ as ua,Ab as va,tu as wa,ge as xa,Nt as ya,ko as za,Lt as Aa,Ue as Ba,Un as Ca,Bn as Da,Be as Ea,xo as Fa,Eo as Ga,Do as Ha,zn as Ia,Ao as Ja,f_ as Ka,m_ as La,Lo as Ma,Mo as Na,g_ as Oa,ku as Pa,Ko as Qa,jo as Ra,Uo as Sa,vu as Ta,xu as Ua,B_ as Va,Du as Wa,Ru as Xa,Au as Ya,ze as Za,W_ as _a,V_ as $a,X_ as ab,us as bb,er as cb,Ut as db,bf as eb,ms as fb,If as gb,Bt as hb,Cf as ib,Sf as jb,Af as kb,Ff as lb,ew as mb,Nf as nb,ps as ob,te as pb,Gt as qb,aw as rb,cw as sb,Kt as tb,tr as ub,nr as vb,Zf as wb,om as xb,sm as yb,rr as zb,ir as Ab,Ht as Bb,Is as Cb,hw as Db,mm as Eb,ym as Fb,Ts as Gb,Em as Hb,Ds as Ib,Im as Jb,Cw as Kb,As as Lb,Fw as Mb,Nw as Nb,Lw as Ob,Mw as Pb,Fs as Qb,Cm as Rb,Nm as Sb,Ve as Tb,eb as Ub,ar as Vb,$m as Wb,Om as Xb,dr as Yb,ye as Zb,lr as _b,fr as $b,mr as ac,Ne as bc,Qe as cc,qt as dc,tb as ec,Mp as fc,nb as gc,Up as hc,mb as ic,pb as jc,Hp as kc,gb as lc,hb as mc,ug as nc,Tb as oc,Db as pc};
|
|
13
|
+
//# sourceMappingURL=chunk-DSKYD4LG.js.map
|