@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
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
import{f as Ee,g as nt}from"./chunk-IW43E4XL.js";import{a as Jt,g as tt,i as Xt}from"./chunk-I4YM2I7S.js";import{g as kn}from"./chunk-M6RPIXKC.js";import{s as ge,t as gn,u as ye,v as yn,xa as wn}from"./chunk-MXYSIQ56.js";import{$ as an,Aa as ln,Da as Z,Ea as dn,Ga as un,Ja as mn,Ka as fn,L as de,M as X,Ma as L,Q as tn,Va as pn,W as nn,X as rn,_ as sn,_a as _n,bb as xe,ca as rt,cb as Ce,db as Ie,ea as on,fb as hn,ib as Te,k as J,oa as cn,q as en}from"./chunk-FF4MNAYB.js";import{$ as Kt,E as V,J as Ht,K as B,L as he,N as U,Q as Vt,Qa as Zt,U as M,ca as Ze,h as Gt,o as Je,p as N,r as qt,s as oe,v as Xe,w as Wt}from"./chunk-2EXI2DKR.js";import{i as Qt}from"./chunk-RIIN5V4N.js";import{N as Ut,U as zt,V as Ae,Y as h,Z as g,aa as Qe,ba as Yt,ca as et,t as Ye}from"./chunk-GHTN2ILR.js";import{readFile as Fe,realpath as ot,writeFile as Oi}from"node:fs/promises";import{execFile as Fi}from"node:child_process";import T from"node:path";import{promisify as Pi}from"node:util";import{readFile as Ai,writeFile as Ei}from"node:fs/promises";import we 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]="bbfa5b19-d801-582a-98e8-0c4925dd57c0")}catch{}})();var bn="# pm-cli:runtime-cache:start",it="# pm-cli:runtime-cache:end",Rn=".agents/pm",st=["runtime/","search/","locks/","transactions/","checkpoints/"],xi=["search/eval-queries.json"];async function vn(e){try{return await e()}catch(t){throw t instanceof Error&&"code"in t&&typeof t.code=="string"&&["EACCES","EPERM","EROFS"].includes(t.code)?new g("The workspace .gitignore is not writable.",h.GENERIC_FAILURE,{code:"init_gitignore_unwritable",reason:t.code.toLowerCase(),required:"Grant the current user read and write access to the workspace .gitignore before initialization.",why:"pm init must publish its managed runtime-cache ignore fence without replacing unrelated entries.",nextSteps:["Grant read and write access to the workspace .gitignore and rerun pm init.","If the workspace is intentionally read-only, initialize pm in a writable workspace or clone."]}):t}}function Sn(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/\/+$/,"")}function at(e){let t=e.replaceAll("\\","/");return we.isAbsolute(e)||t===".."||t.startsWith("../")}function Ci(e=Rn){let t=Sn(e);return[bn,...st.map(n=>n==="search/"?`${t}/${n}*`:`${t}/${n}`),...xi.map(n=>`!${t}/${n}`),it].join(`
|
|
2
|
-
`)}async function Po(e,t={}){let n=we.join(e,".gitignore"),r=Rn;if(t.pmRoot!==void 0){let d=Sn(we.relative(we.resolve(e),we.resolve(t.pmRoot)));if(at(d))return{path:n,changed:!1};d.length>0&&(r=d)}let i="";try{i=await vn(()=>Ai(n,"utf8"))}catch(d){if(!(d instanceof Error&&"code"in d&&d.code==="ENOENT"))throw d}let s=i.indexOf(bn),a=i.indexOf(it),c=(s>=0&&a>=s?`${i.slice(0,s)}${i.slice(a+it.length)}`:i).trimEnd(),l=`${c.length>0?`${c}
|
|
3
|
-
|
|
4
|
-
`:""}${Ci(r)}
|
|
5
|
-
`;return l===i?{path:n,changed:!1}:(await vn(()=>Ei(n,l,"utf8")),{path:n,changed:!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]="f97516b2-f75c-5ce0-82dc-f850466284c7")}catch{}})();var Ii="PM_SOURCE_CONTEXT_ACCESS",Ti="PM_ALLOW_SOURCE_CONTEXT_WRITES";function An(e){let t=e[Ii],n=t===void 0||t.trim().toLowerCase()==="write"?"write":"read_only",r=n==="read_only"&&e[Ti]?.trim()==="1";return{access:n,write_override_applied:r,source_writes_allowed:n==="write"||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]="94d2a7a8-ce00-5689-b2f6-3d4813234b55")}catch{}})();var lt=Pi(Fi),Oe="# pm-cli:merge-drivers:start",In="# pm-cli:merge-drivers:end",ue="# pm-cli:merge-drivers:v2:start",ct="# pm-cli:merge-drivers:v2:end",Di="merge-fence";function En(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function Tn(){let e=Wt(import.meta.url,["../../.."]);return`${En(process.execPath)} ${En(T.join(e,"dist","cli.js"))}`}var On=[{key:"pm-item-toon",name:"pm field-aware TOON item document merge",artifact:"item",itemPath:"%P"},{key:"pm-item-markdown",name:"pm field-aware JSON-markdown item document merge",artifact:"item",itemPath:"%P"},{key:"pm-history",name:"pm append-only history stream merge",artifact:"history",itemPath:void 0},{key:"pm-relationship",name:"pm append-only relationship event store merge",artifact:"relationship",itemPath:void 0},{key:"pm-json",name:"pm key-level JSON config merge",artifact:"json",itemPath:void 0}];function Ni(e){let t=e.explicitPath?.trim(),n=e.environment.PM_SOURCE_WORKSPACE_ROOT?.trim(),r=e.environment.PM_SOURCE_PM_PATH?.trim(),i=An(e.environment),s=!!(n&&r),a=t===void 0&&s&&(e.dryRun||i.source_writes_allowed);if(t!==void 0){let o=B(e.cwd,t);return{pm_root:o,workspace_start:o,source_coordinates_available:s,source_context_selected:!1,source_policy:i}}return a?{pm_root:T.resolve(r),workspace_start:T.resolve(n),source_coordinates_available:!0,source_context_selected:!0,source_policy:i}:{pm_root:s?B(e.cwd,".agents/pm"):B(e.cwd),workspace_start:e.cwd,source_coordinates_available:s,source_context_selected:!1,source_policy:i}}async function ke(e){try{let{stdout:t}=await lt("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return await ot(t.trim())}catch{return null}}async function Fn(e){let t=await ke(e);if(t===null)throw new g("pm merge install requires a git repository (merge drivers are git configuration).",h.USAGE);return t}function dt(e,t){return T.relative(e,t).replaceAll("\\","/")}function K(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function xn(e,t){if(e[t]!=="'")return null;let n="";for(let r=t+1;r<e.length;r+=1){if(e.startsWith(`'"'"'`,r)){n+="'",r+=4;continue}if(e[r]==="'")return{value:n,nextOffset:r+1};n+=e[r]}return null}async function Mi(e,t){let n=xn(e,0);if(n===null||e[n.nextOffset]!==" ")return!1;let r=xn(e,n.nextOffset+1);if(r===null||e.slice(r.nextOffset)!==t||!/^node(?:\.exe)?$/iu.test(T.basename(n.value))||T.basename(r.value)!=="cli.js"||T.basename(T.dirname(r.value))!=="dist"||!await N(n.value)||!await N(r.value))return!1;try{let i=T.dirname(T.dirname(r.value)),s=JSON.parse(await Fe(T.join(i,"package.json"),"utf8")),a=typeof s.bin=="object"&&s.bin!==null&&"pm"in s.bin?s.bin.pm:void 0;return s.name==="@unbrained/pm-cli"&&(s.bin==="dist/cli.js"||a==="dist/cli.js")}catch{return!1}}function ut(e,t){let n=e.length>0?`${e}/`:"",r=[`${K(`${n}**/*.toon`)} merge=pm-item-toon`,`${K(`${n}**/*.md`)} merge=pm-item-markdown`];for(let i of t)r.push(`${K(`${n}${i}/*.toon`)} merge=pm-item-toon`),r.push(`${K(`${n}${i}/*.md`)} merge=pm-item-markdown`);return r.push(`${K(`${n}**/*.jsonl`)} merge=pm-relationship`),r.push(`${K(`${n}history/*.jsonl`)} merge=pm-history`),r.push(`${K(`${n}settings.json`)} merge=pm-json`),r.push(`${K(`${n}**/*.json`)} merge=pm-json`),r.push(`${K(`${n}extensions/**`)} -merge`),r.push(`${K(`${n}extensions/.managed-extensions.json`)} merge=pm-json`),r}function Cn(e,t,n){let r=e.indexOf(t),i=e.indexOf(n);return r>=0&&i>r?`${e.slice(0,r)}${e.slice(i+n.length)}`:e.replace(t,"").replace(n,"")}async function Pn(e,t,n){let r=T.join(e,".gitattributes"),i="";try{i=await Fe(r,"utf8")}catch(l){if(!(l instanceof Error&&"code"in l&&l.code==="ENOENT"))throw l}let s=[ue,...t,ct].join(`
|
|
6
|
-
`),o=Cn(Cn(i,ue,ct),Oe,In).trimEnd(),c=`${o.length>0?`${o}
|
|
7
|
-
|
|
8
|
-
`:""}${s}
|
|
9
|
-
`;return c===i?{path:r,changed:!1}:(n||await Oi(r,c,"utf8"),{path:r,changed:!0})}function Pe(e){let t=V(e,null);return[...new Set(Object.values(t.type_to_folder))].sort((n,r)=>n.localeCompare(r))}async function Dn(e,t){let n=T.resolve(e),r=null,i="",s=n;for(let b=0;b<8;b+=1){let S=T.join(s,".gitattributes");try{let E=await Fe(S,"utf8");if(E.includes(ue)||E.includes(Oe)){r=s,i=E;break}}catch{}let A=T.dirname(s);if(A===s)break;s=A}if(r===null)return{status:"not_installed",missing_patterns:[],stale_patterns:[],schema_scope:"project"};let a=T.join(r,".gitattributes"),o=i.includes(ue),c=o?ue:Oe,l=o?ct:In,d=i.indexOf(c),u=i.indexOf(l),m=u>d?i.slice(d+c.length,u).split(`
|
|
10
|
-
`).map(b=>b.trim()).filter(b=>b.length>0):[],f=ut(dt(r,n),t),p=new Set(m),y=new Set(f),_=f.filter(b=>!p.has(b)),w=m.filter(b=>!y.has(b));return{status:_.length>0||w.length>0?"drift":"ok",path:a,missing_patterns:_,stale_patterns:w,schema_scope:"project"}}async function Nn(e){let t=Tn(),n=[],r=[];for(let i of On){let s=`merge.${i.key}.driver`,a=` merge driver ${i.artifact} "%O" "%A" "%B"${i.itemPath===void 0?"":` --item-path ${i.itemPath}`}`,o=`${t}${a}`;try{let{stdout:c}=await lt("git",["config","--local","--get",s],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),l=c.trim();l!==o&&!await Mi(l,a)&&r.push(s)}catch{n.push(s)}}return{status:n.length>0?"missing":r.length>0?"drift":"ok",missing_keys:n,drifted_keys:r}}async function Zo(e){let t;try{t=await Fn(T.resolve(e))}catch{return{status:"no_git"}}let n=dt(t,T.resolve(e)),r=await L(e),i=de(void 0,r.author_default),s=await tn(e,Di,r.locks.ttl_seconds,i,!1,fn(r).force_required_for_stale_lock,r.locks.wait_ms);try{let a=T.join(t,".gitattributes"),o;try{o=await Fe(a,"utf8")}catch(u){if(u instanceof Error&&"code"in u&&u.code==="ENOENT")return{status:"not_installed",path:a};throw u}if(!o.includes(ue)&&!o.includes(Oe))return{status:"not_installed",path:a};let c=await L(e),l=Pe(c),d=await Pn(t,ut(n,l),!1);return{status:d.changed?"refreshed":"unchanged",path:d.path}}finally{await s()}}async function Qo(e,t){let n=Ni({cwd:process.cwd(),explicitPath:t.path,dryRun:e.dryRun===!0,environment:process.env}),r=n.pm_root;if(!await N(U(r)))throw new g(`Tracker is not initialized at ${r}. Run pm init first.`,h.NOT_FOUND);let i=await Fn(n.workspace_start);return Li({pmRoot:r,workspaceRoot:i,dryRun:e.dryRun===!0})}async function Li(e){let t=T.resolve(e.pmRoot),n=T.resolve(e.workspaceRoot),r=e.dryRun===!0,i,s;try{[i,s]=await Promise.all([ot(t),ot(n)])}catch(f){throw new g(`Cannot resolve tracker root ${t} or workspace root ${n}: ${String(f)}`,h.NOT_FOUND,{code:"merge_root_not_found",nextSteps:["Initialize the tracker and ensure both paths are accessible.",'Retry "pm merge install" from the repository workspace.']})}let a=dt(s,i);if(at(a))throw new g(`Tracker root ${t} is outside the git repository ${n}; there is nothing to configure for this repository.`,h.USAGE);let o=await L(i),c=Pe(o),l=ut(a,c),d=[],u=Tn();for(let f of On)d.push({key:`merge.${f.key}.name`,value:f.name}),d.push({key:`merge.${f.key}.driver`,value:`${u} merge driver ${f.artifact} "%O" "%A" "%B"${f.itemPath===void 0?"":` --item-path ${f.itemPath}`}`});if(!r)try{for(let f of d)await lt("git",["config","--local",f.key,f.value],{cwd:s,encoding:"utf8",windowsHide:!0,timeout:1e4})}catch{throw new g(`Cannot install repository-local merge drivers in ${s}. Ensure the repository Git config is writable and no other Git process holds its lock, then retry.`,h.DEPENDENCY_FAILED,{code:"merge_git_config_unwritable",why:"pm merge install must persist clone-local driver commands before publishing their shared .gitattributes mappings.",nextSteps:["Make the repository Git config writable or wait for the process holding its lock to finish.",'Retry "pm merge install"; the operation is idempotent.','Use "pm merge install --dry-run --json" when the workspace is intentionally read-only.']})}let m=await Pn(s,l,r);return{ok:!0,dry_run:r,workspace_root:s,pm_root:i,gitattributes:{path:m.path,changed:m.changed,patterns:l,schema_scope:"project"},git_config:d,guidance:["Commit .gitattributes so every branch and collaborator shares the merge mapping.",'git config is per-clone: each collaborator (and each fresh worktree/clone) runs "pm merge install" once.','After merging branches, run "pm merge reconcile --dry-run" to inspect the complete receipt and history repair, then apply "pm merge reconcile"; use --force only after explicitly accepting any discarded values.',"Custom item types registered later refresh this fence automatically (pm schema add-type/remove-type); rerun pm merge install only after out-of-band type-folder edits."],generated_at:X()}}import Me from"node:fs/promises";import Le from"node:path";import{Option as hc}from"commander";(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]="5f92dd0d-4eb1-5a7b-8891-931dd15deb81")}catch{}})();function $i(e,t){let n=[],r=new Set;for(let i of t.keys){if(!Object.hasOwn(e,i))continue;let s=e[i];if(s!=null){if(typeof s=="string"){n.push(s);continue}if(!Array.isArray(s)||!s.every(a=>typeof a=="string"))return;r.has(s)||(r.add(s),n.push(...s))}}return n.length>0?n.join("; "):void 0}function De(e,t){return e.find(r=>r.target===t)??{target:t,keys:[t]}}function k(e,t){return e[t]===!0?!0:void 0}function Q(e,t){return e[t]===!1?!0:void 0}function Mn(e,t){return t.some(n=>e[n]===!0)?!0:void 0}function Ln(e,t){for(let[n,r]of Object.entries(t))n==="__proto__"||n==="constructor"||n==="prototype"||Object.hasOwn(e,n)||(e[n]=r)}function $n(e){let t=i=>tt(e,De(Ee,i)),n=i=>Xt(e,De(nt,i)),r={title:t("title"),description:t("description"),body:t("body"),status:t("status"),closeReason:t("closeReason"),priority:t("priority"),type:t("type"),tags:t("tags"),addTags:n("addTags"),removeTags:n("removeTags"),deadline:t("deadline"),estimatedMinutes:t("estimatedMinutes"),acceptanceCriteria:$i(e,De(nt,"acceptanceCriteria")),addAc:n("addAc"),removeAc:n("removeAc"),definitionOfReady:t("definitionOfReady"),order:t("order"),rank:t("rank"),goal:t("goal"),objective:t("objective"),value:t("value"),impact:t("impact"),outcome:t("outcome"),whyNow:t("whyNow"),author:t("author"),message:t("message"),force:!!e.force,ownershipMetadataBypass:e.ownershipMetadataBypass===!0?!0:void 0,ownershipDependencyBypass:e.ownershipDependencyBypass===!0?!0:void 0,assignee:t("assignee"),parent:t("parent"),allowUnresolvedDeps:Mn(e,["allowUnresolvedDeps","allow_unresolved_deps"])===!0,reviewer:t("reviewer"),risk:t("risk"),confidence:t("confidence"),sprint:t("sprint"),release:t("release"),blockedBy:t("blockedBy"),blockedReason:t("blockedReason"),unblockNote:t("unblockNote"),reporter:t("reporter"),severity:t("severity"),environment:t("environment"),reproSteps:t("reproSteps"),resolution:t("resolution"),expectedResult:t("expectedResult"),actualResult:t("actualResult"),affectedVersion:t("affectedVersion"),fixedVersion:t("fixedVersion"),component:t("component"),regression:e.regression===!0?"true":t("regression"),customerImpact:t("customerImpact"),dep:n("dep"),depRemove:n("depRemove"),replaceDeps:k(e,"replaceDeps"),replaceTests:k(e,"replaceTests"),replaceFiles:k(e,"replaceFiles"),replaceDocs:k(e,"replaceDocs"),comment:n("comment"),note:n("note"),learning:n("learning"),file:n("file"),test:n("test"),doc:n("doc"),reminder:n("reminder"),event:n("event"),typeOption:n("typeOption"),field:n("field"),unset:n("unset"),clearDeps:k(e,"clearDeps"),clearComments:k(e,"clearComments"),clearNotes:k(e,"clearNotes"),clearLearnings:k(e,"clearLearnings"),clearFiles:k(e,"clearFiles"),clearTests:k(e,"clearTests"),clearDocs:k(e,"clearDocs"),clearReminders:k(e,"clearReminders"),clearEvents:k(e,"clearEvents"),clearTypeOptions:k(e,"clearTypeOptions")};return Ln(r,e),r}function C(e,t){let n=De(Jt,t),r=tt(e,n);if(r!==void 0)return r;for(let i of n.keys){let s=e[i];if(Array.isArray(s)){let a=s.filter(o=>typeof o=="string");if(a.length>0)return a.join(",")}if(t==="ids"&&typeof s=="string")return s;if(typeof s=="number"&&Number.isFinite(s))return String(s)}}function ji(e){let t=k(e,"filterFilesMissing"),n=k(e,"filterDocsMissing");return{filterReviewerMissing:k(e,"filterReviewerMissing"),filterRiskMissing:k(e,"filterRiskMissing"),filterConfidenceMissing:k(e,"filterConfidenceMissing"),filterSprintMissing:k(e,"filterSprintMissing"),filterReleaseMissing:k(e,"filterReleaseMissing"),hasNotes:k(e,"hasNotes"),hasLearnings:k(e,"hasLearnings"),hasFiles:k(e,"hasFiles"),hasDocs:k(e,"hasDocs"),hasTests:k(e,"hasTests"),hasComments:k(e,"hasComments"),hasDeps:k(e,"hasDeps"),hasBody:k(e,"hasBody"),hasLinkedCommand:k(e,"hasLinkedCommand"),noNotes:Q(e,"notes"),noLearnings:Q(e,"learnings"),noFiles:Q(e,"files")??t,filterFilesMissing:t,noDocs:Q(e,"docs")??n,filterDocsMissing:n,noTests:Q(e,"tests"),noComments:Q(e,"comments"),noDeps:Q(e,"deps"),emptyBody:k(e,"emptyBody"),noLinkedCommand:Q(e,"linkedCommand")}}function mt(e){let t={status:C(e,"status"),type:C(e,"type"),tag:C(e,"tag"),priority:C(e,"priority"),deadlineBefore:C(e,"deadlineBefore"),deadlineAfter:C(e,"deadlineAfter"),updatedAfter:C(e,"updatedAfter"),updatedBefore:C(e,"updatedBefore"),createdAfter:C(e,"createdAfter"),createdBefore:C(e,"createdBefore"),today:k(e,"today"),recent:k(e,"recent"),ids:C(e,"ids"),assignee:C(e,"assignee"),assigneeFilter:C(e,"assigneeFilter"),parent:C(e,"parent"),sprint:C(e,"sprint"),release:C(e,"release"),limit:C(e,"limit"),offset:C(e,"offset"),noTruncate:Q(e,"truncate"),includeBody:k(e,"includeBody"),strictRead:k(e,"strictRead"),compact:k(e,"compact"),brief:k(e,"brief"),full:k(e,"full"),fields:C(e,"fields"),sort:C(e,"sort"),order:C(e,"order"),tree:k(e,"tree"),treeDepth:C(e,"treeDepth"),filterAcMissing:k(e,"filterAcMissing"),filterEstimatesMissing:Mn(e,["filterEstimatesMissing","filterEstimateMissing"]),filterResolutionMissing:k(e,"filterResolutionMissing"),filterMetadataMissing:k(e,"filterMetadataMissing"),...ji(e)};return Ln(t,e),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]="bcda2578-3b01-5e64-9d53-cd32c0f927b8")}catch{}})();function R(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n:void 0}function O(e,t){let n=e[t];return typeof n=="string"?n.trim().length>0?n:void 0:typeof n=="number"&&Number.isFinite(n)?String(n):void 0}function Bi(e,t){let n=e[t];return typeof n=="string"?n:typeof n=="number"&&Number.isFinite(n)?String(n):void 0}function ve(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ac(e,t){if(typeof e=="number"){if(!Number.isInteger(e))throw new g(`${t} must be a finite integer.`,h.USAGE);return e}if(typeof e=="string"&&e.trim().length>0){let n=Number(e);if(!Number.isInteger(n))throw new g(`${t} must be a finite integer.`,h.USAGE);return n}}function Ec(e,t){return typeof e.limit=="number"&&Number.isFinite(e.limit)?e.limit:typeof t.limit=="number"&&Number.isFinite(t.limit)?t.limit:R(e,"limit")??R(t,"limit")}function xc(e){let t=R(e,"outputFormat");return{json:!0,quiet:!0,author:R(e,"author"),path:R(e,"path"),noExtensions:e.noExtensions===!0||e.no_extensions===!0,noPager:!0,outputInclude:R(e,"outputInclude"),outputLimit:O(e,"outputLimit"),outputBudget:O(e,"outputBudget"),outputSession:R(e,"outputSession"),outputFormat:t==="json"||t==="toon"?t:void 0}}var Ui=new Set(["tags","blockedBy","blocked_by","skills","fields"]),zi=new Set(["comment","note","learning","reminder","event","dep","depRemove","dep_remove","file","doc","test","unset","addGlob","add_glob","migrate","envSet","env_set","envClear","env_clear"]),Gi=new Set(["files","files-discover","docs","test","test-all"]),qi=new Set(["claim","release","start-task","pause-task","close-task"]),Wi={list:["status","type","tag","priority","limit","offset"],search:["mode","status","type","tag","priority","limit"],create:["title","type","status","description","body","priority","tags","parent","createMode","create_mode","allowMissingParent","allowDuplicate"],update:["parent","allowMissingParent","completedAt"],copy:["allowDuplicate"],close:["duplicateOf","completedAt"],append:["body"]},Hi=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession"];function Bn(e,t){let n={},r=t!==void 0&&Gi.has(t),i=t==="files"||t==="files-discover"||t==="docs";for(let[s,a]of Object.entries(e)){if(Array.isArray(a)&&Ui.has(s)){n[s]=a.join(",");continue}if(s==="note"&&i){n[s]=a;continue}if(typeof a=="string"&&zi.has(s)){n[s]=[a];continue}if(typeof a=="string"&&r&&(s==="add"||s==="remove")){n[s]=[a];continue}n[s]=a}return n}function Cc(e,t){let n=Kt(e.options),r={},i=c=>{n[c]!==void 0||e[c]===void 0||(r[c]=e[c])};for(let c of Wi[t??""]??[])i(c);for(let c of Hi)i(c);let s=Bn({...r,...n},t),a=R(e,"author"),o=t!==void 0&&qi.has(t)?R(e,"assignee")??R(s,"assignee"):void 0;return a&&s.author===void 0?{...s,author:a}:o&&s.author===void 0?{...s,author:o}:s}function Ic(e){if(e.addNote===void 0)return e;let t={...e};return t.note===void 0&&typeof t.addNote=="string"&&(t.note=t.addNote),delete t.addNote,t}function Tc(e){let t={...e};return t.discoveryNote!==void 0&&t.note===void 0&&typeof t.discoveryNote=="string"&&(t.note=t.discoveryNote),delete t.discover,delete t.discoveryNote,t}function Oc(e){let t=[],n=!0;for(let r of e.trim().toLowerCase()){if(r>="a"&&r<="z"||r>="0"&&r<="9"){t.push(r),n=!1;continue}n||(t.push("-"),n=!0)}return t.at(-1)==="-"&&t.pop(),t.join("")}function Fc(e){return e.trim().toLowerCase().split(/\s+/).filter(Boolean).join(" ")}function _t(e){return Array.isArray(e)?e.map(t=>String(t)).filter(t=>t.length>0):[]}function Pc(e,t){let n=new Set(["action","args","author","cwd","fullChangedFields","id","options","path","query","reason","target"]),r={};for(let[s,a]of Object.entries(e))n.has(s)||(r[s]=a);let i={...r,...t};return delete i.args,i}function Dc(e,t){return{changedFields:e.fullChangedFields===!0?"full":"compact",idOnly:e.idOnly===!0,runnerOptions:{...t}}}function pt(e){return{type:O(e,"filterType"),tag:O(e,"filterTag"),priority:O(e,"filterPriority"),deadlineBefore:O(e,"filterDeadlineBefore"),deadlineAfter:O(e,"filterDeadlineAfter"),updatedAfter:O(e,"filterUpdatedAfter"),updatedBefore:O(e,"filterUpdatedBefore"),createdAfter:O(e,"filterCreatedAfter"),createdBefore:O(e,"filterCreatedBefore"),ids:Bi(e,"ids"),assignee:O(e,"filterAssignee"),assigneeFilter:O(e,"filterAssigneeFilter")??O(e,"filterAssignee_filter"),parent:O(e,"filterParent"),sprint:O(e,"filterSprint"),release:O(e,"filterRelease"),limit:O(e,"limit"),offset:O(e,"offset")}}function ft(e){if(typeof e=="string"&&e.trim().length>0)return e;if(Array.isArray(e))return _t(e)}function Ne(e){if(typeof e=="number"&&Number.isFinite(e)||typeof e=="string"&&e.trim().length>0)return e}function Nc(e){let t=ft(e.kind),n=ft(e.exemptIsolate),r=ft(e.exemptIsolateType);return{...t===void 0?{}:{kind:t},maxDepth:Ne(e.maxDepth),limit:Ne(e.limit),after:R(e,"after"),direction:R(e,"direction"),maxPaths:Ne(e.maxPaths),sample:Ne(e.sample),...n===void 0?{}:{exemptIsolate:n},...r===void 0?{}:{exemptIsolateType:r},saveBaseline:e.saveBaseline===!0,rebuild:e.rebuild===!0,clear:e.clear===!0,summary:e.summary===!0,...e.full===!0?{full:!0}:{}}}function Mc(e){return{status:R(e,"filterStatus"),list:ve(e.list)?mt(e.list):pt(e),reason:R(e,"reason"),resolution:R(e,"resolution"),expectedResult:R(e,"expectedResult")??R(e,"expected_result")??R(e,"expected"),actualResult:R(e,"actualResult")??R(e,"actual_result")??R(e,"actual"),validateClose:R(e,"validateClose")??R(e,"validate_close"),author:R(e,"author"),message:R(e,"message"),force:e.force===!0?!0:void 0,dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:R(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}var Vi=new Set(["filterStatus","filterType","filterTag","filterPriority","filterDeadlineBefore","filterDeadlineAfter","filterUpdatedAfter","filterUpdatedBefore","filterCreatedAfter","filterCreatedBefore","filterAssignee","filterAssigneeFilter","filterAssignee_filter","filterParent","filterSprint","filterRelease","ids","list","update","limit","offset","dryRun","dry_run","rollback","checkpoint","noCheckpoint","no_checkpoint"]);function jn(e){let t={};for(let[n,r]of Object.entries(e))Vi.has(n)||(t[n]=r);return Un(t)}function Un(e){let t=Bn(e,"update-many");for(let n of Ee)for(let r of n.keys){let i=t[r];typeof i=="number"&&Number.isFinite(i)&&(t[r]=String(i))}return $n(t)}function Lc(e){if(ve(e.list)||ve(e.update)){let t=ve(e.update)?e.update:jn(e);return{status:O(e,"filterStatus"),list:ve(e.list)?mt(e.list):pt(e),update:Un(t),dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:R(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}return{status:O(e,"filterStatus"),list:pt(e),update:jn(e),dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:R(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1: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]="4fd16197-979e-5269-bed7-f2fb0e2038c2")}catch{}})();function ee(e,t){throw new g(e,h.USAGE,t)}var Ki="2026-07-15T06:22:12.276Z",Yi=Date.parse(Ki),Ji=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],zn=e=>typeof e=="string"?e:"",Gn=e=>{let t=e??{},n=zn(t.author).trim().toLowerCase(),r=Number(["","unknown"].includes(n)),i=+(Date.parse(zn(t.ts))>=Yi);return Ji[r][i]};function qn(e,t,n=20,r=new Set,i=!1){let s=[],a=[],o={legacy_unknown:0,actionable_unknown:0},c=Math.max(0,n),l=0,d=0,u=0;for(let[m,f]of t.split(/\r?\n/).entries()){let p;try{p=JSON.parse(f)}catch{continue}l+=1;let y=Gn(p);if(y!=="attributed"){if(d+=1,y==="actionable_unknown"&&r.has(`${e}:${m+1}`)){u+=1;continue}o[y]+=1,i&&y==="actionable_unknown"&&a.push({item_id:e,line:m+1}),s.length<c&&s.push({item_id:e,line:m+1})}}return{checked_events:l,unknown_event_count:d,legacy_unknown_event_count:o.legacy_unknown,actionable_unknown_event_count:o.actionable_unknown,acknowledged_actionable_event_count:u,samples:s,samples_truncated:o.legacy_unknown+o.actionable_unknown>s.length,actionable_events:a}}var Hc=(e,t,n=20,r=new Set)=>qn(e,t,n,r);function Xi(e){let t=new Set;for(let n of e.split(/\r?\n/)){let r;try{r=JSON.parse(n)}catch{continue}let s=(typeof r=="object"&&r!==null&&typeof r.context=="object"&&r.context!==null?r.context:{}).author_acknowledgment;if(!(typeof s!="object"||s===null||!Array.isArray(s.events)))for(let a of s.events)typeof a=="object"&&a!==null&&typeof a.item_id=="string"&&Number.isSafeInteger(a.line)&&t.add(`${a.item_id}:${String(a.line)}`)}return t}var ht=async(e,t=20,n=!1)=>{let r=Le.join(e,"history"),i;try{i=(await Me.readdir(r)).filter(w=>w.endsWith(".jsonl")).sort((w,b)=>w.localeCompare(b))}catch{i=[]}let s=new Set,a=[],o=[],c=0,l=0,d=0,u=0,m=0,f=0,p="_workspace.jsonl",y=new Set;if(i.includes(p))try{y=Xi(await Me.readFile(Le.join(r,p),"utf8"))}catch{y=new Set}for(let w of i){let b;try{b=await Me.readFile(Le.join(r,w),"utf8")}catch{continue}let S=w.slice(0,-6),A=qn(S,b,t-a.length,y,n);c+=1,l+=A.checked_events,d+=A.unknown_event_count,u+=A.legacy_unknown_event_count,m+=A.actionable_unknown_event_count,f+=A.acknowledged_actionable_event_count,A.unknown_event_count>0&&s.add(S),a.push(...A.samples),n&&o.push(...A.actionable_events)}let _=u+m;return{checked_streams:c,checked_events:l,unknown_event_count:d,legacy_unknown_event_count:u,actionable_unknown_event_count:m,acknowledged_actionable_event_count:f,affected_item_ids:[...s].sort((w,b)=>w.localeCompare(b)),samples:a,samples_truncated:_>a.length,...n?{actionable_events:o}:{}}};function Zi(e,t){let n=e.length>0;return n&&t&&ee("Specify exactly one selector: repeat --event or pass --all-actionable.",{code:"history_author_acknowledge_selector_conflict",required:"Exactly one of --event or --all-actionable",examples:['pm history-author-acknowledge --event pm-a1b2:4 --attributed-author agent --reviewer maintainer --reason "Verified provenance"','pm history-author-acknowledge --all-actionable --attributed-author import-agent --reviewer maintainer --reason "Reviewed the complete actionable set"']}),!n&&!t&&ee("Specify exactly one selector: repeat --event or pass --all-actionable.",{code:"history_author_acknowledge_selector_required",required:"Exactly one of --event or --all-actionable",examples:['pm history-author-acknowledge --event pm-a1b2:4 --attributed-author agent --reviewer maintainer --reason "Verified provenance"','pm history-author-acknowledge --all-actionable --attributed-author import-agent --reviewer maintainer --reason "Reviewed the complete actionable set"']}),{events:Qi(e),all_actionable:t}}function Qi(e){return e.map(t=>{let n=t.lastIndexOf(":"),r=t.slice(0,n).trim(),i=Number(t.slice(n+1)),s=r===Z||/^[a-z0-9][a-z0-9-]*$/iu.test(r);return(n<1||!s||!Number.isSafeInteger(i)||i<1)&&ee(`history-author-acknowledge --event expects <item-id>:<one-based-line>, received "${t}".`,{code:"history_author_acknowledge_target_unreadable"}),{item_id:r,line:i}})}function Vc(e,t){let n=Zi(_t(t.historyEvent),t.allActionable===!0||t.all_actionable===!0);return es(e,{events:n.events,all_actionable:n.all_actionable,attributed_author:R(t,"attributedAuthor")??R(t,"attributed_author")??"",reviewer:R(t,"reviewer")??"",reason:R(t,"reason")??""})}async function es(e,t){let n=t.reviewer.trim(),r=t.attributed_author.trim(),i=t.reason.trim(),s=t.events??[],a=+(t.all_actionable===!0)+ +(s.length>0);a===0&&ee("Specify exactly one selector: events or all_actionable.",{code:"history_author_acknowledge_selector_required"}),a>1&&ee("Author acknowledgment accepts either explicit events or all_actionable, not both.",{code:"history_author_acknowledge_selector_conflict"});let o=t.all_actionable===!0?(await ht(e,0,!0)).actionable_events:s;[o.length>0,n.length>0,n.toLowerCase()!=="unknown",r.length>0,r.toLowerCase()!=="unknown",i.length>0].includes(!1)&&ee("Author acknowledgment requires events, reviewer, attributed_author, and reason.",{code:"history_author_acknowledge_required_values_missing"});let l=[...new Map(o.map(m=>[`${m.item_id}:${m.line}`,{item_id:m.item_id,line:m.line}])).values()].sort((m,f)=>m.item_id.localeCompare(f.item_id)||m.line-f.line);for(let m of l){[m.item_id===Z||/^[a-z0-9][a-z0-9-]*$/i.test(m.item_id),Number.isSafeInteger(m.line),m.line>=1].includes(!1)&&ee(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"});let p;try{let _=(await Me.readFile(Le.join(e,"history",`${m.item_id}.jsonl`),"utf8")).split(/\r?\n/)[m.line-1];p=JSON.parse(_??"")}catch{ee(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}Gn(p)!=="actionable_unknown"&&ee(`Author acknowledgment target ${m.item_id}:${m.line} is not an actionable unknown-author event.`,{code:"history_author_acknowledge_target_not_actionable"})}let d=await L(e),u=await un({pmRoot:e,op:"history:author-acknowledge",author:n,context:{author_acknowledgment:{events:l,attributed_author:r}},message:i,lockTtlSeconds:d.locks.ttl_seconds,lockWaitMs:d.locks.wait_ms});return{acknowledged:l.length,history_path:u.historyPath}}import{execFile as ts}from"node:child_process";import{randomUUID as ns}from"node:crypto";import{readdir as rs,readFile as Vn}from"node:fs/promises";import j from"node:path";import{promisify as is}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="59863597-bf57-5d96-9cba-983443e5b209")}catch{}})();var ss=is(ts);async function gt(e){try{let{stdout:t}=await ss("git",["rev-parse","--path-format=absolute","--git-path","pm-merge-receipts"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return t.trim()}catch{return null}}async function Kn(e,t){let n=j.dirname(j.resolve(e,t));for(let r=0;r<12;r+=1){if(await N(j.join(n,"settings.json")))return n;let i=j.dirname(n);if(i===n)break;n=i}return null}function yt(e){return j.join(e,"merge-receipts")}function $e(e){return`${e}.json`}function as(e){return{receipt_id:e.id,item_id:e.item_id,item_path:e.item_path,conflict_fields:e.decisions.map(t=>t.field),fields_from_theirs:e.fields_from_theirs,union_fields:e.union_fields,preferred:e.preferred,conflict_resolution:e.conflict_resolution,decisions:e.decisions.map(t=>({field:t.field,retained_hash:Wn(t.retained)??et(Qe(t.retained)),discarded_hash:Wn(t.discarded)??et(Qe(t.discarded))}))}}function Wn(e){if(typeof e!="object"||e===null||Array.isArray(e)||!("pm_value_hash"in e))return;let t=e.pm_value_hash;return typeof t=="string"&&/^[a-f0-9]{64}$/u.test(t)?t:void 0}async function rl(e){let t=await gt(e.cwd);if(t===null)return null;let n=e.itemPath.trim(),r=n.length>=2&&(n.startsWith("'")&&n.endsWith("'")||n.startsWith('"')&&n.endsWith('"'))?n.slice(1,-1):n,i=j.basename(r,j.extname(r)),s={version:1,id:ns(),item_path:r.replaceAll("\\","/"),item_id:i,preferred:e.preferred,conflict_resolution:e.conflictResolution??"preferred_side",fields_from_theirs:[...e.fieldsFromTheirs],union_fields:[...e.unionFields],decisions:structuredClone(e.decisions),state:"pending",created_at:X(),value_availability:"clone_local"};await Je(t),await oe(j.join(t,$e(s.id)),`${JSON.stringify(s,null,2)}
|
|
11
|
-
`);let a=await Kn(e.cwd,s.item_path);if(a!==null){let o=yt(a),c=as(s),l={...s,decisions:c.decisions.map(d=>({field:d.field,base:null,ours:null,theirs:null,retained:{pm_value_hash:d.retained_hash},discarded:{pm_value_hash:d.discarded_hash}})),value_availability:"hash_only"};await Je(o),await oe(j.join(o,$e(s.id)),`${JSON.stringify(l,null,2)}
|
|
12
|
-
`)}return s}async function Hn(e,t){if(!await N(e))return[];let n;try{n=await rs(e)}catch{return[]}let r=[];for(let i of n.sort((s,a)=>s.localeCompare(a)))if(i.endsWith(".json"))try{let s=JSON.parse(await Vn(j.join(e,i),"utf8")),a={...s,conflict_resolution:s.conflict_resolution??"preferred_side"};a.version===1&&(t.includeReconciled||a.state==="pending")&&(t.includeLossless!==!1||a.decisions.length>0)&&r.push(a)}catch{}return r}async function wt(e,t={}){let n=await gt(e),r=n===null?[]:await Hn(n,t),i=t.pmRoot??j.join(e,".agents","pm"),s=await Hn(yt(i),t),a=new Map(s.map(o=>[o.id,o]));for(let o of r)a.set(o.id,o);return[...a.values()].sort((o,c)=>o.created_at.localeCompare(c.created_at))}function Yn(e){let t=[],n=[];for(let r of e)(Array.isArray(r.decisions)&&r.decisions.length>0?t:n).push(r);return{pendingDecisions:t,lossless:n}}async function il(e,t){let n=await gt(e);if(n===null)return;await oe(j.join(n,$e(t.id)),`${JSON.stringify({...t,state:"reconciled",reconciled_at:X()},null,2)}
|
|
13
|
-
`);let r=await Kn(e,t.item_path);if(r!==null){let i=j.join(yt(r),$e(t.id));if(await N(i)){let s=JSON.parse(await Vn(i,"utf8"));await oe(i,`${JSON.stringify({...s,state:"reconciled",reconciled_at:X()},null,2)}
|
|
14
|
-
`)}}}async function sl(e){let t=await wt(e.cwd??process.cwd(),{...e,includeLossless:!0});return{ok:!0,count:t.length,receipts:t,generated_at:X()}}import me from"node:fs/promises";import fe 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]="59b566d5-1d4f-500b-98e3-004e6f57d2b4")}catch{}})();async function os(e,t){let n=[...new Set(Object.values(t))],r=[];return await Promise.all(n.map(async i=>{let s;try{s=await me.readdir(fe.join(e,i))}catch{return}for(let a of s)for(let o of Ht)if(a.toLowerCase().endsWith(o)){r.push({relativePath:`${i}/${a}`,id:a.slice(0,-o.length)});break}})),r.sort((i,s)=>i.relativePath.localeCompare(s.relativePath))}function cs(e,t){let{id:n,relativePath:r,liveItemIds:i,out:s}=e,a=rt(t);if(a){s.conflictMarkers.push({id:n,path:r,line:a.line,detail:`unresolved merge conflict marker ${a.marker}`});return}let o=null,c=t.split(/\r?\n/).map((l,d)=>({content:l.trim(),number:d+1})).filter(l=>l.content.length>0);for(let l of c)try{let d=JSON.parse(l.content);if(typeof d!="object"||d===null||Array.isArray(d))throw new TypeError("history entry must be an object");o=d}catch{s.unparseable.push({id:n,path:r,line:l.number,detail:"history line is not a valid JSON object"});return}o!==null&&(o.op==="delete"&&i.has(n)&&s.resurrected.push({id:n,deleted_at:typeof o.ts=="string"?o.ts:"",deleted_by:typeof o.author=="string"?o.author:""}),o.op==="history_repair"&&Array.isArray(o.patch)&&o.patch.length>0&&(s.repairReconciliations+=1))}function kt(e,t){let n=typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"?t.code:"UNKNOWN";return`${e} could not be read (error code: ${n})`}async function ls(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},r;try{r=await me.readdir(fe.join(e,"history"))}catch{return n}for(let i of r.sort((s,a)=>s.localeCompare(a))){if(!i.endsWith(".jsonl"))continue;n.scanned+=1;let s;try{s=await me.readFile(fe.join(e,"history",i),"utf8")}catch(a){n.unparseable.push({id:i.slice(0,-6),path:`history/${i}`,detail:kt("history stream",a)});continue}cs({id:i.slice(0,-6),relativePath:`history/${i}`,liveItemIds:t,out:n},s)}return n}function Jn(e){let t=rt(e);if(t)return`unresolved merge conflict marker ${t.marker} at line ${t.line}`;try{return JSON.parse(e),null}catch(n){return`invalid JSON (${String(n)})`}}async function ds(e){let t=[],n=0,r=null;try{r=await qt(U(e))}catch(s){n+=1,t.push({path:"settings.json",detail:kt("configuration file",s)})}if(r!==null){n+=1;let s=Jn(r);s!==null&&t.push({path:"settings.json",detail:s})}let i;try{i=await me.readdir(fe.join(e,"schema"))}catch{return{scanned:n,unparseable:t}}for(let s of i.sort((a,o)=>a.localeCompare(o))){if(!s.endsWith(".json"))continue;n+=1;let a;try{a=await me.readFile(fe.join(e,"schema",s),"utf8")}catch(c){t.push({path:`schema/${s}`,detail:kt("configuration file",c)});continue}let o=Jn(a);o!==null&&t.push({path:`schema/${s}`,detail:o})}return{scanned:n,unparseable:t}}async function Xn(e,t,n,r={}){let i=await os(e,n),s=new Set(i.map(u=>u.id)),a=new Map;for(let u of i){let m=a.get(u.id);m===void 0?a.set(u.id,[u.relativePath]):m.push(u.relativePath)}let o=[...a.entries()].filter(([,u])=>u.length>1).map(([u,m])=>({id:u,paths:[...m].sort((f,p)=>f.localeCompare(p))})).sort((u,m)=>u.id.localeCompare(m.id)),c=(await Promise.all(i.map(async u=>{if(!t.has(u.id))return{path:u.relativePath,id:u.id};try{let m=fe.join(e,u.relativePath);return on(await me.readFile(m,"utf8"),{format:m.toLowerCase().endsWith(".md")?"json_markdown":"toon",schema:r.schema,extensionFieldNames:r.extensionFieldNames}),null}catch{return{path:u.relativePath,id:u.id}}}))).filter(u=>u!==null),l=await ls(e,s),d=await ds(e);return{item_files_on_disk:i.length,item_ids_on_disk:s.size,parsed_items:t.size,unreadable_item_files:c,duplicate_item_ids:o,history_streams_scanned:l.scanned,history_conflict_marker_streams:l.conflictMarkers,history_unparseable_streams:l.unparseable,resurrected_items:l.resurrected,history_repair_reconciliations:l.repairReconciliations,config_files_scanned:d.scanned,unparseable_config_files:d.unparseable}}import Nt from"node:fs/promises";import{realpathSync as Ca}from"node:fs";import{execFile as Ia}from"node:child_process";import $ from"node:path";import{promisify as Ta}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="31d625d8-44be-5298-ab64-c17508ed07d0")}catch{}})();var us=Object.freeze([{code:"missing_directory",command:"pm init",summary:"Recreate missing tracker directories (pm init is idempotent and restores the scaffold)."},{code:"settings_read_fs_error",command:"pm config list --json",summary:"settings.json could not be read as a regular file and pm fell back to defaults; repair the reported path or permissions, then re-run."},{code:"settings_read_invalid_json",command:"pm config list --json",summary:"settings.json is not valid JSON and pm fell back to defaults; fix the syntax error in the reported path, then re-run."},{code:"settings_read_invalid_schema",command:"pm config list --json",summary:"settings.json failed schema validation and pm fell back to defaults; correct the reported key in the file, then re-run."},{code:"settings_read_merge_failed",command:"pm config list --json",summary:"Global/project settings could not be merged; reconcile the conflicting keys in the reported settings files."},{code:"settings:id_prefix_empty",command:"pm config list --json",summary:'id_prefix is empty; set a non-empty "id_prefix" in settings.json so generated item ids are well-formed.'},{code:"settings:locks_ttl_non_positive",command:"pm config list --json",summary:'locks.ttl_seconds must be positive; set a positive "locks.ttl_seconds" in settings.json.'},{code:"telemetry_state_invalid_json",command:"pm health --check-telemetry",summary:"Local telemetry state file is corrupt; pm recreates it on the next flush. Advisory only."},{code:"telemetry_queue_invalid_rows",command:"pm health --check-telemetry",summary:"The telemetry queue has unparseable rows; they are skipped on the next flush. Advisory only."},{code:"telemetry_queue_pending",command:"pm health --check-telemetry",summary:"Telemetry events are queued; they flush automatically on the next reachable command. Advisory only."},{code:"telemetry_queue_high_retries",command:"pm telemetry flush",summary:"Some queued telemetry events are near retry exhaustion; flush now and verify endpoint reachability before entries are dropped."},{code:"telemetry_endpoint_probe_failed",command:"pm health --check-telemetry",summary:"The telemetry endpoint is unreachable; events stay queued until it recovers. Advisory only."},{code:"telemetry_endpoint_probe_http_status",command:"pm health --check-telemetry",summary:"The telemetry endpoint returned a non-success status; events stay queued until it recovers. Advisory only."},{code:"telemetry_schema_version_behind",command:"pm health --check-telemetry",summary:"Client schema is behind server; upgrade pm-cli to emit the latest event shape."},{code:"telemetry_otel_export_failing",command:"pm health --check-telemetry",summary:"OTLP trace spans are queued but the traces endpoint export is failing; spans retry automatically on the next reachable command, or set PM_TELEMETRY_OTEL_DISABLED=1 to skip OTLP export. Advisory only."},{code:"integrity_item_unreadable",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file could not be read; restore or repair the file at the reported path."},{code:"integrity_item_parse_failed",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file failed to parse; fix the malformed item metadata at the reported path."},{code:"integrity_item_conflict_marker",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file contains Git conflict markers; resolve the <<<<<<< / >>>>>>> markers at the reported line."},{code:"integrity_history_unreadable",command:"pm history-repair <id>",summary:"A history stream could not be read; re-anchor the affected item's history chain."},{code:"integrity_history_invalid_json",command:"pm history-repair <id>",summary:"A history stream contains invalid JSON; re-anchor the affected item's history chain."},{code:"integrity_history_conflict_marker",command:"pm history-repair <id>",summary:"A history stream contains Git conflict markers; resolve the markers, then re-anchor the chain."},{code:"validate_storage_unreadable_items",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"An on-disk item file cannot be parsed (for example a botched merge resolution with stale TOON count headers); repair or restore the file at the reported path \u2014 list commands silently skip it while pm get hard-errors."},{code:"validate_storage_duplicate_item_ids",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"One item id is claimed by multiple item documents \u2014 usually two branches minting the same id for different items before merging (GH-600). Keep one document, recreate the other item under a fresh id (pm copy, then delete the colliding file), and consider raising ids.token_length for concurrent multi-agent work."},{code:"validate_storage_history_conflict_markers",command:"pm merge driver history <base> <ours> <theirs>",summary:"A history stream contains unresolved Git conflict markers; re-merge it with the pm history merge driver (or resolve the markers by hand), then run pm history-repair for the item."},{code:"validate_storage_unparseable_history",command:"pm history-repair <id>",summary:"A history stream's newest line is not valid JSONL; repair or restore the stream before further mutations."},{code:"validate_storage_resurrected_items",command:"pm delete <id>",summary:"A live item's newest history operation is a delete: a delete/modify merge silently resurrected it. Decide the winner \u2014 re-delete the item, or keep it and append a mutation documenting the revival."},{code:"validate_storage_unparseable_config",command:"pm merge driver json <base> <ours> <theirs>",summary:"settings.json or a schema file cannot be parsed, so pm silently falls back to defaults; re-merge it with the pm JSON merge driver or fix the file by hand, then rerun pm validate."},{code:"validate_merge_fence_drift",command:"pm merge install",summary:"The committed .gitattributes merge fence no longer matches the active schema's type folders or tracker JSONL stores; rerun pm merge install (and commit .gitattributes) so every tracker artifact keeps its field-aware merge driver."},{code:"validate_storage_tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command, commit the index-only removals and managed .gitignore fence, then rerun validation."},{code:"integrity_item_outdated_format_version",command:"pm validate --verbose-diagnostics",summary:"An item predates the current storage format version; a pm storage migration rewrites it. Use --verbose-diagnostics to list the affected items."},{code:"integrity_item_ahead_format_version",command:"npm install -g @unbrained/pm-cli@latest",summary:"An item was written by a newer pm format version than this runtime supports; upgrade pm to read and validate it safely."},{code:"tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command from the integrity check, commit the index-only removals, and keep the managed .gitignore fence."},{code:"merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts, re-apply any intended discarded values, then run pm merge reconcile; lossy receipts require explicit --force acceptance."},{code:"validate_merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts before reconciliation; history-repair alone does not settle them, and lossy receipts require explicit --force acceptance."},{code:"history_drift_missing_stream",command:"pm history-repair <id>",summary:"The item has no history stream; re-anchor the chain to rebuild it (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_unreadable_stream",command:"pm history-repair <id>",summary:"The item's history stream is unreadable; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_hash_mismatch",command:"pm history-repair <id>",summary:"The item's content hash no longer matches its history; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_chain_mismatch",command:"pm history-repair <id>",summary:"The item's history chain is broken; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_stream_over_compact_threshold",command:"pm history-compact <id>",summary:"The history stream exceeds the configured compaction threshold; compact it (pm history-compact --all-streams sweeps every over-threshold stream in one pass)."},{code:"history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"validate_history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"locks_stale_count",command:"pm gc --scope locks",summary:"Stale item-claim locks (embedded ttl elapsed) can block mutations; sweep them \u2014 gc retains active and unparseable locks."},{code:"locks_unreadable",command:"pm gc --scope locks --dry-run",summary:"Some lock files could not be read; preview the sweep and inspect the unreadable files manually \u2014 gc never deletes what it cannot read."},{code:"extension_update_health_partial_coverage",command:"pm extension --adopt-all --project",summary:"Update-health coverage is partial because unmanaged extensions were skipped; adopt the existing installs into managed metadata so the update scan covers them (use --global for global-scope extensions, or pm package --adopt-all when working with packages)."},{code:"vectorization_stale_items_remaining",command:"pm health --refresh-vectors",summary:"Some items have stale embeddings; refresh vectors so semantic search results stay current."},{code:"vectorization_embedding_identity_changed",command:"pm reindex --mode semantic",summary:"Embedding provider/model changed since the last index; run a semantic reindex to rebuild vectors."},{code:"validate_metadata_missing_acceptance_criteria",command:'pm update <id> --acceptance-criteria "<criteria>"',summary:"Backfill the missing acceptance criteria on the reported item(s)."},{code:"validate_metadata_missing_estimate",command:'pm update <id> --estimate "<estimate>"',summary:"Backfill the missing estimate on the reported item(s)."},{code:"validate_metadata_missing_close_reason",command:'pm update <id> --close-reason "<reason>"',summary:"Backfill the missing close reason on the reported closed item(s)."},{code:"validate_metadata_missing_reviewer",command:'pm update <id> --reviewer "<name>"',summary:"Backfill the missing reviewer on the reported item(s)."},{code:"validate_metadata_missing_risk",command:'pm update <id> --risk "<level>"',summary:"Backfill the missing risk on the reported item(s)."},{code:"validate_metadata_missing_confidence",command:'pm update <id> --confidence "<level>"',summary:"Backfill the missing confidence on the reported item(s)."},{code:"validate_metadata_missing_sprint",command:'pm update <id> --sprint "<sprint>"',summary:"Backfill the missing sprint on the reported item(s)."},{code:"validate_metadata_missing_release",command:'pm update <id> --release "<release>"',summary:"Backfill the missing release on the reported item(s)."},{code:"validate_metadata_custom_profile_missing_required_fields",command:'pm config set metadata-required-fields --criterion "<field>"',summary:"Config-driven finding: the custom metadata profile has no required fields configured and falls back to core, so configure the fields rather than mutating items."},{code:"validate_metadata_duplicate_issue_codes",command:'pm update <id> --title "<distinct title>"',summary:"Two or more items share one logical issue code (GH-235); give each a distinct title so the derived code is unique, or close the redundant item with pm close <id> --duplicate-of <canonical-id> (closed-as-duplicate items are excluded from the check)."},{code:"validate_resolution_missing_fields",command:'pm update <id> --resolution "<how resolved>"',summary:"Backfill resolution / expected_result / actual_result on the reported closed item(s)."},{code:"validate_lifecycle_active_closure_like_metadata",command:"pm update <id> --unset <closure-like-field>",summary:"Clear the closure-like field the validator flags on this active item \u2014 the detail row names it (resolution / actual-result / blocked-reason) \u2014 or close the item if it is actually done."},{code:"validate_lifecycle_active_terminal_parent",command:"pm update <id> --parent <active-parent-id>",summary:"Reopen the terminal parent or move the active child under a non-terminal parent."},{code:"validate_lifecycle_stale_blockers",command:"pm update <id> --unset blocked-by --unset blocked-reason",summary:"Resolve the stale blocker the validator flags: clear blocked-by/blocked-reason when they linger on a non-blocked item or report a resolved blocker; if instead a blocked item is missing blocker context, add the context or move it out of a blocked status."},{code:"validate_lifecycle_dependency_cycles_error",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_lifecycle_dependency_cycles",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_hierarchy_parent_cycle_error",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_hierarchy_parent_cycle",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_files_missing_linked_paths",command:"pm <files|docs> <id> --remove <path>",summary:"The check spans both item.files and item.docs under one code: restore the missing linked artifact, or unlink it with pm files (linked file) or pm docs (linked doc)."},{code:"validate_files_orphaned_paths",command:"pm <files|docs> <id> --add <path>",summary:"Link the orphaned artifact with pm files (file) or pm docs (doc), or remove it from the workspace."},{code:"validate_files_tracked_all_strict_forces_pm_internals",command:"pm validate --check-files --include-pm-internals",summary:"tracked-all-strict scan flagged pm internals; re-run with --include-pm-internals or a softer --scan-mode."},{code:"validate_history_drift_missing_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items missing a history stream."},{code:"validate_history_drift_unreadable_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with an unreadable history stream."},{code:"validate_history_drift_hash_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items whose content hash drifted."},{code:"validate_history_drift_chain_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with a broken history chain."},{code:"validate_command_references_stale_pm_ids",command:'pm update <id> --replace-tests --test "command=<corrected-command>" [--test ...]',summary:"Correct the stale pm-ID inside the item's linked test command (the check scans tests[].command, not the body). --replace-tests overwrites the entire tests list, so re-include the item's other linked tests in the same call."},{code:"validate_format_version_outdated_items",command:"pm validate --verbose-diagnostics",summary:"One or more items predate the current storage format version; a pm storage migration rewrites them. Use --verbose-diagnostics to list the affected items."},{code:"validate_format_version_ahead_items",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more items were written by a newer pm format version than this runtime supports; upgrade pm to read and validate them safely."}]);function ms(e){if(typeof e!="string")return;let t=e.trim();for(let n of us)if(t===n.code||t.startsWith(`${n.code}:`))return n}function fs(e){let t={};for(let n of e){let r=ms(n);r!==void 0&&!Object.prototype.hasOwnProperty.call(t,r.code)&&(t[r.code]=r.command)}return t}function Zn(e){return Object.values(fs(e))}import pe from"node:fs/promises";import{createHash as ps}from"node:crypto";import er 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]="90364096-b94c-591c-9024-e697fa9322a5")}catch{}})();var tr=3,_s="history-drift-cache.json";function nr(e){return er.join(e,"runtime",_s)}async function hs(e){try{let t=await pe.readFile(nr(e),"utf8"),n=JSON.parse(t);return n.version!==tr||typeof n.entries!="object"||n.entries===null?null:n}catch{return null}}function rr(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}async function gs(e,t,n,r,i){let s=dn(e),a;try{a=await pe.stat(s)}catch(l){return rr(l,"ENOENT")||i.unreadableStreams.push(Z),!1}let o=i.missingStreams.length,c=await sr({itemId:Z,historyPath:s,stat:a,cached:t[Z],verifyCacheHitByContent:r,accumulator:i});return c.verification?(c.verification.chainOk||i.chainMismatches.push(Z),n[Z]={mtime_ms:a.mtimeMs,ctime_ms:a.ctimeMs,size:a.size,content_hash:c.verification.contentHash,latest_after_hash:c.verification.latestAfterHash,chain_ok:c.verification.chainOk},c.cacheDirty):(i.missingStreams.splice(o),c.cacheDirty)}function ir(e){return ps("sha256").update(e).digest("hex")}async function ys(e){let t=await pe.readFile(e,"utf8");return ir(t)}async function ws(e){let t=await pe.readFile(e,"utf8"),n=ir(t);if(t.trim().length===0)return null;let r=[],i=null;for(let s of t.split(/\r?\n/)){let a=s.trim();if(a.length===0)continue;let o=JSON.parse(a);if(typeof o.after_hash!="string"||o.after_hash.trim().length===0)throw new Error("missing after_hash");r.push(o),i=o.after_hash}return i?{latestAfterHash:i,chainOk:ln(r).ok,contentHash:n}:null}function ks(e,t){return e!==void 0&&e.mtime_ms===t.mtimeMs&&e.ctime_ms===t.ctimeMs&&e.size===t.size}async function Qn(e,t,n){try{let r=await ws(t);return r||(n.missingStreams.push(e),null)}catch{return n.unreadableStreams.push(e),null}}async function sr(e){let t=typeof e.cached?.content_hash=="string"&&e.cached.content_hash.length>0?e.cached.content_hash:void 0;if(!(ks(e.cached,e.stat)&&t!==void 0&&e.cached!==void 0)||!e.cached)return{verification:await Qn(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0};let r;if(e.verifyCacheHitByContent)try{r=await ys(e.historyPath)}catch{return e.accumulator.unreadableStreams.push(e.itemId),{verification:null,cacheDirty:!1}}else r=t;return!e.verifyCacheHitByContent||r===t?{verification:{latestAfterHash:e.cached.latest_after_hash,chainOk:e.cached.chain_ok,contentHash:r},cacheDirty:!1}:{verification:await Qn(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0}}async function ar(e,t,n={}){let r={missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[]},s=(await hs(e))?.entries??{},a={},o=!1,c=n.cacheHitVerification!=="metadata";for(let u of t){let m=Vt(e,u.id),f;try{f=await pe.stat(m)}catch(S){rr(S,"ENOENT")?r.missingStreams.push(u.id):r.unreadableStreams.push(u.id);continue}let p=s[u.id],y=await sr({itemId:u.id,historyPath:m,stat:f,cached:p,verifyCacheHitByContent:c,accumulator:r});if(o||=y.cacheDirty,!y.verification)continue;y.verification.chainOk||r.chainMismatches.push(u.id),a[u.id]={mtime_ms:f.mtimeMs,ctime_ms:f.ctimeMs,size:f.size,content_hash:y.verification.contentHash,latest_after_hash:y.verification.latestAfterHash,chain_ok:y.verification.chainOk};let{body:_,...w}=u;cn({metadata:w,body:_})!==y.verification.latestAfterHash&&r.hashMismatches.push(u.id)}let l=await gs(e,s,a,c,r);if(o||=l,o||Object.keys(s).length!==Object.keys(a).length){let u=nr(e);try{await pe.mkdir(er.dirname(u),{recursive:!0}),await oe(u,JSON.stringify({version:tr,entries:a}))}catch{}}let d=[...new Set([...r.missingStreams,...r.unreadableStreams,...r.hashMismatches,...r.chainMismatches])].sort((u,m)=>u.localeCompare(m));return{...r,driftedItems:d}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ab236f47-a866-5236-b8da-f7f23140b978")}catch{}})();var vs=["metadata","resolution"],vt=["metadata","resolution","estimates","lifecycle"],bs="completed";function bt(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function or(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function cr(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let r=or(n.close_reason)??bs;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:r,command:`pm update ${n.id} --resolution ${bt(r)}`,gate:"resolution"})}return t}function lr(e){let t=[];for(let n of e){let r=or(n.resolution);r!==void 0&&t.push({item_id:n.id,check:"metadata",field:"close_reason",kind:"set_close_reason",value:r,command:`pm update ${n.id} --close-reason ${bt(r)}`,gate:"metadata"})}return t}function dr(e,t){return e.map(n=>{let r=mn(n.type,t);return{item_id:n.id,check:"metadata",field:"estimated_minutes",kind:"set_estimate",value:String(r),command:`pm update ${n.id} --estimate ${r}`,gate:"estimates"}})}function ur(e){return e.map(t=>t.grandparent_id!==void 0&&t.grandparent_active===!0?{item_id:t.id,check:"lifecycle",field:"parent",kind:"reparent",parent_id:t.grandparent_id,command:`pm update ${t.id} --parent ${t.grandparent_id}`,gate:"lifecycle"}:{item_id:t.id,check:"lifecycle",field:"parent",kind:"unset_parent",command:`pm update ${t.id} --unset parent`,gate:"lifecycle"})}function mr(e){let t=[];for(let n of e){if(n.classification!=="deleted")continue;let r=n.link_kind==="files"?"files":"docs";t.push({item_id:n.item_id,check:"files",field:n.link_kind,kind:n.link_kind==="files"?"prune_file_link":"prune_doc_link",path:n.path,command:`pm ${r} ${n.item_id} --remove ${bt(n.path)}`})}return t}function fr(e){let t=(e??[]).flatMap(r=>r.split(",")).map(r=>r.trim()).filter(r=>r.length>0);if(t.length===0){if(e!==void 0&&e.length>0)throw new g(`--fix-scope values must not be empty. Supported values: ${vt.join(", ")}.`,h.USAGE);return new Set(vs)}let n=new Set;for(let r of t){let i=r.toLowerCase().replaceAll("-","_");if(vt.includes(i)){n.add(i);continue}throw new g(`Unknown --fix-scope value "${r}". Supported values: ${vt.join(", ")}.`,h.USAGE)}return n}function pr(e,t){let n=[],r=[];for(let i of e)i.gate!==void 0&&!t.has(i.gate)?r.push(i):n.push(i);return{applicable:n,gated:r}}function be(e){return{item_id:e.item_id,check:e.check,field:e.field,command:e.command,...e.gate!==void 0?{gate:e.gate}:{}}}(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]="087bac58-e32d-5cb8-8fda-0e09075c3f35")}catch{}})();var Rs=/^([A-Z][A-Z0-9]*-\d+)\b/;function Ss(e){if(typeof e!="string")return null;let t=e.trim().toUpperCase();if(t.length===0)return null;let n=Rs.exec(t);return n?n[1]:null}function _r(e){return typeof e=="string"&&e.trim().length>0}function hr(e){let t=new Map;for(let r of e){if(typeof r.title!="string"||_r(r.duplicate_of))continue;let i=Ss(r.title);if(i===null)continue;let s=t.get(i);s||(s=[],t.set(i,s)),s.some(a=>a.id===r.id)||s.push({id:r.id,title:r.title,parent:_r(r.parent)?r.parent.trim():null})}let n=[];for(let[r,i]of t){if(i.length<2)continue;let s=new Set(i.map(c=>c.id.toLowerCase())),a=i.filter(c=>c.parent===null||!s.has(c.parent.toLowerCase()));if(a.length<2)continue;let o=[...a].sort((c,l)=>c.id.localeCompare(l.id));n.push({code:r,count:o.length,ids:o.map(c=>c.id),titles:o.map(c=>c.title)})}return n.sort((r,i)=>r.code.localeCompare(i.code))}(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]="1951b0f1-11fa-5728-b516-7458a55b1e29")}catch{}})();function gr(e){let t=new Map;for(let r of e){let i=t.get(r.item_type);i||(i=new Map,t.set(r.item_type,i)),i.set(r.field,(i.get(r.field)??0)+1)}let n={};for(let r of[...t.keys()].sort((i,s)=>i.localeCompare(s))){let i=t.get(r),s={};for(let a of[...i.keys()].sort((o,c)=>o.localeCompare(c)))s[a]=i.get(a);n[r]=s}return 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]="5a5b0bd8-d99b-52fb-82ae-52ba48c54c30")}catch{}})();var yr=3;function wr(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function kr(e,t,n=yr){let r=Number.isFinite(n)&&n>=1?Math.floor(n):yr,i=new Map;for(let s of t){let a=wr(s);if(a.length===0)continue;let o=i.get(a);o?o.push(s):i.set(a,[s])}return e.map(s=>{let a=(i.get(wr(s))??[]).filter(o=>o!==s).sort((o,c)=>o.localeCompare(c));return a.length===0?{path:s,classification:"deleted",candidates:[],candidates_truncated:!1}:{path:s,classification:"moved",candidates:a.slice(0,r),candidates_truncated:a.length>r}})}function vr(e){return e.map(t=>t.classification==="moved"?`${t.path}:moved:${t.candidates[0]}`:`${t.path}:deleted`)}(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]="2b9ba0a4-396f-5870-bc89-e7fc789bb49d")}catch{}})();var As=/^[a-z][a-z0-9+.-]+:\/\//i;function Re(e){return As.test(e.trim())}(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]="e063d634-4306-5725-927a-5f2af1722458")}catch{}})();function Es(e,t){return e==="moved"||t==="moved"?"moved":"deleted"}function br(e){return`${e.item_id} ${e.link_kind}`}function Rr(e,t){let n=new Map;for(let r of e){let i=n.get(r.path);i?(i.classification=Es(i.classification,r.classification),i.owners.set(br(r),r)):n.set(r.path,{classification:r.classification,owners:new Map([[br(r),r]])})}return[...n.entries()].sort(([r],[i])=>r.localeCompare(i)).map(([r,i])=>({path:r,classification:i.classification,items:[...i.owners.values()].map(s=>{let a=t(s.item_id);return{id:s.item_id,type:a?.type??"Unknown",title:a?.title??"",status:a?.status??"",field:s.link_kind}}).sort((s,a)=>{let o=s.id.localeCompare(a.id);return o!==0?o:s.field.localeCompare(a.field)})}))}function xs(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Sr(e){let t=[];for(let n of e)for(let r of n.items)t.push(`${n.path}:${n.classification} owner=${r.id} status=${r.status} field=${r.field} title="${xs(r.title)}"`);return t}import{execFile as Cs}from"node:child_process";import{realpath as Is}from"node:fs/promises";import Ar from"node:path";import{promisify as Ts}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d18b51d7-294a-52da-b1cf-a10f24aefbc9")}catch{}})();var Os=Ts(Cs),Fs=32*1024*1024,Ps=1e4,Ds=["search/eval-queries.json"];function Rt(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}function Ns(e){return`'${e.replaceAll("'","'\\''")}'`}async function Ms(e,t=Is){return t(e).catch(()=>Ar.resolve(e))}async function Er(e){let t=await ke(e);if(t===null)return{git_workspace_root:null,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let n=await Ms(e),r=Rt(Ar.relative(t,n));if(r.length===0)return{git_workspace_root:t,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let i=st.map(s=>`${r}/${Rt(s)}`);try{let{stdout:s}=await Os("git",["ls-files","-z","--",...i.map(l=>`:(literal)${l}`)],{cwd:t,encoding:"utf8",maxBuffer:Fs,windowsHide:!0,timeout:Ps}),a=new Set(Ds.map(l=>`${r}/${l}`)),o=[...new Set(s.split("\0").filter(l=>l.length>0&&!a.has(Rt(l))))].sort((l,d)=>l.localeCompare(d)),c=i.filter(l=>o.some(d=>d===l||d.startsWith(`${l}/`)));return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:o,tracked_path_count:o.length,remediation_command:o.length===0?null:`git rm --cached -r -- ${c.map(l=>Ns(`:(literal)${l}`)).join(" ")}`}}catch{return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:[],tracked_path_count:0,remediation_command:null}}}import Ls from"node:fs/promises";import z from"node:path";import $s from"fast-glob";(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]="3fe80124-596b-591c-9f0d-fbbc129c6bb4")}catch{}})();var js=["path","scope","note"],Bs=["pattern","glob","path","scope","note"],Us=["path"],zs=["from","to"],Gs=new Set(["note","scope"]);function Cr(e){let t=e??"project";if(!Ye.includes(t))throw new g(`Invalid scope "${e}". Valid scopes: ${Ye.join(", ")} (default: project).`,h.USAGE);return t}function Ir(e){return e.startsWith("```")||e.includes(`
|
|
15
|
-
`)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(e)?!0:gn(e)}function qs(e){return e.flatMap(t=>{let n=t.trim();return n.length===0||Ir(n)||!n.includes(",")?[t]:wn(n)})}function Ws(e,t){return e?qs(e).map(n=>{let r=n.trim(),i=Ir(r)?ge(n,"--add"):{path:r};if(ye(i,"--add",js),!i.path)throw new g(`--add requires path=<value> or a bare ${t} path`,h.USAGE);return{path:i.path,scope:Cr(i.scope),note:i.note?.trim()||void 0}}):[]}function Hs(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new g("--add-glob requires a glob pattern value",h.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(n)||n.startsWith("```")){let r=ge(n,"--add-glob");ye(r,"--add-glob",Bs);let i=r.pattern?.trim()||r.glob?.trim()||r.path?.trim();if(!i)throw new g("--add-glob key/value form requires pattern=<glob>",h.USAGE);return{pattern:i,scope:Cr(r.scope),note:r.note?.trim()||void 0}}return{pattern:n,scope:"project"}}):[]}function Vs(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new g("--remove requires a path value",h.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(n)||n.startsWith("```")){let r=ge(n,"--remove"),i=Object.keys(r).filter(s=>Gs.has(s.toLowerCase()));if(i.length>0)throw new g(`--remove identifies a linked artifact by path only and does not accept ${i.map(s=>`"${s}"`).join(", ")}. Pass just the path (path=<value>, path:<value>, or a bare path); record removal context with --message "<why removed>".`,h.USAGE);if(ye(r,"--remove",Us),!r.path)throw new g("--remove key/value form requires path=<value>",h.USAGE);return r.path}return n}):[]}function Ks(e){return e?e.map(t=>{let n=ge(t,"--migrate");ye(n,"--migrate",zs);let r=n.from?.trim(),i=n.to?.trim();if(!r||!i)throw new g("--migrate requires from=<value> and to=<value>",h.USAGE);return{from:r,to:i}}):[]}function St(e,t){let n=e;for(let r of t)n.startsWith(r.from)&&(n=`${r.to}${n.slice(r.from.length)}`);return n}function te(e){return e.split(z.sep).join("/")}function At(e,t,n=process.cwd()){let r=e.trim();if(Re(r))return r;if(z.isAbsolute(r)||/^[A-Za-z]:[\\/]/.test(r))return te(r.replaceAll("\\",z.sep));let i=z.relative(t,n);return i.startsWith(`..${z.sep}`)||i===".."||z.isAbsolute(i)?te(z.normalize(r)):te(z.relative(t,z.resolve(n,r)))}async function Ys(e,t=process.cwd(),n=process.cwd()){let r=[];for(let i of e){let s=z.isAbsolute(i.pattern),a=await $s(i.pattern,{cwd:n,absolute:s,onlyFiles:!0,dot:!0,unique:!0,followSymbolicLinks:!0}),o=[...new Set(a.map(c=>At(c,t,n)))].sort((c,l)=>c.localeCompare(l));for(let c of o)r.push({path:c,scope:i.scope,note:i.note})}return r}function Js(e,t,n){if(t===void 0)return e;if(!n)throw new g("--note requires --add or --add-glob in the same invocation (the note annotates the links being added)",h.USAGE);let r=t.trim();return r.length===0?e:e.map(i=>i.note===void 0?{...i,note:r}:i)}function Xs(e){return`${e.path}::${e.scope}`}function Et(e){return[...e].sort((t,n)=>{let r=t.path.localeCompare(n.path);return r!==0?r:t.scope.localeCompare(n.scope)})}function xt(e){return[...new Map(e.map(t=>[Xs(t),t])).values()].map(t=>({...t,note:t.note?.trim()||void 0}))}async function Zs(e,t=process.cwd()){let n=[...new Set(e)].sort((o,c)=>o.localeCompare(c)),r=[],i=[],s=[],a=[];for(let o of n){if(Re(o)){a.push(o.trim());continue}let c=z.isAbsolute(o)?o:z.resolve(t,o);try{(await Ls.stat(c)).isFile()?r.push(o):s.push(o)}catch(l){if(typeof l=="object"&&l!==null&&"code"in l&&l.code==="ENOENT"){i.push(o);continue}s.push(o)}}return{checked:n.length,existing_files:r,missing_paths:i,non_file_paths:s,remote_references:a}}function Qs(e,t,n,r){let i=0;for(let a=0;a<e.length;a+=1){let o=St(e[a].path,r);o!==e[a].path&&(e[a]={...e[a],path:o},i+=1)}return{adds:t.map(a=>{let o=St(a.path,r);return o!==a.path&&(i+=1),{...a,path:o}}),removes:n.map(a=>St(a,r)),count:i}}function ea(e,t,n,r){for(let s of t)e.some(a=>a.path===s.path&&a.scope===s.scope)||e.push(s);if(n.length>0)for(let s=e.length-1;s>=0;s-=1)n.includes(e[s].path)&&e.splice(s,1);let i=xt(e);return r?i:Et(i)}async function xr(e){let t=e.artifacts.map(n=>n.path);return{id:e.id,artifacts:e.artifacts,changed:e.changed,count:e.artifacts.length,migrations_applied:e.migrationsApplied&&e.migrationsApplied>0?e.migrationsApplied:void 0,validation:e.options.validatePaths?await Zs(t,e.workspaceRoot):void 0}}async function je(e,t,n,r){let{metadataKey:i}=r,s=yn(),a=B(process.cwd(),n.path),o=he(a),c=process.cwd();if(!await N(U(a)))throw new g(`Tracker is not initialized at ${a}. Run pm init first.`,h.NOT_FOUND);let l=await L(a),d=V(l,J()),u=await s.resolveList(t.add,"--add"),m=await s.resolveList(t.addGlob,"--add-glob"),f=await s.resolveList(t.remove,"--remove"),p=await s.resolveList(t.migrate,"--migrate"),y=Ws(u,r.bareNoun).map(D=>({...D,path:At(D.path,o,c)})),_=Hs(m),w=await Ys(_,o,c),b=Js([...y,...w],t.note,y.length>0||_.length>0),S=Vs(f).map(D=>At(D,o,c)),A=Ks(p);if(!(b.length>0||S.length>0||A.length>0)){let D=await xe(a,e,l.id_prefix,l.item_format,d.type_to_folder);if(!D)throw new g(`Item ${e} not found`,h.NOT_FOUND);let I=(await Ce(D,{schema:l.schema})).document.metadata[i]??[];return xr({id:D.id,artifacts:I,changed:!1,options:t,workspaceRoot:o})}let Y=de(t.author,l.author_default),W=await Te({pmRoot:a,settings:l,id:e,op:r.op,author:Y,message:t.message,force:t.force,skipNoop:!0,mutate(D){let v=D.metadata,I=v[i]??[],le=[...I],ae=Qs(le,b,S,A),Ke=ea(le,ae.adds,ae.removes,r.supportsAppendStable&&t.appendStable===!0);Ke.length>0?v[i]=Ke:delete v[i];let Bt=!Yt(I,Ke);return{changedFields:Bt?[i]:[],warnings:Bt&&ae.count>0?[`path_migrations_applied:${ae.count}`]:[]}}}),x=W.item[i]??[],P=W.warnings.find(D=>D.startsWith("path_migrations_applied:")),H=P?Number(P.slice(24)):0;return xr({id:W.item.id,artifacts:x,changed:W.changedFields.includes(i),migrationsApplied:H,options:t,workspaceRoot:o})}function Be(e,t){let n={};for(let[r,i]of Object.entries(e))n[r==="artifacts"?t:r]=i;return 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]="c4c82f8f-7890-5ed2-8f0f-a82ba42cf807")}catch{}})();async function Tr(e,t,n){let r=await je(e,t,n,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return Be(r,"docs")}import Or from"node:fs/promises";import G 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]="5e45d0f1-a1a7-50ea-a9a3-ec6283d3471d")}catch{}})();var ta=32768;function Ct(e){return te(G.normalize(e))}async function Ue(e){try{return await Or.realpath(e)}catch{return G.resolve(e)}}function _e(e,t){let n=G.isAbsolute(e.path)?G.resolve(e.path):G.resolve(t,e.path);return`${Ct(n)}::${e.scope}`}function ze(e,t,n){if(typeof e=="string"){let r=e.trim();r.length>0&&n.push({field:t,value:r});return}if(Array.isArray(e)){e.forEach((r,i)=>ze(r,`${t}[${i}]`,n));return}if(typeof e=="object"&&e!==null)for(let[r,i]of Object.entries(e))ze(i,t?`${t}.${r}`:r,n)}function na(e){let t=[];return ze(e.metadata,"metadata",t),ze(e.body,"body",t),t}function ra(e){let t=e.trim();return t=t.replace(/^[`"'<([{]+/u,""),t=t.replace(/[`"'>)\]},;!?]+$/u,""),t=t.replace(/[.]+$/u,""),t=t.replace(/:(?:\d+)(?::\d+)?$/u,""),t=t.replace(/[.]+$/u,""),t}function ia(e){let t=[],n=/(?:[A-Za-z]:[\\/]|\/)[^\s"'`<>()[\]{},;]+/gu,r=/(?:\.{1,2}[\\/])?(?:(?:[A-Za-z0-9_.@-]+[\\/])+[A-Za-z0-9_.@-]+|[A-Za-z0-9_.@-]+\.[A-Za-z0-9][A-Za-z0-9._-]*)/gu;for(let i of e){let s=new Set,a=i.value.slice(0,ta);for(let[o,c]of[[n,i.value],[r,a]]){o.lastIndex=0;for(let l of c.matchAll(o)){let d=ra(l[0]);!d||s.has(d)||(s.add(d),t.push({field:i.field,value:d}))}}}return t}async function sa(e,t,n=t){let r=G.isAbsolute(e)?G.resolve(e):G.resolve(n,e),i;try{i=await Or.stat(r)}catch{return}if(!i.isFile())return;let[s,a]=await Promise.all([Ue(t),Ue(r)]);if(Xe(s,a)){let o=G.relative(s,a);return!o||o.startsWith("..")||G.isAbsolute(o)?void 0:{path:Ct(o),scope:"project"}}return{path:Ct(r),scope:"global"}}async function aa(e,t,n=t){let r=new Set((e.metadata.files??[]).map(c=>_e(c,t))),i=new Map,s=ia(na(e)),a=new Map;await Promise.all([...new Set(s.map(c=>c.value))].map(async c=>{a.set(c,await sa(c,t,n))}));let o=s.map(c=>({reference:c,resolved:a.get(c.value)}));for(let{reference:c,resolved:l}of o){if(!l)continue;let d=_e(l,t),u=i.get(d)??{path:l.path,scope:l.scope,sourceFields:new Set,originalPaths:new Set,sourceCount:0};u.sourceFields.add(c.field),u.originalPaths.add(c.value),u.sourceCount+=1,i.set(d,u)}return[...i.entries()].map(([c,l])=>({path:l.path,scope:l.scope,status:r.has(c)?"already_linked":"addable",source_count:l.sourceCount,source_fields:[...l.sourceFields].sort((d,u)=>d.localeCompare(u)),original_paths:[...l.originalPaths].sort((d,u)=>d.localeCompare(u))})).sort((c,l)=>{let d=c.status.localeCompare(l.status);if(d!==0)return d;let u=c.path.localeCompare(l.path);return u!==0?u:c.scope.localeCompare(l.scope)})}async function Fr(e,t,n){let r=await je(e,t,n,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return Be(r,"files")}async function oa(e,t){let n=await Ue(t),r=await Promise.all(e.map(async s=>{let a=s.trim();if(!a)throw new g("Files lookup paths must not be empty.",h.USAGE);if(!G.isAbsolute(a))return te(a);let o=await Ue(a);return Xe(n,o)?te(G.relative(n,o)):te(o)})),i=[...new Set(r)].sort((s,a)=>s.localeCompare(a));if(i.length===0)throw new g("Files lookup requires at least one path.",h.USAGE);return i}function ca(e){for(let[r,i]of[["limit",e.limit],["offset",e.offset]])if(i!==void 0&&(!Number.isInteger(i)||i<0))throw new g(`Files lookup ${r} must be a non-negative integer.`,h.USAGE);let{offset:t=0,limit:n=50}=e;return{offset:Math.max(0,Math.floor(t)),limit:e.noTruncate?void 0:Math.max(0,Math.floor(n))}}function Pr(e){return{id:e.id,title:e.title,type:e.type,status:e.status,priority:e.priority,updated_at:e.updated_at}}async function la(e){if([e.strictRead,e.noTruncate,en()].includes(!0))return null;let t=await _n(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]);return t?pn({pmRoot:e.pmRoot,expectedSourceCursor:t.source_cursor,paths:e.paths,scope:e.scope,limit:e.limit,offset:e.offset}):null}async function da(e){let t=[],r=(await Ie(e.pmRoot,e.settings.item_format,e.typeToFolder,t,e.settings.schema)).map(a=>({item:a,files:(a.files??[]).filter(o=>e.paths.includes(te(o.path))&&(e.scope===void 0||o.scope===e.scope)).sort((o,c)=>{let l=o.path.localeCompare(c.path);return l===0?o.scope.localeCompare(c.scope):l})})).filter(a=>a.files.length>0).sort((a,o)=>{let c=a.item.priority-o.item.priority;if(c!==0)return c;let l=o.item.updated_at.localeCompare(a.item.updated_at);return l===0?a.item.id.localeCompare(o.item.id):l}),i=t.filter(a=>/^item_list_(?:item|directory)_read_failed:/u.test(a));if(e.strictRead&&i.length>0)throw new g(`Files lookup could not read every item: ${i.join("; ")}`,h.GENERIC_FAILURE);let s=r.slice(e.offset,e.limit===void 0?void 0:e.offset+e.limit);return{paths:e.paths,total:r.length,count:s.length,offset:e.offset,limit:e.limit??null,has_more:e.offset+s.length<r.length,truncated:e.offset+s.length<r.length,completeness:{status:i.length===0?"complete":"partial",source:"source_scan"},warnings:t,matches:s.map(a=>({item:Pr(a.item),files:a.files}))}}async function vd(e,t){let n=B(process.cwd(),t.path),r=he(n);if(!await N(U(n)))throw new g(`Tracker is not initialized at ${n}. Run pm init first.`,h.NOT_FOUND);let i=await oa(e.paths,r),s=await L(n),a=V(s,J()),{offset:o,limit:c}=ca(e),l=await la({pmRoot:n,typeToFolder:a.type_to_folder,paths:i,scope:e.scope,limit:c,offset:o,strictRead:e.strictRead===!0,noTruncate:e.noTruncate===!0});return l?{paths:i,total:l.total,count:l.matches.length,offset:o,limit:c,has_more:o+l.matches.length<l.total,truncated:o+l.matches.length<l.total,completeness:{status:"unchecked",source:"index"},warnings:[],matches:l.matches.map(d=>({item:Pr(d.item),files:d.files}))}:da({pmRoot:n,settings:s,typeToFolder:a.type_to_folder,paths:i,scope:e.scope,limit:c,offset:o,strictRead:e.strictRead===!0})}async function bd(e,t,n){let r=B(process.cwd(),n.path),i=he(r);if(!await N(U(r)))throw new g(`Tracker is not initialized at ${r}. Run pm init first.`,h.NOT_FOUND);let s=await L(r),a=V(s,J()),o=await xe(r,e,s.id_prefix,s.item_format,a.type_to_folder);if(!o)throw new g(`Item ${e} not found`,h.NOT_FOUND);let c=await Ce(o,{schema:s.schema}),l=await aa(c.document,i,process.cwd()),d=l.filter(x=>x.status==="addable"),u=l.filter(x=>x.status==="already_linked"),m=t.apply===!0,f=t.note?.trim()||"discovered from item text";if(!m||d.length===0){let x=c.document.metadata.files??[];return{id:o.id,files:x,changed:!1,apply:m,count:x.length,candidate_count:l.length,addable_count:d.length,added_count:0,skipped_existing_count:u.length,candidates:l,added:[],skipped_existing:u}}let p=de(t.author,s.author_default),y=d.map(x=>({path:x.path,scope:x.scope,note:f})),_=[],w=new Set,b=await Te({pmRoot:r,settings:s,id:e,op:"files_discover",author:p,message:t.message??"Discover referenced file links",force:t.force,mutate(x){let P=[...x.metadata.files??[]],H=new Set(P.map(I=>_e(I,i)));_=[],w.clear();for(let[I,le]of y.entries()){let ae=_e(le,i);H.has(ae)||(P.push(le),H.add(ae),_.push(le),w.add(I))}let D=xt(P),v=t.appendStable?D:Et(D);return v.length>0?x.metadata.files=v:delete x.metadata.files,{changedFields:_.length>0?["files"]:[],warnings:_.length!==y.length?[`files_discover_skipped_existing:${y.length-_.length}`]:[]}}}),S=b.item.files??[],A=new Set(_.map(x=>_e(x,i))),E=S.filter(x=>A.has(_e(x,i))),Y=d.filter((x,P)=>!w.has(P)),W=[...u,...Y];return{id:b.item.id,files:S,changed:E.length>0,apply:!0,count:S.length,candidate_count:l.length,addable_count:d.length,added_count:E.length,skipped_existing_count:W.length,candidates:l,added:E,skipped_existing:W}}import{readFileSync as ua}from"node:fs";import Ge 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]="673a5a26-6214-58d6-af19-baee5a8359f0")}catch{}})();var ma=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),It=new Set(["--pm-path","--path","--author"]),fa={get:new Set(["--depth","--fields","--tree-depth","--tree_depth","--at","--format"]),history:new Set(["--limit","--field","--format"]),restore:new Set(["--message"]),update:new Set(["--title","-t","--description","-d","--body","-b","--status","-s","--close-reason","--close_reason","--priority","-p","--type","--tags","--add-tags","--add_tags","--remove-tags","--remove_tags","--deadline","--estimated-minutes","--estimate","--estimated_minutes","--acceptance-criteria","--ac","--acceptance_criteria","--definition-of-ready","--definition_of_ready","--order","--rank","--goal","--objective","--value","--impact","--outcome","--why-now","--why_now","--message","--assignee","--parent","--reviewer","--risk","--confidence","--sprint","--release","--blocked-by","--blocked_by","--blocked-reason","--blocked_reason","--unblock-note","--unblock_note","--reporter","--severity","--environment","--repro-steps","--repro_steps","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual","--affected-version","--affected_version","--fixed-version","--fixed_version","--component","--regression","--customer-impact","--customer_impact","--dep","--dep-remove","--dep_remove","--comment","--note","--learning","--file","--test","--doc","--reminder","--event","--type-option","--type_option","--field","--unset","--body-file"]),close:new Set(["--reason","-r","--close-reason","--duplicate-of","-d","--message","-m","--validate-close","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual"]),delete:new Set(["--message"]),append:new Set(["--body","--text","--message"]),claim:new Set(["--assignee","--message","--type","--tag","--priority","--assignee-filter","--parent","--sprint","--release","--max-attempts"]),release:new Set(["--assignee","--message"]),comments:new Set(["--add","--body","--comment","--file","--edit","--delete","--limit","--message"]),notes:new Set(["--add","--file","--edit","--delete","--limit","--message"]),learnings:new Set(["--add","--file","--edit","--delete","--limit","--message"]),files:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),docs:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),deps:new Set(["--format","--max-depth","--collapse","--node-limit","--edge-limit","--token-budget","--cursor","--direction","--kind"]),test:new Set(["--add","--add-json","--remove","--match","--only-index","--timeout","--env-set","--env-clear","--pm-context","--message"])},pa=new Set(["-p","--package"]),_a=new Set(["-c","--call"]),ha=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),ga=new Set(["-C","--prefix","--userconfig","--cache"]),Ed=new Set(["--cwd"]),xd=new Set(["--cwd"]),ya=new Set(["exec","x"]),Cd=new Set(["run","run-script"]),Id=new Set(["-C","--dir","--cwd","-w","--workspace","--filter"]);function wa(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function ka(e,t=process.cwd()){let n=va(e.split(" ").filter(a=>a.length>0));if(n.length===0)return null;let[r,...i]=n;if(Dr(r)||Nr(r,t))return i;if(r==="node"&&i[0]&&Nr(i[0],t))return i.slice(1);let s=r==="npx"||r==="bunx"?Tt(i):r==="pnpm"?Sa(i):r==="npm"?Aa(i):null;return s&&(Dr(s.command)||Ra(s.command))?s.args:null}var Mr=(e,t="pm")=>{let n=t.trim().toLowerCase(),r=n.length;for(;r>0&&n[r-1]==="-";)r-=1;let i=n.slice(0,r);if(i.length===0)return[];let s=e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase(),a=new Set;for(let o of wa(s)){let c=ka(o),l=c?Ea(c):null,d=l&&ma.has(l.subcommand)?xa(l.remaining,fa[l.subcommand]):void 0,u=d?.trim().toLowerCase();u?.startsWith(`${i}-`)===!0&&u.length>i.length+1&&a.add(d)}return[...a].sort((o,c)=>o.localeCompare(c))};function va(e){let t=0;for(e[t]==="env"&&(t+=1);t<e.length;){let n=e[t];if(/^(?:[a-z_][a-z0-9_]*|\$env:[a-z_][a-z0-9_]*)=.*/.test(n)){t+=1;continue}break}return e.slice(t)}function Td(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(It.has(n)){t+=2;continue}t+=1;continue}return n}}function Dr(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function ba(e){let t=e.trim();if(!t.startsWith("@")){let i=t.indexOf("@");return i===-1?t:t.slice(0,i)}let n=t.indexOf("/");if(n===-1)return t;let r=t.indexOf("@",n+1);return r===-1?t:t.slice(0,r)}function Ra(e){let t=ba(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function Nr(e,t=process.cwd()){let n=e.replaceAll("\\","/");if(n!=="dist/cli.js"&&n!=="./dist/cli.js"&&!n.endsWith("/dist/cli.js"))return!1;let r=Ge.resolve(t,e);try{return JSON.parse(ua(Ge.join(Ge.dirname(Ge.dirname(r)),"package.json"),"utf8")).name==="@unbrained/pm-cli"}catch{return!1}}function Tt(e){let t=0;for(;t<e.length;){let r=e[t];if(r==="--"){t+=1;break}if(!r.startsWith("-"))break;let i=/^(?:-c|--call)=(.*)$/.exec(r);if(i){let s=i[1];return s?{command:s,args:e.slice(t+1)}:null}if(_a.has(r)){t+=1;break}t+=pa.has(r)&&!r.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function Lr(e,t){let n=0;for(;n<e.length;){let r=e[n];if(r==="--"){n+=1;continue}if(r.startsWith("-")){if(r.includes("=")){n+=1;continue}if(t.has(r)){n+=2;continue}n+=1;continue}return{subcommand:r,args:e.slice(n+1)}}return null}function Sa(e){let t=Lr(e,ha);return t?.subcommand!=="dlx"?null:Tt(t.args)}function Aa(e){let t=Lr(e,ga);return!t||!ya.has(t.subcommand)?null:Tt(t.args)}function Ea(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(It.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function xa(e,t=new Set){for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="--")return e[n+1];if(!r.startsWith("-"))return r;!r.includes("=")&&(It.has(r)||t.has(r))&&(n+=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]="896ffe11-2cf1-5de0-8d07-5585d4f30c94")}catch{}})();async function $r(e){return e.includeBody?hn(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema):Ie(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema)}(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]="b5b7e497-f067-5504-9ffa-fd177997c518")}catch{}})();var Oa=["src","tests","docs"],Fa=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],Pa=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),Da=["resolution","expected_result","actual_result"],Na=["default","tracked-all","tracked-all-strict"],jr=["core","strict","custom"],We=["off","warn","error"];var Ft=["author","acceptance_criteria","estimated_minutes","close_reason"],qr=[...Ft,"reviewer","risk","confidence","sprint","release"],Mt=Array.from(new Set(qr)),Ma={author:"author",acceptance_criteria:"acceptance_criteria","acceptance-criteria":"acceptance_criteria",estimated_minutes:"estimated_minutes","estimated-minutes":"estimated_minutes",estimate:"estimated_minutes",close_reason:"close_reason","close-reason":"close_reason",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release"},La={author:"validate_metadata_missing_author",acceptance_criteria:"validate_metadata_missing_acceptance_criteria",estimated_minutes:"validate_metadata_missing_estimate",close_reason:"validate_metadata_missing_close_reason",reviewer:"validate_metadata_missing_reviewer",risk:"validate_metadata_missing_risk",confidence:"validate_metadata_missing_confidence",sprint:"validate_metadata_missing_sprint",release:"validate_metadata_missing_release"},$a={author:"missing_author",acceptance_criteria:"missing_acceptance_criteria",estimated_minutes:"missing_estimated_minutes",close_reason:"closed_missing_close_reason",reviewer:"missing_reviewer",risk:"missing_risk",confidence:"missing_confidence",sprint:"missing_sprint",release:"missing_release"},ja={author:"missing_author_item_ids",acceptance_criteria:"missing_acceptance_criteria_item_ids",estimated_minutes:"missing_estimated_minutes_item_ids",close_reason:"closed_missing_close_reason_item_ids",reviewer:"missing_reviewer_item_ids",risk:"missing_risk_item_ids",confidence:"missing_confidence_item_ids",sprint:"missing_sprint_item_ids",release:"missing_release_item_ids"},Ba={author:"missing_author_truncated",acceptance_criteria:"missing_acceptance_criteria_truncated",estimated_minutes:"missing_estimated_minutes_truncated",close_reason:"closed_missing_close_reason_truncated",reviewer:"missing_reviewer_truncated",risk:"missing_risk_truncated",confidence:"missing_confidence_truncated",sprint:"missing_sprint_truncated",release:"missing_release_truncated"},Ua=32*1024*1024,za=1e4,Wr=40,re=5,Ga=4096,qa=255,Wa=Ta(Ia);function Hr(e){let t={};for(let[n,r]of Object.entries(e))Array.isArray(r)||(t[n]=typeof r=="object"&&r!==null?Hr(r):r);return t}function Ha(e){return{...e,checks:e.checks.map(t=>({...t,details:Hr(t.details)})),...e.fixes?{fixes:{mode:e.fixes.mode,auto_fix:e.fixes.auto_fix,prune_missing:e.fixes.prune_missing,planned_count:e.fixes.planned_count,applied_count:e.fixes.applied_count,gated_count:e.fixes.gated_count,failed_count:e.fixes.failed_count}}:{}}}function ce(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function Br(e){return ce(e).replace(/\/+$/,"")}function q(e){let t=M(e);if(!t)return;let n=t.toLowerCase();if(!(n==="none"||n==="null"||n==="n/a"||n==="na"))return t}function Ve(e,t){return an(e,t)??e}function Se(e,t){return t.terminal_statuses.has(Ve(e,t))}function ie(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function qe(e,t){return e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function Va(e){let t=ie(zt),n={blocked_reason:ie(Ae.blocked_reason),resolution:ie(Ae.resolution),actual_result:ie(Ae.actual_result)},r=ie(e.validation.lifecycle_stale_blocker_reason_patterns),i={blocked_reason:ie(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:ie(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:ie(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:r,stale_blocker_reason_pattern_source:qe(r,t)?"default":"settings",closure_like_metadata_field_patterns:i,closure_like_metadata_field_pattern_sources:{blocked_reason:qe(i.blocked_reason,n.blocked_reason)?"default":"settings",resolution:qe(i.resolution,n.resolution)?"default":"settings",actual_result:qe(i.actual_result,n.actual_result)?"default":"settings"}}}function Vr(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(jr.includes(t))return t;throw new g(`Unknown --metadata-profile value "${e}". Supported values: ${jr.join(", ")}.`,h.USAGE)}function Kr(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(We.includes(t))return t;throw new g(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${We.join(", ")}.`,h.USAGE)}function Yr(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(We.includes(t))return t;throw new g(`Unknown --parent-cycle-severity value "${e}". Supported values: ${We.join(", ")}.`,h.USAGE)}function Ka(e){return[...new Set((e??[]).map(n=>n.trim().toLowerCase().replaceAll("-","_")))].map(n=>Ma[n]).filter(n=>n!==void 0).sort((n,r)=>n.localeCompare(r))}function Ya(e,t,n){let r=Ka(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...Ft],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...qr],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:r.length>0?{profile:e,profile_source:t,required_fields:r,configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:{profile:e,profile_source:t,required_fields:[...Ft],configured_custom_fields:r,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var Ja=new Set(["acceptance_criteria","estimated_minutes"]);function Jr(e,t,n,r){return!r&&Ja.has(t)&&Se(e.status,n)?!1:t==="author"?!M(e.author):t==="acceptance_criteria"?!M(e.acceptance_criteria):t==="estimated_minutes"?!Number.isFinite(e.estimated_minutes):t==="close_reason"?Ve(e.status,n)===n.close_status&&!M(e.close_reason):t==="reviewer"?!M(e.reviewer):t==="risk"?!M(e.risk):t==="confidence"?typeof e.confidence=="number"?!Number.isFinite(e.confidence):!M(e.confidence):t==="sprint"?!M(e.sprint):!M(e.release)}function Xr(e){if(e===void 0)return"default";let t=e.trim().toLowerCase();if(t.length===0||t==="default")return"default";if(t==="tracked-all"||t==="tracked_all")return"tracked-all";if(t==="tracked-all-strict"||t==="tracked_all_strict")return"tracked-all-strict";throw new g(`Unknown --scan-mode value "${e}". Supported values: ${Na.join(", ")}.`,h.USAGE)}function Zr(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim();if(t)return $.resolve(t);let n=$.resolve(e);if(n.replaceAll("\\","/").endsWith("/.agents/pm"))return $.dirname($.dirname(n));let i=$.resolve(process.cwd()),s=Ur(n),a=Ur(i),o=$.relative(s,a);return o.length===0||!o.startsWith("..")&&!$.isAbsolute(o)?n:i}function Ur(e){try{return Ca.native(e)}catch{return $.resolve(e)}}function Qr(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function Lt(e,t,n){let r=t.length>0?$.join(e,t):e,i;try{i=await Nt.readdir(r,{withFileTypes:!0})}catch(s){if(Qr(s,["ENOENT"]))return;throw s}for(let s of i){if(s.name.startsWith("."))continue;let a=t.length>0?$.join(t,s.name):s.name;if(s.isDirectory()){if(Pa.has(s.name))continue;await Lt(e,a,n);continue}s.isFile()&&n.push(ce(a))}}async function Pt(e){let t=[];for(let n of Oa)await Lt(e,n,t);for(let n of Fa){let r=$.join(e,n);try{(await Nt.stat(r)).isFile()&&t.push(ce(n))}catch{}}return[...new Set(t)].sort((n,r)=>n.localeCompare(r))}async function ei(e){try{let{stdout:t}=await Wa("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:Ua,windowsHide:!0,timeout:za}),n=t.split("\0").map(r=>ce(r)).filter(r=>r.length>0);return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}catch{return null}}function Xa(e,t){let n=new Set,r=Br(Ut);r.length>0&&n.add(r);let i=Br($.relative(t,e));return i.length>0&&!i.startsWith("..")&&n.add(i),[...n].sort((s,a)=>s.localeCompare(a))}function zr(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function Za(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let r=await ei(e);if(r)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length};let i=await Pt(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:i,candidateTotal:i.length,candidateScanned:i.length}}let n=await Pt(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function F(e,t=re){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function se(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=F(e,Wr);return{values:n.values,truncated:n.truncated,total:e.length}}var Qa={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},eo={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function to(e){let t=e.missing_fields.map(n=>`${Qa[n]} "${eo[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function ti(e,t){let n=e.details?.missing_resolution_remediation_hints,r=Array.isArray(n)&&n.length>0,i=r?n.filter(a=>typeof a=="string"):Zn(t);if(i.length===0)return;let s=r&&e.details?.missing_resolution_remediation_hints_truncated===!0;e.details={...e.details,fix_hints:i,...s?{fix_hints_truncated:!0}:{}}}function ni(e){let t=new Set;return e.checkMetadata&&t.add("metadata"),e.checkResolution&&t.add("resolution"),(e.checkLifecycle||e.checkStaleBlockers)&&t.add("lifecycle"),e.checkFiles&&t.add("files"),e.checkHistoryDrift&&t.add("history_drift"),e.checkCommandReferences&&t.add("command_references"),e.checkStorageIntegrity&&t.add("storage_integrity"),t.size===0?(e.autoFix&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle")),e.pruneMissing&&t.add("files"),t.size===0&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle"),t.add("files"),t.add("command_references"),t.add("history_drift"),t.add("format_version"),t.add("storage_integrity")),t):(e.pruneMissing&&t.add("files"),t)}var no="validate_metadata_duplicate_issue_codes";function ri(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:re,r=e.slice(0,n);return{rows:r.map(s=>({code:s.code,count:s.count,ids:s.ids,titles:s.titles,remediation_hint:`Items ${s.ids.join(", ")} share issue code "${s.code}"; rename or merge so each logical code maps to one item.`})),truncated:r.length<e.length,warnings:[`${no}:${e.length}`]}}function ro(){return Object.fromEntries(Mt.map(e=>[e,[]]))}function io(e,t,n){let r=ro();for(let i of e)for(let s of Mt)Jr(i,s,t,n)&&r[s].push(i.id);return r}function so(e,t,n){let r=[...e.warnings];for(let i of e.required_fields){let s=t[i];s.length>0&&r.push(`${La[i]}:${s.length}`)}return r.push(...n),r}function ii(e,t){let n={};for(let r of e.required_fields){let i=t[r],s=i?i.length:0,a=$a[r];s>0&&a&&(n[a]=s)}return n}function si(e,t,n){let r=[];for(let i of e.required_fields){let s=t[i];if(s)for(let a of s){let o=n.get(a)?.type,c=typeof o=="string"&&o.length>0?o:"Unknown";r.push({item_type:c,field:i})}}return r}function ao(e,t,n,r){for(let i of t.required_fields){let s=n[i];if(!s||s.length===0)continue;let a=ja[i],o=Ba[i];if(!a||!o)continue;let c=F(s,r?s.length:re);e[a]=c.values,e[o]=c.truncated}}function ai(e,t,n){if(!e.required_fields.includes("close_reason"))return[];let r=t.close_reason;return r?r.map(i=>({id:i,resolution:M(n.get(i)?.resolution)})):[]}function oi(e,t,n){if(!e.required_fields.includes("estimated_minutes"))return[];let r=t.estimated_minutes;return r?r.map(i=>({id:i,type:M(n.get(i)?.type)})):[]}function oo(e,t,n,r){let i=new Map(e.map(_=>[_.id,_])),s=t.profile==="strict",a=io(e,n,s),o=hr(e),c=ri(o,r),l=so(t,a,c.warnings),d=ii(t,a),u=si(t,a,i),m=gr(u),f={checked_items:e.length,metadata_profile:t.profile,metadata_profile_source:t.profile_source,metadata_profile_fallback_to_core:t.fallback_to_core,required_fields:[...t.required_fields],supported_required_fields:[...Mt],counts:d,missing_by_type:m,duplicate_issue_codes_count:o.length,duplicate_issue_codes:c.rows,duplicate_issue_codes_truncated:c.truncated};t.configured_custom_fields.length>0&&(f.configured_custom_required_fields=[...t.configured_custom_fields]),ao(f,t,a,r);let p=ai(t,a,i),y=oi(t,a,i);return{check:{name:"metadata",status:l.length===0?"ok":"warn",details:f},warnings:l,closeReasonBackfillRows:p,estimateBackfillRows:y}}function co(e,t,n){let r=new Set(t.terminal_done_statuses);r.add(t.close_status);let i=e.filter(m=>r.has(Ve(m.status,t))),s=[],a=[];for(let m of i){let f=Da.filter(p=>!M(m[p]));f.length!==0&&(s.push({id:m.id,missing_fields:f}),a.push({id:m.id,missing_fields:f,close_reason:M(m.close_reason)}))}let o=s.length>0?[`validate_resolution_missing_fields:${s.length}`]:[],c=n?Number.POSITIVE_INFINITY:re,l=F(s.map(m=>`${m.id}:${m.missing_fields.join(",")}`),c),d=s.map(m=>to(m)),u=F(d,c);return{check:{name:"resolution",status:o.length===0?"ok":"warn",details:{checked_closed_items:i.length,missing_resolution_items:s.length,missing_resolution_rows:l.values,missing_resolution_rows_truncated:l.truncated,missing_resolution_remediation_hints:u.values,missing_resolution_remediation_hints_truncated:u.truncated}},warnings:o,resolutionBackfillRows:a}}function ci(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function li(e,t="pm",n=Ze()){let r=new Set(e.map(s=>s.id)),i=[...e].sort((s,a)=>s.id.localeCompare(a.id));return new Map(i.map(s=>{let a=new Set,o=q(s.blocked_by);o&&r.has(o)&&a.add(o),(s.dependencies??[]).filter(l=>{let d=q(l.kind);return d!==void 0&&n.resolve(d)?.ordering===!0}).map(l=>q(l.id)).filter(l=>l!==void 0&&r.has(l)).forEach(l=>a.add(l));let c=q(s.definition_of_ready);return ui(c??"",t).filter(l=>r.has(l)).forEach(l=>a.add(l)),[s.id,[...a].sort((l,d)=>l.localeCompare(d))]}))}function di(e,t,n){let r=kn(e,n?d=>Se(d,n):void 0),i=r.active.map(d=>`${d.holder_id}:${d.target_id}:${d.kind}`),s=r.legacy_terminal.map(d=>`${d.holder_id}:${d.target_id}:${d.kind}:${d.holder_status}`),a=t?Number.POSITIVE_INFINITY:re,o=F(i,a),c=F(s,a),l=F(r.active.map(d=>d.source==="parent"?`pm update ${d.holder_id} --unset parent`:d.source==="blocked_by"?`pm update ${d.holder_id} --unset blocked_by`:`pm update ${d.holder_id} --replace-deps '<correct dependency edges>'`),a);return{check:{name:"dependency_references",status:i.length===0?"ok":"warn",details:{checked_items:e.length,dangling_reference_count:i.length+s.length,active_dangling_reference_count:i.length,dangling_reference_rows:o.values,dangling_reference_rows_truncated:o.truncated,legacy_terminal_dangling_reference_count:s.length,legacy_closed_dangling_reference_count:r.legacy_terminal.filter(d=>d.holder_status==="closed").length,legacy_terminal_dangling_reference_rows:c.values,legacy_terminal_dangling_reference_rows_truncated:c.truncated,no_active_blocker_sentinel_count:r.no_active_blocker_sentinels.length,remediation_hints:l.values,remediation_hints_truncated:l.truncated}},warnings:i.length>0?[`validate_dangling_dependency_references:${i.length}`]:[]}}function ui(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),r=new RegExp(`(?:^|[^a-z0-9-])(${ci(n)}-[a-z0-9][a-z0-9-]*)`,"gi");return[...new Set([...e.matchAll(r)].map(i=>i[1].toLowerCase()))].sort((i,s)=>i.localeCompare(s))}function $t(e){let t=0,n=new Map,r=new Map,i=[],s=new Set,a=[],o=d=>{n.set(d,t),r.set(d,t),t+=1,i.push(d),s.add(d);for(let m of e.get(d)??[])n.has(m)?s.has(m)&&r.set(d,Math.min(r.get(d),n.get(m))):(o(m),r.set(d,Math.min(r.get(d),r.get(m))));if(r.get(d)!==n.get(d))return;let u=[];for(;i.length>0;){let m=i.pop();if(s.delete(m),u.push(m),m===d)break}u.sort((m,f)=>m.localeCompare(f)),a.push(u)},c=[...e.keys()].sort((d,u)=>d.localeCompare(u));for(let d of c)n.has(d)||o(d);return a.filter(d=>{if(d.length>1)return!0;let u=d[0];return(e.get(u)??[]).includes(u)}).sort((d,u)=>d[0].localeCompare(u[0])||d.length-u.length||d.join(",").localeCompare(u.join(",")))}function jt(e,t){let n=e[0];if(e.length===1)return[n,n];let r=new Set(e),i=[n],s=new Set([n]),a=o=>{let c=(t.get(o)??[]).filter(l=>r.has(l));for(let l of c){if(l===n&&i.length>1)return i.push(n),!0;if(!s.has(l)){if(s.add(l),i.push(l),a(l))return!0;i.pop(),s.delete(l)}}return!1};return a(n)?[...i]:[...e,n]}function mi(e,t="pm"){let n=li(e,t),r=$t(n),i=[...new Set(r.flat())].sort((a,o)=>a.localeCompare(o)),s=r.map(a=>jt(a,n).join("->"));return{cycle_count:r.length,cycle_item_ids:i,cycle_sample_paths:s}}function fi(e,t=Ze()){let n=new Map(e.map(s=>[s.id.toLowerCase(),s.id])),r=new Map(e.map(s=>[s.id,[]]));return[...e].sort((s,a)=>s.id.localeCompare(a.id)).forEach(s=>{let a=r.get(s.id),o=q(s.parent),c=o?n.get(o.toLowerCase()):void 0;c&&a.push(c),(s.dependencies??[]).forEach(l=>{let d=t.resolve(l.kind);if(!d?.hierarchy)return;let u=n.get(l.id.toLowerCase());u&&(d.hierarchyDirection==="source_parent"?r.get(u).push(s.id):a.push(u))})}),r.forEach((s,a)=>{r.set(a,[...new Set(s)].sort((o,c)=>o.localeCompare(c)))}),r}function pi(e){let t=fi(e),n=$t(t),r=[...new Set(n.flat())].sort((s,a)=>s.localeCompare(a)),i=n.map(s=>jt(s,t).join("->"));return{cycle_count:n.length,cycle_item_ids:r,cycle_sample_paths:i}}function _i(e){return e.startsWith("docs/")?"docs_unowned":e.startsWith("tests/")?"tests_unowned":e.startsWith("src/")?"source_unowned":e.endsWith(".md")?"docs_unowned":"unlinked_existing"}function He(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function hi(e,t){let n=He(e).split("/").filter(Boolean),r=He(t).split("/").filter(Boolean),i=0;for(;i<n.length&&i<r.length&&n[i]===r[i];)i+=1;return i}function lo(e,t){let n=He(t),r=He(e),i=t.endsWith("/")?t:`${t}/`,s=e.startsWith(i),a=n.length>0&&n===r,o=hi(e,t);return!s&&!a&&o===0?null:s?{score:t.length+1e3,confidence:"path_prefix"}:a?{score:o+500,confidence:"same_directory"}:{score:o,confidence:"shared_directory"}}function uo(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function mo(e,t,n){let r=t==="docs_unowned"?"docs":"files",i;return n.flatMap(s=>(r==="docs"?s.docs??[]:s.files??[]).map(a=>({item:s,link:a}))).forEach(({item:s,link:a})=>{if(a.scope!=="project")return;let o=ce(a.path);if(o.length===0||o===e)return;let c=lo(e,o);c!==null&&uo(i,s,c.score)&&(i={item:s,score:c.score,confidence:c.confidence})}),i?{id:i.item.id,type:i.item.type,title:i.item.title,status:i.item.status,confidence:i.confidence}:null}function gi(e,t){return e.map(n=>{let r=_i(n),i=r==="docs_unowned"?"docs":"files",s=mo(n,r,t),a=s?.id??"<id>";return{path:n,classification:r,owner_candidate:s,remediation_hint:`pm ${i} ${a} --add path=${n},scope=project,note="<why this artifact belongs to the item>"`}})}function yi(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function fo(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,r])=>{let i=q(e[n]);return i?r.some(s=>i.toLowerCase().includes(s)):!1}).map(([n])=>n).sort((n,r)=>n.localeCompare(r))}function po(e,t,n,r,i){let s=q(t.parent),a=s?n.get(r.get(s.toLowerCase())??s):void 0;return{id:e.id,parent_id:t.id,grandparent_id:a?.id,grandparent_active:a!==void 0&&!Se(a.status,i)}}function _o(e,t,n,r){let i=q(e.blocked_by),s=q(e.blocked_reason),a=s?.toLowerCase(),o=Ve(e.status,n),c=[];return t.has(o)?(!i&&!s&&c.push("blocked_status_missing_blocker_context"),a?.includes("no active blocker")&&c.push("blocked_status_reason_reports_no_active_blocker"),a&&r.stale_blocker_reason_patterns.some(l=>a.includes(l))&&c.push("blocked_status_reason_matches_stale_pattern"),c):(i&&c.push("non_blocked_status_has_blocked_by"),s&&c.push("non_blocked_status_has_blocked_reason"),c)}function ho(e,t,n,r){let i=new Map(e.map(c=>[c.id,c])),s=new Map(e.map(c=>[c.id.toLowerCase(),c.id])),a=n.blocked_statuses.size>0?n.blocked_statuses:new Set(["blocked"]),o={activeItems:e.filter(c=>!Se(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of o.activeItems){let l=fo(c,r);l.length>0&&o.closureLikeRows.push({id:c.id,fields:l});let d=q(c.parent),u=d?i.get(s.get(d.toLowerCase())??d):void 0;if(u&&Se(u.status,n)&&(o.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),o.terminalParentFixRows.push(po(c,u,i,s,n))),t){let m=_o(c,a,n,r);m.length>0&&o.staleBlockerRows.push({id:c.id,status:c.status,reasons:[...new Set(m)].sort((f,p)=>f.localeCompare(p))})}}return o}function go(e){e.closureLikeRows.sort((t,n)=>t.id.localeCompare(n.id)),e.terminalParentRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.terminalParentFixRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.staleBlockerRows.sort((t,n)=>t.id.localeCompare(n.id))}function Gr(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function yo(e,t,n,r,i,s){let a=[];e.closureLikeRows.length>0&&a.push(`validate_lifecycle_active_closure_like_metadata:${e.closureLikeRows.length}`),e.terminalParentRows.length>0&&a.push(`validate_lifecycle_active_terminal_parent:${e.terminalParentRows.length}`),t&&e.staleBlockerRows.length>0&&a.push(`validate_lifecycle_stale_blockers:${e.staleBlockerRows.length}`);let o=Gr("validate_lifecycle_dependency_cycles",n,i),c=Gr("validate_hierarchy_parent_cycle",r,s);return[...a,...o?[o]:[],...c?[c]:[]]}function wi(e){let t=ce(e);return t.length>Ga||t.split(/[\\/]/).some(n=>n.length>qa)}async function wo(e,t){let n=$.isAbsolute(t)?t:$.resolve(e,t);if(wi(n))return!1;try{let r=await Nt.stat(n);return!r.isFile()&&!r.isDirectory()}catch(r){return Qr(r,["ENOENT","ENOTDIR"])}}async function ko(e,t){let n={linkedProjectPaths:new Set,remoteLinkedPaths:new Set,missingLinkedPaths:[],staleLinkRows:[]},r=e.flatMap(i=>[...(i.files??[]).map(s=>({item:i,artifact:s,link_kind:"files"})),...(i.docs??[]).map(s=>({item:i,artifact:s,link_kind:"docs"}))]);for(let{item:i,artifact:s,link_kind:a}of r){if(s.scope!=="project")continue;if(Re(s.path)){n.remoteLinkedPaths.add(s.path.trim());continue}let o=ce(s.path);o.length!==0&&(n.linkedProjectPaths.add(o),await wo(t,s.path)&&(n.missingLinkedPaths.push(o),n.staleLinkRows.push({item_id:i.id,path:o,link_kind:a})))}return n}function vo(e,t,n,r,i,s){let a=r==="tracked-all-strict",o=a&&!i,c=i||a,l=c?[]:Xa(t,n),d=l.length===0?[]:e.candidateFiles.filter(f=>zr(f,l)),u=l.length===0?e.candidateFiles:e.candidateFiles.filter(f=>!zr(f,l)),m={};if(d.length>0){let f=se(d,s);m.pm_internals={count:d.length,paths:f.values,paths_truncated:f.truncated,paths_total:f.total}}return{strictTrackedAllMode:a,strictModeForcesPmInternals:o,includePmInternalsEffective:c,pmInternalCandidatePrefixes:l,excludedPmInternalPaths:d,candidateFiles:u,excludedByReason:m}}function ki(e,t,n,r,i,s,a,o="pm"){let c=ho(e,t,i,s);go(c);let l=mi(c.activeItems,o),d=pi(e),u=yo(c,t,n,r,l.cycle_count,d.cycle_count),m=a?Number.POSITIVE_INFINITY:re,f=F(c.closureLikeRows.map(E=>`${E.id}:${E.fields.join(",")}`),m),p=F(c.terminalParentRows.map(E=>`${E.id}:${E.parent_id}:${E.parent_status}`),m),y=F(c.staleBlockerRows.map(E=>`${E.id}:${E.status}:${E.reasons.join(",")}`),m),_=F(l.cycle_item_ids,m),w=F(l.cycle_sample_paths,m),b=F(d.cycle_item_ids,m),S=F(d.cycle_sample_paths,m);return{check:{name:"lifecycle",status:l.cycle_count>0&&n==="error"||d.cycle_count>0&&r==="error"?"error":u.length===0?"ok":"warn",details:{checked_active_items:c.activeItems.length,active_closure_like_metadata_items:c.closureLikeRows.length,active_closure_like_metadata_rows:f.values,active_closure_like_metadata_rows_truncated:f.truncated,active_terminal_parent_items:c.terminalParentRows.length,active_terminal_parent_rows:p.values,active_terminal_parent_rows_truncated:p.truncated,stale_blocker_checks_enabled:t,stale_blocker_items:c.staleBlockerRows.length,stale_blocker_rows:y.values,stale_blocker_rows_truncated:y.truncated,dependency_cycle_severity_policy:n,dependency_cycle_count:l.cycle_count,dependency_cycle_item_count:l.cycle_item_ids.length,dependency_cycle_item_ids:_.values,dependency_cycle_item_ids_truncated:_.truncated,dependency_cycle_sample_paths:w.values,dependency_cycle_sample_paths_truncated:w.truncated,parent_cycle_severity_policy:r,parent_cycle_count:d.cycle_count,parent_cycle_item_count:d.cycle_item_ids.length,parent_cycle_item_ids:b.values,parent_cycle_item_ids_truncated:b.truncated,parent_cycle_sample_paths:S.values,parent_cycle_sample_paths_truncated:S.truncated,stale_blocker_reason_patterns:[...s.stale_blocker_reason_patterns],stale_blocker_reason_pattern_source:s.stale_blocker_reason_pattern_source,closure_like_blocked_reason_patterns:[...s.closure_like_metadata_field_patterns.blocked_reason],closure_like_blocked_reason_pattern_source:s.closure_like_metadata_field_pattern_sources.blocked_reason,closure_like_resolution_patterns:[...s.closure_like_metadata_field_patterns.resolution],closure_like_resolution_pattern_source:s.closure_like_metadata_field_pattern_sources.resolution,closure_like_actual_result_patterns:[...s.closure_like_metadata_field_patterns.actual_result],closure_like_actual_result_pattern_source:s.closure_like_metadata_field_pattern_sources.actual_result}},warnings:u,terminalParentFixRows:c.terminalParentFixRows}}async function vi(e,t,n,r,i,s){let a=await ko(e,t),o=new Map(e.map(v=>[v.id,v])),c=[...new Set(a.missingLinkedPaths)].sort((v,I)=>v.localeCompare(I)),l=await Za(t,r),d=vo(l,n,t,r,i,s),u=d.candidateFiles.filter(v=>!a.linkedProjectPaths.has(v)),m=gi(u,e),f=kr(c,d.candidateFiles),p=new Map(f.map(v=>[v.path,v.classification])),y=f.filter(v=>v.classification==="moved").length,_=a.staleLinkRows.map(v=>({...v,classification:p.get(v.path)??"deleted"})).sort((v,I)=>v.item_id.localeCompare(I.item_id)||v.path.localeCompare(I.path)||v.link_kind.localeCompare(I.link_kind)),w=[];d.strictModeForcesPmInternals&&w.push("validate_files_tracked_all_strict_forces_pm_internals"),c.length>0&&w.push(`validate_files_missing_linked_paths:${c.length}`),u.length>0&&w.push(`validate_files_orphaned_paths:${u.length}`);let b=[...a.remoteLinkedPaths].sort((v,I)=>v.localeCompare(I)),S=se(b,s),A=se(c,s),E=se(u,s),Y=se(m.map(v=>`${v.path}:${v.classification}:owner_candidate=${v.owner_candidate?.id??"unowned"}`),s),W=s?m:se(yi(m),!1).values,x=se(vr(f),s),P=_.map(v=>({item_id:v.item_id,path:v.path,link_kind:v.link_kind,classification:v.classification})),H=Rr(P,v=>{let I=o.get(v);return I?{type:I.type,title:I.title,status:I.status}:void 0}),D=s?H:se(Sr(H),!1).values;return{check:{name:"files",status:w.length===0?"ok":"warn",details:{workspace_root:t,scan_mode_requested:l.requestedMode,scan_mode_applied:l.appliedMode,strict_tracked_all_mode:d.strictTrackedAllMode,strict_mode_forces_pm_internals:d.strictModeForcesPmInternals,strict_mode_forces_pm_internals_notice:d.strictModeForcesPmInternals?"tracked-all-strict force-enables PM internals; pass --include-pm-internals to make inclusion explicit.":null,file_list_detail_mode:s?"full":"summary",file_list_summary_limit:Wr,candidate_scan_source:l.source,include_pm_internals:d.includePmInternalsEffective,include_pm_internals_requested:i,pm_internal_candidate_prefixes:d.pmInternalCandidatePrefixes,pm_internal_excluded_count:d.excludedPmInternalPaths.length,excluded_total:d.excludedPmInternalPaths.length,excluded_by_reason:d.excludedByReason,linked_project_paths:a.linkedProjectPaths.size,remote_linked_paths_count:b.length,remote_linked_paths_total:S.total,remote_linked_paths:S.values,remote_linked_paths_truncated:S.truncated,candidate_total_raw:l.candidateTotal,candidate_scanned_raw:l.candidateScanned,candidate_total:d.candidateFiles.length,candidate_scanned:d.candidateFiles.length,scanned_candidate_files:d.candidateFiles.length,missing_linked_paths_count:c.length,missing_linked_paths_total:A.total,missing_linked_paths:A.values,missing_linked_paths_truncated:A.truncated,missing_linked_paths_moved_count:y,missing_linked_paths_deleted_count:c.length-y,missing_linked_path_classifications:x.values,missing_linked_path_classifications_truncated:x.truncated,missing_linked_path_rows_count:H.length,missing_linked_path_rows:D,orphaned_paths_count:u.length,orphaned_paths_total:E.total,orphaned_paths:E.values,orphaned_paths_truncated:E.truncated,orphaned_path_classifications:Y.values,orphaned_path_classifications_truncated:Y.truncated,orphaned_path_rows_count:m.length,orphaned_path_rows:W}},warnings:w,staleLinkPruneRows:_}}async function bo(e,t,n){let{missingStreams:r,unreadableStreams:i,hashMismatches:s,chainMismatches:a,driftedItems:o}=await ar(e,t),c=[];r.length>0&&c.push(`validate_history_drift_missing_streams:${r.length}`),i.length>0&&c.push(`validate_history_drift_unreadable_streams:${i.length}`),s.length>0&&c.push(`validate_history_drift_hash_mismatches:${s.length}`),a.length>0&&c.push(`validate_history_drift_chain_mismatches:${a.length}`);let l=n?Number.POSITIVE_INFINITY:re,d=F(o,l);return{check:{name:"history_drift",status:c.length===0?"ok":"warn",details:{checked_items:t.length,drifted_items_count:o.length,drifted_items:d.values,drifted_items_truncated:d.truncated,counts:{missing_streams:r.length,unreadable_streams:i.length,hash_mismatches:s.length,chain_mismatches:a.length}}},warnings:c}}function Ro(e,t,n){let r=n.trim().replaceAll(/\s+/g," "),i=r.length>120?`${r.slice(0,117)}...`:r;return`${e}:${t}:${i}`}function bi(e,t,n){let r=new Set(e.map(_=>_.id.toLowerCase())),i=0,s=0,a=new Set,o=[],c=e.flatMap(_=>(_.tests??[]).map(w=>({item:_,linkedTest:w})));for(let{item:_,linkedTest:w}of c){if(typeof w.command!="string"||w.command.trim().length===0)continue;i+=1;let b=Mr(w.command,t);if(b.length!==0){s+=b.length;for(let S of b)a.add(S),r.has(S.toLowerCase())||o.push(Ro(_.id,S,w.command))}}let l=[...new Set(o)].sort((_,w)=>_.localeCompare(w)),d=[...new Set(l.map(_=>_.split(":")[1]??""))].filter(_=>_.length>0).sort((_,w)=>_.localeCompare(w)),u=l.length>0?[`validate_command_references_stale_pm_ids:${l.length}`]:[],m=n?Number.POSITIVE_INFINITY:re,f=F(l,m),p=F(d,m),y=F([...a].sort((_,w)=>_.localeCompare(w)),m);return{check:{name:"command_references",status:u.length===0?"ok":"warn",details:{checked_items:e.length,linked_commands_scanned:i,referenced_pm_ids_count:s,unique_referenced_pm_ids_count:a.size,unique_referenced_pm_ids:y.values,unique_referenced_pm_ids_truncated:y.truncated,stale_pm_id_references_count:l.length,stale_pm_ids_count:d.length,stale_pm_ids:p.values,stale_pm_ids_truncated:p.truncated,stale_pm_id_reference_rows:f.values,stale_pm_id_reference_rows_truncated:f.truncated}},warnings:u}}function So(e,t){let n=sn(e.map(c=>({ref:c.id,version:rn(c)}))),r=[];n.outdated.length>0&&r.push(`validate_format_version_outdated_items:${n.outdated.length}`),n.ahead.length>0&&r.push(`validate_format_version_ahead_items:${n.ahead.length}`);let i=t?Number.POSITIVE_INFINITY:re,s=F(n.outdated,i),a=F(n.ahead,i);return{check:{name:"format_version",status:n.ahead.length>0?"error":n.outdated.length>0?"warn":"ok",details:{checked_items:e.length,current_format_version:nn,outdated_items_count:n.outdated.length,outdated_items:s.values,outdated_items_truncated:s.truncated,ahead_items_count:n.ahead.length,ahead_items:a.values,ahead_items_truncated:a.truncated}},warnings:r}}var Dt="pm validate auto-fix";async function Ri(e,t,n){switch(e.kind){case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let r={message:Dt};if(e.kind==="set_resolution"?r.resolution=e.value:e.kind==="set_close_reason"?r.closeReason=e.value:e.kind==="set_estimate"?r.estimatedMinutes=e.value:e.kind==="reparent"?r.parent=e.parent_id:r.unset=["parent"],!n.runUpdate)throw new g("Applying validate metadata/lifecycle fixes requires a runUpdate mutation service.",h.USAGE);await n.runUpdate(e.item_id,r,t);return}case"prune_file_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`);case"prune_doc_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`)}}function Ot(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function Si(e,t,n){let r=[],i=[],s=new Map;for(let a of e.filter(o=>Ot(o)===null))try{await Ri(a,t,n),r.push(a)}catch(o){i.push({fix:a,error:o})}for(let a of e.filter(o=>Ot(o)!==null)){let o=Ot(a),c=s.get(o);c?c.push(a):s.set(o,[a])}for(let a of s.values()){let o=a[0];if(!o)continue;let c=a.map(l=>l.path).filter(l=>typeof l=="string"&&l.length>0);try{o.kind==="prune_file_link"?await Fr(o.item_id,{remove:c,message:Dt},t):await Tr(o.item_id,{remove:c,message:Dt},t),r.push(...a)}catch(l){i.push(...a.map(d=>({fix:d,error:l})))}}return{applied:r,failed:i}}var yu={applyValidateFix:Ri,applyValidateFixes:Si,attachValidateFixHints:ti,buildCommandReferencesCheck:bi,buildDependencyReferencesCheck:di,buildCloseReasonBackfillRows:ai,buildFilesCheck:vi,buildLifecycleCheck:ki,buildLifecycleDependencyGraph:li,buildLifecycleParentGraph:fi,buildEstimateBackfillRows:oi,buildMetadataCounts:ii,buildMissingFieldOccurrences:si,buildOrphanedPathRows:gi,classifyOrphanedPath:_i,collectDefaultProjectFileCandidates:Pt,collectTrackedGitFileCandidates:ei,detectLifecycleDependencyCycles:mi,detectLifecycleParentCycles:pi,escapeRegExp:ci,extractItemIds:ui,findLifecycleDependencyCycleComponents:$t,isMetadataFieldMissing:Jr,linkedArtifactPathExceedsFilesystemLimits:wi,listFilesRecursive:Lt,resolveDependencyCycleSeverity:Kr,resolveParentCycleSeverity:Yr,resolveFileScanMode:Xr,resolveLifecycleDependencyCycleSamplePath:jt,resolveRequestedChecks:ni,resolveValidateMetadataProfile:Vr,resolveWorkspaceRoot:Zr,sharedDirectoryPrefixLength:hi,summarizeOrphanedPathRows:yi,summarizeDuplicateIssueCodes:ri,toMeaningfulString:q};async function Ao(e,t,n,r){let i=await Xn(e,new Set(t.map(p=>p.id)),n,{schema:r.schema,extensionFieldNames:Gt(J())}),s=[];i.unreadable_item_files.length>0&&s.push(`validate_storage_unreadable_items:${i.unreadable_item_files.length}`),i.duplicate_item_ids.length>0&&s.push(`validate_storage_duplicate_item_ids:${i.duplicate_item_ids.length}`),i.history_conflict_marker_streams.length>0&&s.push(`validate_storage_history_conflict_markers:${i.history_conflict_marker_streams.length}`),i.history_unparseable_streams.length>0&&s.push(`validate_storage_unparseable_history:${i.history_unparseable_streams.length}`),i.resurrected_items.length>0&&s.push(`validate_storage_resurrected_items:${i.resurrected_items.length}`),i.unparseable_config_files.length>0&&s.push(`validate_storage_unparseable_config:${i.unparseable_config_files.length}`);let a=s.length,o=await Er(e);o.tracked_path_count>0&&s.push(`validate_storage_tracked_runtime_cache_files:${o.tracked_path_count}`);let c=await Dn(e,Pe(r));c.status==="drift"&&s.push(`validate_merge_fence_drift:${c.missing_patterns.length+c.stale_patterns.length}`);let l=await ke(e),d=l===null?null:await Nn(l);d!==null&&d.status!=="ok"&&s.push(`validate_merge_driver_configuration:${d.missing_keys.length+d.drifted_keys.length}`);let u=l===null?[]:await wt(l,{includeLossless:!0,pmRoot:e}),{pendingDecisions:m,lossless:f}=Yn(u);return m.length>0&&s.push(`validate_merge_decisions_unreviewed:${m.length}`),{check:{name:"storage_integrity",status:a>0?"error":s.length>0?"warn":"ok",details:{...i,merge_fence:c,merge_driver_configuration:d,pending_merge_decision_count:m.length,pending_merge_decision_items:[...new Set(m.map(p=>p.item_id))].sort((p,y)=>p.localeCompare(y)),lossless_merge_receipt_count:f.length,lossless_merge_receipt_items:[...new Set(f.map(p=>p.item_id))].sort((p,y)=>p.localeCompare(y)),tracked_runtime_cache:{tracker_relative_root:o.tracker_relative_root,tracked_paths:o.tracked_paths,tracked_path_count:o.tracked_path_count,remediation_command:o.remediation_command}}},warnings:s}}function ne(e,t,n){n&&ti(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function Eo(e){let t={checks:[],warnings:[...e.initialWarnings],closeReasonBackfillRows:[],estimateBackfillRows:[],resolutionBackfillRows:[],terminalParentFixRows:[],staleLinkPruneRows:[]},n=e.options.fixHints===!0,r=e.options.verboseDiagnostics===!0||e.options.allAffectedIds===!0||e.global.json===!0;if(e.requestedChecks.has("metadata")){let i=oo(e.items,e.metadataPolicy,e.statusRegistry,r);t.closeReasonBackfillRows=i.closeReasonBackfillRows,t.estimateBackfillRows=i.estimateBackfillRows,ne(t,i,n)}if(e.requestedChecks.has("resolution")){let i=co(e.items,e.statusRegistry,r);t.resolutionBackfillRows=i.resolutionBackfillRows,ne(t,i,n)}if(e.requestedChecks.has("lifecycle")){let i=ki(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,r,e.settings.id_prefix);t.terminalParentFixRows=i.terminalParentFixRows,ne(t,i,n),ne(t,di(e.items,r,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let i=await vi(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists);t.staleLinkPruneRows=i.staleLinkPruneRows,ne(t,i,n)}return e.requestedChecks.has("command_references")&&ne(t,bi(e.items,e.settings.id_prefix,r),n),e.requestedChecks.has("history_drift")&&ne(t,await bo(e.pmRoot,e.items,r),n),e.requestedChecks.has("format_version")&&ne(t,So(e.items,r),n),e.requestedChecks.has("storage_integrity")&&ne(t,await Ao(e.pmRoot,e.items,V(e.settings,J()).type_to_folder,e.settings),n),t}function xo(e,t,n){let r=[];return e.autoFix===!0&&(r.push(...lr(t.closeReasonBackfillRows)),r.push(...cr(t.resolutionBackfillRows)),r.push(...dr(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),r.push(...ur(t.terminalParentFixRows))),e.pruneMissing===!0&&r.push(...mr(t.staleLinkPruneRows)),r}async function Co(e,t,n,r,i,s){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let a=xo(e,t,n),{applicable:o,gated:c}=pr(a,r),l=e.dryRun===!0,d=[],u=[];if(!l){let m=await Si(o,i,s);d.push(...m.applied.map(be)),u.push(...m.failed.map(({fix:f,error:p})=>({...be(f),error:p instanceof Error?p.message:String(p)})))}return{mode:l?"dry_run":"apply",auto_fix:e.autoFix===!0,prune_missing:e.pruneMissing===!0,granted_fix_scopes:[...r].sort((m,f)=>m.localeCompare(f)),planned_count:a.length,applied_count:d.length,gated_count:c.length,failed_count:u.length,planned_fixes:a.map(be),applied_fixes:d,gated_fixes:c.map(m=>({...be(m),gate_hint:`Withheld: re-run with --fix-scope ${m.gate} to apply.`})),failed_fixes:u}}async function wu(e,t,n={}){Qt(e.counts===!0,e.full===!0,"--counts");let r=e.autoFix===!0||e.pruneMissing===!0;if(e.dryRun===!0&&!r)throw new g("--dry-run requires --auto-fix or --prune-missing (there is nothing to preview otherwise).",h.USAGE);if(e.fixScope!==void 0&&e.fixScope.length>0&&e.autoFix!==!0)throw new g("--fix-scope requires --auto-fix.",h.USAGE);let i=fr(e.fixScope),s=B(process.cwd(),t.path);if(!await N(U(s)))throw new g(`Tracker is not initialized at ${s}. Run pm init first.`,h.NOT_FOUND);let a=await L(s),o=Zt(a.schema),c=V(a,J()),l=ni(e),d=[],u=await $r({includeBody:l.has("history_drift"),pmRoot:s,settings:a,typeToFolder:c.type_to_folder,warnings:d});if(l.has("history_drift")){let P=await ht(s);P.actionable_unknown_event_count>0&&d.push(`validate_history_unknown_author_events:${P.actionable_unknown_event_count}`)}let m=typeof e.metadataProfile=="string"?"option":"settings",f=Vr(typeof e.metadataProfile=="string"?e.metadataProfile:a.validation.metadata_profile),p=Ya(f,m,a.validation.metadata_required_fields),y=Va(a),_=Kr(e.dependencyCycleSeverity),w=Yr(e.parentCycleSeverity),b=Xr(e.scanMode),S=Zr(s),A=await Eo({requestedChecks:l,options:e,global:t,pmRoot:s,workspaceRoot:S,settings:a,items:u,statusRegistry:o,metadataPolicy:p,lifecyclePatternPolicy:y,dependencyCycleSeverity:_,parentCycleSeverity:w,fileScanMode:b,initialWarnings:[...new Set(d)]}),E=r?await Co(e,A,a,i,t,n):void 0,Y=[...new Set(A.warnings)].sort((P,H)=>P.localeCompare(H)),x={ok:!A.checks.some(P=>P.status==="error"),has_warnings:Y.length>0,checks:A.checks,warnings:Y,...E!==void 0?{fixes:E}:{},generated_at:X(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return e.counts!==!0?x:{...Ha(x),projection:{mode:"counts",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:[]}}}export{Po as a,Ii as b,Ti as c,Oe as d,In as e,ue as f,ct as g,Ni as h,ke as i,ut as j,Pe as k,Dn as l,Nn as m,Zo as n,Qo as o,Li as p,ar as q,fs as r,R as s,O as t,Bi as u,Ac as v,Ec as w,xc as x,Bn as y,Cc as z,Ic as A,Tc as B,Oc as C,Fc as D,_t as E,Pc as F,Dc as G,pt as H,Nc as I,Mc as J,Un as K,Lc as L,Ki as M,Gn as N,Hc as O,ht as P,Zi as Q,Qi as R,Vc as S,es as T,Er as U,as as V,rl as W,wt as X,Yn as Y,il as Z,sl as _,Xn as $,Tr as aa,Fr as ba,vd as ca,bd as da,ha as ea,ga as fa,Ed as ga,xd as ha,Cd as ia,Id as ja,wa as ka,ka as la,va as ma,Td as na,Dr as oa,Ra as pa,Nr as qa,Tt as ra,Lr as sa,Sa as ta,Aa as ua,Ea as va,Ha as wa,yu as xa,wu as ya};
|
|
16
|
-
//# sourceMappingURL=chunk-3CQECMKR.js.map
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import{d as ut,e as O,g as lt,i as N}from"./chunk-M6RPIXKC.js";import{Ma as re,Q as se,ba as R,bb as ct,cb as dt,eb as ie,k as ne,ka as Re}from"./chunk-FF4MNAYB.js";import{E as H,K as J,N as X,Qa as Q,ca as x,ha as Y,p as W,r as j,s as F,u as st}from"./chunk-2EXI2DKR.js";import{h as Z,i as ee,k as Ce,m as L,n as te,o as rt,p as it,q as ot,r as at}from"./chunk-RIIN5V4N.js";import{Y as y,Z as w,aa as G,la as Se}from"./chunk-GHTN2ILR.js";import{constants as B}from"node:fs";import{lstat as ft,mkdir as Ae,open as ht}from"node:fs/promises";import T 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]="c53bb1b7-12b9-5370-a85b-cdd8bef57936")}catch{}})();function De(e,t){if(typeof e!="string"||e.trim().length===0)throw new TypeError(`Relationship event ${t} must be non-empty`);return e.trim()}function Le(e,t){let n=t.require(e.kind),s=n.direction==="undirected"?[e.source,e.target].sort().join("\0"):`${e.source}\0${e.target}`;return`${n.kind}\0${s}`}function yn(e){return Object.freeze({...e,...e.payload===void 0?{}:{payload:Object.freeze(structuredClone(e.payload))}})}function wn(e,t,n,s){let r=n.require(e.kind),i=s.outgoingOne.get(`${r.kind}\0${e.source}`);if(i!==void 0&&i!==t)throw new TypeError(`Relationship outgoing cardinality exceeded for ${r.kind}`);let o=s.incomingOne.get(`${r.kind}\0${e.target}`);if(o!==void 0&&o!==t)throw new TypeError(`Relationship incoming cardinality exceeded for ${r.kind}`);let a=Le(e,n),c=s.identities.get(a);if(c!==void 0&&c!==t)throw new TypeError(`Relationship edge already active: ${a}`)}function bn(e){let t=new Map;for(let n of e)n.action==="remove"?t.delete(n.relationshipId):t.set(n.relationshipId,n.edge);return t}function _n(e,t,n){if(e.expectedVersion!==void 0&&e.expectedVersion!==t)throw new TypeError(`Relationship event version conflict: expected ${e.expectedVersion}, current ${t}`);let s=De(e.eventId,"eventId");if(n.has(s))throw new TypeError(`Relationship event already exists: ${s}`);if(e.action!=="add"&&e.action!=="remove"&&e.action!=="supersede")throw new TypeError(`Unknown relationship event action: ${e.action}`);if(!Number.isFinite(Date.parse(e.timestamp)))throw new TypeError("Relationship event timestamp must be valid");return{eventId:s,relationshipId:De(e.relationshipId,"relationshipId"),author:De(e.author,"author"),timestamp:new Date(e.timestamp).toISOString()}}function vn(e,t,n,s,r,i){let o=n.has(t);if(e.action==="add"&&o)throw new TypeError(`Relationship is already active: ${t}`);if(e.action!=="add"&&!o)throw new TypeError(`Relationship is not active: ${t}`);if(e.action==="remove")return;if(!e.edge)throw new TypeError(`Relationship ${e.action} event requires an edge`);let a=typeof e.edge.source=="string"?e.edge.source.trim():"",c=typeof e.edge.target=="string"?e.edge.target.trim():"";if(!s.has(a)||!s.has(c))throw new TypeError(`Relationship endpoint not found: ${a} -> ${c}`);let d=new Y([a,c],[e.edge],r).edges()[0];return wn(d,t,r,i),yn(d)}var Oe=class{#e;#n;#s=[];#i=new Set;#t=new Map;#r={identities:new Map,outgoingOne:new Map,incomingOne:new Map};constructor(t,n={}){this.#e=new Set([...t].filter(s=>typeof s=="string").map(s=>s.trim()).filter(Boolean)),this.#n=n.registry??x()}get version(){return this.#s.length}events(){return Object.freeze([...this.#s])}*stream(t={}){let n=t.fromVersion??1,s=t.toVersion??this.version,r=t.batchSize??100;if(!Number.isInteger(n)||n<1)throw new TypeError("Relationship event stream fromVersion must be positive");if(!Number.isInteger(s)||s<0||s>this.version)throw new TypeError(`Relationship event stream toVersion out of range: ${s}`);if(!Number.isInteger(r)||r<1)throw new TypeError("Relationship event stream batchSize must be positive");if(n>s+1)throw new TypeError("Relationship event stream fromVersion exceeds the selected prefix");for(let i=n-1;i<s;i+=r)yield Object.freeze(this.#s.slice(i,Math.min(i+r,s)))}project(t,n,s={}){if(typeof n!="function")throw new TypeError("Relationship event projection requires a reducer");let r=t,i=0,o;for(let a of this.stream({...s,batchSize:256}))for(let c of a)r=n(r,c),i+=1,o=c;return Object.freeze({state:r,version:o?.sequence??Math.max(0,(s.fromVersion??1)-1),processed:i,...o===void 0?{}:{asOf:o.timestamp}})}#o(t,n){let s=this.#n.require(n.kind);this.#r.identities.set(Le(n,this.#n),t),s.outgoing==="one"&&this.#r.outgoingOne.set(`${s.kind}\0${n.source}`,t),s.incoming==="one"&&this.#r.incomingOne.set(`${s.kind}\0${n.target}`,t)}#a(t){let n=this.#n.require(t.kind);this.#r.identities.delete(Le(t,this.#n)),n.outgoing==="one"&&this.#r.outgoingOne.delete(`${n.kind}\0${t.source}`),n.incoming==="one"&&this.#r.incomingOne.delete(`${n.kind}\0${t.target}`)}append(t){let n=_n(t,this.version,this.#i),s=this.#t.get(n.relationshipId),r=vn(t,n.relationshipId,this.#t,this.#e,this.#n,this.#r),i=Object.freeze({eventId:n.eventId,relationshipId:n.relationshipId,action:t.action,...r===void 0?{}:{edge:r},author:n.author,timestamp:n.timestamp,...t.reason?.trim()?{reason:t.reason.trim()}:{},sequence:this.version+1});return this.#s.push(i),this.#i.add(n.eventId),s&&this.#a(s),t.action==="remove"?this.#t.delete(n.relationshipId):(this.#t.set(n.relationshipId,r),this.#o(n.relationshipId,r)),i}snapshot(t={}){if(t.atVersion!==void 0&&t.atTimestamp!==void 0)throw new TypeError("Relationship snapshot accepts one target");let n;if(t.atTimestamp!==void 0){let i=Date.parse(t.atTimestamp);if(!Number.isFinite(i))throw new TypeError("Relationship snapshot timestamp must be valid");n=this.#s.filter(o=>Date.parse(o.timestamp)<=i)}else{let i=t.atVersion??this.version;if(!Number.isInteger(i)||i<0||i>this.version)throw new TypeError(`Relationship snapshot version out of range: ${i}`);n=this.#s.slice(0,i)}let s=bn(n),r=new Y(this.#e,s.values(),this.#n);return Object.freeze({version:n.at(-1)?.sequence??0,...n.at(-1)?{asOf:n.at(-1).timestamp}:{},edges:r.edges(),graph:r})}page(t){if(!Number.isInteger(t.limit)||t.limit<1)throw new TypeError("Relationship event page limit must be positive");let n=L("relationship-events",{order:"append-sequence"}),s=t.cursor===void 0?this.version:Number(rt(t.cursor,n).snapshot);if(!Number.isSafeInteger(s)||s<0||s>this.version)throw new TypeError("Relationship event cursor snapshot version is invalid");let r=at(this.#s.slice(0,s),{cursor:t.cursor,fingerprint:n,limit:t.limit,readId:i=>i.eventId,snapshot:String(s)});return{version:s,events:r.rows,hasMore:r.has_more,...r.next_cursor?{nextCursor:r.next_cursor}:{}}}},kn="relationship-event-store",gt=B.O_NOFOLLOW;function oe(e){return se(e,kn,30,`relationship-store:${process.pid}`,!1,!1,3e3)}async function D(e,t="relationships/events.jsonl"){let n=T.resolve(e),s=T.resolve(n,t),r=T.relative(n,s);if(r.length===0)throw new TypeError("Relationship event path must name a file within the tracker root");if(r===".."||r.startsWith(`..${T.sep}`)||T.isAbsolute(r))throw new TypeError("Relationship event path must stay within the tracker root");if(await Ae(n,{recursive:!0}),(await ft(n)).isSymbolicLink())throw new TypeError("Relationship event tracker root must not be a symbolic link");let o=n;for(let a of r.split(T.sep)){o=T.join(o,a);try{if((await ft(o)).isSymbolicLink())throw new TypeError("Relationship event path must not contain symbolic links")}catch(c){if(c.code==="ENOENT")break;throw c}}return s}async function ae(e,t,n){let s=new Oe(t,{registry:n}),r,i;try{i=await ht(e,B.O_RDONLY|gt),r=await i.readFile("utf8")}catch(a){if(a.code==="ENOENT")return{log:s,raw:""};throw a}finally{await i?.close()}let o=r.split(`
|
|
2
|
-
`);for(let a=0;a<o.length;a+=1){let c=o[a].trim();if(!c)continue;let d;try{d=JSON.parse(c)}catch{throw new TypeError(`Invalid relationship event JSONL at line ${a+1}`)}if(d.sequence!==s.version+1)throw new TypeError(`Invalid relationship event sequence at line ${a+1}`);s.append({eventId:d.eventId,relationshipId:d.relationshipId,action:d.action,...d.edge===void 0?{}:{edge:d.edge},author:d.author,timestamp:d.timestamp,...d.reason===void 0?{}:{reason:d.reason},expectedVersion:s.version})}return{log:s,raw:r}}function xn(e,t,n,s){let r=Date.parse(t.timestamp),i;return t.action!=="remove"&&t.edge!==void 0&&(i=new Y(n,[t.edge],s).edges()[0]),e.eventId===t.eventId.trim()&&e.relationshipId===t.relationshipId.trim()&&e.action===t.action&&e.author===t.author.trim()&&Number.isFinite(r)&&e.timestamp===new Date(r).toISOString()&&e.reason===(t.reason?.trim()||void 0)&&G(e.edge)===G(i)}var pt=class e{#e;#n;#s;#i;#t;constructor(t,n,s,r){this.#e=t.pmRoot,this.#n=n,this.#s=t.registry,this.#i=s,this.#t=r}static async open(t){let n=Object.freeze([...t.nodes]),s=await D(t.pmRoot,t.relativePath),r=await oe(t.pmRoot);try{await D(t.pmRoot,s);let{log:i}=await ae(s,n,t.registry);return new e(t,n,s,i)}finally{await r()}}get path(){return this.#i}async currentVersion(){return this.#t=await this.#r(),this.#t.version}async append(t){let n=await oe(this.#e);try{let s=await D(this.#e,this.#i),{log:r}=await ae(s,this.#n,this.#s),i=r.append(t);await Ae(T.dirname(s),{recursive:!0}),await D(this.#e,s);let o=await ht(s,B.O_APPEND|B.O_CREAT|B.O_WRONLY|gt);try{await o.appendFile(`${JSON.stringify(i)}
|
|
3
|
-
`,"utf8")}finally{await o.close()}return this.#t=r,i}finally{await n()}}async appendBatch(t,n={}){let s=await oe(this.#e);try{let r=await D(this.#e,this.#i),{log:i,raw:o}=await ae(r,this.#n,this.#s),a=i.version,c=new Map(i.events().map(l=>[l.eventId,l])),d=[],u=[];for(let l of t){let f=l.eventId.trim(),h=c.get(f);if(h!==void 0){if(n.existingEventPolicy==="skip_identical"&&xn(h,l,this.#n,this.#s)){u.push(h.eventId);continue}if(n.existingEventPolicy==="skip_identical")throw new TypeError(`Relationship event id collision with different content: ${f}`)}let p=i.append(l);c.set(p.eventId,p),d.push(p)}if(d.length>0){let l=o.length===0||o.endsWith(`
|
|
4
|
-
`)?o:`${o}
|
|
5
|
-
`;await Ae(T.dirname(r),{recursive:!0}),await D(this.#e,r),await F(r,`${l}${d.map(f=>JSON.stringify(f)).join(`
|
|
6
|
-
`)}
|
|
7
|
-
`)}return this.#t=i,Object.freeze({version_before:a,version_after:i.version,appended:Object.freeze(d),skipped_event_ids:Object.freeze(u)})}finally{await s()}}async snapshot(t={}){return this.#t=await this.#r(),this.#t.snapshot(t)}async page(t){return this.#t=await this.#r(),this.#t.page(t)}async*stream(t={}){this.#t=await this.#r(),yield*this.#t.stream(t)}async project(t,n,s={}){return this.#t=await this.#r(),this.#t.project(t,n,s)}async#r(){let t=await oe(this.#e);try{let n=await D(this.#e,this.#i);return(await ae(n,this.#n,this.#s)).log}finally{await 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]="3a33af50-3d2c-57bb-884a-4d5394599ba2")}catch{}})();function En(e,t,n,s,r,i){if(e.seen.has(t))return"skip";if(e.cursorFound&&e.affected.length>=i)return"truncate";e.seen.add(t),e.parents.set(t,n.id);let o=n.depth+1;return e.queue.push({id:t,depth:o}),e.cursorFound?(e.affected.push({id:t,distance:o,path:Ln(s,t,e.parents)}),"continue"):(e.cursorFound=t===r,"skip")}function In(e,t,n,s){let r=L("graph impact",{root:e,direction:n,kinds:[...t.kinds??[]].sort(),max_depth:Number.isFinite(s)?s:"unbounded"});return{fingerprint:r,after:t.after===void 0?void 0:it(t.after,r)}}function q(e,t,n){e.get(t).add(n)}function de(e){return new Map(e.map(t=>[t,new Set]))}function yt(e){for(let t of e)t.sort();return e.sort((t,n)=>n.length-t.length||t[0].localeCompare(n[0]))}function ce(e){if(Array.isArray(e))return e.map(n=>ce(n));if(e===null||typeof e!="object")return e;let t=e.toJSON;return typeof t=="function"?ce(t.call(e)):Object.fromEntries(Object.entries(e).sort(([n],[s])=>n.localeCompare(s)).map(([n,s])=>[n,ce(s)]))}function mt(e){return JSON.stringify(ce(e))}function Tn(e,t,n,s){let r=[{id:e,expanded:!1}];for(;r.length>0;){let i=r.pop();if(i.expanded){s.push(i.id);continue}if(n.has(i.id))continue;n.add(i.id),r.push({id:i.id,expanded:!0});let o=[...t.get(i.id)].sort().reverse();for(let a of o)n.has(a)||r.push({id:a,expanded:!1})}}function Sn(e,t){let n=new Set,s=[];for(let r of e)n.has(r)||Tn(r,t,n,s);return s}function Cn(e,t){let n=new Set,s=[];for(let r of[...e].reverse()){if(n.has(r))continue;let i=[],o=[r];for(n.add(r);o.length>0;){let a=o.pop();i.push(a);for(let c of t.get(a))n.has(c)||(n.add(c),o.push(c))}s.push(i)}return yt(s)}function wt(e,t){let n=de(e);for(let[s,r]of t)for(let i of r)q(n,i,s);return Cn(Sn(e,t),n)}function Rn(e,t){let n=de(e.nodes());for(let s of e.edges()){let r=t.require(s.kind);if(!r.ordering)continue;let i=(r.precedence??"source_before_target")==="source_before_target";q(n,i?s.source:s.target,i?s.target:s.source)}return n}function Dn(e,t){let n=new Map(e.map(i=>[i,0]));for(let i of t.values())for(let o of i)n.set(o,n.get(o)+1);let s=e.filter(i=>n.get(i)===0).sort(),r=[];for(;s.length>0;){r.push(s);let i=[];for(let o of s)for(let a of t.get(o)){let c=n.get(a)-1;n.set(a,c),c===0&&i.push(a)}s=i.sort()}return r}function An(e,t){let n=new Map(e.map(o=>[o,0])),s=new Map;for(let o of e)for(let a of t.get(o)){if(!n.has(a))continue;let c=n.get(o)+1,d=s.get(a);(c>n.get(a)||c===n.get(a)&&(d===void 0||o.localeCompare(d)<0))&&(n.set(a,c),s.set(a,o))}let r=[...e].sort((o,a)=>n.get(a)-n.get(o)||o.localeCompare(a))[0],i=r===void 0?[]:[r];for(;i[0]!==void 0&&s.has(i[0]);)i.unshift(s.get(i[0]));return{depth:Object.fromEntries(n),path:i}}function Ln(e,t,n){let s=[t],r=t;for(;r!==e;)r=n.get(r),s.push(r);return s.reverse()}function ue(e,t={}){let n=t.registry??x(),s=[...e.nodes()],r=Rn(e,n),i=Dn(s,r),o=i.flat(),a=o.length===s.length,c=a?[]:wt(s,r).filter(u=>u.length>1||r.get(u[0]).has(u[0])),d=An(o,r);return{exact:!0,acyclic:a,order:o,layers:i,frontier:i[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 bt(e,t,n={}){let s=n.direction??"outgoing",r=n.maxDepth??Number.POSITIVE_INFINITY,i=n.limit??Number.POSITIVE_INFINITY,{fingerprint:o,after:a}=In(t,n,s,r),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 h=0;h<c.queue.length;h+=1){n.signal?.throwIfAborted();let p=c.queue[h];d+=1;let g=e.adjacency(p.id,{direction:s,kinds:n.kinds,signal:n.signal});if(u+=g.meta.inspectedEdges,p.depth>=r){g.value.some(m=>!c.seen.has(m))&&(l=!0);continue}for(let m of g.value)if(En(c,m,p,t,a,i)==="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:te(o,c.affected.at(-1)?.id??t)}:{},cost:{visitedNodes:d,inspectedEdges:u}}}function _t(e){let t=[...e.nodes()],n=de(t),s=de(t);for(let c of e.edges())q(n,c.source,c.target),q(n,c.target,c.source),q(s,c.source,c.target);let r=[],i=new Set;for(let c of t){if(i.has(c))continue;let d=[],u=[c];for(i.add(c);u.length>0;){let l=u.pop();d.push(l);for(let f of n.get(l))i.has(f)||(i.add(f),u.push(f))}r.push(d)}let o=t.map(c=>({id:c,degree:n.get(c).size})),a=Math.max(0,...o.map(({degree:c})=>c));return{components:yt(r),stronglyConnected:wt(t,s),orphans:o.filter(({degree:c})=>c===0).map(({id:c})=>c),hubs:o.filter(({degree:c})=>c>0&&c===a),exact:!0,provenance:{algorithm:"component-degree",edgeFamily:"all"}}}function Zr(e,t){let n=new Map(e.edges.map(r=>[mt(r),r])),s=new Map(t.edges.map(r=>[mt(r),r]));return{fromVersion:e.version,toVersion:t.version,added:[...s].filter(([r])=>!n.has(r)).map(([,r])=>r),removed:[...n].filter(([r])=>!s.has(r)).map(([,r])=>r),unchangedCount:[...n.keys()].filter(r=>s.has(r)).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]="c0fb747e-1f9f-55c4-808b-b77d3a881f87")}catch{}})();var On=5,Nn=1e4,Mn=8;function Ne(e,t){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new TypeError(`Invalid path ${e} bound: ${String(t)}`)}function le(e,t){return t.hierarchyDirection==="target_parent"?e.target:e.source}function z(e,t){return(t.precedence??"source_before_target")==="target_before_source"?e.target:e.source}function fe(e,t){let n=z(e,t);return{predecessor:n,successor:n===e.source?e.target:e.source}}function $n(e,t,n){if(t===void 0)return;let s=e.registry(),r=new Set;for(let i of t){let o=s.require(i);if(!o[n])throw new TypeError(`Relationship kind ${o.kind} is not a ${n} kind`);r.add(o.kind)}return r}function Pn(e,t,n,s,r){let i=e.registry(),o=e.neighborEdges(t,{direction:"both",...n===void 0?{}:{kinds:[...n]}}),a=[],c=new Set;for(let d of o.value){let u=i.require(d.edge.kind);u[s]&&r(d,u,t)&&(c.has(d.id)||(c.add(d.id),a.push(d.id)))}return{neighbors:a,inspectedEdges:o.meta.inspectedEdges}}function jn(e,t,n,s,r,i){if(t>=n)return e.neighbors.some(o=>!i.seen.has(o))&&(i.truncated=!0),!1;for(let o of e.neighbors)if(!i.seen.has(o)){if(i.seen.add(o),i.queue.push({id:o,depth:t+1}),!i.resumed){o===r&&(i.resumed=!0);continue}if(i.value.length>=s)return i.truncated=!0,!0;i.value.push(o)}return!1}function pe(e,t,n,s,r){if(!e.hasNode(t))throw new TypeError(`Relationship node not found: ${t}`);let i=$n(e,n.kinds,s),o=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 h=d.queue[f];u+=1;let p=Pn(e,h.id,i,s,r);if(l+=p.inspectedEdges,jn(p,h.depth,a,o,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 vt(e,t){if(!e.hasNode(t))throw new TypeError(`Relationship node not found: ${t}`)}function kt(e,t,n,s,r){let i=e.neighborEdges(t.nodes.at(-1),{direction:s,...n.kinds===void 0?{}:{kinds:n.kinds}});return r.inspectedEdges+=i.meta.inspectedEdges,i.value.filter(o=>!t.nodeSet.has(o.id))}function Fn(e,t,n,s,r,i,o){for(let a of kt(e,t,s,r,o)){let c=[...t.nodes,a.id],d=new Set(t.nodeSet).add(a.id),u=[...t.edges,a.edge];if(a.id===n){if(o.value.push({nodes:c,edges:u,length:u.length}),o.value.length>=i)return!0}else o.queue.push({nodes:c,nodeSet:d,edges:u})}return!1}function xt(e,t,n={}){return pe(e,t,n,"hierarchy",(s,r)=>le(s.edge,r)===s.id)}function Et(e,t,n={}){return pe(e,t,n,"hierarchy",(s,r,i)=>le(s.edge,r)===i)}function It(e,t,n={}){return pe(e,t,n,"ordering",(s,r)=>z(s.edge,r)===s.id)}function Tt(e,t,n={}){return pe(e,t,n,"ordering",(s,r,i)=>z(s.edge,r)===i)}function Gn(e,t,n,s,r,i,o,a){let c={value:[],queue:[{nodes:[t],nodeSet:new Set([t]),edges:[]}],inspectedEdges:0},d=0,u=!1,l=r+1;for(let f=0;f<c.queue.length;f+=1){if(s.signal?.throwIfAborted(),c.value.length>=l||d>=i){u=!0;break}let h=c.queue[f];if(d+=1,h.edges.length>=o){kt(e,h,s,a,c).length>0&&(u=!0);continue}if(Fn(e,h,n,s,a,l,c)){u=!0;break}}return{value:c.value.slice(0,r),meta:{visitedNodes:d,inspectedEdges:c.inspectedEdges,truncated:u}}}function St(e,t,n,s={}){vt(e,t),vt(e,n);let r=s.maxPaths??On,i=s.maxVisitedPaths??Nn,o=s.maxDepth??Mn;Ne("maxPaths",r),Ne("maxVisitedPaths",i),Ne("maxDepth",o);let a=s.direction??"outgoing";s.signal?.throwIfAborted();for(let c of s.kinds??[])e.registry().require(c);return t===n?r===0?{value:[],meta:{visitedNodes:1,inspectedEdges:0,truncated:!0}}:{value:[{nodes:[t],edges:[],length:0}],meta:{visitedNodes:1,inspectedEdges:0,truncated:!1}}:Gn(e,t,n,s,r,i,o,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 Bn=16,qn=2,zn=8;function he(e,t){if(!Number.isInteger(t)||t<1)throw new TypeError(`Invalid ${e} bound: ${String(t)}`)}function ge(e,t,n){let s=e.registry(),r=t===void 0?void 0:new Set(t.map(i=>s.require(i).kind));for(let i of e.edges()){if(i.source===i.target)continue;let o=s.require(i.kind);r!==void 0&&!(r.has(o.kind)||o.inverse!==void 0&&r.has(o.inverse))||n(i,o)}}function Un(e,t){let n=new Map;ge(e,t,s=>{Ct(n,s.source,s.target),Ct(n,s.target,s.source)});for(let s of n.values())s.sort();return n}function Ct(e,t,n){let s=e.get(t);s===void 0?e.set(t,[n]):s.push(n)}function Vn(e,t){let n=new Map;for(let i of e){let o=t.get(i);n.set(o,(n.get(o)??0)+1)}let s,r=0;for(let[i,o]of n)(o>r||o===r&&i<s)&&(s=i,r=o);return s}function Kn(e,t){let n=new Map;for(let[r,i]of e){let o=n.get(i);o===void 0?n.set(i,[r]):o.push(r)}let s=[];for(let r of n.values())r.length<t||(r.sort(),s.push({representative:r[0],size:r.length,members:r}));return s.sort((r,i)=>i.size-r.size||r.representative.localeCompare(i.representative))}function Rt(e,t={}){let n=t.maxIterations??Bn,s=t.minSize??qn;he("maxIterations",n),he("minSize",s);let r=Un(e,t.kinds),i=e.nodes(),o=new Map(i.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 i){d+=1;let f=r.get(l);if(f===void 0)continue;u+=f.length;let h=Vn(f,o);h!==o.get(l)&&(o.set(l,h),c=!1)}}return{value:{communities:Kn(o,s),iterations:a,converged:c},meta:{visitedNodes:d,inspectedEdges:u,truncated:!c}}}function me(e){return e.direction==="directed"&&(e.ordering||e.hierarchy)}function ye(e){return e.inverse!==void 0&&e.inverse<e.kind?e.inverse:e.kind}function Me(e,t){return(t.hierarchy?le(e,t):e.source===z(e,t)?e.target:e.source)===e.target?{from:e.source,to:e.target}:{from:e.target,to:e.source}}function Wn(e,t){if(t===void 0)return;let n=e.registry(),s=new Set;for(let r of t){let i=n.require(r);if(!me(i))throw new TypeError(`Relationship kind ${i.kind} is not a directed ordering or hierarchy kind`);s.add(ye(i))}return s}function Hn(e,t){let n=e.registry(),s=new Map;for(let r of e.edges()){let i=n.require(r.kind);if(!me(i))continue;let o=ye(i);if(t!==void 0&&!t.has(o))continue;let a=Me(r,i);if(a.from===a.to)continue;let c=s.get(o);c===void 0&&(c={adjacency:new Map,records:[]},s.set(o,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:r})}return s}function Jn(e){let t=new Map;for(let[n,s]of e.adjacency)t.set(n,[...s].sort());return t}function Xn(e,t,n,s){let r=[s];for(let i=n;i!==t;i=e.get(i))r.push(i);return r.push(t),r.reverse()}function Yn(e,t,n,s,r,i){for(let o of e.get(n.id)??[])if(i.inspectedEdges+=1,!(n.depth===0&&o===t.to)&&!s.has(o)){if(s.set(o,n.id),o===t.to)return Xn(s,t.from,n.id,o);r.push({id:o,depth:n.depth+1})}}function Qn(e,t,n,s){let r=new Map([[t.from,t.from]]),i=[{id:t.from,depth:0}];for(let o=0;o<i.length;o+=1){let a=i[o];if(s.visitedNodes+=1,a.depth>=n)continue;let c=Yn(e,t,a,r,i,s);if(c!==void 0)return c}}function we(e,t={}){let n=t.maxDepth??zn;he("maxDepth",n),t.limit!==void 0&&he("limit",t.limit);let s=t.limit??Number.POSITIVE_INFINITY,r=Wn(e,t.kinds),i=Hn(e,r),o=[],a={visitedNodes:0,inspectedEdges:0},c=!1;e:for(let d of[...i.keys()].sort()){let u=i.get(d),l=Jn(u);for(let f of u.records){t.signal?.throwIfAborted();let h=Qn(l,f,n,a);if(h!==void 0){if(o.length>=s){c=!0;break e}o.push({edge:f.edge,witness:h})}}}return{value:o,meta:{visitedNodes:a.visitedNodes,inspectedEdges:a.inspectedEdges,truncated:c}}}function Zn(e,t,n,s,r){let i=new Set,o=[];for(let a of n){if(a.id===e||i.has(a.id))continue;if(!r.seen.has(a.id)){if(t>=s){r.truncated=!0;continue}r.seen.add(a.id),r.queue.push({id:a.id,depth:t+1})}i.add(a.id),o.push(a.id);let c=r.predecessors.get(a.id);c===void 0&&(c=new Set,r.predecessors.set(a.id,c)),c.add(e)}return o}function es(e,t,n){let s=n.direction??"outgoing",r=n.maxDepth??Number.POSITIVE_INFINITY,i=[],o=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];i.push(u);let f=e.neighborEdges(u,{direction:s,...n.kinds===void 0?{}:{kinds:n.kinds}});c+=f.meta.inspectedEdges,o.set(u,Zn(u,l,f.value,r,a))}return{order:i,successors:o,predecessors:a.predecessors,inspectedEdges:c,truncated:a.truncated}}function ts(e,t){let n=[],s=new Set([t]),r=[{id:t,index:0}];for(;r.length>0;){let i=r.at(-1),o=e.successors.get(i.id);if(i.index<o.length){let a=o[i.index];i.index+=1,s.has(a)||(s.add(a),r.push({id:a,index:0}))}else n.push(i.id),r.pop()}return n.reverse()}function ns(e,t,n,s){let r=e,i=t;for(;r!==i;){for(;s.get(r)>s.get(i);)r=n.get(r);for(;s.get(i)>s.get(r);)i=n.get(i)}return r}function ss(e,t,n){let s;for(let r of[...e].sort())t.has(r)&&(s=s===void 0?r:ns(s,r,t,n));return s}function rs(e,t,n,s,r){let i=new Map([[t,t]]),o=!0;for(;o;){o=!1;for(let a of n){if(r?.throwIfAborted(),a===t)continue;let c=ss(e.predecessors.get(a),i,s);c!==void 0&&i.get(a)!==c&&(i.set(a,c),o=!0)}}return i}function Dt(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 s=es(e,t,n),r=ts(s,t),i=new Map(r.map((d,u)=>[d,u])),o=rs(s,t,r,i,n.signal),a=new Map(r.map(d=>[d,1]));for(let d=r.length-1;d>=0;d-=1){let u=r[d];if(u===t)continue;let l=o.get(u);a.set(l,a.get(l)+a.get(u))}let c=r.filter(d=>d!==t).map(d=>({id:d,idom:o.get(d),dominatedCount:a.get(d)-1})).sort((d,u)=>u.dominatedCount-d.dominatedCount||d.id.localeCompare(u.id));return{value:{root:t,reachableCount:s.order.length,rows:c},meta:{visitedNodes:s.order.length,inspectedEdges:s.inspectedEdges,truncated:s.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]="76fa19c7-a421-5026-8de8-450285987c4e")}catch{}})();var is=25,At={error:0,warning:1,info:2};function Pe(e,t,n,s,r,i,o){let a=[...r].sort((c,d)=>c.localeCompare(d));return{code:e,severity:t,policy:n,message:s(a.length),count:a.length,sample:a.slice(0,i),sample_truncated:a.length>i,remediation:o}}function os(e){let t=e.graph.registry(),n=new Map;for(let s of e.graph.edges()){let r=t.require(s.kind);if(!r.ordering)continue;let[i,o]=(r.precedence??"source_before_target")==="target_before_source"?[s.target,s.source]:[s.source,s.target],a=n.get(i);a?a.push(o):n.set(i,[o])}for(let s of n.values())s.sort((r,i)=>r.localeCompare(i));return n}function Nt(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 as(e,t,n,s){let r=n.get(e.node)??[];if(e.neighborIndex>=r.length)return!1;let i=r[e.neighborIndex];return e.neighborIndex+=1,s.indexes.has(i)?s.onStack.has(i)&&s.lowLinks.set(e.node,Math.min(s.lowLinks.get(e.node),s.indexes.get(i))):(Nt(i,s),t.push({node:i,neighborIndex:0})),!0}function cs(e,t,n,s){t.pop();let r=t.at(-1);if(r&&s.lowLinks.set(r.node,Math.min(s.lowLinks.get(r.node),s.lowLinks.get(e.node))),s.lowLinks.get(e.node)!==s.indexes.get(e.node))return;let i=[];for(;;){let o=s.stack.pop();if(s.onStack.delete(o),i.push(o),o===e.node)break}(i.length>1||i.length===1&&n.get(i[0])?.includes(i[0]))&&s.components.push(i.sort((o,a)=>o.localeCompare(a)))}function Fe(e){let t={indexes:new Map,lowLinks:new Map,onStack:new Set,stack:[],components:[],nextIndex:0},n=[...e.keys()].sort((s,r)=>s.localeCompare(r));for(let s of n){if(t.indexes.has(s))continue;let r=[{node:s,neighborIndex:0}];for(Nt(s,t);r.length>0;){let i=r.at(-1);as(i,r,e,t)||cs(i,r,e,t)}}return t.components.sort((s,r)=>s[0].localeCompare(r[0]))}function $e(e){return`${e.holder_id} -> ${e.target_id} (${e.kind})`}function E(e,t,n,s,r,i,o,a){t.length!==0&&e.push(Pe(s,r,i,o,t,n,a))}function ds(e,t,n){let s=[],r=[...e.dangling.active,...e.dangling.legacy_terminal].filter(i=>!i.no_active_blocker_sentinel);return E(s,r.filter(i=>!t(i.holder_status)).map($e),n,"missing_reference_active","error","Active items must not reference absent targets; missing prerequisites distort scheduling.",i=>`${i} active dangling reference(s) to absent items`,"Restore or re-create the referenced item, or remove/retype the reference on the holder."),E(s,r.filter(i=>t(i.holder_status)).map($e),n,"missing_reference_terminal","info","Terminal items may retain historical references, but absent targets remain unexplainable context.",i=>`${i} terminal dangling reference(s) to absent items`,"Leave as history debt or clean up in a dedicated changelog-safe closed-item batch."),E(s,e.dangling.no_active_blocker_sentinels.map($e),n,"legacy_no_blocker_sentinel","info","The pre-structured-dependency no-active-blocker sentinel is retired; real edges carry blocker state.",i=>`${i} legacy no-active-blocker sentinel reference(s)`,"Delete the sentinel reference; blocker state is derived from blocked_by edges."),s}function je(e,t){let n=t.get(e);return n?!n.terminal:!0}function us(e,t,n,s){let r=[],i=os(e);for(let c of Fe(i)){let d=c.some(u=>je(u,t));r.push(d?Pe("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,s,"Remove or retype one ordering edge inside the cycle, or split the work so precedence is linear."):Pe("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,s,"Leave as history debt, or clean up in a dedicated changelog-safe closed-item batch; never repair closed items ad hoc."))}let o=new Map;for(let[c,d]of i)for(let u of d){let l=o.get(u);l?l.push(c):o.set(u,[c])}let a=[...t.values()].filter(c=>!c.missing&&!c.terminal&&n(c.status)&&!(o.get(c.id)??[]).some(d=>{let u=t.get(d);return u===void 0||!u.terminal})).map(c=>c.id);return E(r,a,s,"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.'),r}function be(e){let t=e.edges.map(n=>n.kind).sort((n,s)=>n.localeCompare(s));return`${e.from} -> ${e.to} (${t.join(" + ")})`}function Ge(e){let t=e.graph.registry(),n=new Map;for(let r of e.graph.edges()){let i=t.require(r.kind);if(!me(i))continue;let o=Me(r,i);if(o.from===o.to)continue;let a=`${ye(i)}::${o.from}::${o.to}`,c=n.get(a);c?c.edges.push(r):n.set(a,{...o,edges:[r]})}let s=[...n.values()].filter(r=>r.edges.length>=2);for(let r of s)r.edges.sort((i,o)=>i.kind.localeCompare(o.kind));return s.sort((r,i)=>r.from.localeCompare(i.from)||r.to.localeCompare(i.to))}function ls(e,t,n){let s=[],r=[];for(let o of Ge(e))(je(o.from,t)||je(o.to,t)?s:r).push(be(o));let i=[];return E(i,s,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.",o=>`${o} duplicated relationship(s) between active endpoints`,"Remove all but one stored spelling of the relationship; keep the canonical direction the holder declared first."),E(i,r,n,"legacy_duplicate_edge","info","Duplicated spellings between exclusively terminal items are historical noise with no scheduling effect.",o=>`${o} duplicated relationship(s) between terminal endpoints`,"Leave as history debt or clean up in a dedicated changelog-safe closed-item batch."),i}function fs(e,t){let n=[],s=[];for(let i of e.duplicateRows??[])(i.legacy_terminal?s:n).push(`${i.holder_id} -> ${i.target_id} (${i.kind} x${i.occurrences})`);let r=[];return E(r,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.",i=>`${i} 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."),E(r,s,t,"legacy_duplicate_dependency_row","info","Identical repeated dependency rows on terminal holders are historical storage noise with no scheduling effect.",i=>`${i} 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."),r}function ps(e,t,n,s,r){e.active+=1;let i=t.type??"(untyped)",o=e.byType.get(i);o||(o={active:0,isolated:0,degree_leq_one:0},e.byType.set(i,o)),o.active+=1,!(n>1)&&(e.degreeLeqOne+=1,o.degree_leq_one+=1,n===0&&(e.isolated+=1,o.isolated+=1),!(s.has(t.id.toLowerCase())||r.has(i.toLowerCase()))&&(n===0?e.isolates.push(t.id):e.sparse.push(t.id)))}function hs(e,t,n,s,r,i){let o={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){o.missing+=1;continue}l.terminal||ps(o,l,e.graph.incidentEdges(u).length,n,s)}}let{isolates:a,sparse:c}=o,d=[];return E(d,a,r,"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."),E(d,c,r,"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(i).sort(([u],[l])=>u.localeCompare(l))),active_nodes:o.active,missing_nodes:o.missing,isolated_active_nodes:o.isolated,degree_leq_one_active_nodes:o.degreeLeqOne,coverage_by_type:Object.fromEntries([...o.byType.entries()].sort(([u],[l])=>u<l?-1:1))}}}function _e(e,t={}){let n=t.isTerminal??(l=>l==="closed"||l==="canceled"),s=t.isBlocked??(l=>l==="blocked"),r=t.maxSampleSize??is;if(!Number.isInteger(r)||r<1)throw new TypeError(`Invalid audit sample bound: ${String(t.maxSampleSize)}`);let i=new Set((t.exemptIsolates??[]).filter(l=>typeof l=="string").map(l=>l.trim().toLowerCase())),o=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=ds(e,n,r);t.signal?.throwIfAborted(),d.push(...us(e,a,s,r)),t.signal?.throwIfAborted(),d.push(...ls(e,a,r),...fs(e,r)),t.signal?.throwIfAborted();let u=hs(e,a,i,o,r,c);return d.push(...u.findings),d.sort((l,f)=>At[l.severity]-At[f.severity]||l.code.localeCompare(f.code)||l.sample[0].localeCompare(f.sample[0])),{findings:d,profile:u.profile}}function Lt(e,t){let n=[...new Set([...Object.keys(e),...Object.keys(t)])].sort(),s={};for(let r of n){let i=(t[r]??0)-(e[r]??0);i!==0&&(s[r]=i)}return s}function Ot(e){return e.profile.coverage_by_type??{}}function Mt(e,t){let n={},s=Ot(e),r=Ot(t),i=[...new Set([...Object.keys(s),...Object.keys(r)])].sort();for(let o of i){let a=s[o],c=r[o],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[o]=d)}return{baseline_saved_at:e.saved_at,same_snapshot:e.fingerprint===t.fingerprint,affected_subjects_by_code:Lt(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:Lt(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]="4198a3b2-2541-50eb-bec5-93ac58601f40")}catch{}})();function $t(e){return[...e].sort().join("\0")}function gs(e,t,n){let s=e.successors.get(t);s?s.push(n):e.successors.set(t,[n]);let r=e.predecessors.get(n);r?r.push(t):e.predecessors.set(n,[t])}function Pt(e,t,n,s,r){let i=t.resolve(r);if(i?.ordering!==!0)return;let o=ut(s),a=o===void 0?void 0:e.canonicalIds.get(o.toLowerCase());if(a===void 0)return;let c=(i.precedence??"source_before_target")==="source_before_target";gs(e,c?n:a,c?a:n)}function ms(e,t){let n={successors:new Map,predecessors:new Map,canonicalIds:new Map},s=e.filter(r=>typeof r?.id=="string"&&r.id.trim().length>0);for(let r of s){let i=r.id.trim();n.canonicalIds.set(i.toLowerCase(),i)}for(let r of s){let i=r.id.trim();Pt(n,t,i,r.blocked_by,"blocked_by");for(let o of r.dependencies??[])typeof o!="object"||o===null||Pt(n,t,i,o.id,typeof o.kind=="string"?o.kind:"related")}for(let r of[n.successors,n.predecessors])for(let i of r.values())i.sort();return n}function ys(e,t){let n=new Set([t]),s=[t];for(;s.length>0;){let r=s.pop();for(let i of[e.successors,e.predecessors])for(let o of i.get(r)??[])n.has(o)||(n.add(o),s.push(o))}return n}function ws(e,t){let n=new Map;for(let s of t){let r=(e.successors.get(s)??[]).filter(i=>t.has(i));r.length>0&&n.set(s,r)}return n}function jt(e,t,n){let s=ms(e,t),r=s.canonicalIds.get(n.trim().toLowerCase());if(r===void 0)return{cycles:[],successors:new Map,canonical:n};let i=ws(s,ys(s,r));return{cycles:Fe(i).filter(o=>o.includes(r)),successors:i,canonical:r}}function bs(e,t,n){let s=new Set(t),r=s.has(n)?n:t[0];if(e.get(r)?.includes(r))return[r,r];for(let i of e.get(r)??[]){if(!s.has(i))continue;let o=_s(e,s,r,i);if(o)return o}return[...t,t[0]]}function _s(e,t,n,s){let r=[[s]],i=new Set([n,s]);for(;r.length>0;){let o=r.shift(),a=o.at(-1);for(let c of e.get(a)??[]){if(c===n)return[n,...o,n];!t.has(c)||i.has(c)||(i.add(c),r.push([...o,c]))}}}function ci(e,t,n){let s=O(),r=jt(e,s,n),i=jt(t,s,n),o=new Set(r.cycles.map($t));return i.cycles.filter(a=>!o.has($t(a))).map(a=>`ordering_cycle_created:${bs(i.successors,a,i.canonical).join(" -> ")}:items_will_not_be_ready:run_pm_graph_audit`)}import{createHash as vs}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 ks=64,xs=8;function Es(e,t){let n=(e.dependencies??[]).map(s=>{if(typeof s!="object"||s===null)return"";let r=s;return`${typeof r.kind=="string"?r.kind:"related"}:${typeof r.id=="string"?r.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 ve(e,t=s=>s==="closed"||s==="canceled",n=x()){let s=e.filter(i=>typeof i?.id=="string"&&i.id.trim().length>0).map(i=>Es(i,t)).sort(),r=n.list().map(i=>G(i)).sort();return vs("sha256").update(s.join("")).update("").update(r.join("")).digest("hex")}function Ft(e,t,n){let s=t??n;if(!Number.isInteger(s)||s<1)throw new TypeError(`Invalid ${e} bound: ${String(t)}`);return s}var Be=class{#e=new Map;#n;#s;constructor(t={}){this.#n=Ft("maxResultsPerWorkspace",t.maxResultsPerWorkspace,ks),this.#s=Ft("maxWorkspaces",t.maxWorkspaces,xs)}lookup(t,n,s){let r=this.#e.get(t),i=!0;(r===void 0||r.fingerprint!==n)&&(r={fingerprint:n,assembly:s(),results:new Map},i=!1,!this.#e.has(t)&&this.#e.size>=this.#s&&this.#e.delete(this.#e.keys().next().value)),this.#e.delete(t),this.#e.set(t,r);let o=r,a=this.#n;return{assembly:o.assembly,assemblyReused:i,fingerprint:n,memoize(c,d){let u=o.results.get(c);if(u!==void 0||o.results.has(c))return o.results.delete(c),o.results.set(c,u),{value:structuredClone(u),reused:!0};let l=d();return o.results.size>=a&&o.results.delete(o.results.keys().next().value),o.results.set(c,structuredClone(l)),{value:l,reused:!1}}}}clear(){this.#e.clear()}},Gt=new Be;function ke(){return Gt}function pi(){Gt.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 Is=["prerequisite","dependent","ancestor","descendant","provenance","related"],Ts=new TextEncoder;function qe(e,t,n){let s=e??t;if(!Number.isInteger(s)||s<1)throw new TypeError(`Relationship context ${n} must be positive`);return s}function xe(e){return Math.max(1,Math.ceil(Ts.encode(JSON.stringify(e)).byteLength/4))}function ze(e,t,n){let s=n.resolve(e.kind);if(s?.ordering){let i=(s.precedence??"source_before_target")==="source_before_target"?e.source:e.target;return t===i?"prerequisite":"dependent"}if(s?.hierarchy){let i=(s.hierarchyDirection??"source_parent")==="source_parent"?e.source:e.target;return t===i?"ancestor":"descendant"}return e.kind==="discovered_from"||e.kind==="incident_from"?"provenance":"related"}function Ss(e,t,n,s){let r=e.filter(i=>i.source===t&&i.target===n||i.target===t&&i.source===n).map(i=>ze(i,n,s));return[...new Set(r)].sort()}function Cs(e){return Is.find(t=>e.includes(t))}function Rs(e,t,n,s){let r=s.direction??"both",i=s.maxDepth??3;if(!Number.isInteger(i)||i<0)throw new TypeError("Relationship context maxDepth must be non-negative");let o=new Set([t]),a=[{id:t,distance:0}],c=[],d=0,u=!1;for(let l=0;l<a.length;l+=1){s.signal?.throwIfAborted();let f=a[l];if(f.distance>=i&&u)continue;let h=e.neighborEdges(f.id,{direction:r,kinds:s.kinds,signal:s.signal});if(d+=h.meta.inspectedEdges,f.distance>=i){h.value.some(p=>!o.has(p.id))&&(u=!0);continue}for(let{id:p,edge:g}of h.value){if(o.has(p))continue;o.add(p);let m={id:p,distance:f.distance+1,via:f.id,role:ze(g,p,n)};c.push(m),a.push(m)}}return c.sort((l,f)=>l.distance-f.distance||l.id.localeCompare(f.id)),{rows:c,visitedNodes:a.length,inspectedEdges:d,depthTruncated:u}}function Ds(e,t,n,s){let r={prerequisite:0,dependent:0,ancestor:0,descendant:0,provenance:0,related:0},i=e.neighborEdges(t,{direction:s.direction??"both",kinds:s.kinds,signal:s.signal}).value;for(let{id:o,edge:a}of i)r[ze(a,o,n)]+=1;return{directEdges:r,directTotal:i.length,rootEdges:i.map(({edge:o})=>o)}}function As(e){let t=[],n=e.initialTokens;for(let s of e.candidates){if(t.length>=e.nodeLimit)break;let r=s.distance===1?Ss(e.rootEdges,e.rootId,s.id,e.registry):[],i={...e.details.get(s.id)??{id:s.id},distance:s.distance,role:r.length>0?Cs(r):s.role,via:s.via,reasons:r.length>0?r:[`${s.role} via ${s.via} (depth ${s.distance})`]},o=xe(i);if(n+o>e.tokenBudget)break;t.push(i),n+=o}if(e.candidates.length>0&&t.length===0)throw new TypeError("Relationship context tokenBudget cannot fit one node");return{nodes:t,usedTokens:n}}function Ls(e){let t=e.options.kinds?new Set(e.options.kinds.map(i=>e.registry.require(i).kind)):void 0,n=e.graph.edges().filter(i=>{if(!e.included.has(i.source)||!e.included.has(i.target))return!1;if(t===void 0||t.has(i.kind))return!0;let o=e.registry.resolve(i.kind)?.inverse;return o!==void 0&&t.has(o)}),s=[],r=e.initialTokens;for(let i of n){if(s.length>=e.edgeLimit)break;let o=xe(i);if(r+o>e.tokenBudget)break;s.push(i),r+=o}return{edges:s,usedTokens:r,candidateCount:n.length}}function Bt(e,t,n,s={}){if(!e.nodes().includes(t))throw new TypeError(`Relationship node not found: ${t}`);let r=qe(s.nodeLimit,20,"nodeLimit"),i=qe(s.edgeLimit,40,"edgeLimit"),o=qe(s.tokenBudget,1200,"tokenBudget"),a=s.registry??x(),c=new Map(n.map(A=>[A.id,A])),d=c.get(t)??{id:t},{evidence:u=[],...l}=d,f=[...u],h=Rs(e,t,a,s),{rootEdges:p,...g}=Ds(e,t,a,s),m=L("relationship-context",{rootId:t,direction:s.direction??"both",kinds:[...s.kinds??[]].sort(),maxDepth:s.maxDepth??3}),b=ot(h.rows,s.cursor,m,({id:A})=>A),k=h.rows.slice(b),_=xe(l)+xe(f);if(_>o)throw new TypeError("Relationship context tokenBudget cannot fit root and evidence");let C=As({candidates:k,details:c,rootEdges:p,rootId:t,registry:a,nodeLimit:r,tokenBudget:o,initialTokens:_}),{nodes:v}=C,V=new Set([t,...v.map(({id:A})=>A)]),$=Ls({graph:e,included:V,options:s,registry:a,edgeLimit:i,tokenBudget:o,initialTokens:C.usedTokens}),{edges:P,usedTokens:gn}=$,K=b+v.length,Ie=K<h.rows.length,tt=v.at(-1),Te=$.candidateCount-P.length,nt=h.depthTruncated||Ie||Te>0,mn={rootId:t,...l.status===void 0?{}:{rootStatus:l.status},...g,discoveredNodes:h.rows.length,returnedNodes:v.length,returnedEdges:P.length,omittedNodes:h.rows.length-K,omittedEdges:Te,evidenceCount:f.length,hasMore:Ie};return{root:l,summary:mn,nodes:v,edges:P,evidence:f,meta:{exact:!0,truncated:nt,completeness:nt?"truncated":"complete",nodeLimit:r,edgeLimit:i,tokenBudget:o,usedTokens:gn,visitedNodes:h.visitedNodes,inspectedEdges:h.inspectedEdges,omittedNodes:h.rows.length-K,omittedEdges:Te,...Ie&&tt?{nextCursor:te(m,tt.id,K-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]="348c9246-2fb9-529e-b627-f60c901a6cf2")}catch{}})();function qt(e){return Math.round(e*1e6)/1e6}function zt(e,t,n){let s=e.get(t);s===void 0?e.set(t,new Set([n])):s.add(n)}function Ut(e,t){let n=new Map(e.nodes().map(r=>[r,new Set]));ge(e,t,r=>{n.get(r.source).add(r.target),n.get(r.target).add(r.source)});let s=new Map;for(let[r,i]of n)s.set(r,[...i].sort());return s}function Os(e,t){let n=new Map,s=new Map;return ge(e,t,(r,i)=>{if(!i.ordering)return;let{predecessor:o,successor:a}=fe(r,i);zt(s,o,a),zt(n,a,o)}),{incoming:n,outgoing:s}}function Ns(e,t,n){let s=new Map([[e,0]]),r=new Map([[e,1]]),i=new Map,o=[],a=[e],c=0,d=0;for(let u=0;u<a.length;u+=1){let l=a[u];n.visitedNodes+=1,o.push(l);let f=s.get(l);l!==e&&(c+=1,d+=f);for(let h of t.get(l))if(n.inspectedEdges+=1,s.has(h)||(s.set(h,f+1),a.push(h)),s.get(h)===f+1){r.set(h,(r.get(h)??0)+r.get(l));let p=i.get(h);p===void 0?i.set(h,[l]):p.push(l)}}return{stack:o,sigma:r,predecessors:i,reachableCount:c,distanceSum:d}}function Ms(e,t,n){let s=new Map;for(let r=e.stack.length-1;r>=0;r-=1){let i=e.stack[r],o=(1+(s.get(i)??0))/e.sigma.get(i);for(let a of e.predecessors.get(i)??[])s.set(a,(s.get(a)??0)+e.sigma.get(a)*o);i!==t&&n.set(i,(n.get(i)??0)+(s.get(i)??0))}}function $s(e,t){return t<=1||e.reachableCount===0?0:e.reachableCount/(t-1)*(e.reachableCount/e.distanceSum)}function Ps(e,t,n,s,r){return{id:e,degree:t.get(e).length,inDegree:n.incoming.get(e)?.size??0,outDegree:n.outgoing.get(e)?.size??0,betweenness:qt((s.get(e)??0)/2),closeness:qt(r.get(e))}}function Vt(e,t={}){let n=Ut(e,t.kinds),s=Os(e,t.kinds),r=e.nodes(),i=new Map,o=new Map,a={visitedNodes:0,inspectedEdges:0};for(let u of r){t.signal?.throwIfAborted();let l=Ns(u,n,a);o.set(u,$s(l,r.length)),Ms(l,u,i)}let c=0;for(let u of n.values())c+=u.length;let d=r.map(u=>Ps(u,n,s,i,o)).sort((u,l)=>l.betweenness-u.betweenness||l.degree-u.degree||u.id.localeCompare(l.id));return{value:{nodeCount:r.length,edgeCount:c/2,rows:d},meta:{visitedNodes:a.visitedNodes,inspectedEdges:a.inspectedEdges,truncated:!1}}}function js(e,t){return e<=t?{source:e,target:t}:{source:t,target:e}}function Fs(e,t,n){let r=t.get(e.node)[e.neighborIndex];if(e.neighborIndex+=1,n.inspectedEdges+=1,r!==e.parent){if(n.discovery.has(r)){n.low.set(e.node,Math.min(n.low.get(e.node),n.discovery.get(r)));return}return e.children+=1,n.discovery.set(r,n.timer),n.low.set(r,n.timer),n.timer+=1,{node:r,parent:e.node,neighborIndex:0,children:0}}}function Gs(e,t,n){if(e.parent===null){e.children>1&&n.articulation.add(e.node);return}let s=e.parent,r=n.low.get(e.node);n.low.set(s,Math.min(n.low.get(s),r)),s!==t&&r>=n.discovery.get(s)&&n.articulation.add(s),r>n.discovery.get(s)&&n.bridges.push(js(s,e.node))}function Bs(e,t,n,s){n.discovery.set(e,n.timer),n.low.set(e,n.timer),n.timer+=1;let r=[{node:e,parent:null,neighborIndex:0,children:0}];for(;r.length>0;){s?.throwIfAborted();let i=r.at(-1);if(i.neighborIndex<t.get(i.node).length){let o=Fs(i,t,n);o!==void 0&&r.push(o)}else Gs(i,e,n),r.pop()}}function Kt(e,t={}){let n=Ut(e,t.kinds),s={discovery:new Map,low:new Map,timer:0,articulation:new Set,bridges:[],inspectedEdges:0};for(let r of e.nodes())s.discovery.has(r)||Bs(r,n,s,t.signal);return{value:{articulationPoints:[...s.articulation].sort(),bridges:s.bridges.sort((r,i)=>r.source.localeCompare(i.source)||r.target.localeCompare(i.target))},meta:{visitedNodes:s.discovery.size,inspectedEdges:s.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 qs(e){let t=e.registry(),n=new Map,s=new Set;for(let r of e.edges()){let i=t.require(r.kind);if(!i.ordering)continue;let{predecessor:o,successor:a}=fe(r,i);if(s.add(o),s.add(a),o===a)continue;let c=n.get(o);c===void 0?n.set(o,new Set([a])):c.add(a)}return{forward:n,participants:s}}function zs(e,t,n,s){if(e===void 0)return s;let r=s;for(let i of e)t.has(i)&&(r=Math.min(r,n.get(i)));return r}function Us(e,t,n){let s=n-t;return{id:e,earliestStart:t,earliestFinish:t+1,latestStart:n,latestFinish:n+1,slack:s,critical:s===0}}function Vs(e,t,n,s,r){let i=new Map;for(let o=e.length-1;o>=0;o-=1){let a=e[o],c=zs(t.forward.get(a),s,i,r);i.set(a,c-1)}return e.map(o=>Us(o,n[o],i.get(o))).sort((o,a)=>o.slack-a.slack||o.earliestStart-a.earliestStart||o.id.localeCompare(a.id))}function Wt(e,t={}){t.signal?.throwIfAborted();let n=ue(e,{registry:e.registry()}),s=qs(e),r=new Set(n.order),i=n.order.filter(d=>s.participants.has(d)),o=i.reduce((d,u)=>Math.max(d,n.depth[u]+1),0),a=Vs(i,s,n.depth,r,o),c=a.length>0;return{exact:!0,acyclic:n.acyclic,makespan:o,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 Jt 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 Xt=1,Ue=500,Ks=64,Ws="graph-durable-cache";function Yt(e){return se(e,Ws,30,`graph-cache:${process.pid}`,!1,!1,3e3)}function U(e){return Jt.join(e,"runtime","graph-cache.json")}function Qt(e){return Jt.join(e,"runtime","graph-audit-baseline.json")}function Ve(e){if(e!==null)try{let t=JSON.parse(e);return typeof t!="object"||t===null||t.version!==Xt||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 Ke(e,t){let n=await j(U(e)),s=Ve(n),r=s?.fingerprint===t;return{exists:n!==null,fresh:r,results:r?s.results:{}}}async function We(e,t,n,s,r){let i=await Yt(e);try{let o=Ve(await j(U(e))),a=o?.fingerprint===t?o.results:{};delete a[s],a[s]=r;let c=Object.keys(a);for(let d of c.slice(0,Math.max(0,c.length-Ks)))delete a[d];await F(U(e),JSON.stringify({version:Xt,fingerprint:t,saved_at:new Date().toISOString(),results:a})),n.results=a}finally{await i()}}async function He(e){let t=await Yt(e);try{await st(U(e))}finally{await t()}}async function Zt(e,t){let n=U(e),s=await j(n),r=Ve(s);return r===void 0?{exists:s!==null,fresh:!1,entry_count:0}:{exists:!0,fresh:r.fingerprint===t,entry_count:Object.keys(r.results).length,fingerprint:r.fingerprint.slice(0,12),saved_at:r.saved_at,bytes:Buffer.byteLength(s,"utf8")}}function Je(e,t){return t||e>=Ue}function Ht(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.values(e).every(t=>Number.isInteger(t)&&t>=0)}function Hs(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 Js(e){if(e!==null)try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return;let n=t,s=n.profile;return typeof n.saved_at!="string"||typeof n.fingerprint!="string"||!Ht(n.affected_subjects_by_code)||typeof s!="object"||s===null||![s.nodes,s.edges,s.active_nodes,s.missing_nodes,s.isolated_active_nodes,s.degree_leq_one_active_nodes].every(r=>Number.isInteger(r)&&r>=0)||!Ht(s.edges_by_kind)||s.coverage_by_type!==void 0&&!Hs(s.coverage_by_type)?void 0:{...n,profile:{...s,coverage_by_type:s.coverage_by_type??{}}}}catch{return}}async function en(e){return Js(await j(Qt(e)))}async function tn(e,t){await F(Qt(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]="9b8e22ad-6268-515d-994e-6b98a062ba93")}catch{}})();var Xs={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 nn(e){return`${e.source} -${e.kind}-> ${e.target}`}function Ys(e){let[t,...n]=e.edges;return n.map(s=>({op:"remove",code:"duplicate_edge",subject:nn(s),rationale:"This stored spelling restates the kept canonical edge of the same semantic family; removing it leaves the relationship stated exactly once.",evidence:[`keep: ${nn(t)}`,`group: ${be(e)}`],confidence:"high"}))}function Qs(e,t){if(e.code==="duplicate_edge")return e.sample.flatMap(s=>Ys(t.get(s)));let n=Xs[e.code];return e.sample.map(s=>({op:n.op,code:e.code,subject:s,rationale:n.rationale,evidence:[e.policy],confidence:n.confidence}))}function sn(e,t={}){let{redundancyLimit:n,...s}=t,r=_e(e,s),i=new Map(Ge(e).map(d=>[be(d),d])),o=r.findings.flatMap(d=>Qs(d,i)),a=r.findings.some(d=>d.sample_truncated);t.signal?.throwIfAborted();let c=we(e.graph,{limit:n??t.maxSampleSize??25,...t.signal===void 0?{}:{signal:t.signal}});for(let d of c.value)o.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:o,report:r,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]="ee0547d9-ae0f-5762-8bff-e25f0a3cd4d5")}catch{}})();var Zs=["tree","graph","context"],er=["none","repeated"],tr=["outgoing","incoming","both"],nr=32,sr=200,rr=400,ir=16e3;function or(e){let t=e?.trim().toLowerCase()??"tree";if(Zs.includes(t))return t;throw new w(`Invalid --format value "${e}". Use "tree", "graph", or "context".`,y.USAGE)}function I(e,t){if(e===void 0)return;let n=typeof e=="number"?e:Number(e.trim());if(!Number.isInteger(n)||n<1)throw new w(`Invalid --${t} value "${e}". Use a positive integer.`,y.USAGE);return n}function Ee(e){if(e===void 0)return;let t=typeof e=="number"?e:Number(e.trim());if(!Number.isInteger(t)||t<0)throw new w(`Invalid --max-depth value "${e}". Use a non-negative integer.`,y.USAGE);return t}function ar(e){let t=e?.trim().toLowerCase()??"none";if(er.includes(t))return t;throw new w(`Invalid --collapse value "${e}". Use "none" or "repeated".`,y.USAGE)}function Ye(e){let t=e?.trim().toLowerCase()??"both";if(tr.includes(t))return t;throw new w(`Invalid --direction value "${e}". Use "outgoing", "incoming", or "both".`,y.USAGE)}function Qe(e,t=x()){if(e===void 0)return;let n=(Array.isArray(e)?e:[e]).flatMap(r=>r.split(",")).map(r=>r.trim()).filter(r=>r.length>0);if(n.length===0)return;let s=new Set;for(let r of n){let i=t.resolve(r);if(!i){let o=t.list().map(a=>a.kind).join(", ");throw new w(`Invalid --kind value "${r}". Registered kinds: ${o}.`,y.USAGE)}s.add(i.kind)}return[...s].sort()}function cr(e){if(!e||e.length===0)return[];let t=e.map(({id:s,kind:r})=>({id:s.trim(),kind:r.trim().toLowerCase()})).sort((s,r)=>{let i=s.kind.localeCompare(r.kind);return i!==0?i:s.id.localeCompare(r.id)}),n=new Map;for(let s of t){let r=`${s.kind.toLowerCase()}::${s.id.toLowerCase()}`;n.has(r)||n.set(r,{id:s.id,kind:s.kind})}return[...n.values()]}function dr(e){return{id:e.id,title:e.title,type:e.type,status:e.status,dependencies:cr(e.dependencies)}}function ur(e){return Z(new TextEncoder().encode(JSON.stringify({...e,dependencies:void 0})).byteLength)}function lr(e,t,n,s,r,i,o,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(on(d.id,n,s,r,i,o,a,c+1,d.kind))}}function fr(e,t,n,s,r,i,o,a){return o.estimatedTokens>=o.tokenBudget&&t?.dependencies.length?(e.truncated=!0,o.reasons.add("token_budget"),!0):!t||e.cycle?!0:s!==void 0&&a>=s?(t.dependencies.length>0&&(e.truncated=!0,o.reasons.add("max_depth")),!0):r==="repeated"&&i.has(n)?(e.collapsed=!0,!0):!1}function on(e,t,n,s,r,i,o,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(o.nodes+=1,o.estimatedTokens+=ur(l),fr(l,u,d,s,r,i,o,a))return l;r==="repeated"&&i.add(d);let f=new Set(n);return f.add(d),lr(l,u,t,f,s,r,i,o,a),l}function rn(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 pr(e){let t=new Map,n=new Map,s=[e];for(;s.length>0;){let a=s.pop();t.set(a.id,rn(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,rn(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||s.push(c)}}let r=[...t.values()].sort((a,c)=>a.id.localeCompare(c.id)),i=[...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)}),o=r.filter(a=>a.missing).map(a=>a.id);return{root_id:e.id,nodes:r,edges:i,missing_ids:o}}function an(e,t,n){let s=new Set,r=new Set,i=new Set,o=new Set,a=[{id:e,depth:0}],c=0;for(;c<a.length;){let d=a[c++],u=d.id.trim().toLowerCase();s.add(u);let l=t.get(u);if(!l){i.add(u);continue}if(!(n!==void 0&&d.depth>=n)&&!o.has(u)){o.add(u);for(let f of l.dependencies)r.add(`${u}::${f.id.trim().toLowerCase()}::${f.kind}`),a.push({id:f.id,depth:d.depth+1})}}return{node_count:s.size,edge_count:r.size,edge_basis:"deduplicated_directed",missing_count:i.size}}function hr(e,t=x()){let n=Ee(e.maxDepth),s=I(e.nodeLimit,"node-limit"),r=I(e.edgeLimit,"edge-limit"),i=I(e.tokenBudget,"token-budget"),o=Qe(e.kind,t);return{direction:Ye(e.direction),...o===void 0?{}:{kinds:o},...n===void 0?{}:{maxDepth:n},...s===void 0?{}:{nodeLimit:s},...r===void 0?{}:{edgeLimit:r},...i===void 0?{}:{tokenBudget:i},...e.cursor?.trim()?{cursor:e.cursor.trim()}:{}}}function gr(e,t,n,s){return Bt(e.graph,t,e.details.map(r=>r.id===t&&s.length>0?{...r,evidence:s}:r),n)}function Xe(e,t,n,s){for(let r of n.slice(0,s)){let i=r?.trim();i&&e.push(`${t}:${i}`)}}async function mr(e,t,n,s){let r=await ct(e,t,n.id_prefix,n.item_format,s);if(!r)return[];let{document:i}=await dt(r,{schema:n.schema}),o=i.metadata,a=o.files??[],c=o.tests??[],d=o.docs??[],u=[["files",a.length],["tests",c.length],["docs",d.length],["comments",(o.comments??[]).length],["notes",(o.notes??[]).length],["learnings",(o.learnings??[]).length]];if(u.every(([,f])=>f===0))return[];let l=[`linked:${u.map(([f,h])=>`${f}=${h}`).join(",")}`];return Xe(l,"file",a.map(f=>f.path),3),Xe(l,"test",c.map(f=>f.command??f.path),2),Xe(l,"doc",d.map(f=>f.path),2),l}function yr(e){let{canonicalId:t,context:n,missingCount:s,missingReferences:r,referenceLimit:i,summaryOnly:o}=e;return{id:t,format:"context",node_count:n.nodes.length+1,edge_count:n.edges.length,edge_basis:"deduplicated_directed",missing_count:s,missing_scope:"traversal",missing_reference_count:r.length,...o?{}:{missing_references:r.slice(0,i),context:n}}}function wr(e){let{row:t,missingReachableSet:n,packetIds:s,filteredKinds:r,registry:i}=e;if(t.no_active_blocker_sentinel||!n.has(t.target_id.trim().toLowerCase())||!s.has(t.holder_id))return!1;if(r===void 0)return!0;let o=i.resolve(t.kind);return o!==void 0&&(r.has(o.kind)||o.inverse!==void 0&&r.has(o.inverse))}function cn(e,t,n){let s;for(;;){let r=Z(new TextEncoder().encode(Re(Ce("deps",e),t)).byteLength);if(r===s)return r;n(r),s=r}}function br(e){return e instanceof TypeError&&e.message.startsWith("Relationship context tokenBudget cannot fit ")}function _r(e){try{return gr(e.assembly,e.canonicalId,{...e.contextOptions,...e.internalTokenBudget===void 0?{}:{tokenBudget:e.internalTokenBudget}},e.rootEvidence)}catch(t){if(e.smallestResult!==void 0&&br(t))return e.smallestResult;throw t}}function vr(e){let{assembly:t,canonicalId:n,contextOptions:s,rootEvidence:r,summaryOnly:i,outputFormat:o,missingCount:a,missingReferences:c}=e,u=s.edgeLimit??40,l=s.tokenBudget,f,h;for(;;){let p=_r({assembly:t,canonicalId:n,contextOptions:s,internalTokenBudget:l,rootEvidence:r,smallestResult:h});if("format"in p)return p;let g=p;f??=g.meta.tokenBudget,l??=f;let m=yr({canonicalId:n,context:g,missingCount:a,missingReferences:c,referenceLimit:u,summaryOnly:i});if(h=m,i||(g.meta.tokenBudget=f,g.meta.usedTokens=cn(M(m,!1),o,_=>{g.meta.usedTokens=_}),g.meta.usedTokens<=f))return m;if(u>0){u-=1;continue}let b=l,k=b*f/g.meta.usedTokens;l=Math.min(b-1,Math.max(1,Math.floor(k*.9)))}}function kr(e){let{assembly:t,canonicalId:n,options:s,rootEvidence:r,summaryOnly:i,outputFormat:o}=e,a=hr(s,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(g=>t.missingIdSet.has(g.toLowerCase())),u=new Set(d.map(g=>g.toLowerCase())),l=t.graph.registry(),f=a.kinds?new Set(a.kinds.map(g=>l.require(g).kind)):void 0,h=new Set([n,...c.value]),p=[...t.dangling.active,...t.dangling.legacy_terminal].filter(g=>wr({row:g,missingReachableSet:u,packetIds:h,filteredKinds:f,registry:l}));return vr({assembly:t,canonicalId:n,contextOptions:a,rootEvidence:r,summaryOnly:i,outputFormat:o,missingCount:d.length,missingReferences:p})}function xr(e){let t=[e],n;for(;t.length>0;){let s=t.pop();s.dependencies.length>0&&(n=s,t.push(...s.dependencies))}return n?(n.dependencies.pop(),n.truncated=!0,!0):!1}function Er(e,t,n,s,r,i,o){let a=r??nr,c=I(n.nodeLimit,"node-limit")??sr,d=I(n.edgeLimit,"edge-limit")??rr,u=I(n.tokenBudget,"token-budget")??ir,l={nodeLimit:c,edgeLimit:d,tokenBudget:u,nodes:0,edges:0,estimatedTokens:0,reasons:new Set},f=on(e,s,new Set,a,t==="graph"?"repeated":i,new Set,l),h=an(e,s,void 0),p;for(;;){let g=pr(f),m=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:h.node_count,total_edge_count:h.edge_count,omitted_node_count:Math.max(0,h.node_count-g.nodes.length),omitted_edge_count:Math.max(0,h.edge_count-g.edges.length)},b={id:e,format:t,node_count:g.nodes.length,edge_count:g.edges.length,edge_basis:"deduplicated_directed",missing_count:g.missing_ids.length,...m?{truncation:m}:{}};if(p=t==="tree"?{...b,tree:f}:{...b,graph:g},(p.truncation===void 0?Z(new TextEncoder().encode(Re(Ce("deps",M(p,!1)),o)).byteLength):cn(M(p,!1),o,_=>{p.truncation.estimated_tokens=_}))<=u)return p;if(!xr(f))return l.reasons.add("token_budget"),p;l.reasons.add("token_budget")}}function M(e,t,n={}){let s={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:[s],included_field_groups:t?[]:[s.name]}}}async function Hi(e,t,n){let s=J(process.cwd(),n.path);if(!await W(X(s)))throw new w(`Tracker is not initialized at ${s}. Run pm init first.`,y.NOT_FOUND);let r=or(t.format),i=Ee(t.maxDepth),o=ar(t.collapse);ee(t.summary===!0,t.full===!0,"--summary");let a=t.summary===!0,c=await re(s),d=H(c,ne()),u=await ie(s,c.item_format,d.type_to_folder,void 0,c.schema),l=Q(c.schema),f=new Map(u.map(p=>[p.id.trim().toLowerCase(),dr(p)])),h=lt(u,p=>R(p,l));for(let p of[...h.active,...h.legacy_terminal]){let g=f.get(p.holder_id.trim().toLowerCase()),m=p.kind.trim().toLowerCase();g&&!g.dependencies.some(b=>b.id.trim().toLowerCase()===p.target_id.trim().toLowerCase()&&b.kind===m)&&g.dependencies.push({id:p.target_id,kind:m})}if(!f.has(e.trim().toLowerCase()))throw new w(`Item ${e} not found`,y.NOT_FOUND);if(r==="context"){let p=f.get(e.trim().toLowerCase()).id,g=a?[]:await mr(s,p,c,d.type_to_folder),m=_=>R(_,l),b=O(),k=ke().lookup(s,ve(u,m,b),()=>N(u,m,b));return M(kr({assembly:k.assembly,canonicalId:p,options:t,rootEvidence:g,summaryOnly:a,outputFormat:n.json===!0?"json":"toon"}),a,k.assembly.legacyAliasCounts)}return a?M({id:e,format:r,...an(e,f,i)},!0,Object.fromEntries(Object.entries(N(u,p=>R(p,l)).legacyAliasCounts))):M(Er(e,r,t,f,i,o,n.json===!0?"json":"toon"),!1,Object.fromEntries(Object.entries(N(u,p=>R(p,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]="ba8e7432-539e-55d3-b105-689db55d26b2")}catch{}})();var fn=new Set(["ancestors","descendants","predecessors","successors","paths","impact","dominators"]),S=10;function dn(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 un(e){return e===void 0?[]:(Array.isArray(e)?e:[e]).flatMap(t=>t.split(",")).map(t=>t.trim()).filter(t=>t.length>0)}function Ir(e,t,n){let s=e.trim().toLowerCase();if(!Se.includes(s))throw new w(`Invalid graph subcommand "${e}". Use one of: ${Se.join(", ")}.`,y.USAGE);let r=s;if(fn.has(r)&&!t?.trim())throw new w(`graph ${r} requires an item id.`,y.USAGE);if(r==="paths"&&!n?.trim())throw new w("graph paths requires a source and a target item id.",y.USAGE);return r}function Ze(e){throw e instanceof TypeError?new w(e.message,y.USAGE):e}function et(e){return{truncated:e.truncated,cost:{visited_nodes:e.visitedNodes,inspected_edges:e.inspectedEdges}}}function ln(e,t){let n=t.trim().toLowerCase();for(let s of e.details)if(s.id.trim().toLowerCase()===n&&!e.missingIdSet.has(s.id.toLowerCase()))return s.id;throw new w(`Item ${t} not found`,y.NOT_FOUND)}function Tr(e,t,n){let s={ancestors:xt,descendants:Et,predecessors:It,successors:Tt}[e],r;try{r=s(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(o){Ze(o)}let i=et(r.meta);return{subcommand:e,root:t,count:r.value.length,...i,...r.meta.nextCursor===void 0?{}:{next_cursor:r.meta.nextCursor},...n.summary?{}:{ids:r.value}}}function Sr(e,t,n){let s=St(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:s.value.length,...et(s.meta),...n.summary?{}:{paths:s.value.map(r=>({nodes:r.nodes,kinds:r.edges.map(i=>i.kind),length:r.length}))}}}function Cr(e,t){let n;try{n=bt(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??S},...t.after===void 0?{}:{after:t.after}})}catch(s){Ze(s)}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 Rr(e){let t=e.assembly.graph,n=e.limit??S,s=ue(t,{registry:t.registry()}),r=_t(t);return{subcommand:"analyze",node_count:t.nodes().length,edge_count:t.edges().length,edge_basis:"deduplicated_directed",sample_limit:n,execution:{acyclic:s.acyclic,ordered_node_count:s.order.length,layer_count:s.layers.length,frontier_count:s.frontier.length,critical_path_length:s.criticalPathLength,cycle_count:s.cycles.length,...e.summary?{}:{frontier:s.frontier.slice(0,n),critical_path:s.criticalPath.slice(0,n),cycles:s.cycles.slice(0,n)}},knowledge:{component_count:r.components.length,largest_component_size:r.components[0]?.length??0,orphan_count:r.orphans.length,...e.summary?{}:{orphans:r.orphans.slice(0,n),hubs:r.hubs.slice(0,n)}}}}function Dr(e,t){let n=_e(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}}),s={},r={},i={},o={};for(let a of n.findings)s[a.severity]=(s[a.severity]??0)+1,r[a.code]=(r[a.code]??0)+1,i[a.severity]=(i[a.severity]??0)+a.count,o[a.code]=(o[a.code]??0)+a.count;return{subcommand:"audit",finding_count:n.findings.length,findings_by_severity:s,findings_by_code:r,affected_subjects_by_severity:i,affected_subjects_by_code:o,profile:n.profile,legacy_alias_counts:e.assembly.legacyAliasCounts,...e.summary?{}:{findings:n.findings}}}function Ar(e){let t=e.limit??S,n={};e.kinds!==void 0&&(n.kinds=e.kinds);let s=Rt(e.assembly.graph,n),r=s.value;return{subcommand:"communities",community_count:r.communities.length,largest_community_size:r.communities[0]?.size??0,iterations:r.iterations,converged:r.converged,truncated:!r.converged||r.communities.length>t,cost:{visited_nodes:s.meta.visitedNodes,inspected_edges:s.meta.inspectedEdges},...e.summary?{}:{communities:r.communities.slice(0,t).map(i=>({representative:i.representative,size:i.size,members:i.members.slice(0,t)}))}}}function Lr(e){let t;try{t=we(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){Ze(n)}return{subcommand:"redundancy",redundant_count:t.value.length,...et(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 Or(e,t){let n=t.limit??S,s=Dt(t.assembly.graph,e,{direction:t.direction,...t.kinds===void 0?{}:{kinds:t.kinds},...t.maxDepth===void 0?{}:{maxDepth:t.maxDepth}}),r=s.value.rows.filter(i=>i.dominatedCount>0);return{subcommand:"dominators",root:e,direction:t.direction,reachable_count:s.value.reachableCount,bottleneck_count:r.length,truncated:s.meta.truncated||r.length>n,cost:{visited_nodes:s.meta.visitedNodes,inspected_edges:s.meta.inspectedEdges},...t.summary?{}:{bottlenecks:r.slice(0,n).map(i=>({id:i.id,idom:i.idom,dominated_count:i.dominatedCount}))}}}function Nr(e){let t=e.limit??S,n=Wt(e.assembly.graph),s=n.rows.filter(r=>r.critical).length;return{subcommand:"slack",acyclic:n.acyclic,makespan:n.makespan,scheduled_count:n.scheduledCount,critical_count:s,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(r=>({id:r.id,earliest_start:r.earliestStart,latest_start:r.latestStart,slack:r.slack,critical:r.critical}))}}}function Mr(e){let t=e.limit??S,n=Vt(e.assembly.graph,e.kinds===void 0?{}:{kinds:e.kinds}),s=n.value;return{subcommand:"centrality",node_count:s.nodeCount,edge_count:s.edgeCount,edge_basis:"simple_undirected",truncated:s.rows.length>t,cost:{visited_nodes:n.meta.visitedNodes,inspected_edges:n.meta.inspectedEdges},...e.summary?{}:{rows:s.rows.slice(0,t).map(r=>({id:r.id,degree:r.degree,in_degree:r.inDegree,out_degree:r.outDegree,betweenness:r.betweenness,closeness:r.closeness}))}}}function $r(e){let t=e.limit??S,n=Kt(e.assembly.graph,e.kinds===void 0?{}:{kinds:e.kinds}),{articulationPoints:s,bridges:r}=n.value;return{subcommand:"articulation",articulation_count:s.length,bridge_count:r.length,truncated:s.length>t||r.length>t,cost:{visited_nodes:n.meta.visitedNodes,inspected_edges:n.meta.inspectedEdges},...e.summary?{}:{articulation_points:s.slice(0,t),bridges:r.slice(0,t)}}}function Pr(e,t){let n=e.limit??S,s=sn(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}}),r={},i={};for(let o of s.steps)r[o.op]=(r[o.op]??0)+1,i[o.code]=(i[o.code]??0)+1;return{subcommand:"plan",step_count:s.steps.length,steps_by_op:r,steps_by_code:i,finding_count:s.report.findings.length,truncated:s.truncated||s.steps.length>n,cost:{visited_nodes:s.cost.visitedNodes,inspected_edges:s.cost.inspectedEdges},...e.summary?{}:{steps:s.steps.slice(0,n)}}}function pn(e,t,n,s){return JSON.stringify({subcommand:e,root:t??null,target:n??null,kinds:s.kinds??null,maxDepth:s.maxDepth??null,limit:s.limit??null,after:s.after??null,direction:s.direction,maxPaths:s.maxPaths??null,sample:s.sample??null,exemptIsolates:[...new Set(s.exemptIsolates.map(r=>r.toLowerCase()))].sort(),exemptIsolateTypes:[...new Set(s.exemptIsolateTypes.map(r=>r.toLowerCase()))].sort(),summary:s.summary,unbounded:s.unbounded})}function hn(e,t,n,s,r){return e==="analyze"?Rr(s):e==="audit"?Dr(s,r):e==="plan"?Pr(s,r):e==="communities"?Ar(s):e==="redundancy"?Lr(s):e==="dominators"?Or(t,s):e==="slack"?Nr(s):e==="centrality"?Mr(s):e==="articulation"?$r(s):e==="paths"?Sr(t,n,s):e==="impact"?Cr(t,s):Tr(e,t,s)}function jr(e,t){if(e!=="index"&&(t.rebuild===!0||t.clear===!0))throw new w("--rebuild and --clear apply only to graph index.",y.USAGE);if(e!=="audit"&&t.saveBaseline===!0)throw new w("--save-baseline applies only to graph audit.",y.USAGE);if(e==="slack"&&t.kind!==void 0)throw new w("graph slack analyzes every ordering kind; --kind is not supported.",y.USAGE);if(t.rebuild===!0&&t.clear===!0)throw new w("graph index accepts either --rebuild or --clear, not both.",y.USAGE);if(e==="impact"&&t.full===!0&&t.limit!==void 0)throw new w("graph impact accepts either --full or --limit, not both.",y.USAGE)}async function Fr(e,t,n,s,r,i){let o="status";if(i.clear===!0&&(await He(e),o="cleared"),i.rebuild===!0){await He(e);let c=await Ke(e,t),d={assembly:n.assembly,direction:"both",exemptIsolates:[],exemptIsolateTypes:[],saveBaseline:!1,summary:!0,unbounded:!1};for(let u of["analyze","audit"])await We(e,t,c,pn(u,void 0,void 0,d),hn(u,void 0,void 0,d,r));o="rebuilt"}let a=await Zt(e,t);return{subcommand:"index",action:o,state:a.exists?a.fresh?"fresh":"stale":"absent",entry_count:a.entry_count,item_count:s,min_items_threshold:Ue,persist_enabled:Je(s,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 Gr(e,t,n,s){let r={saved_at:new Date().toISOString(),fingerprint:t,affected_subjects_by_code:n.affected_subjects_by_code,profile:n.profile},i=await en(e);return s&&await tn(e,r),i===void 0?n:{...n,baseline:Mt(i,r)}}async function Br(e,t,n,s,r){try{await We(e,t,n,s,r)}catch{}}async function _o(e,t,n,s,r){let i=Ir(e,t,n);ee(s.summary===!0,s.full===!0,"--summary");let o=J(process.cwd(),r.path);if(!await W(X(o)))throw new w(`Tracker is not initialized at ${o}. Run pm init first.`,y.NOT_FOUND);let a=await re(o),c=H(a,ne()),d=await ie(o,a.item_format,c.type_to_folder,void 0,a.schema),u=Q(a.schema),l=P=>R(P,u);jr(i,s);let f=O(),h=Qe(s.kind,f),p=ke().lookup(o,ve(d,l,f),()=>N(d,l,f)),g={assembly:p.assembly,...h===void 0?{}:{kinds:h},maxDepth:Ee(s.maxDepth),limit:I(s.limit,"limit"),after:s.after?.trim()||void 0,direction:Ye(s.direction),maxPaths:I(s.maxPaths,"max-paths"),sample:I(s.sample,"sample"),exemptIsolates:un(s.exemptIsolate),exemptIsolateTypes:un(s.exemptIsolateType),saveBaseline:s.saveBaseline===!0,summary:s.summary===!0,unbounded:s.full===!0};if(i==="index")return dn(await Fr(o,p.fingerprint,g,d.length,l,s),!1);let m=fn.has(i)?ln(g.assembly,t):void 0,b=i==="paths"?ln(g.assembly,n):void 0,k=pn(i,m,b,g),_=await Ke(o,p.fingerprint),C=_.results[k],v=p.memoize(k,()=>C!==void 0?structuredClone(C):hn(i,m,b,g,l)),V=Je(d.length,_.exists);!v.reused&&C===void 0&&V&&await Br(o,p.fingerprint,_,k,v.value);let $=v.value.subcommand==="audit"?await Gr(o,p.fingerprint,v.value,g.saveBaseline):v.value;return $.cache={fingerprint:p.fingerprint.slice(0,12),assembly:p.assemblyReused?"hit":"miss",result:v.reused?"hit":"miss",durable:C!==void 0?"hit":V?"miss":"off"},dn($,g.summary,"result_rows")}export{Oe as a,pt as b,ue as c,bt as d,_t as e,Zr as f,xt as g,Et as h,It as i,Tt as j,St as k,ge as l,Rt as m,we as n,Dt as o,Fe as p,be as q,Ge as r,_e as s,Mt as t,ci as u,ve as v,Be as w,ke as x,pi as y,Bt as z,Hi as A,Vt as B,Kt as C,Wt as D,Xt as E,Ue as F,U as G,Qt as H,Ke as I,We as J,He as K,Zt as L,Je as M,en as N,tn as O,sn as P,Ir as Q,_o as R};
|
|
8
|
-
//# sourceMappingURL=chunk-CHIBMEZR.js.map
|