@unbrained/pm-cli 2026.10.17 → 2026.10.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/CHANGELOG.md +35 -0
- package/dist/cli/help-content.js +2 -2
- package/dist/cli/register-list-query.js +2 -2
- package/dist/cli/register-mutation.js +2 -2
- package/dist/cli/register-setup.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/chunk-4CXQSRSP.js +126 -0
- package/dist/cli-bundle/chunks/{chunk-EA2CG7UM.js → chunk-4ICKT4GH.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-W3KZ22DW.js → chunk-4MJ6WBMA.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-4XFVAXA4.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-6ZDKKOKM.js → chunk-5GZSX5HU.js} +72 -66
- package/dist/cli-bundle/chunks/{chunk-3QKI3XNX.js → chunk-6DS5CAN2.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-B5QVGCZX.js → chunk-D3EDNAN7.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-DMFM5R4G.js +3 -0
- package/dist/cli-bundle/chunks/chunk-H3XYP24A.js +70 -0
- package/dist/cli-bundle/chunks/chunk-LBEMB3BW.js +6 -0
- package/dist/cli-bundle/chunks/chunk-NX7Q4LGN.js +8 -0
- package/dist/cli-bundle/chunks/chunk-O2ZRRLAP.js +8 -0
- package/dist/cli-bundle/chunks/chunk-OEJ3G7XT.js +20 -0
- package/dist/cli-bundle/chunks/{chunk-O4YBC3OM.js → chunk-QBNEZII5.js} +30 -30
- package/dist/cli-bundle/chunks/chunk-QG4LMU7A.js +112 -0
- package/dist/cli-bundle/chunks/chunk-QKAAZWGC.js +3 -0
- package/dist/cli-bundle/chunks/chunk-RUKSEZE7.js +2 -0
- package/dist/cli-bundle/chunks/chunk-TK3G3GAP.js +2 -0
- package/dist/cli-bundle/chunks/chunk-VS565KBX.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-JS3B2M4D.js → chunk-XH7C3A5N.js} +2 -2
- package/dist/cli-bundle/chunks/indexed-receipt-blobs-BVSHK4WQ.js +4 -0
- package/dist/cli-bundle/chunks/{register-list-query-RU3QZSAQ.js → register-list-query-WQUVDJIH.js} +7 -7
- package/dist/cli-bundle/chunks/register-mutation-IWIBQIO3.js +20 -0
- package/dist/cli-bundle/chunks/register-operations-SUWOZNDU.js +2 -0
- package/dist/cli-bundle/chunks/register-setup-QGM5YJW7.js +2 -0
- package/dist/cli-bundle/chunks/settlement-hook-UNFMCKKQ.js +7 -0
- package/dist/cli-bundle/chunks/stage-7DELI4Z5.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-LDKX4KYJ.js → chunk-2IEWB6MB.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-3TEIACFU.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-5YTOYBTZ.js +65 -0
- package/dist/cli-bundle/focused-chunks/chunk-AK2CI2GI.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-BJMPRB7A.js +91 -0
- package/dist/cli-bundle/focused-chunks/chunk-ENZMATOY.js +20 -0
- package/dist/cli-bundle/focused-chunks/chunk-EOQ6W25I.js +8 -0
- package/dist/cli-bundle/focused-chunks/{chunk-FTUZ3JF2.js → chunk-FEN7WOOP.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-FOA7XKWP.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-GWTV45SB.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-SIGIGZCG.js → chunk-H6BVQ63U.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-RBLSY6ML.js → chunk-HYMYAGSY.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-JBJJW2WL.js +6 -0
- package/dist/cli-bundle/focused-chunks/chunk-JCLC6HKT.js +8 -0
- package/dist/cli-bundle/focused-chunks/{chunk-2IOHHNRT.js → chunk-JDBO7SMR.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-UNTQE37U.js → chunk-KLJN44VY.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-L4PL3GZR.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-OV2WVLUR.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-PXDR77TO.js +78 -0
- package/dist/cli-bundle/focused-chunks/chunk-RLRMNFLF.js +3 -0
- package/dist/cli-bundle/focused-chunks/{chunk-E33QA7PK.js → chunk-SKYLOPU2.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-VVRXF4JO.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-WZTEFFQI.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-Y54ONBEX.js +25 -0
- package/dist/cli-bundle/focused-chunks/indexed-receipt-blobs-QW2VWWJE.js +4 -0
- package/dist/cli-bundle/focused-chunks/settlement-hook-X4FNHTOD.js +7 -0
- package/dist/cli-bundle/focused-chunks/stage-MZSVQYO4.js +2 -0
- package/dist/cli-bundle/main.js +3 -3
- 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 +29 -23
- 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 +66 -52
- 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/history/event-index.d.ts +8 -1
- package/dist/core/history/event-index.js +19 -18
- package/dist/core/item/item-format.js +1 -1
- package/dist/core/lock/lock.d.ts +8 -1
- package/dist/core/lock/lock.js +3 -3
- package/dist/core/output/output.js +2 -2
- package/dist/core/store/paths.js +1 -1
- package/dist/core/telemetry/policy.d.ts +2 -0
- package/dist/core/telemetry/policy.js +1 -1
- package/dist/core/telemetry/runtime.d.ts +5 -3
- package/dist/core/telemetry/runtime.js +3 -3
- package/dist/sdk/cli-contracts/bootstrap-command-scanner.js +1 -1
- package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
- package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
- package/dist/sdk/cli-contracts/runtime-contracts.d.ts +1 -0
- package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
- package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
- package/dist/sdk/cli-contracts/tool-schema.js +1 -1
- package/dist/sdk/extension/install-sources.js +3 -3
- package/dist/sdk/extension/shared.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
- package/dist/sdk/governance/health/projection.d.ts +37 -0
- package/dist/sdk/governance/health/projection.js +2 -0
- package/dist/sdk/governance/health.d.ts +7 -18
- package/dist/sdk/governance/health.js +2 -2
- package/dist/sdk/history-repair.js +1 -1
- package/dist/sdk/merge/driver.js +7 -1
- package/dist/sdk/merge/indexed-receipt-blobs.d.ts +2 -0
- package/dist/sdk/merge/indexed-receipt-blobs.js +4 -0
- package/dist/sdk/merge/install.d.ts +8 -0
- package/dist/sdk/merge/install.js +3 -3
- package/dist/sdk/merge/receipts.d.ts +6 -0
- package/dist/sdk/merge/receipts.js +2 -2
- package/dist/sdk/merge/reconcile.d.ts +6 -0
- package/dist/sdk/merge/reconcile.js +1 -1
- package/dist/sdk/merge/settlement-hook.d.ts +12 -0
- package/dist/sdk/merge/settlement-hook.js +7 -0
- package/dist/sdk/merge/stage.d.ts +13 -0
- package/dist/sdk/merge/stage.js +2 -0
- package/dist/sdk/mutation-events.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/list.d.ts +2 -0
- package/dist/sdk/query/list.js +1 -1
- package/dist/sdk/runtime-extended-actions.js +1 -1
- package/dist/types.d.ts +2 -2
- package/dist/types.js +1 -1
- package/docs/COMMANDS.md +39 -0
- package/docs/CONFIGURATION.md +36 -1
- package/docs/DEVELOPMENT_DEPENDENCY_SECURITY.md +22 -3
- package/docs/MERGE_SAFETY.md +88 -5
- package/docs/OUTPUT_PROJECTION_CONTRACTS.md +10 -0
- package/docs/RELEASING.md +8 -1
- package/docs/SDK.md +26 -0
- package/docs/SDK_CONTEXT_COORDINATION.md +71 -7
- package/docs/SDK_STORAGE_LIFECYCLE.md +24 -2
- package/docs/TESTING.md +15 -0
- package/docs/examples/ci/github-actions-pm-extension-gate.yml +1 -1
- package/docs/examples/ci/gitlab-ci-pm-extension-gate.yml +1 -1
- package/docs/examples/ci/jenkins-pm-extension-gate.Jenkinsfile +1 -1
- package/docs/generated/FLAG_LEXICON_BUDGETS.md +2 -2
- package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +6 -3
- package/marketplace.json +1 -1
- package/node_modules/@opentelemetry/core/package.json +2 -1
- package/node_modules/@opentelemetry/instrumentation/package.json +2 -1
- package/node_modules/@opentelemetry/resources/package.json +2 -1
- package/node_modules/@opentelemetry/sdk-trace/package.json +2 -1
- package/node_modules/@opentelemetry/sdk-trace-base/package.json +2 -1
- package/node_modules/@sentry/core/build/cjs/client.js +5 -4
- package/node_modules/@sentry/core/build/cjs/tracing/ai/gen-ai-attributes.js +0 -4
- package/node_modules/@sentry/core/build/cjs/tracing/ai/utils.js +33 -23
- package/node_modules/@sentry/core/build/cjs/tracing/anthropic-ai/index.js +7 -6
- package/node_modules/@sentry/core/build/cjs/tracing/anthropic-ai/streaming.js +3 -1
- package/node_modules/@sentry/core/build/cjs/tracing/google-genai/index.js +13 -14
- package/node_modules/@sentry/core/build/cjs/tracing/google-genai/streaming.js +6 -1
- package/node_modules/@sentry/core/build/cjs/tracing/langchain/utils.js +71 -21
- package/node_modules/@sentry/core/build/cjs/tracing/langgraph/utils.js +23 -33
- package/node_modules/@sentry/core/build/cjs/tracing/openai/streaming.js +6 -0
- package/node_modules/@sentry/core/build/cjs/tracing/openai/utils.js +11 -0
- package/node_modules/@sentry/core/build/cjs/tracing/workers-ai/utils.js +1 -1
- package/node_modules/@sentry/core/build/cjs/utils/eventUtils.js +4 -0
- package/node_modules/@sentry/core/build/cjs/utils/prepareEvent.js +2 -2
- package/node_modules/@sentry/core/build/cjs/utils/version.js +1 -1
- package/node_modules/@sentry/core/build/esm/client.js +6 -5
- package/node_modules/@sentry/core/build/esm/package.json +1 -1
- package/node_modules/@sentry/core/build/esm/tracing/ai/gen-ai-attributes.js +1 -3
- package/node_modules/@sentry/core/build/esm/tracing/ai/utils.js +34 -24
- package/node_modules/@sentry/core/build/esm/tracing/anthropic-ai/index.js +8 -7
- package/node_modules/@sentry/core/build/esm/tracing/anthropic-ai/streaming.js +3 -1
- package/node_modules/@sentry/core/build/esm/tracing/google-genai/index.js +15 -16
- package/node_modules/@sentry/core/build/esm/tracing/google-genai/streaming.js +6 -1
- package/node_modules/@sentry/core/build/esm/tracing/langchain/utils.js +73 -24
- package/node_modules/@sentry/core/build/esm/tracing/langgraph/utils.js +24 -34
- package/node_modules/@sentry/core/build/esm/tracing/openai/streaming.js +6 -0
- package/node_modules/@sentry/core/build/esm/tracing/openai/utils.js +11 -0
- package/node_modules/@sentry/core/build/esm/tracing/workers-ai/utils.js +2 -2
- package/node_modules/@sentry/core/build/esm/utils/eventUtils.js +4 -1
- package/node_modules/@sentry/core/build/esm/utils/prepareEvent.js +2 -2
- package/node_modules/@sentry/core/build/esm/utils/version.js +1 -1
- package/node_modules/@sentry/core/build/types/tracing/ai/utils.d.ts +3 -7
- package/node_modules/@sentry/core/build/types/tracing/anthropic-ai/types.d.ts +2 -2
- package/node_modules/@sentry/core/build/types/tracing/langchain/types.d.ts +15 -0
- package/node_modules/@sentry/core/build/types/tracing/langchain/utils.d.ts +1 -0
- package/node_modules/@sentry/core/build/types/tracing/langgraph/utils.d.ts +2 -0
- package/node_modules/@sentry/core/build/types/tracing/openai/types.d.ts +2 -0
- package/node_modules/@sentry/core/build/types/utils/eventUtils.d.ts +2 -1
- package/node_modules/@sentry/core/build/types-ts3.8/tracing/ai/utils.d.ts +3 -7
- package/node_modules/@sentry/core/build/types-ts3.8/tracing/anthropic-ai/types.d.ts +2 -2
- package/node_modules/@sentry/core/build/types-ts3.8/tracing/langchain/types.d.ts +15 -0
- package/node_modules/@sentry/core/build/types-ts3.8/tracing/langchain/utils.d.ts +1 -0
- package/node_modules/@sentry/core/build/types-ts3.8/tracing/langgraph/utils.d.ts +2 -0
- package/node_modules/@sentry/core/build/types-ts3.8/tracing/openai/types.d.ts +2 -0
- package/node_modules/@sentry/core/build/types-ts3.8/utils/eventUtils.d.ts +2 -1
- package/node_modules/@sentry/core/package.json +1 -1
- package/node_modules/@sentry/node/build/esm/package.json +1 -1
- package/node_modules/@sentry/node/package.json +5 -5
- package/node_modules/@sentry/node-core/build/cjs/integrations/anr/index.js +1 -1
- package/node_modules/@sentry/node-core/build/cjs/integrations/local-variables/local-variables-async.js +1 -1
- package/node_modules/@sentry/node-core/build/esm/integrations/anr/index.js +1 -1
- package/node_modules/@sentry/node-core/build/esm/integrations/anr/worker-script.js +2 -2
- package/node_modules/@sentry/node-core/build/esm/integrations/local-variables/local-variables-async.js +1 -1
- package/node_modules/@sentry/node-core/build/esm/integrations/local-variables/worker-script.js +1 -1
- package/node_modules/@sentry/node-core/build/esm/package.json +1 -1
- package/node_modules/@sentry/node-core/package.json +10 -4
- package/node_modules/@sentry/opentelemetry/build/esm/package.json +1 -1
- package/node_modules/@sentry/opentelemetry/package.json +5 -2
- package/node_modules/@sentry/server-utils/build/THIRD-PARTY-LICENSES.txt +55 -55
- package/node_modules/@sentry/server-utils/build/esm/package.json +1 -1
- package/node_modules/@sentry/server-utils/package.json +2 -2
- package/node_modules/@toon-format/toon/README.md +10 -41
- package/node_modules/@toon-format/toon/dist/index.d.mts +12 -36
- package/node_modules/@toon-format/toon/dist/index.mjs +134 -202
- package/node_modules/@toon-format/toon/package.json +2 -2
- package/node_modules/debug/package.json +3 -0
- package/node_modules/fdir/package.json +3 -0
- package/node_modules/has-flag/index.d.ts +39 -0
- package/node_modules/has-flag/index.js +8 -0
- package/node_modules/has-flag/license +9 -0
- package/node_modules/has-flag/package.json +46 -0
- package/node_modules/has-flag/readme.md +89 -0
- package/node_modules/supports-color/browser.js +5 -0
- package/node_modules/supports-color/index.js +135 -0
- package/node_modules/supports-color/license +9 -0
- package/node_modules/supports-color/package.json +53 -0
- package/node_modules/supports-color/readme.md +76 -0
- package/package.json +4 -4
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-claude/package.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/pm-codex/package.json +1 -1
- package/plugins/pm-codex/plugin.json +1 -1
- package/runtime-dependencies.json +1 -1
- package/dist/cli-bundle/chunks/chunk-4PNPDT2N.js +0 -236
- package/dist/cli-bundle/chunks/chunk-HY7FQ7QX.js +0 -2
- package/dist/cli-bundle/chunks/chunk-J4LPQCET.js +0 -8
- package/dist/cli-bundle/chunks/chunk-OZCSXX4D.js +0 -80
- package/dist/cli-bundle/chunks/chunk-VMCSTFSO.js +0 -2
- package/dist/cli-bundle/chunks/chunk-X2ONXFBP.js +0 -3
- package/dist/cli-bundle/chunks/chunk-X53HM753.js +0 -20
- package/dist/cli-bundle/chunks/register-mutation-EQYMT32A.js +0 -20
- package/dist/cli-bundle/chunks/register-operations-VXBGE4XI.js +0 -2
- package/dist/cli-bundle/chunks/register-setup-UUDEGFRO.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-5JEFDEL3.js +0 -166
- package/dist/cli-bundle/focused-chunks/chunk-AH6NX6GM.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-JXR6UKFM.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-MBQF6HT6.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-NZO7GOXD.js +0 -20
- package/dist/cli-bundle/focused-chunks/chunk-PYC7BF6Z.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-QOSVJDOO.js +0 -75
- package/dist/cli-bundle/focused-chunks/chunk-RHTH5ILM.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-TRFVAWF2.js +0 -26
|
@@ -1,30 +1,30 @@
|
|
|
1
|
-
import{$a as go,A as un,B as mn,Ca as _o,Ma as Z_,Na as po,Oa as fo,P as Q_,Sa as ep,Xa as tp,f as Tu,l as J_,p as Jn,q as X_,x as Tt,z as ln}from"./chunk-OZCSXX4D.js";import{$ as H_,$a as op,B as G_,C as Hn,Eb as lp,F as q_,Ia as sp,Ib as up,Ja as ap,Jb as mp,L as Vn,M as Yn,N as Cr,O as ae,Q as xr,T as Rr,U as K_,W as mo,X as z_,Z as W_,_ as B_,_c as _p,aa as V_,ab as cp,bb as Xn,bd as pp,c as Su,cb as ho,fb as dp,l as U_,na as Y_,sb as Qn,vb as _n,xb as pn,y as j_}from"./chunk-X53HM753.js";import{$ as Oe,$c as Ji,$f as $,$i as Et,$j as Ou,$k as Tm,$m as u_,$o as uo,Aa as Bi,Ac as Pl,Ad as Gl,Ae as qa,Aj as dt,Ak as nm,Al as Ym,An as io,Ao as R_,Ba as cl,Bd as $e,Bg as nu,Bj as Eu,Bk as im,Bl as Jm,Bm as gr,Bo as O_,Bp as ip,Ca as dl,Cd as ql,Cg as iu,Cj as zn,Ck as rm,Cl as Xm,Cm as d_,Cn as y_,Co as Ar,Da as ll,Dd as Kl,Dg as Zi,Dk as sm,Dm as hr,Do as L_,Dp as rp,Ea as ul,Ec as Fl,Ed as zl,Eg as jn,Ej as cr,Ek as am,El as Qm,Em as yr,En as v_,Fa as ml,Fi as pu,Fj as se,Fk as om,Fm as vr,Fn as $t,G as Zd,Ga as _l,Gg as er,Gi as I,Gk as cm,H as el,Ha as pl,Hb as Il,Hi as fu,Hk as dm,Hm as wr,Ia as Fa,Ib as Cl,If as Zl,Ik as lm,Il as Zm,Jb as xl,Jg as tr,Jk as um,Jl as e_,K as tl,Kb as Rl,Kg as me,Kj as Ha,Kk as Qa,Kl as t_,Km as l_,Lb as Ol,Lg as za,Li as gu,Lj as Au,Lk as mm,Ll as n_,M as nl,Mb as Ll,Mg as _e,Mk as _m,Nb as Xe,Ng as sn,Nk as pm,Nl as i_,Nm as Bn,O as il,Ob as Dl,Og as ru,Oj as Iu,Ok as fm,P as Ki,Pd as Wl,Pe as Vl,Pg as su,Pj as Va,Pk as gm,Q as Lt,Qa as $a,Qe as Yl,Qi as kt,Qj as Pt,Qk as hm,R as m,Ra as Fn,Rg as nr,Ri as hu,Rk as ym,Sa as Te,Se as Jl,Sg as au,Sj as Cu,Sk as vm,T as _,Tg as ou,Tk as wm,U as wt,Ub as Nl,Uk as bm,V as te,Va as F,Vb as Ml,Vk as km,W as zi,Wa as st,Wb as Ga,X as q,Xa as Hi,Xi as yu,Xj as Ya,Xl as dr,Xm as br,Xn as ro,Y as Q,Ya as nn,Yf as eu,Yh as lu,Yj as Ja,Yl as r_,Yn as so,Za as $n,Zc as Yi,Zh as uu,Zj as xu,Zk as Em,Zn as ao,_a as Dt,_j as Ru,_k as Sm,_m as kr,_n as oo,aa as rl,ai as mu,aj as ir,ak as Lu,al as Am,am as lr,an as m_,ao as w_,ba as Na,bb as x,bj as rr,bk as Du,bl as Im,bm as ur,bn as __,cb as Je,ce as fe,ck as Nu,cl as Cm,cm as mr,db as qe,dh as cu,dj as sr,dk as Mu,dl as xm,dm as s_,dp as D_,eb as Ae,eg as tu,ek as Pu,el as Rm,em as _r,eo as co,f as Ye,fa as sl,fb as fl,fk as Fu,fl as Om,fm as a_,fn as no,fp as N_,gb as gl,gh as Gn,gk as $u,gl as Lm,gm as Z,gn as p_,gp as M_,h as H,hb as at,hh as qn,hk as Uu,hl as Dm,hm as cn,ho as b_,hp as P_,i as qi,ib as Vi,id as $l,ik as ju,il as Nm,im as Wn,ip as F_,j as Ot,ja as ne,jb as hl,jk as Gu,jl as Mm,jm as we,jo as k_,jp as Ir,ka as al,kb as yl,kk as qu,kl as Pm,km as o_,ko as E_,kp as $_,lb as Ua,lk as Ku,ll as Fm,lo as Er,mb as ja,mk as zu,ml as $m,mm as Qe,mo as S_,mp as np,n as Yd,nb as vl,ni as Mt,nj as vu,nk as Wu,nl as Um,nm as c_,ob as wl,of as O,oi as Kn,oj as wu,ok as Bu,ol as jm,om as Ft,p as Jd,pb as bl,pf as Xl,pk as Hu,pl as Za,qa as ol,qb as kl,qd as P,qf as Ka,qk as Vu,ql as Gm,qm as pr,qn as f_,qo as T_,r as Da,rb as El,re as Bl,rf as Ql,rh as du,ri as an,rj as bu,rk as Yu,rl as qm,rm as dn,ro as Sr,sb as Sl,sf as Xi,sg as Qi,si as on,sj as ar,sl as eo,sm as ye,so as A_,t as Xd,tb as ie,ti as Ba,tj as ku,tk as Ju,tl as Km,tm as fr,to as Tr,ua as Ma,ub as Fe,uf as ge,uk as Xa,ul as zm,uo as I_,vb as Tl,vd as Ul,ve as Hl,vf as bt,vg as K,vh as Wa,vj as Y,vk as Xu,vl as Wm,vm as to,vn as g_,vo as lo,w as Qd,wb as Al,wd as jl,wg as Ke,wh as U,wj as he,wk as Qu,wl as Bm,xa as Pa,xg as rn,xi as _u,xk as Zu,xl as Hm,xn as h_,xo as C_,ya as Pe,yc as Un,yh as ct,yj as or,yk as em,yl as St,yo as x_,za as Wi,zd as ot,zg as Nt,zj as Se,zk as tm,zl as Vm}from"./chunk-4PNPDT2N.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c2e89d3c-9abc-5ca7-a290-69a54dd694ab")}catch{}})();var Wb=Object.freeze({"--body":"Set the item body.","--body-file":"Read the item body from a file, or from stdin when set to -.","--description":"Set the item description.","--stdin":"Read the value from stdin.","--stdin-json":"Read a complete JSON document from stdin."}),Bb=new Set(["--add","--body","--comment","--dep","--dep-remove","--description","--doc","--event","--field","--file","--learning","--note","--remove","--reminder","--test","--type-option"]),Hb=new Set(["append","comments","create","docs","files","learnings","notes","test","update","update-many"]),Vb=new Set(["close-many:--ids","comments:--file","create:--body-file","history-compact:--ids","learnings:--file","notes:--file","update:--body-file","update-many:--ids"]),Yb=new Set(["close-many:--ids","history-compact:--ids","update-many:--ids"]),Jb=["--allow-","--check-","--dry-run","--explain","--fail-","--fix-","--full","--has-","--include-","--json","--no-","--prune-","--quiet","--refresh-","--require-","--runtime-only","--schema-only","--skip-","--stream","--strict-","--summary","--today","--verbose"],Xb=new Set(["--activate","--active-only","--adopt","--adopt-all","--all","--all-actionable","--all-affected-ids","--all-day","--all-streams","--acknowledge-linked-tests","--append-stable","--auto-fix","--auto-pm-context","--availability-only","--background","--brief","--by-assignee","--by-priority","--by-tag","--catalog","--claim","--clear","--clear-comments","--clear-criteria","--clear-deps","--clear-docs","--clear-events","--clear-files","--clear-learnings","--clear-notes","--clear-reminders","--clear-tests","--clear-type-options","--cli-only","--closed","--compact","--completion","--count","--counts","--deactivate","--declarative","--defaults","--describe","--diff","--doctor","--empty-body","--explore","--field-utilization","--filter-empty-body","--flags-only","--follow","--force","--global","--highlight","--hybrid","--id-only","--if-available","--ignore-global","--include_unparented","--infer","--init","--install","--isolated","--lean","--list","--local","--manage","--markdown","--metadata-coverage","--next","--normalize-provenance","--only","--only-last","--output-row-contract","--override-linked-pm-context","--override-linked-workspace-context","--packages-only","--past","--phrase-exact","--profile","--progress","--project","--promote-to-item-dep","--provenance","--provenance-summary","--raw","--ready-only","--ready_only","--rebuild","--recent","--reload","--repair","--replace-deps","--replace-docs","--replace-files","--replace-tests","--required","--required-on-create","--run","--runtime-probe","--save-baseline","--scaffold","--semantic","--shared-host-safe","--storage","--title-exact","--token-accounting","--trace","--tree","--unbounded","--uninstall","--validate-paths","--verify","--watch","--with-packages"]),Qb=new Set(["--only-index"]),Zb=new Set(["activity:--stream","eval:--fail-under","validate:--fix-scope"]),ek=new Set(["activity:--stream","close:--validate-close","close-many:--validate-close","comments:--author","learnings:--author","notes:--author"]),tk=new Set(["--regression"]);function nk(e,t){return t==="--stdin"||t==="--stdin-json"?["stdin"]:Vb.has(`${e}:${t}`)?["argv","file","stdin"]:t.endsWith("-file")?["argv","file"]:Bb.has(t)&&Hb.has(e)?["argv","stdin"]:["argv"]}function ik(e,t){let n=Zb.has(`${e}:${t.flag}`)||t.value_name!==void 0||t.value_type==="string"||t.value_type==="number"||t.list===!0||t.repeatable===!0,i=t.value_type==="boolean"||t.flag==="--stdin"||t.flag==="--stdin-json"||t.flag.startsWith("--filter-")&&(t.flag.endsWith("-missing")||t.flag.startsWith("--filter-has-")||t.flag.startsWith("--filter-no-"))||Jb.some(r=>t.flag.startsWith(r));return n||Qb.has(t.flag)||!Xb.has(t.flag)&&!i}function rk(e,t){return t.value_arity!==void 0?t.value_arity:ik(e,t)?tk.has(t.flag)||ek.has(`${e}:${t.flag}`)?"optional":"required":"none"}function sk(e,t){let n=qi(e),i=rk(n,t),r=i!=="none",s=nk(n,t.flag),a=t.description??Wb[t.flag]??`${r?"Set":"Enable"} ${t.flag.slice(2).replaceAll("-"," ")}.`;return{...t,description:a,takes_value:r,value_required:i==="required",...r?{value_name:t.value_name??"value"}:{},value_type:r?t.value_type??"string":"boolean",required:t.required===!0,repeatable:t.repeatable===!0||t.list===!0,input_sources:s,...s.includes("stdin")&&t.flag!=="--stdin"&&t.flag!=="--stdin-json"?{stdin_token:"-"}:{},...Yb.has(`${n}:${t.flag}`)?{file_token_prefix:"@"}:{}}}function fp(e,t){return t.map(n=>sk(e,n))}function ZP(e,t,n){let i=e.trim().toLowerCase(),r=[],s=new Map,a=0;for(let c of n)if(c.command.trim().toLowerCase()===i){if(a+=1,s.has(c.flag)){r.push({code:"duplicate_observation",command:i,flag:c.flag,detail:`${i} ${c.flag} was observed more than once.`});continue}s.set(c.flag,c)}let o=new Set(t.map(({flag:c})=>c));for(let c of t){let d=s.get(c.flag);if(!d){r.push({code:"missing_observation",command:i,flag:c.flag,detail:`${i} ${c.flag} has no executable option observation.`});continue}for(let[l,u]of[["takes_value","takes_value_mismatch"],["value_required","value_required_mismatch"],["repeatable","repeatable_mismatch"]])c[l]!==d[l]&&r.push({code:u,command:i,flag:c.flag,detail:`${i} ${c.flag} declares ${l}=${String(c[l])} but the executable option reports ${String(d[l])}.`})}for(let c of s.values())o.has(c.flag)||r.push({code:"undeclared_observation",command:i,flag:c.flag,detail:`${i} ${c.flag} is executable but absent from invocation contracts.`});return r.sort((c,d)=>c.flag.localeCompare(d.flag)||c.code.localeCompare(d.code)),{ok:r.length===0,declared_count:t.length,observed_count:a,findings: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]="0c0bb7ab-6157-5861-ad7e-a63ae62220f4")}catch{}})();var ak=new Set(["claim","close","context","create","get","help","init","list","next","plan","release","search","update","validate","workspace"]),ok=new Set(["append","comments","config","contracts","deps","docs","events","files","focus","graph","health","history","learnings","list-all","list-blocked","list-closed","list-in-progress","list-open","notes","profile","schema","test"]),ck=Object.freeze({workspace:new Set(["config","gc","health","init","merge","profile","schema","telemetry","workspace"]),intake:new Set(["copy","create","focus","item","restore"]),context:new Set(["activity","aggregate","context","ctx","duplicates","eval","get","help","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","next","search","stats"]),lifecycle:new Set(["claim","close","close-many","close-task","delete","pause-task","item-reopen","release","start-task","update","update-many"]),evidence:new Set(["append","comments","docs","events","files","history","history-attest","history-author-acknowledge","history-compact","history-redact","history-repair","learnings","notes"]),graph:new Set(["deps","graph","plan"]),quality:new Set(["assurance","contracts","test","test-all","validate"]),automation:new Set(["event","meet","remind"])}),dk=new Set(["extension","install","package","packages","upgrade"]);function lk(e){let t=H(e.trim().toLowerCase());if(t==="ops")return"quality";for(let[n,i]of Object.entries(ck))if(i.has(t))return n;return dk.has(t)?"extensions":"internal"}var fn=Object.freeze([...Xe.flatMap(e=>e==="item"?["item","item-reopen"]:[e,...Ye.filter(t=>t.alias===e).map(t=>t.canonical)]).map(e=>({command:e,tier:ak.has(H(e))?"core":ok.has(H(e))?"standard":"full",family:lk(e)})),{command:"ops",tier:"core",family:"quality"},{command:"completion-statuses",tier:"internal",family:"internal"},{command:"completion-tags",tier:"internal",family:"internal"},{command:"completion-types",tier:"internal",family:"internal"},{command:"test-runs-worker",tier:"internal",family:"internal"},{command:"item test worker",tier:"internal",family:"internal"}]),uk=fn,gp=Object.freeze({max_lines:50,max_utf8_bytes:6e3}),iF=Object.freeze(["-V, --version","--all","--json","--output-include <fields>","--output-limit <count>","--output-budget <tokens|unbounded>","--output-cursor <cursor>","--pm-path <dir>","--no-extensions","--no-pager","--explain","-h, --help"]);function rF(e){let t=e===""?0:e.split(/\r?\n/).length,n=Buffer.byteLength(e,"utf8");return{lines:t,utf8_bytes:n,within_budget:t<=gp.max_lines&&n<=gp.max_utf8_bytes}}var hp={core:0,standard:1,full:2,internal:3},yp=new Map(uk.map(({command:e,tier:t})=>[e,t]));function yo(e,t="standard"){return yp.get(e.trim().toLowerCase())??yp.get(H(e.trim().toLowerCase()))??t}function sF(e){return vp(e,fn)}function vp(e,t){let n=hp[e];return t.filter(i=>i.tier!=="internal"&&hp[i.tier]<=n).map(i=>i.command)}function aF(e){return wp(e,fn)}function wp(e,t){return t.filter(n=>n.family===e).map(n=>n.command)}var mk=["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"],_k=new Set([...Ot.filter(e=>e.hidden).map(e=>e.alias),"ctx","extension","install","item-reopen","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","packages","upgrade"]);function oF(e=fn){return mk.map(t=>({family:t,commands:wp(t,e).filter(n=>e.find(i=>i.command===n)?.tier!=="internal"&&!_k.has(n))})).filter(({commands:t})=>t.length>0)}var pk=Object.freeze({pm_append:"append",pm_claim:"claim",pm_close:"close",pm_comments:"comments",pm_config:"config",pm_context:"context",pm_contracts:"contracts",pm_copy:"copy",pm_create:"create",pm_deps:"deps",pm_discover:"help",pm_docs:"docs",pm_events:"history",pm_files:"files",pm_focus:"focus",pm_get:"get",pm_graph:"graph",pm_health:"health",pm_learnings:"learnings",pm_list:"list",pm_mutate:"update",pm_next:"next",pm_notes:"notes",pm_plan:"plan",pm_profile:"profile",pm_release:"release",pm_run:"package",pm_schema:"schema",pm_search:"search",pm_test:"test",pm_update:"update",pm_validate:"validate"});function cF(e,t){return fk(e,t,fn)}function fk(e,t,n){if(t==="full")return[...e];let i=new Set(vp(t,n));return e.filter(r=>{let s=pk[r];return s!==void 0&&i.has(s)})}var dF=Object.freeze([{uri:"pm://workspace/context",name:"Workspace context",description:"Bounded project context for orientation, including active hierarchy and progress.",mimeType:"application/json"},{uri:"pm://workspace/focus",name:"Active focus",description:"The session focus that supplies the default create parent.",mimeType:"application/json"},{uri:"pm://workspace/claims",name:"Active claims",description:"Bounded in-progress work and active ownership context.",mimeType:"application/json"},{uri:"pm://workspace/agent-guide",name:"Agent guidance",description:"Repository-local AGENTS.md instructions, bounded for safe host attachment.",mimeType:"text/markdown"}]),lF=Object.freeze([{name:"orient",description:"Build bounded live context, search all statuses, and select canonical work without creating duplicates.",arguments:[{name:"request",description:"The user's requested outcome or topic.",required:!0},{name:"scope",description:"Optional bounded workspace or subsystem scope.",required:!1}],template:"Orient to the live pm workspace for: {{request}}. Scope hint: {{scope}}. Read context, search all statuses, inspect full metadata for relevant items, and select canonical lineage before any mutation."},{name:"claim-and-start",description:"Claim one canonical item and begin implementation with linked context.",arguments:[{name:"id",description:"Canonical pm item id.",required:!0}],template:"Read {{id}} in full, claim it, set it in_progress, then implement only its acceptance scope while linking files, docs, tests, and evidence."},{name:"record-evidence-and-close",description:"Record exact verification evidence, close the item, and release ownership.",arguments:[{name:"id",description:"Canonical pm item id.",required:!0},{name:"evidence",description:"Exact verification and outcome evidence.",required:!0}],template:"For {{id}}, record this evidence: {{evidence}}. Verify linked tests, close only if acceptance is met, then release the claim."}]);function uF(){return gk(fn)}function gk(e){return["# Generated agent command surface","","This file is generated from `PM_COMMAND_CAPABILITY_CONTRACTS`. Do not edit it manually.","","| Command | Minimum visibility tier | Capability family |","| --- | --- | --- |",...e.map(({command:t,tier:n,family:i})=>`| \`${t}\` | ${n} | ${i} |`),""].join(`
|
|
2
|
-
`)}(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]="7df4fe91-e8a4-540f-8737-c67f2efa460e")}catch{}})();var hk=[{exit_code:1,class:"generic_failure"},{exit_code:2,class:"usage"},{exit_code:3,class:"not_found"},{exit_code:4,class:"conflict"},{exit_code:5,class:"dependency_failed"}],yk=new Map(hk.map(e=>[e.exit_code,e.class]));function Or(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))].sort()}function vk(e){if(!e)return[];let t=new Set,n=new Set;return e.map(i=>{let r=i.state.trim(),s=i.probe_id.trim(),a=Or(i.entrypoints);if(!/^[a-z][a-z0-9_]*$/.test(r)||!/^[a-z][a-z0-9-]*$/.test(s)||a.length===0||t.has(r)||n.has(s))throw new TypeError("Invalid pm refusal state contract");return t.add(r),n.add(s),{state:r,probe_id:s,entrypoints:a,expected_exit_class:i.expected_exit_class}}).sort((i,r)=>i.state.localeCompare(r.state))}function wk(e,t,n,i,r){return![[1,2,3,4,5].includes(e.exit_code),e.meaning.trim().length>0,e.recovery.trim().length>0,t.length>0,n.length>0,/^[a-z][a-z0-9_]*$/.test(i),r.every(s=>/^[a-z][a-z0-9_]*$/.test(s)),yk.get(e.exit_code)===e.class].includes(!1)}function bk(e,t){let n=e,i=new Set;for(;n.canonical_code!==n.code;){if(i.has(n.code))throw new TypeError(`Alias cycle in pm error code catalog: ${e.code}`);i.add(n.code);let r=t.get(n.canonical_code);if(!r)throw new TypeError(`Invalid pm error code contract: ${e.code}`);n=r}return n}function kk(e){let t=new Map(e.map(n=>[n.code,n]));for(let n of e){let i=bk(n,t);if(i.exit_code!==n.exit_code||i.class!==n.class)throw new TypeError(`Alias transport mismatch for pm error code: ${n.code}`);let r=e.filter(s=>s.code!==i.code&&s.canonical_code===i.code).map(s=>s.code).sort();if(n.code===i.code?JSON.stringify(n.aliases)!==JSON.stringify(r):n.aliases.length>0)throw new TypeError(`Invalid pm error code contract: ${n.code}`)}}function kp(e){let t=new Set,n=e.map(i=>{let r=i.code.trim();if(!/^[a-z][a-z0-9_]*$/.test(r))throw new TypeError(`Invalid pm error code: ${JSON.stringify(i.code)}`);if(t.has(r))throw new TypeError(`Duplicate pm error code: ${r}`);t.add(r);let s=Or(i.sources),a=Or(i.emitting_commands),o=(i.canonical_code??r).trim(),c=Or(i.aliases??[]),d=vk(i.owned_states);if(!wk(i,s,a,o,c))throw new TypeError(`Invalid pm error code contract: ${r}`);if(d.some(l=>l.expected_exit_class!==i.class))throw new TypeError(`Invalid pm refusal state exit class: ${r}`);return Object.freeze({...i,code:r,meaning:i.meaning.trim(),recovery:i.recovery.trim(),sources:s,emitting_commands:a,canonical_code:o,aliases:c,owned_states:d})});return kk(n),Object.freeze(n.sort((i,r)=>i.code.localeCompare(r.code)))}function _F(e,t){let n=bp(e,t);return bp(n.canonical_code??n.code,t)}function bp(e,t){let n=e.trim(),i=t.find(r=>r.code===n);if(!i)throw new TypeError(`Unknown pm error code "${n}"`);return i}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="78d85522-edca-5e60-957c-e837c3a1f69b")}catch{}})();var Ep=[{code:"acceptance_criteria_mutation_conflict",meaning:"Acceptance criteria mutation conflict condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/update.ts"],emitting_commands:["update","update-many"],canonical_code:"acceptance_criteria_mutation_conflict",aliases:[]},{code:"acceptance_criteria_remove_unmatched",meaning:"Acceptance criteria remove unmatched condition.",stability:"provisional",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/update-many.ts","sdk/lifecycle/update.ts"],emitting_commands:["update","update-many"],canonical_code:"acceptance_criteria_remove_unmatched",aliases:[]},{code:"acceptance_criteria_semicolon_forbidden",meaning:"Acceptance criteria semicolon forbidden condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/item/parse.ts"],emitting_commands:["*"],canonical_code:"acceptance_criteria_semicolon_forbidden",aliases:[]},{code:"accepted_rejected_value",meaning:"Accepted rejected value condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts"],emitting_commands:["*"],canonical_code:"accepted_rejected_value",aliases:[]},{code:"alias_collision",meaning:"Alias collision condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"],emitting_commands:["*"],canonical_code:"alias_collision",aliases:[]},{code:"alias_target_missing",meaning:"Alias target missing condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"alias_target_missing",aliases:[]},{code:"already_claimed_by",meaning:"Already claimed by condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/claim.ts"],emitting_commands:["claim"],canonical_code:"already_claimed_by",aliases:[]},{code:"ambiguous_option_combination",meaning:"Ambiguous option combination condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"],canonical_code:"ambiguous_option_combination",aliases:[]},{code:"annotation_alias_conflict",meaning:"Annotation alias conflict condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-annotations.ts"],emitting_commands:["*"],canonical_code:"annotation_alias_conflict",aliases:[]},{code:"annotation_flag_like_value",meaning:"Annotation flag like value condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/annotations.ts"],emitting_commands:["*"],canonical_code:"annotation_flag_like_value",aliases:[]},{code:"annotation_if_absent_without_append",meaning:"Annotation if absent without append condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/annotations.ts"],emitting_commands:["*"],canonical_code:"annotation_if_absent_without_append",aliases:[]},{code:"annotation_message_without_text",meaning:"Annotation message without text condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/annotations.ts"],emitting_commands:["*"],canonical_code:"annotation_message_without_text",aliases:[]},{code:"annotation_transposed_subcommand",meaning:"Annotation transposed subcommand condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-annotations.ts"],emitting_commands:["*"],canonical_code:"annotation_transposed_subcommand",aliases:[]},{code:"append_empty_body",meaning:"Append empty body condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/append.ts"],emitting_commands:["append"],canonical_code:"append_empty_body",aliases:[]},{code:"assurance_registry_invalid",meaning:"Assurance registry invalid condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/governance/assurance.ts"],emitting_commands:["*"],canonical_code:"assurance_registry_invalid",aliases:[]},{code:"bare_comma_entry_ambiguous",meaning:"Bare comma entry ambiguous condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/item/parse.ts"],emitting_commands:["*"],canonical_code:"bare_comma_entry_ambiguous",aliases:[]},{code:"blocker_identity_read_failed",meaning:"Blocker identity read failed condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/query/get.ts"],emitting_commands:["get"],canonical_code:"blocker_identity_read_failed",aliases:[]},{code:"body_file_conflicts_with_body",meaning:"Body file conflicts with body condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/io/body-file.ts"],emitting_commands:["*"],canonical_code:"body_file_conflicts_with_body",aliases:[]},{code:"body_file_missing_path",meaning:"Body file missing path condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/io/body-file.ts"],emitting_commands:["*"],canonical_code:"body_file_missing_path",aliases:[]},{code:"body_file_unreadable",meaning:"Body file unreadable condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/io/body-file.ts"],emitting_commands:["*"],canonical_code:"body_file_unreadable",aliases:[]},{code:"budget_exceeded",meaning:"Budget exceeded condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"],emitting_commands:["*"],canonical_code:"budget_exceeded",aliases:[]},{code:"bulk_create_route",meaning:"Bulk create route condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-mutation.ts"],emitting_commands:["*"],canonical_code:"bulk_create_route",aliases:[]},{code:"bulk_ids_input_empty",meaning:"Bulk ids input empty condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/io/bulk-ids-input.ts","sdk/history-compact.ts","sdk/history-mcp.ts"],emitting_commands:["*"],canonical_code:"bulk_ids_input_empty",aliases:[],owned_states:[{state:"bulk_ids_stdin_contains_no_nonempty_ids",probe_id:"bulk-ids-stdin-empty",entrypoints:["update-many"],expected_exit_class:"usage"}]},{code:"bulk_ids_input_missing_path",meaning:"Bulk ids input missing path condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/io/bulk-ids-input.ts"],emitting_commands:["*"],canonical_code:"bulk_ids_input_missing_path",aliases:[],owned_states:[{state:"bulk_ids_file_token_omits_its_path",probe_id:"bulk-ids-file-path-missing",entrypoints:["update-many"],expected_exit_class:"usage"}]},{code:"bulk_ids_input_unreadable",meaning:"Bulk ids input unreadable condition.",stability:"provisional",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/io/bulk-ids-input.ts"],emitting_commands:["*"],canonical_code:"bulk_ids_input_unreadable",aliases:[],owned_states:[{state:"bulk_ids_file_path_cannot_be_read",probe_id:"bulk-ids-file-unreadable",entrypoints:["update-many"],expected_exit_class:"not_found"}]},{code:"bundle_integrity_torn_install",meaning:"Bundle integrity torn install condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/bundle-integrity.ts"],emitting_commands:["*"],canonical_code:"bundle_integrity_torn_install",aliases:[]},{code:"capability_undeclared",meaning:"Capability undeclared condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"],canonical_code:"capability_undeclared",aliases:[]},{code:"capability_unused",meaning:"Capability unused condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"],canonical_code:"capability_unused",aliases:[]},{code:"child_projection_item_bound_exceeded",meaning:"Child projection item bound exceeded condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/item-children.ts"],emitting_commands:["*"],canonical_code:"child_projection_item_bound_exceeded",aliases:[]},{code:"close_reason_required",meaning:"Close reason required condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle-policy.ts","sdk/lifecycle/close-many.ts"],emitting_commands:["*","close-many"],canonical_code:"close_reason_required",aliases:[]},{code:"close_through_update",meaning:"Close through update condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/telemetry/observability.ts"],emitting_commands:["*"],canonical_code:"close_through_update",aliases:[]},{code:"close_validation_missing_fields",meaning:"Close validation missing fields condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"],canonical_code:"close_validation_missing_fields",aliases:[]},{code:"collected_zero_items",meaning:"Collected zero items condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution-receipts.ts"],emitting_commands:["*"],canonical_code:"collected_zero_items",aliases:[]},{code:"collection_transposed_subcommand",meaning:"Collection transposed subcommand condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"],canonical_code:"collection_transposed_subcommand",aliases:[]},{code:"command_failed",meaning:"Command failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"],canonical_code:"command_failed",aliases:[]},{code:"command_namespace",meaning:"Command namespace condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/runtime-contracts.ts"],emitting_commands:["*"],canonical_code:"command_namespace",aliases:[]},{code:"command_override_conflict",meaning:"Command override conflict condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"],canonical_code:"command_override_conflict",aliases:[]},{code:"config_duplicate",meaning:"Config duplicate condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"config_duplicate",aliases:[]},{code:"config_key_unknown",meaning:"Config key unknown condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"config_key_unknown",aliases:[]},{code:"config_value_invalid",meaning:"Config value invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"config_value_invalid",aliases:[]},{code:"conflicting_lifecycle_owner",meaning:"Conflicting lifecycle owner condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-operations.ts"],emitting_commands:["*"],canonical_code:"conflicting_lifecycle_owner",aliases:[]},{code:"context_evaluation_read_incomplete",meaning:"Context evaluation read incomplete condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/context-relevance.ts"],emitting_commands:["*"],canonical_code:"context_evaluation_read_incomplete",aliases:[]},{code:"context_signal_store_invalid",meaning:"Context signal store invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/context-signal-store.ts"],emitting_commands:["*"],canonical_code:"context_signal_store_invalid",aliases:[]},{code:"context_signal_store_stale",meaning:"Context signal store stale condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/context-signal-store.ts"],emitting_commands:["*"],canonical_code:"context_signal_store_stale",aliases:[]},{code:"context_signal_store_write_failed",meaning:"Context signal store write failed condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/context-signal-store.ts"],emitting_commands:["*"],canonical_code:"context_signal_store_write_failed",aliases:[]},{code:"context_takes_no_item_argument",meaning:"Context takes no item argument condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"],canonical_code:"context_takes_no_item_argument",aliases:[]},{code:"core_item_field_requires_dedicated_flag",meaning:"Core item field requires dedicated flag condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/item-fields.ts"],emitting_commands:["*"],canonical_code:"core_item_field_requires_dedicated_flag",aliases:[]},{code:"create_positional_type_without_title",meaning:"Create positional type without title condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-mutation.ts"],emitting_commands:["*"],canonical_code:"create_positional_type_without_title",aliases:[]},{code:"dependency_cardinality_created",meaning:"Dependency cardinality created condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/graph/cardinality-integrity.ts"],emitting_commands:["*"],canonical_code:"dependency_cardinality_created",aliases:[]},{code:"dependency_edge_not_allowed",meaning:"Dependency edge not allowed condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/dependency-flag-validation.ts"],emitting_commands:["*"],canonical_code:"dependency_edge_not_allowed",aliases:[]},{code:"dependency_flag_value_invalid",meaning:"Dependency flag value invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/dependency-flag-validation.ts"],emitting_commands:["*"],canonical_code:"dependency_flag_value_invalid",aliases:[]},{code:"dependency_remove_no_match",meaning:"Dependency remove no match condition.",stability:"provisional",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"],canonical_code:"dependency_remove_no_match",aliases:[]},{code:"dependency_target_not_found",meaning:"Dependency target not found condition.",stability:"provisional",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/dependency-flag-validation.ts"],emitting_commands:["*"],canonical_code:"dependency_target_not_found",aliases:[]},{code:"dependency_temporal_order_invalid",meaning:"Dependency temporal order invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/dependency-flag-validation.ts"],emitting_commands:["*"],canonical_code:"dependency_temporal_order_invalid",aliases:[]},{code:"duplicate_canonical_flag",meaning:"Duplicate canonical flag condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"],emitting_commands:["*"],canonical_code:"duplicate_canonical_flag",aliases:[]},{code:"duplicate_command",meaning:"Duplicate command condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"],canonical_code:"duplicate_command",aliases:[]},{code:"duplicate_destination",meaning:"Duplicate destination condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"duplicate_destination",aliases:[]},{code:"duplicate_edge",meaning:"Duplicate edge condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/graph/remediation.ts"],emitting_commands:["*"],canonical_code:"duplicate_edge",aliases:[]},{code:"duplicate_observation",meaning:"Duplicate observation condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/flag-invocation-contracts.ts"],emitting_commands:["*"],canonical_code:"duplicate_observation",aliases:[]},{code:"duplicate_probe",meaning:"Duplicate probe condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts"],emitting_commands:["*"],canonical_code:"duplicate_probe",aliases:[]},{code:"duplicate_sweep_cost_limit",meaning:"Duplicate sweep cost limit condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/query/duplicate-candidates.ts"],emitting_commands:["duplicate-candidates"],canonical_code:"duplicate_sweep_cost_limit",aliases:[]},{code:"duplicate_target_circular",meaning:"Duplicate target circular condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"],canonical_code:"duplicate_target_circular",aliases:[]},{code:"duplicate_target_is_duplicate",meaning:"Duplicate target is duplicate condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"],canonical_code:"duplicate_target_is_duplicate",aliases:[]},{code:"duplicate_target_missing",meaning:"Duplicate target missing condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"],canonical_code:"duplicate_target_missing",aliases:[]},{code:"duplicate_target_self",meaning:"Duplicate target self condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"],canonical_code:"duplicate_target_self",aliases:[]},{code:"empty_corpus",meaning:"Empty corpus condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts"],emitting_commands:["*"],canonical_code:"empty_corpus",aliases:[]},{code:"empty_surface",meaning:"Empty surface condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"],canonical_code:"empty_surface",aliases:[]},{code:"error_code_mismatch",meaning:"Error code mismatch condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts","sdk/agent/tracker-preflight-contracts.ts"],emitting_commands:["*"],canonical_code:"error_code_mismatch",aliases:[]},{code:"event_cursor_query_mismatch",meaning:"Event cursor query mismatch condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-events.ts"],emitting_commands:["*"],canonical_code:"event_cursor_query_mismatch",aliases:[]},{code:"event_index_unavailable",meaning:"Event index unavailable condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-events.ts"],emitting_commands:["*"],canonical_code:"event_index_unavailable",aliases:[]},{code:"exit_code_mismatch",meaning:"Exit code mismatch condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/tracker-preflight-contracts.ts"],emitting_commands:["*"],canonical_code:"exit_code_mismatch",aliases:[]},{code:"extension_command_activation_failed",meaning:"Extension command activation failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/commander-usage.ts"],emitting_commands:["*"],canonical_code:"extension_command_activation_failed",aliases:[]},{code:"extension_dependency_name_unsafe",meaning:"Extension dependency name unsafe condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"],canonical_code:"extension_dependency_name_unsafe",aliases:[]},{code:"extension_dependency_spec_invalid",meaning:"Extension dependency spec invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"],canonical_code:"extension_dependency_spec_invalid",aliases:[]},{code:"extension_dependency_version_unsafe",meaning:"Extension dependency version unsafe condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"],canonical_code:"extension_dependency_version_unsafe",aliases:[]},{code:"extension_flag_value_invalid",meaning:"Extension flag value invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/extension-command-options.ts"],emitting_commands:["*"],canonical_code:"extension_flag_value_invalid",aliases:[]},{code:"extension_install_incomplete_source_scan",meaning:"Extension install incomplete source scan condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-plan.ts"],emitting_commands:["*"],canonical_code:"extension_install_incomplete_source_scan",aliases:[]},{code:"extension_install_soft_failed",meaning:"Extension install soft failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-setup.ts"],emitting_commands:["*"],canonical_code:"extension_install_soft_failed",aliases:[]},{code:"extension_install_source_contains_destination",meaning:"Extension install source contains destination condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-runtime.ts"],emitting_commands:["*"],canonical_code:"extension_install_source_contains_destination",aliases:[]},{code:"extension_item_field_reserved",meaning:"Extension item field reserved condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/item-fields.ts"],emitting_commands:["*"],canonical_code:"extension_item_field_reserved",aliases:[]},{code:"extension_item_field_type_conflict",meaning:"Extension item field type conflict condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/item-fields.ts"],emitting_commands:["*"],canonical_code:"extension_item_field_type_conflict",aliases:[]},{code:"extension_item_field_unknown",meaning:"Extension item field unknown condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/item-fields.ts"],emitting_commands:["*"],canonical_code:"extension_item_field_unknown",aliases:[]},{code:"extension_mutation_guard_failed",meaning:"Extension mutation guard failed condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/extension-hook-runtime.ts"],emitting_commands:["*"],canonical_code:"extension_mutation_guard_failed",aliases:[]},{code:"extension_mutation_guard_invalid_decision",meaning:"Extension mutation guard invalid decision condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/extension-hook-runtime.ts"],emitting_commands:["*"],canonical_code:"extension_mutation_guard_invalid_decision",aliases:[]},{code:"extension_mutation_guard_invalid_denial",meaning:"Extension mutation guard invalid denial condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/extension-hook-runtime.ts"],emitting_commands:["*"],canonical_code:"extension_mutation_guard_invalid_denial",aliases:[]},{code:"extension_mutation_guard_timed_out",meaning:"Extension mutation guard timed out condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/extension-hook-runtime.ts"],emitting_commands:["*"],canonical_code:"extension_mutation_guard_timed_out",aliases:[]},{code:"extension_read_output_invalid",meaning:"Extension read output invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/read-output/extension.ts"],emitting_commands:["*"],canonical_code:"extension_read_output_invalid",aliases:[]},{code:"extension_update_health_partial_coverage",meaning:"Extension update health partial coverage condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"extension_update_health_partial_coverage",aliases:[]},{code:"extensions_unreadable",meaning:"Extensions unreadable condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/static-inventory.ts"],emitting_commands:["*"],canonical_code:"extensions_unreadable",aliases:[]},{code:"field_duplicate",meaning:"Field duplicate condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"field_duplicate",aliases:[]},{code:"field_invalid",meaning:"Field invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"field_invalid",aliases:[]},{code:"field_mcp_input_collision",meaning:"Field mcp input collision condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"field_mcp_input_collision",aliases:[]},{code:"github_source_entry_unbuilt",meaning:"Github source entry unbuilt condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/shared.ts"],emitting_commands:["*"],canonical_code:"github_source_entry_unbuilt",aliases:[]},{code:"hierarchy_cardinality_created",meaning:"Hierarchy cardinality created condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/graph/hierarchy-integrity.ts"],emitting_commands:["*"],canonical_code:"hierarchy_cardinality_created",aliases:[]},{code:"hierarchy_cycle_created",meaning:"Hierarchy cycle created condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/graph/hierarchy-integrity.ts"],emitting_commands:["*"],canonical_code:"hierarchy_cycle_created",aliases:[]},{code:"hierarchy_parent_divergence_created",meaning:"Hierarchy parent divergence created condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/graph/hierarchy-integrity.ts"],emitting_commands:["*"],canonical_code:"hierarchy_parent_divergence_created",aliases:[]},{code:"history_author_acknowledge_plan_conflict",meaning:"History author acknowledge plan conflict condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/author-attribution.ts"],emitting_commands:["*"],canonical_code:"history_author_acknowledge_plan_conflict",aliases:[]},{code:"history_author_acknowledge_plan_fingerprint_required",meaning:"History author acknowledge plan fingerprint required condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/author-attribution.ts"],emitting_commands:["*"],canonical_code:"history_author_acknowledge_plan_fingerprint_required",aliases:[]},{code:"history_author_acknowledge_preview_limit_invalid",meaning:"History author acknowledge preview limit invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/author-attribution.ts"],emitting_commands:["*"],canonical_code:"history_author_acknowledge_preview_limit_invalid",aliases:[]},{code:"history_author_acknowledge_required_values_missing",meaning:"History author acknowledge required values missing condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/author-attribution.ts"],emitting_commands:["*"],canonical_code:"history_author_acknowledge_required_values_missing",aliases:[]},{code:"history_author_acknowledge_selector_conflict",meaning:"History author acknowledge selector conflict condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/author-attribution.ts"],emitting_commands:["*"],canonical_code:"history_author_acknowledge_selector_conflict",aliases:[]},{code:"history_author_acknowledge_selector_required",meaning:"History author acknowledge selector required condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/author-attribution.ts"],emitting_commands:["*"],canonical_code:"history_author_acknowledge_selector_required",aliases:[]},{code:"history_author_acknowledge_target_not_actionable",meaning:"History author acknowledge target not actionable condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/author-attribution.ts"],emitting_commands:["*"],canonical_code:"history_author_acknowledge_target_not_actionable",aliases:[]},{code:"history_author_acknowledge_target_unreadable",meaning:"History author acknowledge target unreadable condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/author-attribution.ts"],emitting_commands:["*"],canonical_code:"history_author_acknowledge_target_unreadable",aliases:[]},{code:"history_baseline_unavailable",meaning:"History baseline unavailable condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/projection.ts"],emitting_commands:["*"],canonical_code:"history_baseline_unavailable",aliases:[]},{code:"history_drift_chain_mismatch",meaning:"History drift chain mismatch condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_chain_mismatch",aliases:["validate_history_drift_chain_mismatches"]},{code:"history_drift_hash_mismatch",meaning:"History drift hash mismatch condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_hash_mismatch",aliases:["validate_history_drift_hash_mismatches"]},{code:"history_drift_merge_receipt",meaning:"History drift merge receipt condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_merge_receipt",aliases:[]},{code:"history_drift_missing_stream",meaning:"History drift missing stream condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_missing_stream",aliases:["validate_history_drift_missing_streams"]},{code:"history_drift_unreadable_stream",meaning:"History drift unreadable stream condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_unreadable_stream",aliases:["validate_history_drift_unreadable_streams"]},{code:"history_drift_version_skew",meaning:"History drift version skew condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_version_skew",aliases:["validate_history_drift_version_skews"]},{code:"history_json_invalid",meaning:"History json invalid condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/read.ts"],emitting_commands:["*"],canonical_code:"history_json_invalid",aliases:[]},{code:"history_merge_conflict_markers_detected",meaning:"History merge conflict markers detected condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/read.ts"],emitting_commands:["*"],canonical_code:"merge_conflict_markers_detected",aliases:[]},{code:"history_replay_invalid",meaning:"History replay invalid condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/projection.ts","core/history/tombstone.ts"],emitting_commands:["*"],canonical_code:"history_replay_invalid",aliases:[]},{code:"history_salvage_refused",meaning:"History salvage refused condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/history/salvage.ts"],emitting_commands:["*"],canonical_code:"history_salvage_refused",aliases:[]},{code:"history_stream_over_compact_threshold",meaning:"History stream over compact threshold condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_stream_over_compact_threshold",aliases:[]},{code:"history_target_out_of_range",meaning:"History target out of range condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/projection.ts"],emitting_commands:["*"],canonical_code:"history_target_out_of_range",aliases:[]},{code:"history_timestamp_invalid",meaning:"History timestamp invalid condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/event-index.ts","core/history/history.ts"],emitting_commands:["*"],canonical_code:"history_timestamp_invalid",aliases:[]},{code:"history_unknown_author_events",meaning:"History unknown author events condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_unknown_author_events",aliases:["validate_history_unknown_author_events"]},{code:"history_version_mapping_unavailable",meaning:"History version mapping unavailable condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/version-address.ts"],emitting_commands:["*"],canonical_code:"history_version_mapping_unavailable",aliases:[]},{code:"history_version_pruned",meaning:"History version pruned condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/projection.ts"],emitting_commands:["*"],canonical_code:"history_version_pruned",aliases:[]},{code:"host_environment_capacity_fault",meaning:"Host environment capacity fault condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/fs/host-environment-errors.ts"],emitting_commands:["*"],canonical_code:"host_environment_capacity_fault",aliases:[]},{code:"host_environment_operation_invalid",meaning:"Host environment operation invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/fs/host-environment-errors.ts"],emitting_commands:["*"],canonical_code:"host_environment_operation_invalid",aliases:[]},{code:"host_environment_permission_fault",meaning:"Host environment permission fault condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/fs/host-environment-errors.ts"],emitting_commands:["*"],canonical_code:"host_environment_permission_fault",aliases:[]},{code:"host_environment_resource_fault",meaning:"Host environment resource fault condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/fs/host-environment-errors.ts"],emitting_commands:["*"],canonical_code:"host_environment_resource_fault",aliases:[]},{code:"improvement_metric_contract_conflict",meaning:"Improvement metric contract conflict condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/improvement-ledger.ts"],emitting_commands:["*"],canonical_code:"improvement_metric_contract_conflict",aliases:[]},{code:"improvement_observation_conflict",meaning:"Improvement observation conflict condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/improvement-ledger.ts"],emitting_commands:["*"],canonical_code:"improvement_observation_conflict",aliases:[]},{code:"incomplete_allowed_values",meaning:"Incomplete allowed values condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts"],emitting_commands:["*"],canonical_code:"incomplete_allowed_values",aliases:[]},{code:"inconsistent_concept_kind",meaning:"Inconsistent concept kind condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"],emitting_commands:["*"],canonical_code:"inconsistent_concept_kind",aliases:[]},{code:"init_existing_settings_requires_force",meaning:"Init existing settings requires force condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/init.ts"],emitting_commands:["*"],canonical_code:"init_existing_settings_requires_force",aliases:[]},{code:"init_gitignore_unwritable",meaning:"Init gitignore unwritable condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace.ts"],emitting_commands:["*"],canonical_code:"init_gitignore_unwritable",aliases:[]},{code:"init_id_prefix_conflict",meaning:"Init id prefix conflict condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/init.ts"],emitting_commands:["*"],canonical_code:"init_id_prefix_conflict",aliases:[]},{code:"init_id_prefix_path_like",meaning:"Init id prefix path like condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/init.ts"],emitting_commands:["*"],canonical_code:"init_id_prefix_path_like",aliases:[]},{code:"integrity_history_conflict_marker",meaning:"Integrity history conflict marker condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_history_conflict_marker",aliases:["validate_storage_history_conflict_markers"]},{code:"integrity_history_invalid_json",meaning:"Integrity history invalid json condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_history_invalid_json",aliases:[]},{code:"integrity_history_unreadable",meaning:"Integrity history unreadable condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_history_unreadable",aliases:[]},{code:"integrity_item_ahead_format_version",meaning:"Integrity item ahead format version condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_item_ahead_format_version",aliases:["validate_format_version_ahead_items"]},{code:"integrity_item_conflict_marker",meaning:"Integrity item conflict marker condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_item_conflict_marker",aliases:[]},{code:"integrity_item_outdated_format_version",meaning:"Integrity item outdated format version condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_item_outdated_format_version",aliases:["validate_format_version_outdated_items"]},{code:"integrity_item_parse_failed",meaning:"Integrity item parse failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_item_parse_failed",aliases:[]},{code:"integrity_item_unreadable",meaning:"Integrity item unreadable condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_item_unreadable",aliases:[]},{code:"invalid_argument_value",meaning:"Invalid argument value condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/context-intent-contracts.ts","sdk/governance/assurance-mutation-error.ts","sdk/lifecycle/create.ts","sdk/lifecycle/task-composition.ts","sdk/runtime/schema-preview.ts"],emitting_commands:["*","create","task-composition"],canonical_code:"invalid_argument_value",aliases:[]},{code:"invalid_command_usage",meaning:"Invalid command usage condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts"],emitting_commands:["*"],canonical_code:"invalid_command_usage",aliases:[]},{code:"invalid_event_cursor",meaning:"Invalid event cursor condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-events.ts"],emitting_commands:["*"],canonical_code:"invalid_event_cursor",aliases:[]},{code:"invalid_event_cursor_mode",meaning:"Invalid event cursor mode condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-list-query.ts","sdk/mutation-events.ts","sdk/runtime-extended-actions.ts"],emitting_commands:["*"],canonical_code:"invalid_event_cursor_mode",aliases:[]},{code:"invalid_event_follow_interval",meaning:"Invalid event follow interval condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-events.ts"],emitting_commands:["*"],canonical_code:"invalid_event_follow_interval",aliases:[]},{code:"invalid_event_limit",meaning:"Invalid event limit condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-events.ts"],emitting_commands:["*"],canonical_code:"invalid_event_limit",aliases:[]},{code:"invalid_event_since",meaning:"Invalid event since condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-events.ts"],emitting_commands:["*"],canonical_code:"invalid_event_since",aliases:[]},{code:"invalid_history_analytics_limit",meaning:"Invalid history analytics limit condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/history-analytics.ts"],emitting_commands:["*"],canonical_code:"invalid_history_analytics_limit",aliases:[]},{code:"invalid_history_analytics_minimum_sample",meaning:"Invalid history analytics minimum sample condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/history-analytics.ts"],emitting_commands:["*"],canonical_code:"invalid_history_analytics_minimum_sample",aliases:[]},{code:"invalid_history_analytics_since",meaning:"Invalid history analytics since condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/history-analytics.ts"],emitting_commands:["*"],canonical_code:"invalid_history_analytics_since",aliases:[]},{code:"invalid_improvement_ledger",meaning:"Invalid improvement ledger condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/improvement-ledger-validation.ts"],emitting_commands:["*"],canonical_code:"invalid_improvement_ledger",aliases:[]},{code:"invalid_improvement_metric",meaning:"Invalid improvement metric condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/improvement-ledger.ts"],emitting_commands:["*"],canonical_code:"invalid_improvement_metric",aliases:[]},{code:"invalid_improvement_observation",meaning:"Invalid improvement observation condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/improvement-ledger.ts"],emitting_commands:["*"],canonical_code:"invalid_improvement_observation",aliases:[]},{code:"invalid_improvement_observation_limit",meaning:"Invalid improvement observation limit condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/improvement-ledger.ts"],emitting_commands:["*"],canonical_code:"invalid_improvement_observation_limit",aliases:[]},{code:"invalid_improvement_observation_timestamp",meaning:"Invalid improvement observation timestamp condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/improvement-ledger.ts"],emitting_commands:["*"],canonical_code:"invalid_improvement_observation_timestamp",aliases:[]},{code:"invalid_provenance_predicate",meaning:"Invalid provenance predicate condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/history-provenance.ts"],emitting_commands:["*"],canonical_code:"invalid_provenance_predicate",aliases:[]},{code:"invalid_query_cursor",meaning:"Invalid query cursor condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/pagination.ts"],emitting_commands:["*"],canonical_code:"invalid_query_cursor",aliases:[]},{code:"invalid_read_output_session",meaning:"Invalid read output session condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/read-output-session.ts"],emitting_commands:["*"],canonical_code:"invalid_read_output_session",aliases:[]},{code:"invalid_reproducible_process_environment",meaning:"Invalid reproducible process environment condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/reproducibility/process.ts"],emitting_commands:["*"],canonical_code:"invalid_reproducible_process_environment",aliases:[]},{code:"invalid_workspace_snapshot_target",meaning:"Invalid workspace snapshot target condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"],canonical_code:"invalid_workspace_snapshot_target",aliases:[]},{code:"item_already_active",meaning:"Item already active condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"],canonical_code:"item_already_active",aliases:[]},{code:"item_already_exists",meaning:"Item already exists condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/create.ts"],emitting_commands:["create"],canonical_code:"item_already_exists",aliases:[]},{code:"item_deleted",meaning:"Item deleted condition.",stability:"provisional",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/tombstone.ts"],emitting_commands:["*"],canonical_code:"item_deleted",aliases:[]},{code:"item_document_encoding_invalid",meaning:"Item document encoding invalid condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/store/item-store.ts"],emitting_commands:["*"],canonical_code:"item_document_encoding_invalid",aliases:[]},{code:"item_document_invalid",meaning:"Item document invalid condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/item/item-format.ts"],emitting_commands:["*"],canonical_code:"item_document_invalid",aliases:[]},{code:"item_document_roundtrip_failed",meaning:"Item document roundtrip failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/item/item-format.ts"],emitting_commands:["*"],canonical_code:"item_document_roundtrip_failed",aliases:[]},{code:"item_format_version_unsupported",meaning:"Item format version unsupported condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/item/item-format.ts"],emitting_commands:["*"],canonical_code:"item_format_version_unsupported",aliases:[]},{code:"item_id_collision",meaning:"Item id collision condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/copy.ts"],emitting_commands:["copy"],canonical_code:"item_id_collision",aliases:[]},{code:"item_identity_ambiguous",meaning:"Item identity ambiguous condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/store/item-store.ts"],emitting_commands:["*"],canonical_code:"item_identity_ambiguous",aliases:[]},{code:"item_identity_conflict",meaning:"Item identity conflict condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/governance/validate-history-drift.ts","sdk/merge/three-way.ts","sdk/query/get.ts"],emitting_commands:["*","get"],canonical_code:"item_identity_conflict",aliases:[]},{code:"item_identity_reserved",meaning:"Item identity reserved condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/history.ts"],emitting_commands:["*"],canonical_code:"item_identity_reserved",aliases:[]},{code:"item_not_found",meaning:"Item not found condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/governance/validate-history-drift.ts"],emitting_commands:["*"],canonical_code:"item_not_found",aliases:[]},{code:"likely_duplicate",meaning:"Likely duplicate condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/similarity.ts"],emitting_commands:["*"],canonical_code:"likely_duplicate",aliases:[]},{code:"linked_artifact_mutation_conflict",meaning:"Linked artifact mutation conflict condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/linked-artifacts.ts"],emitting_commands:["*"],canonical_code:"linked_artifact_mutation_conflict",aliases:[]},{code:"linked_test_context_invalid",meaning:"Linked test context invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/entry.ts"],emitting_commands:["*"],canonical_code:"linked_test_context_invalid",aliases:[]},{code:"linked_test_remove_no_match",meaning:"Linked test remove no match condition.",stability:"provisional",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution.ts"],emitting_commands:["*"],canonical_code:"linked_test_remove_no_match",aliases:[]},{code:"linked_test_update_ambiguous",meaning:"Linked test update ambiguous condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/update.ts"],emitting_commands:["*"],canonical_code:"linked_test_update_ambiguous",aliases:[]},{code:"linked_test_update_no_match",meaning:"Linked test update no match condition.",stability:"provisional",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/update.ts"],emitting_commands:["*"],canonical_code:"linked_test_update_no_match",aliases:[]},{code:"linked_test_value_not_quoted",meaning:"Linked test value not quoted condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"],canonical_code:"linked_test_value_not_quoted",aliases:[]},{code:"list_source_incomplete",meaning:"List source incomplete condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/query/list.ts"],emitting_commands:["list"],canonical_code:"list_source_incomplete",aliases:[]},{code:"local_package_archive_unsafe",meaning:"Local package archive unsafe condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"],canonical_code:"local_package_archive_unsafe",aliases:[]},{code:"local_source_not_found_bare_name",meaning:"Local source not found bare name condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"],canonical_code:"local_source_not_found_bare_name",aliases:[]},{code:"lock_conflict",meaning:"Lock conflict condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/lock/lock.ts","core/telemetry/observability.ts"],emitting_commands:["*"],canonical_code:"lock_conflict",aliases:[]},{code:"locks_stale_count",meaning:"Locks stale count condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"locks_stale_count",aliases:[]},{code:"locks_unreadable",meaning:"Locks unreadable condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"locks_unreadable",aliases:[]},{code:"malformed_plan_step_evidence",meaning:"Malformed plan step evidence condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"],canonical_code:"malformed_plan_step_evidence",aliases:[]},{code:"managed_state_invalid",meaning:"Managed state invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/static-inventory.ts"],emitting_commands:["*"],canonical_code:"managed_state_invalid",aliases:[]},{code:"managed_state_unreadable",meaning:"Managed state unreadable condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/static-inventory.ts"],emitting_commands:["*"],canonical_code:"managed_state_unreadable",aliases:[]},{code:"manifest_capabilities_absent",meaning:"Manifest capabilities absent condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"],canonical_code:"manifest_capabilities_absent",aliases:[]},{code:"manifest_invalid",meaning:"Manifest invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/static-inventory.ts"],emitting_commands:["*"],canonical_code:"manifest_invalid",aliases:[]},{code:"manifest_unknown_key",meaning:"Manifest unknown key condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/manifest-schema.ts"],emitting_commands:["*"],canonical_code:"manifest_unknown_key",aliases:[],owned_states:[{state:"author_workspace_manifest_declares_an_unknown_top_level_key",probe_id:"author-manifest-unknown-key",entrypoints:["health"],expected_exit_class:"generic_failure"}]},{code:"manifest_unreadable",meaning:"Manifest unreadable condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/static-inventory.ts"],emitting_commands:["*"],canonical_code:"manifest_unreadable",aliases:[]},{code:"mcp_annotation_file_unavailable",meaning:"Mcp annotation file unavailable condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/runtime-input.ts"],emitting_commands:["*"],canonical_code:"mcp_annotation_file_unavailable",aliases:[]},{code:"mcp_stdin_unavailable",meaning:"Mcp stdin unavailable condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/annotations.ts"],emitting_commands:["*"],canonical_code:"mcp_stdin_unavailable",aliases:[]},{code:"mcp_task_not_found_or_not_authorized",meaning:"Mcp task not found or not authorized condition.",stability:"provisional",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mcp/tasks.ts"],emitting_commands:["*"],canonical_code:"mcp_task_not_found_or_not_authorized",aliases:[]},{code:"merge_bun_launcher_unavailable",meaning:"Merge bun launcher unavailable condition.",stability:"provisional",exit_code:5,class:"dependency_failed",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/merge/install.ts"],emitting_commands:["*"],canonical_code:"merge_bun_launcher_unavailable",aliases:[]},{code:"merge_conflict_markers_detected",meaning:"Merge conflict markers detected condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/item/item-format.ts"],emitting_commands:["*"],canonical_code:"merge_conflict_markers_detected",aliases:["history_merge_conflict_markers_detected"]},{code:"merge_decisions_unreviewed",meaning:"Merge decisions unreviewed condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"merge_decisions_unreviewed",aliases:[]},{code:"merge_driver_configuration_drift",meaning:"Merge driver configuration drift condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"merge_driver_configuration_drift",aliases:[]},{code:"merge_driver_configuration_missing",meaning:"Merge driver configuration missing condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"merge_driver_configuration_missing",aliases:[]},{code:"merge_fence_drift",meaning:"Merge fence drift condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"merge_fence_drift",aliases:[]},{code:"merge_fence_missing",meaning:"Merge fence missing condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"merge_fence_missing",aliases:[]},{code:"merge_git_config_unwritable",meaning:"Merge git config unwritable condition.",stability:"stable",exit_code:5,class:"dependency_failed",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/merge/install.ts"],emitting_commands:["*"],canonical_code:"merge_git_config_unwritable",aliases:[]},{code:"merge_receipt_evidence_invalid",meaning:"Merge receipt evidence invalid condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts","sdk/merge/reconcile.ts"],emitting_commands:["*"],canonical_code:"merge_receipt_evidence_invalid",aliases:[]},{code:"merge_receipt_history_reference_missing",meaning:"Merge receipt history reference missing condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"merge_receipt_history_reference_missing",aliases:[]},{code:"merge_receipts_pending",meaning:"Merge receipts pending condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"merge_receipts_pending",aliases:[]},{code:"merge_reconcile_receipt_evidence_untrusted",meaning:"Merge reconcile receipt evidence untrusted condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/history-repair.ts"],emitting_commands:["*"],canonical_code:"merge_reconcile_receipt_evidence_untrusted",aliases:[]},{code:"merge_root_not_found",meaning:"Merge root not found condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/merge/install.ts"],emitting_commands:["*"],canonical_code:"merge_root_not_found",aliases:[]},{code:"missing_allowed_values",meaning:"Missing allowed values condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts"],emitting_commands:["*"],canonical_code:"missing_allowed_values",aliases:[]}];(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]="4694b850-ced0-5a5b-aeb1-ee1be380b060")}catch{}})();var Sp=[{code:"missing_budget",meaning:"Missing budget condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"],emitting_commands:["*"],canonical_code:"missing_budget",aliases:[]},{code:"missing_cli_flag",meaning:"Missing cli flag condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/tool-option-contracts.ts"],emitting_commands:["*"],canonical_code:"missing_cli_flag",aliases:[]},{code:"missing_destination",meaning:"Missing destination condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"missing_destination",aliases:[]},{code:"missing_directory",meaning:"Missing directory condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"missing_directory",aliases:[]},{code:"missing_init_recovery",meaning:"Missing init recovery condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/tracker-preflight-contracts.ts"],emitting_commands:["*"],canonical_code:"missing_init_recovery",aliases:[]},{code:"missing_lifecycle_target",meaning:"Missing lifecycle target condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension.ts"],emitting_commands:["*"],canonical_code:"missing_lifecycle_target",aliases:[]},{code:"missing_observation",meaning:"Missing observation condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/flag-invocation-contracts.ts"],emitting_commands:["*"],canonical_code:"missing_observation",aliases:[]},{code:"missing_observed_signature",meaning:"Missing observed signature condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"missing_observed_signature",aliases:[]},{code:"missing_parameter_alias",meaning:"Missing parameter alias condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/tool-option-contracts.ts"],emitting_commands:["*"],canonical_code:"missing_parameter_alias",aliases:[]},{code:"missing_positive_execution_receipt",meaning:"Missing positive execution receipt condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution.ts"],emitting_commands:["*"],canonical_code:"missing_positive_execution_receipt",aliases:[]},{code:"missing_probe",meaning:"Missing probe condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/tracker-preflight-contracts.ts"],emitting_commands:["*"],canonical_code:"missing_probe",aliases:[]},{code:"missing_required_argument",meaning:"Missing required argument condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","cli/main.ts","cli/register-mutation.ts","cli/schema/registration.ts","core/telemetry/observability.ts","sdk/governance/assurance-action.ts","sdk/history-redact.ts","sdk/invocation-author.ts"],emitting_commands:["*"],canonical_code:"missing_required_argument",aliases:[]},{code:"missing_required_option",meaning:"Missing required option condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/context-intent-contracts.ts","sdk/lifecycle/create.ts","sdk/lifecycle/plan.ts"],emitting_commands:["*","create","plan"],canonical_code:"missing_required_option",aliases:[]},{code:"missing_suggested_retry",meaning:"Missing suggested retry condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts"],emitting_commands:["*"],canonical_code:"missing_suggested_retry",aliases:[]},{code:"missing_suggested_retry_args",meaning:"Missing suggested retry args condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts"],emitting_commands:["*"],canonical_code:"missing_suggested_retry_args",aliases:[]},{code:"module_import_failed",meaning:"Module import failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"],canonical_code:"module_import_failed",aliases:[]},{code:"multi_target_github_install_ambiguous",meaning:"Multi target github install ambiguous condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-setup.ts"],emitting_commands:["*"],canonical_code:"multi_target_github_install_ambiguous",aliases:[]},{code:"mutation_author_required",meaning:"Mutation author required condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-guard.ts"],emitting_commands:["*"],canonical_code:"mutation_author_required",aliases:[]},{code:"mutation_document_unreadable",meaning:"Mutation document unreadable condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-structured-mutation.ts"],emitting_commands:["*"],canonical_code:"mutation_document_unreadable",aliases:[]},{code:"mutation_option_value_invalid",meaning:"Mutation option value invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/mutation-option-validation.ts"],emitting_commands:["item mutate"],canonical_code:"mutation_option_value_invalid",aliases:[]},{code:"mutation_secret_guard_blocked",meaning:"Mutation secret guard blocked condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-guard.ts"],emitting_commands:["*"],canonical_code:"mutation_secret_guard_blocked",aliases:[]},{code:"no_matching_tests",meaning:"No matching tests condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution-receipts.ts"],emitting_commands:["*"],canonical_code:"no_matching_tests",aliases:[]},{code:"no_projects_matched_filters",meaning:"No projects matched filters condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution-receipts.ts"],emitting_commands:["*"],canonical_code:"no_projects_matched_filters",aliases:[]},{code:"no_test_files_found",meaning:"No test files found condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution-receipts.ts"],emitting_commands:["*"],canonical_code:"no_test_files_found",aliases:[]},{code:"no_tests_found",meaning:"No tests found condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution-receipts.ts"],emitting_commands:["*"],canonical_code:"no_tests_found",aliases:[]},{code:"no_update_fields",meaning:"No update fields condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts"],emitting_commands:["*"],canonical_code:"no_update_fields",aliases:[]},{code:"no_version_bounds_declared",meaning:"No version bounds declared condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/manifest-schema.ts"],emitting_commands:["*"],canonical_code:"no_version_bounds_declared",aliases:[],owned_states:[{state:"author_workspace_manifest_omits_canonical_pm_version_bounds",probe_id:"author-manifest-version-bounds-missing",entrypoints:["health"],expected_exit_class:"generic_failure"}]},{code:"non_refusal_exit",meaning:"Non refusal exit condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts"],emitting_commands:["*"],canonical_code:"non_refusal_exit",aliases:[]},{code:"npm_pack_json_shape_unsupported",meaning:"Npm pack json shape unsupported condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"],canonical_code:"npm_pack_json_shape_unsupported",aliases:[]},{code:"npm_package_archive_missing",meaning:"Npm package archive missing condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"],canonical_code:"npm_package_archive_missing",aliases:[]},{code:"npm_package_archive_unsafe",meaning:"Npm package archive unsafe condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"],canonical_code:"npm_package_archive_unsafe",aliases:[]},{code:"npm_package_not_found",meaning:"Npm package not found condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"],canonical_code:"npm_package_not_found",aliases:[]},{code:"ownership_conflict",meaning:"Ownership conflict condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/annotations.ts"],emitting_commands:["*"],canonical_code:"ownership_conflict",aliases:[]},{code:"ownership_dependency_bypass_restricted_options",meaning:"Ownership dependency bypass restricted options condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"],canonical_code:"ownership_dependency_bypass_restricted_options",aliases:[]},{code:"ownership_metadata_bypass_restricted_options",meaning:"Ownership metadata bypass restricted options condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"],canonical_code:"ownership_metadata_bypass_restricted_options",aliases:[]},{code:"package_spec_empty",meaning:"Package spec empty condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"package_spec_empty",aliases:[]},{code:"package_upgrade_modes_mutually_exclusive",meaning:"Package upgrade modes mutually exclusive condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/governance/upgrade.ts"],emitting_commands:["*"],canonical_code:"package_upgrade_modes_mutually_exclusive",aliases:[]},{code:"positional_shape_budget_exceeded",meaning:"Positional shape budget exceeded condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"positional_shape_budget_exceeded",aliases:[]},{code:"positional_signature_mismatch",meaning:"Positional signature mismatch condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"positional_signature_mismatch",aliases:[]},{code:"profile_name_empty",meaning:"Profile name empty condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"profile_name_empty",aliases:[]},{code:"profile_name_not_normalized",meaning:"Profile name not normalized condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"profile_name_not_normalized",aliases:[]},{code:"profile_summary_empty",meaning:"Profile summary empty condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"profile_summary_empty",aliases:[]},{code:"profile_title_empty",meaning:"Profile title empty condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"profile_title_empty",aliases:[]},{code:"project_runtime_history_epoch_incompatible",meaning:"Project runtime history epoch incompatible condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/environment/project-runtime-compatibility.ts"],emitting_commands:["*"],canonical_code:"project_runtime_history_epoch_incompatible",aliases:[]},{code:"project_runtime_item_format_incompatible",meaning:"Project runtime item format incompatible condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/environment/project-runtime-compatibility.ts"],emitting_commands:["*"],canonical_code:"project_runtime_item_format_incompatible",aliases:[]},{code:"project_runtime_stale_mutation",meaning:"Project runtime stale mutation condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/environment/project-runtime-compatibility.ts"],emitting_commands:["*"],canonical_code:"project_runtime_stale_mutation",aliases:[]},{code:"project_runtime_stale_read",meaning:"Project runtime stale read condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/environment/project-runtime-compatibility.ts"],emitting_commands:["*"],canonical_code:"project_runtime_stale_read",aliases:[]},{code:"projection_options_mutually_exclusive",meaning:"Projection options mutually exclusive condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/query/get.ts","sdk/query/list.ts","sdk/query/search-contracts.ts"],emitting_commands:["get","list","search"],canonical_code:"projection_options_mutually_exclusive",aliases:[]},{code:"provenance_value_domain_invalid",meaning:"Provenance value domain invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"provenance_value_domain_invalid",aliases:[]},{code:"read_output_cursor_command_mismatch",meaning:"Read output cursor command mismatch condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/read-output/continuation.ts"],emitting_commands:["*"],canonical_code:"read_output_cursor_command_mismatch",aliases:[]},{code:"read_output_cursor_invalid",meaning:"Read output cursor invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/read-output/continuation.ts"],emitting_commands:["*"],canonical_code:"read_output_cursor_invalid",aliases:[]},{code:"read_output_cursor_stale",meaning:"Read output cursor stale condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/read-output/continuation.ts"],emitting_commands:["*"],canonical_code:"read_output_cursor_stale",aliases:[]},{code:"recovery_kind_mismatch",meaning:"Recovery kind mismatch condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/tracker-preflight-contracts.ts"],emitting_commands:["*"],canonical_code:"recovery_kind_mismatch",aliases:[]},{code:"redundant_edge",meaning:"Redundant edge condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/graph/remediation.ts"],emitting_commands:["*"],canonical_code:"redundant_edge",aliases:[]},{code:"refusal_allowed_values_mismatch",meaning:"Refusal allowed values mismatch condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-corpus-contracts.ts"],emitting_commands:["*"],canonical_code:"refusal_allowed_values_mismatch",aliases:[]},{code:"refusal_error_code_mismatch",meaning:"Refusal error code mismatch condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-corpus-contracts.ts"],emitting_commands:["*"],canonical_code:"refusal_error_code_mismatch",aliases:[]},{code:"refusal_exit_code_mismatch",meaning:"Refusal exit code mismatch condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-corpus-contracts.ts"],emitting_commands:["*"],canonical_code:"refusal_exit_code_mismatch",aliases:[]},{code:"refusal_mutated_state",meaning:"Refusal mutated state condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-corpus-contracts.ts"],emitting_commands:["*"],canonical_code:"refusal_mutated_state",aliases:[]},{code:"refusal_probe_missing",meaning:"Refusal probe missing condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-corpus-contracts.ts"],emitting_commands:["*"],canonical_code:"refusal_probe_missing",aliases:[]},{code:"refusal_recovery_failed",meaning:"Refusal recovery failed condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-corpus-contracts.ts"],emitting_commands:["*"],canonical_code:"refusal_recovery_failed",aliases:[]},{code:"reindex_already_running",meaning:"Reindex already running condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/governance/reindex.ts"],emitting_commands:["*"],canonical_code:"reindex_already_running",aliases:[]},{code:"removed_canonical_spelling",meaning:"Removed canonical spelling condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"],emitting_commands:["*"],canonical_code:"removed_canonical_spelling",aliases:[]},{code:"removed_compatibility_spelling",meaning:"Removed compatibility spelling condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"],emitting_commands:["*"],canonical_code:"removed_compatibility_spelling",aliases:[]},{code:"reopen_reason_required",meaning:"Reopen reason required condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/reopen.ts"],emitting_commands:["item reopen"],canonical_code:"reopen_reason_required",aliases:[]},{code:"reopen_receipt_missing",meaning:"Reopen receipt missing condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"],canonical_code:"reopen_receipt_missing",aliases:[]},{code:"reopen_target_status_invalid",meaning:"Reopen target status invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/reopen.ts"],emitting_commands:["item reopen"],canonical_code:"reopen_target_status_invalid",aliases:[]},{code:"reported_zero_passes",meaning:"Reported zero passes condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution-receipts.ts"],emitting_commands:["*"],canonical_code:"reported_zero_passes",aliases:[]},{code:"reported_zero_tests",meaning:"Reported zero tests condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution-receipts.ts"],emitting_commands:["*"],canonical_code:"reported_zero_tests",aliases:[]},{code:"reserved_item_field",meaning:"Reserved item field condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"],canonical_code:"reserved_item_field",aliases:[]},{code:"retry_failed",meaning:"Retry failed condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts","sdk/agent/tracker-preflight-contracts.ts"],emitting_commands:["*"],canonical_code:"retry_failed",aliases:[]},{code:"schema_migration_input_required",meaning:"Schema migration input required condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/migration-gates.ts"],emitting_commands:["*"],canonical_code:"schema_migration_input_required",aliases:[]},{code:"semantic_spelling_collision",meaning:"Semantic spelling collision condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"],emitting_commands:["*"],canonical_code:"semantic_spelling_collision",aliases:[]},{code:"settings_invalid",meaning:"Settings invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/static-inventory.ts"],emitting_commands:["*"],canonical_code:"settings_invalid",aliases:[]},{code:"settings_read_fs_error",meaning:"Settings read fs error condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"settings_read_fs_error",aliases:[]},{code:"settings_read_invalid_json",meaning:"Settings read invalid json condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"settings_read_invalid_json",aliases:[]},{code:"settings_read_invalid_schema",meaning:"Settings read invalid schema condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"settings_read_invalid_schema",aliases:[]},{code:"settings_read_merge_failed",meaning:"Settings read merge failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"settings_read_merge_failed",aliases:[]},{code:"settings_unreadable",meaning:"Settings unreadable condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/static-inventory.ts"],emitting_commands:["*"],canonical_code:"settings_unreadable",aliases:[]},{code:"settings_write_invalid_existing_json",meaning:"Settings write invalid existing json condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/store/settings.ts"],emitting_commands:["*"],canonical_code:"settings_write_invalid_existing_json",aliases:[]},{code:"stale_budget",meaning:"Stale budget condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"],emitting_commands:["*"],canonical_code:"stale_budget",aliases:[]},{code:"stale_destination",meaning:"Stale destination condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"stale_destination",aliases:[]},{code:"stale_observed_signature",meaning:"Stale observed signature condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"stale_observed_signature",aliases:[]},{code:"status_duplicate",meaning:"Status duplicate condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"status_duplicate",aliases:[]},{code:"status_invalid",meaning:"Status invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"status_invalid",aliases:[]},{code:"status_lifecycle_role_required",meaning:"Status lifecycle role required condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/schema.ts"],emitting_commands:["*"],canonical_code:"status_lifecycle_role_required",aliases:[]},{code:"stdin_json_invalid",meaning:"Stdin json invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/structured-mutations.ts"],emitting_commands:["*"],canonical_code:"stdin_json_invalid",aliases:[]},{code:"stdin_json_persisted_annotation_changed",meaning:"Stdin json persisted annotation changed condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"],canonical_code:"stdin_json_persisted_annotation_changed",aliases:[]},{code:"stdin_json_unknown_key",meaning:"Stdin json unknown key condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/structured-mutations.ts"],emitting_commands:["*"],canonical_code:"stdin_json_unknown_key",aliases:[]},{code:"structured_event_immutable",meaning:"Structured event immutable condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/annotations.ts"],emitting_commands:["*"],canonical_code:"structured_event_immutable",aliases:[]},{code:"structured_event_input_conflict",meaning:"Structured event input conflict condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/notes.ts"],emitting_commands:["*"],canonical_code:"structured_event_input_conflict",aliases:[]},{code:"structured_event_json_empty",meaning:"Structured event json empty condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/notes.ts"],emitting_commands:["*"],canonical_code:"structured_event_json_empty",aliases:[]},{code:"structured_event_json_invalid",meaning:"Structured event json invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/notes.ts"],emitting_commands:["*"],canonical_code:"structured_event_json_invalid",aliases:[]},{code:"structured_event_since_invalid",meaning:"Structured event since invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/notes.ts"],emitting_commands:["*"],canonical_code:"structured_event_since_invalid",aliases:[]},{code:"suggested_retry_args_mismatch",meaning:"Suggested retry args mismatch condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts"],emitting_commands:["*"],canonical_code:"suggested_retry_args_mismatch",aliases:[]},{code:"telemetry_endpoint_probe_failed",meaning:"Telemetry endpoint probe failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"telemetry_endpoint_probe_failed",aliases:[]},{code:"telemetry_endpoint_probe_http_status",meaning:"Telemetry endpoint probe http status condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"telemetry_endpoint_probe_http_status",aliases:[]},{code:"telemetry_otel_export_failing",meaning:"Telemetry otel export failing condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"telemetry_otel_export_failing",aliases:[]},{code:"telemetry_queue_high_retries",meaning:"Telemetry queue high retries condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"telemetry_queue_high_retries",aliases:[]},{code:"telemetry_queue_invalid_rows",meaning:"Telemetry queue invalid rows condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"telemetry_queue_invalid_rows",aliases:[]},{code:"telemetry_queue_pending",meaning:"Telemetry queue pending condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"telemetry_queue_pending",aliases:[]},{code:"telemetry_schema_version_behind",meaning:"Telemetry schema version behind condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"telemetry_schema_version_behind",aliases:[]},{code:"telemetry_state_invalid_json",meaning:"Telemetry state invalid json condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"telemetry_state_invalid_json",aliases:[]},{code:"template_type_unknown",meaning:"Template type unknown condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"template_type_unknown",aliases:[]},{code:"terminal_plan_mutation",meaning:"Terminal plan mutation condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"],canonical_code:"terminal_plan_mutation",aliases:[]},{code:"terminal_state_conflict",meaning:"Terminal state conflict condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/telemetry/observability.ts"],emitting_commands:["*"],canonical_code:"terminal_state_conflict",aliases:[]},{code:"test_measure_requires_execution",meaning:"Test measure requires execution condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/prerequisites.ts"],emitting_commands:["*"],canonical_code:"test_measure_requires_execution",aliases:[]},{code:"test_measure_requires_run",meaning:"Test measure requires run condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/prerequisites.ts"],emitting_commands:["*"],canonical_code:"test_measure_requires_run",aliases:[]},{code:"text_unpaired_surrogate",meaning:"Text unpaired surrogate condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/item/item-format.ts"],emitting_commands:["*"],canonical_code:"text_unpaired_surrogate",aliases:[]},{code:"tracked_runtime_cache_files",meaning:"Tracked runtime cache files condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"tracked_runtime_cache_files",aliases:["validate_storage_tracked_runtime_cache_files"]},{code:"tracker_not_initialized",meaning:"Tracker not initialized condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/store/tracker-preflight.ts","core/telemetry/observability.ts"],emitting_commands:["*"],canonical_code:"tracker_not_initialized",aliases:[],owned_states:[{state:"selected_tracker_root_exists_without_settings",probe_id:"tracker-root-settings-missing",entrypoints:["list"],expected_exit_class:"not_found"}]},{code:"tracker_root_missing",meaning:"Tracker root missing condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/store/tracker-preflight.ts"],emitting_commands:["*"],canonical_code:"tracker_root_missing",aliases:[],owned_states:[{state:"selected_tracker_root_does_not_exist",probe_id:"tracker-root-missing",entrypoints:["list"],expected_exit_class:"not_found"}]},{code:"tracker_root_not_directory",meaning:"Tracker root not directory condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/store/tracker-preflight.ts"],emitting_commands:["*"],canonical_code:"tracker_root_not_directory",aliases:[],owned_states:[{state:"selected_tracker_root_is_a_regular_file",probe_id:"tracker-root-not-directory",entrypoints:["list"],expected_exit_class:"usage"}]},{code:"tracker_root_unreadable",meaning:"Tracker root unreadable condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/store/tracker-preflight.ts"],emitting_commands:["*"],canonical_code:"tracker_root_unreadable",aliases:[],owned_states:[{state:"selected_tracker_root_is_not_readable",probe_id:"tracker-root-unreadable",entrypoints:["list"],expected_exit_class:"generic_failure"}]},{code:"transaction_create_compensated",meaning:"Transaction create compensated condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/item-transaction.ts"],emitting_commands:["*"],canonical_code:"transaction_create_compensated",aliases:[]},{code:"transaction_journal_invalid",meaning:"Transaction journal invalid condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-transaction.ts"],emitting_commands:["*"],canonical_code:"transaction_journal_invalid",aliases:[]},{code:"transaction_plan_mismatch",meaning:"Transaction plan mismatch condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-transaction.ts"],emitting_commands:["*"],canonical_code:"transaction_plan_mismatch",aliases:[]},{code:"transaction_preview_external_schema",meaning:"Transaction preview external schema condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/item-transaction.ts"],emitting_commands:["*"],canonical_code:"transaction_preview_external_schema",aliases:[]},{code:"transaction_preview_non_regular_file",meaning:"Transaction preview non regular file condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/fs/fs-utils.ts"],emitting_commands:["*"],canonical_code:"transaction_preview_non_regular_file",aliases:[]},{code:"transaction_preview_snapshot_changed",meaning:"Transaction preview snapshot changed condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/item-transaction.ts"],emitting_commands:["*"],canonical_code:"transaction_preview_snapshot_changed",aliases:[]},{code:"type_duplicate",meaning:"Type duplicate condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"type_duplicate",aliases:[]},{code:"type_invalid",meaning:"Type invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"type_invalid",aliases:[]},{code:"undeclared_observation",meaning:"Undeclared observation condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/flag-invocation-contracts.ts"],emitting_commands:["*"],canonical_code:"undeclared_observation",aliases:[]},{code:"unexpected_refusal_probe",meaning:"Unexpected refusal probe condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-corpus-contracts.ts"],emitting_commands:["*"],canonical_code:"unexpected_refusal_probe",aliases:[]},{code:"unknown_command",meaning:"Unknown command condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/cli-contracts/runtime-contracts.ts"],emitting_commands:["*"],canonical_code:"unknown_command",aliases:[]},{code:"unknown_context_intent",meaning:"Unknown context intent condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/context-intent-contracts.ts"],emitting_commands:["*"],canonical_code:"unknown_context_intent",aliases:[]},{code:"unknown_error",meaning:"Unknown error condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"],canonical_code:"unknown_error",aliases:[]},{code:"unknown_field",meaning:"Unknown field condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/schema.ts"],emitting_commands:["*"],canonical_code:"unknown_field",aliases:[]},{code:"unknown_field_projection",meaning:"Unknown field projection condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/query/get.ts","sdk/query/list.ts","sdk/query/search-contracts.ts"],emitting_commands:["get","list","search"],canonical_code:"unknown_field_projection",aliases:[]},{code:"unknown_item_type",meaning:"Unknown item type condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/schema.ts"],emitting_commands:["*"],canonical_code:"unknown_item_type",aliases:[]},{code:"unknown_lifecycle_action",meaning:"Unknown lifecycle action condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/subcommand-recovery.ts"],emitting_commands:["*"],canonical_code:"unknown_subcommand",aliases:[]},{code:"unknown_noun",meaning:"Unknown noun condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"unknown_noun",aliases:[]},{code:"unknown_option",meaning:"Unknown option condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","cli/runtime/invocation-options.ts","core/telemetry/observability.ts"],emitting_commands:["*"],canonical_code:"unknown_option",aliases:[],owned_states:[{state:"declared_option_is_rejected_on_the_selected_command_path",probe_id:"cross-command-unknown-option",entrypoints:["deps"],expected_exit_class:"usage"}]},{code:"unknown_plan_template",meaning:"Unknown plan template condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"],canonical_code:"unknown_plan_template",aliases:[]},{code:"unknown_provenance_dimension",meaning:"Unknown provenance dimension condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/history-provenance.ts"],emitting_commands:["*"],canonical_code:"unknown_provenance_dimension",aliases:[]},{code:"unknown_status",meaning:"Unknown status condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/schema.ts"],emitting_commands:["*"],canonical_code:"unknown_status",aliases:[]},{code:"unknown_subcommand",meaning:"Unknown subcommand condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","sdk/agent/subcommand-recovery.ts"],emitting_commands:["*"],canonical_code:"unknown_subcommand",aliases:["unknown_lifecycle_action"],owned_states:[{state:"config_action_token_is_not_declared",probe_id:"config-unknown-action",entrypoints:["config"],expected_exit_class:"usage"},{state:"graph_command_token_is_not_declared",probe_id:"graph-unknown-subcommand",entrypoints:["graph"],expected_exit_class:"usage"},{state:"nested_command_token_is_not_declared_by_its_family",probe_id:"schema-unknown-subcommand",entrypoints:["schema"],expected_exit_class:"usage"},{state:"package_lifecycle_token_is_not_declared",probe_id:"package-unknown-action",entrypoints:["package"],expected_exit_class:"usage"}]},{code:"unsafe_init_recovery",meaning:"Unsafe init recovery condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/tracker-preflight-contracts.ts"],emitting_commands:["*"],canonical_code:"unsafe_init_recovery",aliases:[]},{code:"unsupported_update_option",meaning:"Unsupported update option condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"],canonical_code:"unsupported_update_option",aliases:[]},{code:"upsert_key_ambiguous",meaning:"Upsert key ambiguous condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/structured-mutations.ts"],emitting_commands:["*"],canonical_code:"upsert_key_ambiguous",aliases:[]},{code:"upsert_key_conflict",meaning:"Upsert key conflict condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/item-transaction.ts"],emitting_commands:["*"],canonical_code:"upsert_key_conflict",aliases:[]},{code:"upsert_key_duplicate",meaning:"Upsert key duplicate condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/item-transaction.ts","sdk/structured-mutations.ts"],emitting_commands:["*"],canonical_code:"upsert_key_duplicate",aliases:[]},{code:"upsert_key_missing",meaning:"Upsert key missing condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/structured-mutations.ts"],emitting_commands:["*"],canonical_code:"upsert_key_missing",aliases:[]},{code:"upsert_match_changed",meaning:"Upsert match changed condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/item-transaction.ts"],emitting_commands:["*"],canonical_code:"upsert_match_changed",aliases:[]},{code:"validate_command_references_stale_pm_ids",meaning:"Validate command references stale pm ids condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_command_references_stale_pm_ids",aliases:[]},{code:"validate_files_missing_linked_paths",meaning:"Validate files missing linked paths condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_files_missing_linked_paths",aliases:[]},{code:"validate_files_orphaned_paths",meaning:"Validate files orphaned paths condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_files_orphaned_paths",aliases:[]},{code:"validate_files_tracked_all_strict_forces_pm_internals",meaning:"Validate files tracked all strict forces pm internals condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_files_tracked_all_strict_forces_pm_internals",aliases:[]},{code:"validate_format_version_ahead_items",meaning:"Validate format version ahead items condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_item_ahead_format_version",aliases:[]},{code:"validate_format_version_outdated_items",meaning:"Validate format version outdated items condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_item_outdated_format_version",aliases:[]},{code:"validate_hierarchy_parent_cycle",meaning:"Validate hierarchy parent cycle condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_hierarchy_parent_cycle",aliases:[]},{code:"validate_hierarchy_parent_cycle_error",meaning:"Validate hierarchy parent cycle error condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_hierarchy_parent_cycle_error",aliases:[]},{code:"validate_history_drift_chain_mismatches",meaning:"Validate history drift chain mismatches condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_chain_mismatch",aliases:[]},{code:"validate_history_drift_hash_mismatches",meaning:"Validate history drift hash mismatches condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_hash_mismatch",aliases:[]},{code:"validate_history_drift_missing_streams",meaning:"Validate history drift missing streams condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_missing_stream",aliases:[]},{code:"validate_history_drift_unreadable_streams",meaning:"Validate history drift unreadable streams condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_unreadable_stream",aliases:[]},{code:"validate_history_drift_version_skews",meaning:"Validate history drift version skews condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_version_skew",aliases:[]},{code:"validate_history_unknown_author_events",meaning:"Validate history unknown author events condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_unknown_author_events",aliases:[]},{code:"validate_lifecycle_active_closure_like_metadata",meaning:"Validate lifecycle active closure like metadata condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_lifecycle_active_closure_like_metadata",aliases:[]},{code:"validate_lifecycle_active_terminal_parent",meaning:"Validate lifecycle active terminal parent condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_lifecycle_active_terminal_parent",aliases:[]},{code:"validate_lifecycle_dependency_cycles",meaning:"Validate lifecycle dependency cycles condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_lifecycle_dependency_cycles",aliases:[]},{code:"validate_lifecycle_dependency_cycles_error",meaning:"Validate lifecycle dependency cycles error condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_lifecycle_dependency_cycles_error",aliases:[]},{code:"validate_lifecycle_stale_blockers",meaning:"Validate lifecycle stale blockers condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_lifecycle_stale_blockers",aliases:[]},{code:"validate_merge_decisions_unreviewed",meaning:"Validate merge decisions unreviewed condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_merge_decisions_unreviewed",aliases:[]},{code:"validate_merge_driver_configuration",meaning:"Validate merge driver configuration condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_merge_driver_configuration",aliases:[]},{code:"validate_merge_fence_drift",meaning:"Validate merge fence drift condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_merge_fence_drift",aliases:[]},{code:"validate_metadata_custom_profile_missing_required_fields",meaning:"Validate metadata custom profile missing required fields condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_custom_profile_missing_required_fields",aliases:[]},{code:"validate_metadata_duplicate_issue_codes",meaning:"Validate metadata duplicate issue codes condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_duplicate_issue_codes",aliases:[]},{code:"validate_metadata_missing_acceptance_criteria",meaning:"Validate metadata missing acceptance criteria condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_missing_acceptance_criteria",aliases:[]},{code:"validate_metadata_missing_close_reason",meaning:"Validate metadata missing close reason condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_missing_close_reason",aliases:[]},{code:"validate_metadata_missing_closed_at",meaning:"Validate metadata missing closed at condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_missing_closed_at",aliases:[]},{code:"validate_metadata_missing_confidence",meaning:"Validate metadata missing confidence condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_missing_confidence",aliases:[]},{code:"validate_metadata_missing_estimate",meaning:"Validate metadata missing estimate condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_missing_estimate",aliases:[]},{code:"validate_metadata_missing_release",meaning:"Validate metadata missing release condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_missing_release",aliases:[]},{code:"validate_metadata_missing_reviewer",meaning:"Validate metadata missing reviewer condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_missing_reviewer",aliases:[]},{code:"validate_metadata_missing_risk",meaning:"Validate metadata missing risk condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_missing_risk",aliases:[]},{code:"validate_metadata_missing_sprint",meaning:"Validate metadata missing sprint condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_missing_sprint",aliases:[]},{code:"validate_resolution_missing_fields",meaning:"Validate resolution missing fields condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_resolution_missing_fields",aliases:[]},{code:"validate_storage_duplicate_item_ids",meaning:"Validate storage duplicate item ids condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_storage_duplicate_item_ids",aliases:[]},{code:"validate_storage_history_conflict_markers",meaning:"Validate storage history conflict markers condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_history_conflict_marker",aliases:[]},{code:"validate_storage_resurrected_items",meaning:"Validate storage resurrected items condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_storage_resurrected_items",aliases:[]},{code:"validate_storage_tracked_runtime_cache_files",meaning:"Validate storage tracked runtime cache files condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"tracked_runtime_cache_files",aliases:[]},{code:"validate_storage_unparseable_config",meaning:"Validate storage unparseable config condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_storage_unparseable_config",aliases:[]},{code:"validate_storage_unparseable_history",meaning:"Validate storage unparseable history condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_storage_unparseable_history",aliases:[]},{code:"validate_storage_unreadable_items",meaning:"Validate storage unreadable items condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_storage_unreadable_items",aliases:[]},{code:"vectorization_embedding_identity_changed",meaning:"Vectorization embedding identity changed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"vectorization_embedding_identity_changed",aliases:[]},{code:"vectorization_stale_items_remaining",meaning:"Vectorization stale items remaining condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"vectorization_stale_items_remaining",aliases:[]},{code:"visible_surface_ceiling_exceeded",meaning:"Visible surface ceiling exceeded condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"visible_surface_ceiling_exceeded",aliases:[]},{code:"workflow_duplicate_type",meaning:"Workflow duplicate type condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"workflow_duplicate_type",aliases:[]},{code:"workflow_policy_approval_history_invalid",meaning:"Workflow policy approval history invalid condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/policy/workflow-policy-store.ts"],emitting_commands:["*"],canonical_code:"workflow_policy_approval_history_invalid",aliases:[]},{code:"workflow_policy_audit_failed",meaning:"Workflow policy audit failed condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/policy/workflow-policy-store.ts"],emitting_commands:["*"],canonical_code:"workflow_policy_audit_failed",aliases:[]},{code:"workflow_policy_input_unreadable",meaning:"Workflow policy input unreadable condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/policy/workflow-policy-store.ts"],emitting_commands:["*"],canonical_code:"workflow_policy_input_unreadable",aliases:[]},{code:"workflow_policy_invalid",meaning:"Workflow policy invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/policy/workflow-policy.ts"],emitting_commands:["*"],canonical_code:"workflow_policy_invalid",aliases:[]},{code:"workflow_policy_refused",meaning:"Workflow policy refused condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/policy/workflow-policy-store.ts"],emitting_commands:["*"],canonical_code:"workflow_policy_refused",aliases:[]},{code:"workflow_policy_registry_invalid",meaning:"Workflow policy registry invalid condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/policy/workflow-policy-store.ts"],emitting_commands:["*"],canonical_code:"workflow_policy_registry_invalid",aliases:[]},{code:"workflow_status_unknown",meaning:"Workflow status unknown condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"workflow_status_unknown",aliases:[]},{code:"workflow_transition_malformed",meaning:"Workflow transition malformed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"workflow_transition_malformed",aliases:[]},{code:"workflow_type_empty",meaning:"Workflow type empty condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"workflow_type_empty",aliases:[]},{code:"workflow_type_unknown",meaning:"Workflow type unknown condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"workflow_type_unknown",aliases:[]},{code:"workspace_history_chain_invalid",meaning:"Workspace history chain invalid condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/workspace-history.ts"],emitting_commands:["*"],canonical_code:"workspace_history_chain_invalid",aliases:[]},{code:"workspace_history_state_conflict",meaning:"Workspace history state conflict condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/workspace-history.ts"],emitting_commands:["*"],canonical_code:"workspace_history_state_conflict",aliases:[]},{code:"workspace_root_pm_path",meaning:"Workspace root pm path condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/init.ts"],emitting_commands:["*"],canonical_code:"workspace_root_pm_path",aliases:[]},{code:"workspace_snapshot_force_required",meaning:"Workspace snapshot force required condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"],canonical_code:"workspace_snapshot_force_required",aliases:[]},{code:"workspace_snapshot_manifest_mismatch",meaning:"Workspace snapshot manifest mismatch condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"],canonical_code:"workspace_snapshot_manifest_mismatch",aliases:[]},{code:"workspace_snapshot_name_reserved_fingerprint",meaning:"Workspace snapshot name reserved fingerprint condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"],canonical_code:"workspace_snapshot_name_reserved_fingerprint",aliases:[]},{code:"workspace_snapshot_not_found",meaning:"Workspace snapshot not found condition.",stability:"provisional",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"],canonical_code:"workspace_snapshot_not_found",aliases:[]},{code:"workspace_snapshot_permission_denied",meaning:"Workspace snapshot permission denied condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"],canonical_code:"workspace_snapshot_permission_denied",aliases:[]},{code:"workspace_snapshot_resource_exhausted",meaning:"Workspace snapshot resource exhausted condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"],canonical_code:"workspace_snapshot_resource_exhausted",aliases:[]},{code:"workspace_snapshot_storage_exhausted",meaning:"Workspace snapshot storage exhausted condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"],canonical_code:"workspace_snapshot_storage_exhausted",aliases:[]},{code:"wrong_item_type",meaning:"Wrong item type condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"],canonical_code:"wrong_item_type",aliases:[]}];(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]="70a7dc18-ab34-5e17-83eb-f5fac0b7fdd9")}catch{}})();var Tp=kp([...Ep,...Sp]);(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]="76c420db-b520-5fde-bd43-16a7324feb0a")}catch{}})();var Ek=["mutation_receipt","entity","collection","diagnostic","stream"],Sk=new Set(["append","claim","close","close-task","copy","create","delete","focus","pause-task","release","restore","start-task","update"]),Tk=new Set(["close-many","update-many"]),Ak=new Set(["activity","comments","contracts","events","history","learnings","list","notes","search"]),Ik=new Set(["aggregate","deps","graph","health","history-redact","history-repair","history-compact","stats","validate"]);function Zn(e){if(e.command.trim().length===0)throw new TypeError("command must be a non-empty command path");if(!Ek.includes(e.kind))throw new TypeError(`Unsupported output envelope kind: ${e.kind}`);return e}function Ap(e){let t=e.trim().replace(/\s+/gu," "),[n=t]=t.split(" ");return Tk.has(n)?Zn({command:t,kind:"collection",wrapper_key:"rows",cardinality:"many",format_flag:"--json"}):Sk.has(n)?Zn({command:t,kind:"mutation_receipt",wrapper_key:null,cardinality:"one",format_flag:"--json"}):Ak.has(n)?Zn({command:t,kind:"collection",wrapper_key:n==="contracts"?null:"items",cardinality:"many",format_flag:"--json"}):Ik.has(n)?Zn({command:t,kind:"diagnostic",wrapper_key:null,cardinality:"none",format_flag:"--json"}):Zn({command:t,kind:n==="get"?"entity":"diagnostic",wrapper_key:n==="get"?"item":null,cardinality:n==="get"?"one":"none",format_flag:"--json"})}var Ck=Xe.map(e=>Ap(e)),xk=new Map(Ck.map(e=>[e.command,e]));function Ip(e){let t=e.trim().replace(/\s+/gu," ");if(t.length===0)throw new TypeError("command must be a non-empty command path");let[n=t]=qi(t).split(" "),i=xk.get(n);return i?{...i,command:t}:Ap(t)}function Rk(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ok(e){return Rk(e)&&typeof e.id=="string"&&e.id.length>0&&typeof e.status=="string"&&e.status.length>0&&Number.isSafeInteger(e.changed_field_count)&&Number(e.changed_field_count)>=0&&(e.close_reason===void 0||typeof e.close_reason=="string")&&(e.deleted===void 0||typeof e.deleted=="boolean")&&(e.previous_status===void 0||typeof e.previous_status=="string")&&(e.warnings===void 0||Array.isArray(e.warnings))}function EF(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch(n){throw new TypeError(`Mutation receipt must be valid JSON: ${String(n)}`,{cause:n})}if(!Ok(t))throw new TypeError("Mutation receipt must be a flat object with top-level id, status, and changed_field_count fields");return{id:t.id,status:t.status,changedFieldCount:t.changed_field_count,...typeof t.close_reason=="string"?{closeReason:t.close_reason}:{},...typeof t.deleted=="boolean"?{deleted:t.deleted}:{},...typeof t.previous_status=="string"?{previousStatus:t.previous_status}:{},...Array.isArray(t.warnings)?{warnings:t.warnings}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7c95b311-b408-50f7-87e8-2c2fa2323092")}catch{}})();var vo=[{exit_code:m.SUCCESS,outcome:"effect",success:!0,meaning:"The requested operation completed with its intended effect."},{exit_code:m.GENERIC_FAILURE,outcome:"internal_failure",success:!1,meaning:"An unexpected runtime or internal failure prevented completion."},{exit_code:m.USAGE,outcome:"refused_input",success:!1,meaning:"The invocation was refused because its input or composition was invalid."},{exit_code:m.NOT_FOUND,outcome:"refused_tracker_state",success:!1,meaning:"The requested tracker, item, or resource was not present."},{exit_code:m.CONFLICT,outcome:"conflict",success:!1,meaning:"Current state or concurrency prevented the requested effect."},{exit_code:m.DEPENDENCY_FAILED,outcome:"dependency_failed",success:!1,meaning:"A required dependency operation failed."},{exit_code:m.NO_EFFECT,outcome:"no_effect",success:!0,meaning:"The request was valid and completed, but matched nothing to change."},{exit_code:m.PARTIAL_EFFECT,outcome:"partial_effect",success:!0,meaning:"The request completed and changed some, but not all, selected targets."}],Cp=[m.SUCCESS,m.GENERIC_FAILURE,m.USAGE,m.NOT_FOUND,m.CONFLICT,m.DEPENDENCY_FAILED],Lk=new Set(["close-many","update-many"]),Rp=Xe.map(e=>({command:e,exit_codes:Lk.has(e)?[...Cp,m.NO_EFFECT,m.PARTIAL_EFFECT]:[...Cp]})),xp=new Map(Rp.map(e=>[e.command,e])),Dk=[m.SUCCESS,m.NO_EFFECT,m.PARTIAL_EFFECT];function IF(e){return Dk.includes(e)}function CF(e){return vo.some(t=>t.exit_code===e)}function Op(e){let t=e.trim().toLowerCase().split(/\s+/u).filter(Boolean).join(" ");return xp.get(t)??xp.get(t.split(" ")[0])}function xF(e,t=Xe,n=Rp){let i=new Map(n.map(c=>[c.command,c])),r=t.filter(c=>!i.has(c)),s=e.filter(c=>{let d=i.get(c.command)??i.get(c.command.split(" ")[0]);return d===void 0||!d.exit_codes.includes(c.exit_code)}),a=new Set(e.map(c=>c.exit_code)),o=[...new Set(n.flatMap(c=>c.exit_codes))].filter(c=>!a.has(c)).sort((c,d)=>c-d);return{ok:r.length===0&&s.length===0&&o.length===0,missing_commands:r,undeclared_observations:s,unreachable_exit_codes:o}}function RF(e){return e.applied===0&&e.failed>0?{outcome:"dependency_failed",exit_code:m.DEPENDENCY_FAILED}:e.applied===0?{outcome:"no_effect",exit_code:m.NO_EFFECT}:e.skipped>0||e.failed>0||e.unmatched>0?{outcome:"partial_effect",exit_code:m.PARTIAL_EFFECT}:{outcome:"effect",exit_code:m.SUCCESS}}(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]="081bf1eb-4b9a-5fa9-a272-34ae781d250c")}catch{}})();var M=class extends TypeError{constructor(t){super(t),this.name="AssuranceMutationRefusalError"}},Le=class extends TypeError{context;constructor(t,n={}){super(t),this.name="AssuranceEvaluationRefusalError",this.context=n}},Ze=class extends TypeError{measurement_id;source_kind;field;check;constructor(t,n){super(t),this.name="AssuranceSourceResolutionError",this.measurement_id=n.measurement_id,this.source_kind=n.source_kind,this.field=n.field,this.check=n.check}};async function gn(e){try{return await e()}catch(t){throw t instanceof M?new _(t.message,m.USAGE,{code:"invalid_argument_value",reason:"assurance_mutation_refused"}):t}}async function Lp(e){try{return await e()}catch(t){throw t instanceof Le?new _(t.message,m.USAGE,{code:"invalid_argument_value",reason:"assurance_evaluation_refused",...t.context}):t}}import{createHash as Nk}from"node:crypto";import Mk 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]="b00dcab2-22c6-55b7-b93d-f6f5413d4b04")}catch{}})();var hn=1e3;(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]="416aaf09-e4f6-5d10-aee0-eba374f1cd83")}catch{}})();var Np=1,lt=["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"],ei=["items","dependency_kind","prose_edge_gap","graph","validate","health","history","links","provider","derived"],Pk=["ceiling","floor","equals","zero","monotone_nondecreasing","monotone_nonincreasing","subset_of"],Fk=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,Lr=30,Dr=5e3,Mp=4,$k=50;function ut(e,t){if(!Fk.test(e))throw new M(`${t} must be a stable lowercase id`)}function Uk(e,t){if(!Number.isFinite(e)||e<0)throw new M(`${t} must be a finite non-negative number`)}function ti(e){let t=Pk.filter(r=>e[r]!==void 0);if(t.length!==1)throw new M(`assertion ${e.id} must declare exactly one polarity`);let n=t[0],i=e[n];return{polarity:n,value:n==="zero"?0:i}}function bo(e,t){return ie(e)===ie(t)}function Pp(e,t){if(t.polarity==="equals")return bo(e,t.value);if(t.polarity==="subset_of"){if(!Array.isArray(e)||!Array.isArray(t.value))return!1;let i=t.value;return e.every(r=>i.includes(r))}if(typeof e!="number")return!1;let n=t.value;return t.polarity==="ceiling"||t.polarity==="monotone_nonincreasing"?e<=n:t.polarity==="floor"||t.polarity==="monotone_nondecreasing"?e>=n:e===0}function Fp(e){let t=ti(e),n=e.negative_control.cases;return n.some(i=>i.expected==="pass")&&n.some(i=>i.expected==="fail")&&n.every(i=>Pp(i.observed,t)===(i.expected==="pass"))}function jk(e,t){if(e.polarity!==t.polarity)return!0;if(typeof e.value=="number"&&typeof t.value=="number")return e.polarity==="ceiling"||e.polarity==="monotone_nonincreasing"?t.value>e.value:e.polarity==="floor"||e.polarity==="monotone_nondecreasing"?t.value<e.value:t.value!==e.value;if(e.polarity==="subset_of"){let n=e.value,i=t.value;return!Array.isArray(n)||!Array.isArray(i)||i.some(r=>!n.includes(r))}return!bo(e.value,t.value)}function Gk(e,t){if(e.measurement_id!==t.measurement_id||e.owner_item_id!==t.owner_item_id||ie(e.scope)!==ie(t.scope))return!0;let n={observe:0,warn:1,block:2},i=(e.lifetime??"hold")==="hold"&&(t.lifetime??"hold")==="retire";return jk(ti(e),ti(t))||n[t.enforcement]<n[e.enforcement]||i}function qk(e){if(e.state!==void 0&&!(e.state==="present"||e.state==="missing"))throw new M("items source state must be present or missing");let t=Object.hasOwn(e,"equals"),n=e.state!==void 0,i=Number(t)+Number(n);if(e.field!==void 0&&i!==1)throw new M("items source with field requires exactly one of equals or state");if(e.field===void 0&&i!==0)throw new M("items source equals/state requires field")}function Kk(e){if(typeof e.dependency_kind!="string"||e.dependency_kind.trim().length===0)throw new M("dependency_kind source requires dependency_kind");if([e.source_kind,e.source_kind_prefix,e.source_kind_state].filter(t=>t!==void 0).length>1)throw new M("dependency_kind source accepts at most one source_kind predicate");if(e.source_kind!==void 0&&e.source_kind.trim().length===0||e.source_kind_prefix!==void 0&&e.source_kind_prefix.trim().length===0)throw new M("dependency_kind source provenance values must not be empty");if(e.source_kind_state!==void 0&&e.source_kind_state!=="present"&&e.source_kind_state!=="missing")throw new M("dependency_kind source source_kind_state must be present or missing")}function zk(e){if(e.sample_limit!==void 0&&(!Number.isInteger(e.sample_limit)||e.sample_limit<1))throw new M("prose_edge_gap sample_limit must be a positive integer");for(let t of e.exemptions??[]){if(typeof t.holder_id!="string"||t.holder_id.trim().length===0||typeof t.reason!="string"||t.reason.trim().length===0)throw new M("prose_edge_gap exemptions require holder_id and reason");if(t.target_id!==void 0&&t.target_id.trim().length===0||t.text_contains!==void 0&&t.text_contains.trim().length===0)throw new M("prose_edge_gap exemption selectors must not be empty")}}function ko(e){ut(e.id,"measurement.id"),e.max_cost!==void 0&&Uk(e.max_cost,"measurement.max_cost");let t=e.source;if(Object.prototype.toString.call(t)!=="[object Object]")throw new M(`measurement.source.kind must be one of ${ei.join(", ")}`);let n=Reflect.get(t,"kind");if(!ei.includes(n))throw new M(`measurement.source.kind must be one of ${ei.join(", ")}`);let i=t;if(i.kind==="items"&&qk(i),i.kind==="dependency_kind"&&Kk(i),i.kind==="prose_edge_gap"&&zk(i),(i.kind==="graph"||i.kind==="validate"||i.kind==="health")&&(typeof i.field!="string"||i.field.trim().length===0))throw new M(`${i.kind} source requires field`);return i.kind==="provider"&&(ut(i.provider,"provider source provider"),ut(i.key,"provider source key")),e}function Eo(e){if(ut(e.id,"assertion.id"),ut(e.measurement_id,"assertion.measurement_id"),typeof e.owner_item_id!="string"||e.owner_item_id.trim().length===0)throw new M("assertion.owner_item_id is required");let t=ti(e);if(typeof t.value=="number"&&!Number.isFinite(t.value))throw new M(`assertion.${t.polarity} must be a finite number`);if(e.lifetime==="retire"&&(typeof e.retire_reason!="string"||e.retire_reason.trim().length===0))throw new M("retired assertion requires retire_reason");e.scope.kind==="filter"&&ut(e.scope.measurement_id,"assertion.scope.measurement_id");let n=e.negative_control?.cases;if(!Array.isArray(n)||!n.some(i=>i.expected==="pass")||!n.some(i=>i.expected==="fail"))throw new M("assertion negative control requires pass and fail cases");if(!Fp(e))throw new M(`assertion ${e.id} negative control does not prove its bound`);return e}function Wk(e){if(!Array.isArray(e.allowed_providers))throw new M("gate provider_policy.allowed_providers must be an array");for(let t of e.allowed_providers)ut(t,"gate.provider_policy.allowed_provider");if(typeof e.triggers!="object"||e.triggers===null||Array.isArray(e.triggers))throw new M("gate provider_policy.triggers must be an object");for(let[t,n]of Object.entries(e.triggers)){if(!lt.includes(t))throw new M(`gate provider policy has unknown trigger ${t}`);if(typeof n!="object"||n===null||!["low","medium","high"].includes(n.max_cost_class)||typeof n.allow_network!="boolean")throw new M(`gate provider policy trigger ${t} is invalid`)}}function $p(e){if(ut(e.id,"gate.id"),!Array.isArray(e.assertion_ids))throw new M("gate.assertion_ids is required and must be an array");if(e.assertion_ids.length===0)throw new M("gate requires at least one assertion");for(let t of e.assertion_ids)ut(t,"gate.assertion_id");if(!Array.isArray(e.triggers))throw new M(`gate.triggers is required and must be an array of ${lt.join(", ")}`);if(e.triggers.length===0)throw new M("gate requires at least one trigger");for(let t of e.triggers)if(!lt.includes(t))throw new M(`gate trigger must be one of ${lt.join(", ")}`);return e.provider_policy&&Wk(e.provider_policy),e}function yn(e){if(e.version!==Np)throw new M(`unsupported assurance document version ${String(e.version)}`);let t=new Set;for(let i of e.measurements){if(ko(i),t.has(`measurement:${i.id}`))throw new M(`duplicate measurement ${i.id}`);t.add(`measurement:${i.id}`)}for(let i of e.assertions){if(Eo(i),t.has(`assertion:${i.id}`))throw new M(`duplicate assertion ${i.id}`);t.add(`assertion:${i.id}`)}for(let i of e.gates){$p(i);let r=i.assertion_ids.filter(s=>!e.assertions.some(a=>a.id===s));if(r.length>0)throw new M(`gate ${i.id} references missing assertions: ${r.join(", ")}`);if(t.has(`gate:${i.id}`))throw new M(`duplicate gate ${i.id}`);t.add(`gate:${i.id}`)}let n=new Set(e.measurements.map(i=>i.id));for(let[i,r]of Up(e))if(!n.has(i))throw new M(`${r.join(", ")} references missing measurement ${i}`);return e}function So(e,t){if("measurement"in e){t.push(e.measurement);return}if("operator"in e)for(let n of e.operands)So(n,t)}function Up(e){let t=new Map,n=(i,r)=>{let s=t.get(i)??[];s.push(r),t.set(i,s)};for(let i of e.assertions)n(i.measurement_id,`assertion ${i.id}`),i.scope.kind==="filter"&&n(i.scope.measurement_id,`assertion ${i.id} scope`);for(let i of e.measurements){if(i.source.kind!=="derived")continue;let r=[];So(i.source.expression,r);for(let s of r)n(s,`derived measurement ${i.id}`)}return t}function Bk(e,t){let n=e.assertion_ids.flatMap(s=>{let a=t.assertions.find(o=>o.id===s);return[a.measurement_id,...a.scope.kind==="filter"?[a.scope.measurement_id]:[]]}),i=new Set,r=new Set;for(;n.length>0;){let s=n.pop();if(i.has(s))continue;i.add(s);let a=t.measurements.find(o=>o.id===s);a.source.kind==="provider"?r.add(a.source.provider):a.source.kind==="derived"&&So(a.source.expression,n)}return r}function ni(){return{version:Np,measurements:[],assertions:[],gates:[]}}function Hk(e,t){let n=t.items.filter(i=>(e.statuses===void 0||e.statuses.includes(i.status))&&(e.types===void 0||e.types.includes(i.type))&&(e.tags===void 0||e.tags.every(r=>i.tags?.includes(r)))&&(e.field===void 0||(()=>{let r=i[e.field];if(e.state!==void 0){let s=r==null||r===""||Array.isArray(r)&&r.length===0;return e.state==="missing"?s:!s}return bo(r,e.equals)})()));return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(i=>i.id)}}function Vk(e,t){return e.source_kind!==void 0?t?.toLowerCase()===e.source_kind.trim().toLowerCase():e.source_kind_prefix!==void 0?t?.toLowerCase().startsWith(e.source_kind_prefix.trim().toLowerCase())===!0:e.source_kind_state==="present"?t!==void 0&&t.length>0:e.source_kind_state==="missing"?t===void 0||t.length===0:!0}function Yk(e,t){let n=[],i=Da(e.dependency_kind)??e.dependency_kind.trim().toLowerCase();for(let r of t.items)for(let s of r.dependencies??[]){let a=Da(s.kind)??s.kind.trim().toLowerCase(),o=s.source_kind?.trim();a===i&&Vk(e,o)&&n.push(`${r.id}->${s.id}${o?`@${o}`:""}`)}return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n}}function Jk(e){let t=[e.description,e.body].filter(n=>typeof n=="string").map(n=>n.trim()).filter(Boolean);for(let n of["comments","notes","learnings"]){let i=e[n];if(Array.isArray(i)){for(let r of i)if(typeof r=="string")t.push(r);else if(typeof r=="object"&&r!==null){let s=Reflect.get(r,"text");typeof s=="string"&&t.push(s)}}}return t}function Xk(e,t,n,i){return e.some(r=>r.holder_id.trim().toLowerCase()===t.toLowerCase()&&(r.target_id===void 0||r.target_id.trim().toLowerCase()===n.toLowerCase())&&(r.text_contains===void 0||i.toLowerCase().includes(r.text_contains.trim().toLowerCase())))}function wo(e,t){return[e.toLowerCase(),t.toLowerCase()].sort().join("\0")}function Qk(e){let t=new Map,n=new Set,i=[],r=/(?<![\w-])[a-z0-9]+(?:-+[a-z0-9]+)+(?![\w-])/giu,s=0;for(let a of e){t.set(a.id.toLowerCase(),a.id);for(let o of a.dependencies??[])n.add(wo(a.id,o.id));for(let o of[a.parent,a.blocked_by])typeof o=="string"&&n.add(wo(a.id,o));for(let o of Jk(a)){let c=[...o.matchAll(r)].map(d=>d[0]);s+=c.length,i.push({holder_id:a.id,segment:o,mentioned_ids:c})}}return{canonical_ids:t,linked_pairs:n,prose_mentions:i,mention_count:s}}function Zk(e,t){let n=Qk(t.items),i=new Map;for(let a of n.prose_mentions){let o=a.mentioned_ids.map(d=>n.canonical_ids.get(d.toLowerCase())).filter(d=>d!==void 0&&d!==a.holder_id),c=[...new Set(o)];for(let d of c){let l=wo(a.holder_id,d);if(n.linked_pairs.has(l)||Xk(e.exemptions??[],a.holder_id,d,a.segment))continue;let u=c.some(p=>p!==d);i.get(l)?.explicit===!0&&!u||i.set(l,{contributor:`${a.holder_id}->${d}|subject=${u?"explicit":"implicit"}`,explicit:u})}}let r=[...i.values()],s=r.map(a=>a.contributor).sort();return{value:s.length,population_size:n.canonical_ids.size,cost:t.items.length+n.linked_pairs.size+n.mention_count,contributors:s.slice(0,e.sample_limit??25),partitions:{explicit_subject:r.filter(a=>a.explicit).length,implicit_subject:r.filter(a=>!a.explicit).length}}}function e0(e,t){return{value:t.history.filter(n=>(e.op===void 0||n.op===e.op)&&(e.author===void 0||n.author===e.author)&&(e.harness===void 0||n.agent_harness===e.harness)&&(e.model===void 0||n.agent_model===e.model)).length,population_size:t.history.length,cost:t.history.length}}function t0(e,t){let n=t.items.filter(i=>{let r=i[e.link],s=Array.isArray(r)&&r.length>0;return e.state==="present"?s:!s});return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(i=>i.id)}}function n0(e,t){let n=e.source;return n.kind==="items"?Hk(n,t):n.kind==="dependency_kind"?Yk(n,t):n.kind==="prose_edge_gap"?Zk(n,t):n.kind==="history"?e0(n,t):n.kind==="links"?t0(n,t):null}function jp(e,t){return e.reduce((n,i)=>({units:n.units+i.units,items_scanned:n.items_scanned+i.items_scanned,history_entries:n.history_entries+i.history_entries,provider_calls:n.provider_calls+i.provider_calls,duration_ms:t}),{units:0,items_scanned:0,history_entries:0,provider_calls:0,duration_ms:t})}function i0(e,t){if(t.length===0)throw new TypeError(`derived ${e} requires operands`);if(e==="add")return t.reduce((n,i)=>n+i,0);if(e==="subtract")return t.slice(1).reduce((n,i)=>n-i,t[0]);if(e==="multiply")return t.reduce((n,i)=>n*i,1);if(e==="divide"){if(t.slice(1).includes(0))throw new TypeError("derived divide cannot divide by zero");return t.slice(1).reduce((n,i)=>n/i,t[0])}return e==="min"?Math.min(...t):Math.max(...t)}async function Gp(e,t,n){let i=new Array(e.length),r=0,s=Array.from({length:Math.min(t,e.length)},async()=>{for(;r<e.length;){let a=r;r+=1,i[a]=await n(e[a],a)}});return await Promise.all(s),i}async function qp(e,t,n,i,r){if("literal"in e)return{value:e.literal,costs:[],population_size:0,contributors:[]};if("measurement"in e){let a=n.find(d=>d.id===e.measurement);if(!a)throw new TypeError(`derived measurement references missing ${e.measurement}`);let o=await Kp(a,t,n,i,r);if(typeof o.value!="number")throw new TypeError(`derived measurement ${a.id} is not numeric`);let c=r.charged.has(a.id)?[]:[o.cost];return r.charged.add(a.id),{value:o.value,costs:c,population_size:o.population_size,contributors:o.contributors}}let s=await Gp(e.operands,Mp,a=>qp(a,t,n,i,r));return{value:i0(e.operator,s.map(a=>a.value)),costs:s.flatMap(a=>a.costs),population_size:Math.max(0,...s.map(a=>a.population_size)),contributors:[...new Set(s.flatMap(a=>a.contributors))]}}async function r0(e,t,n,i,r){ko(e);let s=Date.now(),a,o=[],c=0;if(e.source.kind==="derived"){let u=await qp(e.source.expression,t,n,[...i,e.id],r);a={value:u.value,population_size:u.population_size,cost:0,contributors:u.contributors},o=u.costs}else{let u=n0(e,t);u!==null?a=u:(a=await t.external(e.source),c=1)}let d={units:a.cost,items_scanned:e.source.kind==="items"||e.source.kind==="dependency_kind"||e.source.kind==="prose_edge_gap"||e.source.kind==="links"?t.items.length:0,history_entries:e.source.kind==="history"?t.history.length:0,provider_calls:c,duration_ms:Date.now()-s},l=jp([...o,d],Date.now()-s);if(e.max_cost!==void 0&&l.units>e.max_cost)throw new Le(`measurement ${e.id} exceeded cost ceiling ${e.max_cost} with ${l.units}`);return{id:e.id,definition_fingerprint:`sha256:${Nk("sha256").update(ie(e)).digest("hex")}`,value:a.value,population_size:a.population_size,cost:l,contributors:a.contributors??[],...a.partitions?{partitions:a.partitions}:{}}}function Kp(e,t,n,i,r){if(i.includes(e.id))throw new TypeError(`derived measurement cycle: ${[...i,e.id].join(" -> ")}`);let s=r.cache.get(e.id);if(s)return s;let a=r0(e,t,n,i,r).catch(o=>{if(o instanceof Ze&&o.measurement_id===void 0){let c={measurement_id:e.id,source_kind:o.source_kind,field:o.field,...o.check?{check:o.check}:{}},d=new Ze(o.message,c);throw d.cause=o,d}throw o});return r.cache.set(e.id,a),a}async function To(e,t,n=[e]){return Kp(e,t,n,[],{cache:new Map,charged:new Set})}function s0(e,t){return typeof e!="number"||typeof t.value!="number"?null:t.polarity==="ceiling"||t.polarity==="monotone_nonincreasing"?t.value-e:(t.polarity==="floor"||t.polarity,e-t.value)}function a0(e,t,n={}){Eo(e);let i=ti(e),r=e.lifetime==="retire"&&n.owner_terminal===!0;return{assertion_id:e.id,measurement_id:e.measurement_id,measurement_definition_fingerprint:t.definition_fingerprint,scope:e.scope,population_size:t.population_size,observed:t.value,bound:i,distance:s0(t.value,i),verdict:r?"retired":Pp(t.value,i)?"pass":"fail",enforcement:e.enforcement,negative_control_proven:Fp(e),cost:t.cost,contributors:t.contributors,...t.partitions?{partitions:t.partitions}:{}}}function o0(e,t,n,i){let r=Bk(e,t);if(r.size===0)return;let s=e.provider_policy,a=s?.triggers[i];if(!s||!a)throw new Le(`assurance gate ${e.id} refuses provider execution at trigger ${i} without an explicit provider policy`);let o=new Set(s.allowed_providers),c={low:0,medium:1,high:2};for(let d of r){if(!o.has(d))throw new Le(`assurance gate ${e.id} refuses provider ${d}`);let l=n.provider_capabilities?.[d];if(!l)throw new Le(`assurance provider ${d} has no declared capabilities`);if(c[l.cost_class]>c[a.max_cost_class])throw new Le(`assurance gate ${e.id} refuses ${l.cost_class}-cost provider ${d} at trigger ${i}`);if(l.network&&!a.allow_network)throw new Le(`assurance gate ${e.id} refuses network provider ${d} at trigger ${i}`)}}async function Dp(e,t,n,i,r){try{return await To(n,i,r)}catch(s){if(s instanceof Ze){let a=s.check?` check ${s.check}`:"",o=s.measurement_id??n.id,c=new Le(`assurance gate ${e} assertion ${t} measurement ${o} source ${s.source_kind}${a} field ${s.field} could not resolve: ${s.message}`,{gate_id:e,assertion_id:t,measurement_id:o,source_kind:s.source_kind,field:s.field,...s.check?{check:s.check}:{}});throw c.cause=s,c}throw s}}async function zp(e,t,n,i){yn(t);let r=t.gates.find(c=>c.id===e);if(!r)throw new Le(`assurance gate ${e} not found`);if(!r.triggers.includes(i.trigger))throw new Le(`assurance gate ${e} does not declare trigger ${i.trigger}`);o0(r,t,n,i.trigger);let s=await Gp(r.assertion_ids,Mp,async c=>{let d=t.assertions.find(f=>f.id===c),l=t.measurements.find(f=>f.id===d.measurement_id),u=n;if(d.scope.kind==="active"){let f=new Set(n.terminal_statuses??["closed","canceled"]);u={...n,items:n.items.filter(h=>!f.has(h.status))}}else if(d.scope.kind==="filter"){let f=d.scope.measurement_id,h=t.measurements.find(w=>w.id===f),y=await Dp(r.id,d.id,h,n,t.measurements),v=new Set(y.contributors);u={...n,items:n.items.filter(w=>v.has(w.id))}}let p=n.items.find(f=>f.id===d.owner_item_id),g=p!==void 0&&new Set(n.terminal_statuses??["closed","canceled"]).has(p.status);return a0(d,await Dp(r.id,d.id,l,u,t.measurements),{owner_terminal:g})}),a=s.some(c=>c.verdict==="fail"&&c.enforcement==="block"),o=s.some(c=>c.verdict==="fail"&&c.enforcement==="warn");return{gate_id:r.id,tree_id:n.tree_id,trigger:i.trigger,dry_run:i.dry_run===!0,evaluated_at:new Date().toISOString(),verdict:a?"block":o?"warn":"pass",exit_code:a?1:0,assertions:s,assertions_total:s.length,row_contract:{row_keys:["assertions"],jq_selector:".assertions[]"},cost:jp(s.map(c=>c.cost),Math.max(0,...s.map(c=>c.cost.duration_ms)))}}function Nr(e){return Mk.join(e,"assurance.json")}async function Wp(e){let t=await Q(Nr(e));return t===null?ni():Mr(t)}function Mr(e){try{return yn(JSON.parse(e))}catch(t){throw new _("The assurance registry is invalid. Repair or restore .agents/pm/assurance.json and retry.",m.GENERIC_FAILURE,{code:"assurance_registry_invalid",reason:String(t),nextSteps:["Restore a valid assurance.json from version control or repair its declaration references.","Run pm assurance list measurement after the repair."]})}}function Pr(e,t){return t==="measurement"?e.measurements:t==="assertion"?e.assertions:e.gates}function c0(e,t){e==="measurement"?ko(t):e==="assertion"?Eo(t):$p(t)}async function ii(e,t){let n=structuredClone(Pr(await Wp(e),t));return{items:n,count:n.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function Ao(e,t,n){let i=Pr(await Wp(e),t).find(r=>r.id===n);if(!i)throw new TypeError(`assurance ${t} ${n} not found`);return structuredClone(i)}async function Fr(e,t,n,i={}){c0(t,n);let r=await I(e),s=U(i.author,r.author_default),a=await on({pmRoot:e,filePath:Nr(e),op:`assurance:${t}:put`,author:s,message:i.message,lockTtlSeconds:Lr,lockWaitMs:Dr,mutate:o=>{let c=o===null?ni():Mr(o),d=Pr(c,t),l=d.findIndex(p=>p.id===n.id),u=l<0?"created":"updated";if(t==="assertion"&&l>=0&&Gk(d[l],n)){let p=n.authorization_decision;if(!p||!i.authorized_decision_ids?.includes(p))throw new M(`loosening assertion ${n.id} requires a verified authorization_decision`)}return l<0?d.push(structuredClone(n)):d[l]=structuredClone(n),yn(c),{raw:`${JSON.stringify(c,null,2)}
|
|
3
|
-
`,result:{changed:!0,action:u,kind:t,id:n.id}}}});return{...a.result,changed:a.changed}}async function
|
|
4
|
-
`,result:{changed:d.length>0,created_ids:d,unchanged_ids:l}}}});return{...a.result,changed:a.changed}}async function
|
|
5
|
-
`,result:{changed:!0,action:"removed",kind:t,id:n}}}});return{...a.result,changed:a.changed}}async function Hp(e,t,n={}){if(t.dry_run)throw new TypeError("dry-run assurance verdicts are not persisted");let i=await I(e);await an({pmRoot:e,op:"assurance:gate:verdict",author:U(n.author,i.author_default),context:{assurance_verdict:t},message:n.message??`Assurance gate ${t.gate_id} returned ${t.verdict}`,lockTtlSeconds:Lr,lockWaitMs:Dr})}async function Vp(e,t={}){let n=t.limit??$k;if(!Number.isInteger(n)||n<1||n>hn)throw new TypeError(`assurance verdict limit must be an integer from 1 through ${hn}`);return(await ct(Kn(e),Mt)).reverse().filter(i=>i.op==="assurance:gate:verdict").map(i=>i.context?.assurance_verdict).filter(i=>typeof i=="object"&&i!==null&&"gate_id"in i).filter(i=>t.gate_id===void 0||i.gate_id===t.gate_id).slice(0,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]="16979f9d-779a-595a-abe8-94430fb470d5")}catch{}})();var d0=uo("list").properties.outputSession,l0={outputInclude:{type:"string",minLength:1,description:"Comma-separated fields or sections retained by any built-in read action."},outputLimit:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}],description:"Universal read row ceiling, or unbounded to disable the shared ceiling."},outputBudget:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}],description:"Universal estimated-token ceiling, or unbounded to return the complete read result."},outputFormat:{type:"string",enum:["json","toon"],description:"Universal read-result encoding selector."},outputSession:{...d0},outputCursor:{type:"string",minLength:1,description:"Opaque continuation cursor returned after budget compaction of a declared row collection."}},Yp={definition:{anyOf:[{type:"object"},{type:"string"}],description:"Policy declaration for policy-put, or proposed metadata for policy-check; structured JSON or JSON text."},policy:{type:"string",description:"Approval policy id for policy-approve."},message:{type:"string",description:"History explanation for policy mutations and approvals."},dryRun:{type:"boolean",description:"Preview registry changes without writing; policy-approve rejects previews."}},Jp={type:"object",properties:{cwd:{type:"string",description:"Workspace directory to run the native pm operation in. Defaults to the MCP server process cwd."},path:{type:"string",description:"Optional pm data root, equivalent to PM_PATH/global --path. Leave unset for real repository tracking."},author:{type:"string",description:"Optional mutation author override. Otherwise pm uses PM_AUTHOR, project settings, or detected harness identity."},tokenAccounting:{type:"boolean",description:"Attach the same bounded per-section token-cost receipt emitted by CLI --token-accounting."}},additionalProperties:!0},le={type:"string",description:"pm item id, for example pm-abc1."},u0=`Operation name (one of): ${Ga.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,m0={status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."},offset:{type:["string","number"],description:"Alias for options.offset."}},_0={mode:{type:"string",description:"Alias for options.mode."},status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."}};function z(e,t=[]){return{...Jp,properties:{...Jp.properties,...e},required:t}}var p0=[{name:"pm_run",description:"Run any supported pm operation natively through the pm library. Use this for commands not covered by narrower pm_* tools.",inputSchema:z({action:{type:"string",enum:[...Ga],description:u0},id:le,query:{type:"string",description:"Search query for action=search."},reason:{type:"string",description:"Close reason for action=close."},force:{type:"boolean",description:"Force ownership/terminal-state override when supported."},subcommand:{type:"string",description:"Subcommand selector for actions that take one (for example telemetry, or schema \u2014 prefer the dedicated pm_schema tool for schema operations)."},options:{type:"object",description:"Underlying pm command options using camelCase keys."},fullChangedFields:{type:"boolean",description:"For mutation actions, return the full changed_fields array instead of the default changed_field_count."},idOnly:{type:"boolean",description:"For single-item mutation actions, return only id and status."},...l0},["action"])},{name:"pm_discover",description:"Discover the smallest relevant authorized pm tool catalog under an explicit token budget. Ranking is deterministic and returns public lexical, semantic, graph, permission, freshness, and usage signal explanations. Continue with next_cursor; set includeSchema=true only when complete input schemas are needed.",inputSchema:z({query:{type:"string",maxLength:4096,description:"Free-text capability intent. Empty text lists by stable policy order."},family:{type:"string",enum:["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"],description:"Optional stable capability-family filter."},tier:{type:"string",enum:["core","standard","full"],description:"Maximum command visibility tier included in results."},limit:{type:"integer",minimum:1,maximum:100,description:"Maximum result rows; defaults to 10."},cursor:{type:"string",minLength:1,maxLength:4096,description:"Opaque next_cursor from an equivalent discovery request."},includeSchema:{type:"boolean",description:"Include complete tool input schemas; false by default."},outputBudget:{anyOf:[{type:"integer",minimum:128},{const:"unbounded"}],description:"Estimated-token ceiling; defaults to 1200."}})},{name:"pm_context",description:"Return the agent-oriented project context snapshot. Pass options.depth=brief|standard|deep|full (full = every section with no per-section row cap), options.parent='<id>' to scope the snapshot to one item's subtree (the item plus all descendants), options.fields='id,title,priority' to project focus rows to a field subset for low-token reads, or options.section=['hierarchy','progress',...] to pick sections.",inputSchema:z({options:{type:"object"}})},{name:"pm_next",description:"Recommend the next actionable work item: the single highest-priority READY item (active status, no open blockers, no open children; completed containers surface only when no concrete leaf work is ready) plus the ranked ready and blocked queues. The recommended item carries a rationale and each blocked item lists the open blockers gating it. Pass options.parent='<id>' to scope to one subtree, options.limit=N to cap ready rows, options.readyOnly=true to omit the blocked list, or filters (options.type/tag/priority/assignee/sprint/release). The most token-efficient 'what should I do now?' read for agents.",inputSchema:z({options:{type:"object"}})},{name:"pm_search",description:"Search pm items with keyword, semantic, or hybrid search. Defaults to a compact projection for token efficiency. Pass options.mode=keyword|semantic|hybrid (default follows search.default_mode: auto runs hybrid when semantic search is configured and runnable, else keyword; the result reports mode_source), options.limit=N to cap hits, options.status='all' for no lifecycle restriction, options.fields='id,title,score' for a custom projection, or options.full=true for full item bodies (can be large). The result echoes the applied filters and projection mode in query_summary.",inputSchema:z({query:{type:"string"},options:{type:"object"},..._0},["query"])},{name:"pm_list",description:"List pm items with status/type/tag/priority filters. Defaults to compact projection for token efficiency. options.status accepts CSV (all,open,in_progress). Pass options.compact=false or options.includeBody=true for full bodies/comments. Pass options.brief=true for ultra-terse (id/status/type/title only). Pass options.fields='id,title,priority' for custom projection. Pass options.limit=N to cap row count. The result echoes the applied filters and projection mode in query_summary.",inputSchema:z({options:{type:"object"},...m0})},{name:"pm_get",description:"Read one pm item with shared SDK projections. Pass options.depth='brief' or options.fields='id,title,status' for low-token inspection, options.fields='id,schedule.start_at' for schedule context, or options.at='7' / an ISO timestamp for a verified mutation-free historical read. Parent results include bounded child counts, samples, and continuation metadata.",inputSchema:z({id:le,options:{type:"object",description:"Get options such as depth=brief|standard|deep|full, fields=id,title,status, or at=<version|ISO timestamp>."}},["id"])},{name:"pm_events",description:"Read a bounded, cursor-resumable page of committed mutation events across item history streams. Batch cursors are the token-efficient default; pass cursorMode=row for per-event checkpoints.",inputSchema:z({since:{type:"string",description:"Durable event cursor or ISO timestamp lower bound."},type:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},author:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},item:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},limit:{type:"integer",minimum:0,maximum:1e3},full:{type:"boolean"},cursorMode:{type:"string",enum:["batch","row"],description:"Cursor framing: batch returns one terminal next_cursor (default); row also adds a cursor to every event."}})},{name:"pm_create",description:"Create a pm item natively and write pm history. Output is compact by default (changed_fields replaced with changed_field_count for token efficiency); pass fullChangedFields=true for the full changed_fields array.",inputSchema:z({fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},allowMissingParent:{type:"boolean",description:"Allow unresolved parent references and emit a validation warning."},allowDuplicate:{type:"boolean",description:"Explicitly create when strict similarity governance finds likely duplicates."},options:{type:"object",description:"Create options. title and description are required."}},["options"])},{name:"pm_mutate",description:"Apply an ordered create/update/close/release batch atomically through the public pm SDK. Create rows may declare ref and omit id; @ref forward references resolve deterministically from the stable transactionId, which is derived from the batch when omitted. Bulk creation: rows shaped as {item:{title,type,...}} are create documents using pm create field names; upsertKey updates the existing item whose field matches instead of creating a duplicate. Set dryRun=true to validate and preview without writes.",inputSchema:z({transactionId:{type:"string",description:"Stable idempotency key for this atomic mutation batch; derived from the batch content when omitted."},mutations:{type:"array",minItems:1,description:"Ordered rows shaped as {op:create|update|close|release,id?,ref?,options?,reason?} or create documents {ref?,item:{...}}.",items:{type:"object",properties:{op:{type:"string",enum:["create","update","close","release"],description:"Operation; omitted rows carrying item are creates."},id:le,ref:{type:"string",description:"Batch-local create alias; its deterministic id can be referenced as @alias by any row."},reason:{type:"string"},options:{type:"object"},item:{type:"object",description:"Create document using pm create field names (title, type, description, body, tags, parent, custom fields)."},unique:{type:"object",description:"Create-only guard {key,value} re-checked under the writer lock; keyed upsert sets it on rows that matched nothing at planning time."},match:{type:"object",description:"Update-only guard {key,value} re-read under the writer lock; keyed upsert sets it on rows it converted into updates of a matched item."}},additionalProperties:!1}},upsertKey:{type:"string",description:"Item field whose value identifies an existing item to update instead of creating a duplicate."},dryRun:{type:"boolean",description:"Validate and preview without writing."},createCompensation:{type:"string",enum:["close","delete"],description:"How a failed batch compensates created items; defaults to close."},lockTtlSeconds:{type:"number"},lockWaitMs:{type:"number"}},["mutations"])},{name:"pm_copy",description:"Copy an existing pm item into a new id while resetting lifecycle fields. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:z({id:le,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object",description:"Copy options such as title override, author, and message."}},["id"])},{name:"pm_focus",description:"Set, clear, or show the session focused item. When focused, pm_create defaults its parent to the focused item (an explicit parent still overrides). Pass id to focus an item, options.clear=true to clear, or neither to show current focus.",inputSchema:z({id:le,clear:{type:"boolean",description:"Clear the focused item (cannot be combined with id)."},options:{type:"object",description:"Focus options such as clear (boolean)."}},[])},{name:"pm_update",description:"Update pm item metadata/body/dependencies/log seeds natively. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields delta.",inputSchema:z({id:le,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object"}},["id","options"])},{name:"pm_append",description:"Append markdown text to a pm item body and write pm history. Useful for seeding evidence/log entries before close. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:z({id:le,body:{type:"string",description:"Markdown text to append to the item body. Required here or as options.body."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object",description:"Append options such as body, author, and message."}},["id"])},{name:"pm_claim",description:"Claim a pm item.",inputSchema:z({id:le,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_release",description:"Release a pm item claim.",inputSchema:z({id:le,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_close",description:"Close a pm item with optional close reason and optional close validation (reason requirement follows governance settings). Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:z({id:le,reason:{type:"string",description:"Close reason text when provided or required by governance settings."},duplicateOf:{type:"string",description:"Canonical item id when closing this item as a duplicate."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object"}},["id"])},{name:"pm_comments",description:"List, add, edit, or delete comments on a pm item. Use options.add to append, options.edit=<1-based index> with replacement text to fix a comment, or options.delete=<1-based index> to remove one. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. List calls default to the most recent 20 comments with total_count/has_more metadata for token efficiency. Pass options.limit=N to choose a page size, options.limit=0 for summary-only metadata, or options.full=true for full history.",inputSchema:z({id:le,options:{type:"object"}},["id"])},{name:"pm_files",description:"List, add, remove, or validate linked files for a pm item.",inputSchema:z({id:le,options:{type:"object"}},["id"])},{name:"pm_docs",description:"List, add, or remove linked docs for a pm item.",inputSchema:z({id:le,options:{type:"object"}},["id"])},{name:"pm_notes",description:"List, add, edit, or delete structured notes on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing notes.",inputSchema:z({id:le,options:{type:"object"}},["id"])},{name:"pm_learnings",description:"List, add, edit, or delete learnings on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing learnings.",inputSchema:z({id:le,options:{type:"object"}},["id"])},{name:"pm_deps",description:"Read dependency trees/graphs or one bounded explainable relationship context packet. Use options.format=context with direction, kind, depth, node, edge, token, and cursor bounds; context returns a counts-first summary, per-node roles/reasons, root evidence pointers, and enumerated missing references.",inputSchema:z({id:le,options:{type:"object"}},["id"])},{name:"pm_graph",description:"Run bounded workspace relationship-graph queries: ancestors/descendants (hierarchy), predecessors/successors (ordering), paths, impact (blast radius), analyze (execution + knowledge analytics), audit (governance findings with change-since-baseline deltas), communities (label-propagation clusters), redundancy (transitively implied edges), dominators (structural bottlenecks), slack (critical-path method float per task), centrality (betweenness/closeness/degree with directed fan-in/out), articulation (cut points and bridges \u2014 single points of failure), plan (dry-run remediation proposals derived from the audit), and index (durable cross-process graph index status/rebuild/clear). Traversals, paths, impact, and dominators require id; paths also requires target. Options support kind, maxDepth, limit, after, direction, maxPaths, sample, exemptIsolate, exemptIsolateType, saveBaseline (audit), rebuild/clear (index), and counts-first summary.",inputSchema:z({subcommand:{type:"string",enum:[...Dl]},id:le,target:le,options:{type:"object"}},["subcommand"])},{name:"pm_test",description:"List, add, remove, or run linked tests for a pm item.",inputSchema:z({id:le,options:{type:"object"}},["id"])},{name:"pm_validate",description:"Run pm validation checks.",inputSchema:z({options:{type:"object"}})},{name:"pm_health",description:"Run pm health diagnostics. Pass options.brief=true for compact low-token details, options.skipIntegrity=true, options.skipDrift=true, options.skipVectors=true for a fast status-only check, or options.full=true for the complete deep check.",inputSchema:z({options:{type:"object"}})},{name:"pm_contracts",description:"Inspect pm command, flag, schema, and availability contracts.",inputSchema:z({options:{type:"object"}})},{name:"pm_schema",description:"Inspect or modify the workspace item-type/status/field schema (pm schema). subcommand selects the operation; name carries the item type name (show/add-type/remove-type), status id (show-status/add-status/remove-status), or field key (show-field/add-field/remove-field). apply-preset adopts a domain type preset; add-type with infer=true derives types from title-prefix conventions. Policy verbs author declarations, preview changes, set enforcement, and record content-bound approvals. Registry mutations write workspace history; approvals write item history.",inputSchema:z({...Yp,subcommand:{type:"string",enum:["list","show","show-status","add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset",...Al],description:"Schema subcommand to run."},name:{type:"string",description:"Item type name, status id, field key, policy id, or item id for the selected schema verb; policy-mode requires advise|refuse."},description:{type:"string",description:"Custom item type, status, or field description for add-type/add-status/add-field."},defaultStatus:{type:"string",description:"Default status for add-type."},folder:{type:"string",description:"Storage folder for add-type."},alias:{type:"array",items:{type:"string"},description:"Aliases for add-type/add-status, or extra CLI flag aliases for add-field."},role:{type:"array",items:{type:"string",enum:[...Ma]},description:`Lifecycle roles for add-status: ${Ma.join(", ")}.`},order:{type:"number",description:"Display/sort order for add-status."},fieldType:{type:"string",enum:["string","number","boolean","string_array"],description:"Value type for a custom field (add-field)."},commands:{type:"array",items:{type:"string"},description:"Commands a custom field is wired onto (add-field): create, update, update_many, list, search, calendar, context."},cliFlag:{type:"string",description:"Override the auto-derived CLI flag for a custom field (add-field)."},required:{type:"boolean",description:"Mark a custom field as always required (add-field)."},requiredOnCreate:{type:"boolean",description:"Mark a custom field as required at create time (add-field)."},allowUnset:{type:"boolean",description:"Whether a custom field may be cleared via --unset (add-field); defaults to true."},requiredTypes:{type:"array",items:{type:"string"},description:"Restrict a custom field's requirement to specific item types (add-field)."},typePreset:{type:"string",enum:["agile","ops","research"],description:"Domain type preset to adopt (apply-preset)."},infer:{type:"boolean",description:"Infer item types from title-prefix conventions (add-type); previews unless apply is true."},minCount:{type:"number",description:"Minimum items sharing a prefix for add-type inference (default 10)."},apply:{type:"boolean",description:"Register inferred types (add-type infer); without it the call previews only."},force:{type:"boolean",description:"Override removal guardrails for destructive schema changes when supported."},options:{type:"object",description:"Additional schema options using camelCase keys.",properties:Yp}},["subcommand"])},{name:"pm_profile",description:"List, show, apply, or lint project profiles (pm profile) \u2014 archetype bundles that stage item types, statuses, fields, per-type workflows, config knobs, create templates, and recommended packages. subcommand selects the operation; name carries the profile name (agile, ops, research) for show/apply/lint. apply stages every dimension idempotently; dryRun previews the diff without writing; lint reports author-time consistency findings (graded error/warning) without touching the tracker. Profile staging writes workspace config/schema files, not item history.",inputSchema:z({subcommand:{type:"string",enum:["list","show","apply","lint"],description:"Profile subcommand to run."},name:{type:"string",description:"Profile name for show/apply/lint. Required for those subcommands. Built-ins are agile, ops, and research; an active extension can contribute additional archetype names that resolve here too."},dryRun:{type:"boolean",description:"Preview the apply diff without writing any files (apply)."},author:{type:"string",description:"Mutation author for apply."},force:{type:"boolean",description:"Force ownership/lock override for apply."},options:{type:"object",description:"Additional profile options using camelCase keys."}},["subcommand"])},{name:"pm_config",description:"Read or write pm workspace configuration (pm config). configAction selects get/set/list/export; key/value address a single setting for get/set. scope chooses the project (default) or global settings file.",inputSchema:z({configAction:{type:"string",enum:["get","set","list","export"],description:"Config operation to perform. get/set require key; list/export dump the resolved settings surface."},key:{type:"string",description:"Settings key for get/set, for example governance-require-close-reason, telemetry-tracking, or a nested leaf such as search_provider (dash and underscore variants accepted; configAction=get without a key lists supported keys in the error)."},value:{type:"string",description:"New value for configAction=set."},scope:{type:"string",enum:["project","global"],description:"Settings scope to read or write. Defaults to project."},options:{type:"object",description:"Additional config options such as criterion, clearCriteria, format, or policy."}},["configAction"])},{name:"pm_plan",description:"Run agent-optimized Plan workflows. options.subcommand selects: create|show|add-step|update-step|complete-step|block-step|reorder-step|remove-step|link|unlink|decision|discovery|validation|resume|approve|materialize. Provide id for all non-create subcommands; provide stepRef for step lifecycle subcommands. Plans store agent-readable steps with dependencies, decisions, discoveries, validation, and resume context.",inputSchema:z({id:{type:"string",description:"Plan id (required for all subcommands except create)."},stepRef:{type:"string",description:"Step id or order for step lifecycle subcommands."},options:{type:"object",description:"Plan options including subcommand, stepRef, stepStatus, link, depth, etc."}})}],f0={pm_append:"append",pm_claim:"claim",pm_close:"close",pm_comments:"comments",pm_config:"config",pm_context:"context",pm_contracts:"contracts",pm_copy:"copy",pm_create:"create",pm_deps:"deps",pm_docs:"docs",pm_events:"events",pm_files:"files",pm_focus:"focus",pm_get:"get",pm_graph:"graph",pm_health:"health",pm_learnings:"learnings",pm_list:"list",pm_next:"next",pm_notes:"notes",pm_plan:"plan",pm_profile:"profile",pm_release:"release",pm_schema:"schema",pm_search:"search",pm_test:"test",pm_update:"update",pm_validate:"validate"},g0=p0.map(e=>{let t=f0[e.name];if(!t)return e;let n=e.inputSchema.properties,i=e.inputSchema.required.map(String);return{...e,inputSchema:uo(t,{properties:n,required:i})}});function Xp(){return g0.map(e=>{let t=e.inputSchema.required,n=Array.isArray(t)?t.map(i=>String(i)).sort((i,r)=>i.localeCompare(r)):[];return{name:e.name,description:e.description,required:n,input_schema:e.inputSchema}}).sort((e,t)=>e.name.localeCompare(t.name))}(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]="e90278b3-5dd4-553b-90f8-b1e9db75419f")}catch{}})();var Qp=new Map([["claim",["--if-available","--next","--type","--priority","--token-budget","--explain-ranking"]],["close",["--reason","--validate-close","--resolution","--expected-result","--actual-result","--message"]],["context",["--limit","--after","--depth","--section","--token-budget","--explain-ranking"]],["contracts",["--command","--flags-only","--summary","--runtime-only","--availability-only","--full"]],["create",["--title","--type","--status","--priority","--dep","--comment"]],["get",["--full","--depth","--fields","--tree","--tree-depth","--format"]],["health",["--check-only","--summary","--brief","--check-telemetry","--strict-exit","--full"]],["list",["--status","--type","--limit","--after","--brief","--fields"]],["next",["--limit","--blocked-limit","--ready-only","--token-budget","--explain-ranking","--format"]],["search",["--mode","--status","--type","--limit","--after","--fields"]],["update",["--status","--message","--dep","--comment","--file","--test"]],["validate",["--check-resolution","--check-history-drift","--check-storage-integrity","--counts","--strict-exit","--fix-hints"]]]),h0=["--limit","--after","--offset","--token-budget","--brief","--summary","--compact","--fields","--full","--format","--since","--until"],df=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]),Ur=new Set(["calendar","guide","reindex","completion","test-runs-list","test-runs-status","test-runs-logs","test-runs-stop","test-runs-resume","templates-list","templates-save","templates-show"]),Ut=new Set(["meet","event","remind","search-advanced","dedupe-audit","dedupe-merge","comments-audit","cal","calendar","completion","completion-statuses","completion-tags","completion-types","guide","reindex","normalize","templates","templates list","templates save","templates show","test-runs","test-runs list","test-runs status","test-runs logs","test-runs stop","test-runs resume"]),lf=new Map([["meet","calendar"],["event","calendar"],["remind","calendar"],["search-advanced","search-advanced"],["dedupe-audit","governance-audit"],["dedupe-merge","governance-audit"],["comments-audit","governance-audit"],["cal","calendar"],["calendar","calendar"],["completion","guide-shell"],["completion-statuses","guide-shell"],["completion-tags","guide-shell"],["completion-types","guide-shell"],["guide","guide-shell"],["reindex","search-advanced"],["normalize","governance-audit"],["templates","templates"],["templates list","templates"],["templates save","templates"],["templates show","templates"],["test-runs","linked-test-adapters"],["test-runs list","linked-test-adapters"],["test-runs status","linked-test-adapters"],["test-runs logs","linked-test-adapters"],["test-runs stop","linked-test-adapters"],["test-runs resume","linked-test-adapters"]]),uf=new Map([["calendar","calendar|cal"],["guide","guide"],["reindex","reindex"],["completion","completion"],["test-runs-list","test-runs|test-runs list"],["test-runs-status","test-runs status"],["test-runs-logs","test-runs logs"],["test-runs-stop","test-runs stop"],["test-runs-resume","test-runs resume"],["templates-list","templates|templates list"],["templates-save","templates save"],["templates-show","templates show"]]),mf=new Map([...uf.entries()].flatMap(([e,t])=>mt(t).map(n=>[n,e]))),_f=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages"]}],Ro=new Map(_f.flatMap(e=>e.aliases.map(t=>[t,e.canonical]))),y0=10,v0=20,Zp=new Map([["activity","Read activity."],["aggregate","Group counts."],["append","Append body."],["assurance","Evaluate assurance."],["assurance derive","Derive checks."],["assurance risk","Select checks for changes."],["assurance lineages","Measure recurrence coverage."],["beads","Manage Beads interoperability."],["cal","Manage calendar integration."],["calendar","Manage calendar integration."],["changelog","Generate changelog output."],["claim","Claim work."],["close","Close work."],["close-many","Close matching work."],["close-task","Close task work."],["command-kit","Inspect command authoring primitives."],["comments","Manage comments."],["comments-audit","Audit comment governance."],["completion","Generate shell completions."],["config","Manage settings."],["context","Build context."],["contracts","Inspect contracts."],["copy","Copy work."],["create","Create work."],["dedupe-audit","Audit duplicate work."],["dedupe-merge","Merge duplicate work."],["delete","Delete work."],["deps","Manage deps."],["duplicates","Find duplicate clusters."],["docs","Link docs."],["eval","Run evaluations."],["event","Manage events."],["events","Read events."],["files","Link files."],["focus","Manage focus."],["gc","Clean caches."],["get","Read item."],["graph","Query graph."],["guide","Show user guides."],["health","Check health."],["help","Show help."],["history","Inspect history."],["init","Initialize workspace."],["install","Install packages."],["item","Mutate items."],["learnings","Manage learnings."],["list","List work."],["list-all","List work across every status."],["list-blocked","List blocked work."],["list-canceled","List canceled work."],["list-closed","List closed work."],["list-draft","List draft work."],["list-in-progress","List in-progress work."],["list-open","List open work."],["meet","Record meeting context."],["merge","Manage tracker merges."],["next","Pick next work."],["notes","Manage notes."],["normalize","Normalize tracker data."],["ops","Run operations."],["package","Manage packages."],["packages","Manage packages."],["pause-task","Pause task work."],["plan","Manage plans."],["profile","Manage profiles."],["reindex","Refresh search index."],["release","Release claim."],["remind","Manage reminders."],["restore","Restore history."],["schema","Customize schema."],["search","Search work."],["search-advanced","Run advanced search."],["start-task","Start task work."],["stats","Show stats."],["telemetry","Manage telemetry."],["templates","Manage work templates."],["test","Run linked tests."],["test-all","Run all linked tests."],["test-runs","Inspect background test runs."],["todos","Manage source-code todos."],["twin","Manage repository twins."],["update","Update work."],["update-many","Update matching work."],["upgrade","Upgrade packages."],["validate","Validate data."],["vcs","Inspect version-control context."],["workspace","Manage workspaces."],["history-author-acknowledge","Acknowledge reviewed history authors."],["history-compact","Compact history."],["history-attest","Export or verify detached history proof."],["history-redact","Redact sensitive history values."],["history-repair","Repair history integrity."]]),pf=[["init",Ju],["install",Qu],["uninstall",Zu],["explore",em],["manage",am],["describe",tm],["reload",om],["doctor",cm],["catalog",dm],["adopt",lm],["adopt-all",nm],["activate",im],["deactivate",rm],["migrate",sm]],w0=[...pf.map(([e,t])=>e==="init"?[e,Xu]:[e,t]),["upgrade",Qa]],b0=[...pf.map(([e,t])=>[`extension ${e}`,t]),...w0.flatMap(([e,t])=>[[`package ${e}`,t],[`packages ${e}`,t]]),["init",Hu],["config",Vu],["extension",Yu],["package",Xa],["packages",Xa],["install",um],["create",Dm],["item mutate",Nm],["item complete",Mm],["item reopen",Pm],["copy",Fm],["focus",$m],["update",Um],["update-many",jm],["upgrade",Qa],["calendar",Za],["cal",Za],["context",eo],["ctx",eo],["get",Km],["search",Ym],["eval",Hm],["events",qm],["workspace",St],["workspace position",[]],["workspace snapshot",St],["workspace snapshot create",St],["workspace snapshot list",St],["workspace snapshot inspect",St],["workspace snapshot restore",St],["workspace snapshot delete",St],["next",Vm],["aggregate",Ou],["deps",Wm],["graph",Bm],["guide",zm],["reindex",mm],["history",Fu],["history-compact",qu],["history-attest",Ku],["history-redact",Uu],["history-repair",ju],["history-author-acknowledge",Gu],["merge",$u],["schema",zu],["profile",Wu],["plan",Bu],["restore",hm],["delete",ym],["close",_m],["close-many",pm],["append",fm],["claim",gm],["release",vm],["start-task",wm],["pause-task",bm],["close-task",km],["comments",Lu],["notes",Du],["learnings",Nu],["files",Mu],["docs",Pu],["test",Em],["test-runs-worker",[]],["test-all",Sm],["telemetry",Tm],["test-runs",Am],["gc",Im],["stats",Cm],["ops",[]],["duplicates",xm],["validate",Om],["health",Rm],["assurance",Lm],...Qm,["contracts",Jm],["completion",Xm],["activity",Gm],...[...df].map(e=>[e,Ru])],ri=new Map(b0);for(let{alias:e,canonical:t}of Ye){let n=ri.get(e);n!==void 0&&ri.set(t,n)}function k0(e){return mf.get(e)||(e.startsWith("test-runs ")?`test-runs-${e.slice(10)}`:e.startsWith("templates ")?`templates-${e.slice(10)}`:e)}function ef(e){let t=Ye.find(n=>n.alias===e);return t?`${t.canonical}|${t.alias}`:Xe.includes(e)?be(e):e.startsWith("extension-")?be(`extension ${e.slice(10)}`):e.startsWith("package-")?be(`package ${e.slice(8)}`):e.startsWith("item-")?be(`item ${e.slice(5)}`):e.startsWith("test-runs-")?be(`test-runs ${e.slice(10)}`):e.startsWith("templates-")?be(`templates ${e.slice(10)}`):Ur.has(e)?uf.get(e)??be(e):null}function E0(e,t){let n=H(t);return n!==t||Ye.some(i=>i.alias===t)?e.action===n:e.command_path===null?!1:mt(e.command_path).some(i=>i===t?!0:i.startsWith(`${t} `)||t.startsWith(`${i} `))}function mt(e){return e.split("|").map(t=>be(t)).filter(t=>t.length>0)}function S0(e,t){let n=new Set(t),i=new Set;for(let r of e)if(r.command_path)for(let s of mt(r.command_path)){let a=s.split(" ").filter(o=>o.length>0);if(a.length!==0)for(let o=a.length;o>0;o-=1){let c=a.slice(0,o).join(" ");if(n.has(c)){i.add(c);break}}}return[...i].sort((r,s)=>r.localeCompare(s))}function $r(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function si(e){let t=e.oneOf;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null):[]}function T0(e,t){if(!t)return{...e};let n=si(e).filter(i=>{let r=i.properties;if(typeof r!="object"||r===null)return!1;let s=r.action;return typeof s!="object"||s===null?!1:s.const===t});return{...e,oneOf:n}}function Co(e,t){let n=si(e).filter(i=>{let r=i.properties;if(typeof r!="object"||r===null)return!1;let s=r.action;if(typeof s!="object"||s===null)return!1;let a=s.const;return typeof a=="string"&&t.has(a)});return{...e,oneOf:n}}function be(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function ff(e){return e.replace(/\s+/g,"-")}function At(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function tf(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let i of e){let r=At(i);!r||n.has(r)||(n.add(r),t.push(r))}return t}function xo(e,t,n){n&&(e[t]=!0)}function nf(e,t){if(e==null)return null;if(typeof e!="string")throw new TypeError("Expected string for extension flag name.");let n=e.trim();return n.length===0?null:t==="long"?n.startsWith("--")&&n.length>2?Pl(n):null:n.startsWith("-")&&!n.startsWith("--")&&n.length>1?n:null}function A0(e){let t=nf(e.long,"long"),n=nf(e.short,"short"),i=t??n;if(!i)return null;let r={flag:i};n&&t&&(r.short=n),xo(r,"required",e.required===!0),xo(r,"repeatable",e.repeatable===!0),xo(r,"list",e.list===!0);let s=At(e.description);s&&(r.description=s);let a=Fl(e);r.value_arity=a.value_arity;let o=At(e.value_name)??a.value_name;o&&(r.value_name=o);let c=a.value_type??(a.value_name?"string":null);return c&&(r.value_type=c),r}function gf(e){let t=new Map;for(let i of e){let r=be(i.target_command);if(r.length===0)continue;let s=t.get(r)??{flags:[],sources:[],dedupe:new Set,sourceDedupe:new Set},a=`${i.layer}:${i.name}`;s.sourceDedupe.has(a)||(s.sourceDedupe.add(a),s.sources.push({layer:i.layer,name:i.name}));for(let o of i.flags){let c=A0(o);if(!c)continue;let d=`${c.flag}|${c.short??""}`;s.dedupe.has(d)||(s.dedupe.add(d),s.flags.push(c))}t.set(r,s)}let n=new Map;for(let[i,r]of t.entries())n.set(i,{flags:r.flags,sources:r.sources.sort((s,a)=>{let o=s.layer.localeCompare(a.layer);return o!==0?o:(s.name??"").localeCompare(a.name??"")})});return n}function I0(e,t){return e.read_output===void 0?{flags:t}:{read_output:e.read_output,flags:[...t,...Ja.filter(({flag:n})=>n.startsWith("--output-"))]}}function C0(e){let t=gf(e.flagRegistrations),n=new Map;for(let s of e.commandDefinitions){let a=be(s.command);if(a.length===0)continue;let o=At(s.action)??ff(a),c=Array.isArray(s.arguments)?s.arguments.map(d=>{let l=At(d.name);return l?{name:l,required:d.required===!0,variadic:d.variadic===!0,description:At(d.description)}:null}).filter(d=>d!==null):[];n.set(a,{...s.tier===void 0?{}:{tier:s.tier},...I0(s,t.get(a)?.flags??[]),command:a,action:o,source:{layer:s.layer,name:s.name},description:At(s.description),intent:At(s.intent),arguments:c,examples:tf(s.examples),failure_hints:tf(s.failure_hints)})}let i=new Set;for(let s of e.handlers)i.add(be(s));for(let s of n.keys())i.add(s);for(let s of t.keys())i.add(s);let r=[];for(let s of[...i].sort((a,o)=>a.localeCompare(o))){let a=n.get(s);r.push(x0(s,a,t.get(s)?.flags??[]))}return r}function x0(e,t,n){return t?{...t,flags:t.flags.length>0?t.flags:n}:{command:e,action:ff(e),source:null,description:null,intent:null,arguments:[],flags:n,examples:[],failure_hints:[]}}function R0(e){let t=e.flag.replace(/^-+/,"").trim();if(t.length===0)return null;let n=t.replace(/-([a-z0-9])/g,(i,r)=>r.toUpperCase()).replace(/[^a-zA-Z0-9]/g,"");return n.length>0?n:null}function O0(e,t){return e.variadic?{type:"array",items:{type:"string"},description:e.description??`Variadic argument '${e.name}' for extension action '${t}'.`}:{type:"string",description:e.description??`Argument '${e.name}' for extension action '${t}'.`}}function L0(e,t){let n=e.value_type??"boolean",i=n==="boolean"?"boolean":n==="number"?["number","string"]:"string",r=e.repeatable===!0||e.list===!0;return{type:r?"array":i,...r?{items:{type:i}}:{},description:e.description??`Extension option '${e.flag}' for action '${t}'.`}}function D0(e){let t=e.command.split("|").map(r=>r.trim()).filter(r=>r.length>0),n={action:{type:"string",const:e.action,description:e.intent??e.description??`Invoke extension command '${e.command}'.`}},i=["action"];for(let r of e.arguments)n[r.name]=O0(r,e.action),r.required&&i.push(r.name);for(let r of e.flags){let s=R0(r);!s||n[s]!==void 0||(n[s]=Ja.some(a=>a.flag===r.flag&&a.flag.startsWith("--output-"))?L_[s]:L0(r,e.action),r.required===!0&&i.push(s))}return{type:"object",properties:n,required:i,additionalProperties:!0,"x-extension-source":e.source,"x-extension-command":t[0]??e.command,"x-extension-commands":t}}function N0(e,t){e.description??=t.description,e.value_name??=t.value_name,e.value_type??=t.value_type,t.required===!0&&(e.required=!0),t.repeatable===!0&&(e.repeatable=!0)}function M0(e){let t=new Map;for(let n of e){let i=t.get(n.action);if(!i){t.set(n.action,{...n,flags:[...n.flags],examples:[...n.examples],failure_hints:[...n.failure_hints]});continue}i.command=[...new Set([i.command,n.command])].sort((s,a)=>s.localeCompare(a)).join("|"),i.arguments=i.arguments.length>=n.arguments.length?i.arguments:n.arguments;let r=new Set(i.flags.map(s=>`${s.flag}|${s.short??""}`));for(let s of n.flags){let a=`${s.flag}|${s.short??""}`;if(!r.has(a))r.add(a),i.flags.push(s);else{let o=i.flags.find(c=>`${c.flag}|${c.short??""}`===a);o&&N0(o,s)}}i.examples=[...new Set([...i.examples,...n.examples])],i.failure_hints=[...new Set([...i.failure_hints,...n.failure_hints])]}return[...t.values()].sort((n,i)=>n.action.localeCompare(i.action))}async function P0(e,t=I){let n={mode:Lt.extensions.policy.mode,trust_mode:Lt.extensions.policy.trust_mode,default_sandbox_profile:Lt.extensions.policy.default_sandbox_profile};if(e.noExtensions)return{handlers:new Set,disabledReason:"extensions_disabled",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};let i=x(process.cwd(),e.path);if(!await te(Ae(i)))return{handlers:new Set,disabledReason:null,commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};try{let r=await t(i),s=await Yi({pmRoot:i,settings:r,cwd:process.cwd(),noExtensions:!1}),a=await Ji({...s,loaded:s.loaded});return{handlers:new Set(a.commands.handlers.map(o=>be(o.command))),disabledReason:null,commandDefinitions:a.registrations.commands,flagRegistrations:a.registrations.flags,registrations:a.registrations,policyState:{mode:s.policy.mode,trust_mode:s.policy.trust_mode,default_sandbox_profile:s.policy.default_sandbox_profile}}}catch{return{handlers:new Set,disabledReason:"extension_runtime_probe_failed",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n}}}function F0(e,t={}){let n=new Map;for(let i of Nl){let r=Ur.has(i);if(r&&!t.includePackageOwnedActions)continue;let s=ef(i);n.set(i,{action:i,provider:r?"extension":"core",requires_extension:r,command_path:s})}if(t.includePackageOwnedActions)for(let i of Ur)n.has(i)||n.set(i,{action:i,provider:"extension",requires_extension:!0,command_path:ef(i)});for(let i of e)n.has(i.action)||n.set(i.action,{action:i.action,provider:"extension",requires_extension:!0,command_path:Ye.find(r=>r.alias===i.command)?.canonical??be(i.command)});return[...n.values()].sort((i,r)=>(i.action??"").localeCompare(r.action??""))}function $0(e,t){if(e.provider==="core"&&!e.requires_extension)return{action:e.action,invocable:!0,available:!0,requires_extension:!1,provider:"core",disabled_reason:null,command_path:e.command_path,cli_exposed:e.command_path!==null&&(!Ut.has(e.action)||t.handlers.has(e.action))};let n=e.command_path?mt(e.command_path):[],i=n.some(a=>t.handlers.has(a)||t.handlers.has(H(a))),r=n.map(a=>lf.get(H(a))).find(a=>typeof a=="string"),s=t.disabledReason===null&&i;return{action:e.action,invocable:s,available:s,requires_extension:!0,provider:"extension",disabled_reason:s?null:t.disabledReason??(r?`optional_package_not_installed:${r}`:"extension_command_not_registered"),command_path:e.command_path,cli_exposed:i,policy_state:{mode:t.policyState.mode,trust_mode:t.policyState.trust_mode,default_sandbox_profile:t.policyState.default_sandbox_profile}}}function hf(e){return ri.get(e)??xu}function U0(e){return Ut.has(H(e))?!1:ri.has(e)}function j0(e){return df.has(e)?"list":e==="cal"?"calendar":e==="ctx"?"context":e==="update-many"?"update_many":e}function rf(e){let t=e.trim();return t?t.startsWith("--")?t:t.startsWith("-")?null:`--${t}`:null}function G0(e){let t=e.trim();return!t||t.startsWith("--")?null:t.startsWith("-")?t:null}function q0(e){let t=new Map;for(let i of e.definitions){let r=rf(i.cli_flag);if(!r)continue;let s=i.cli_aliases.map(o=>G0(o)).find(o=>o!==null),a=i.cli_aliases.map(o=>rf(o)).filter(o=>o!==null&&o!==r);for(let o of i.commands){let c=t.get(o)??{flags:[],seen:new Set},d=s?{flag:r,short:s}:{flag:r},l=`${d.flag}|${d.short??""}`;c.seen.has(l)||(c.seen.add(l),c.flags.push(d));for(let u of a){let p=`${u}|`;c.seen.has(p)||(c.seen.add(p),c.flags.push({flag:u}))}t.set(o,c)}}let n=new Map;for(let[i,r]of t.entries())n.set(i,Ya(r.flags));return n}function sf(e,t){let n=[],i=new Set;for(let r of[...e,...t]){let s=`${r.flag}|${r.short??""}`;i.has(s)||(i.add(s),n.push(r))}return Ya(n)}function K0(e,t,n,i,r){let s=new Map(t);for(let{alias:a,canonical:o}of Ye){let c=t.get(o)??t.get(a);c&&(s.set(a,c),s.set(o,c))}return e.map(a=>{let o=U0(a),c=o?hf(a):[],d=n.get(j0(a))??[],l=s.get(a),u=sf(c,d),p=sf(u,l?.flags??[]),g=c.length>0&&(l?.flags.length??0)>0?"mixed":o?"core":"extension";return{command:a,flags:p,...i?{canonical_command:vf(a),visibility:yf(a,r),positionals:Au(a)?.slots??[],flag_invocations:fp(a,p)}:{},provider:g,extension_sources:l?.sources}}).sort((a,o)=>a.command.localeCompare(o.command))}function z0(e,t=Ot){let n=new Set(e),i=new Map;for(let r of _f){let s=r.aliases.filter(a=>n.has(a));i.set(r.canonical,{canonical:r.canonical,aliases:s,contracts:[]})}for(let r of t){if(!n.has(r.canonical)||r.registration==="commander"&&!n.has(r.alias))continue;let s=i.get(r.canonical)??{canonical:r.canonical,aliases:[],contracts:[]};s.aliases.includes(r.alias)||s.aliases.push(r.alias),s.contracts.push(r),i.set(r.canonical,s)}return[...i.values()].map(({contracts:r,...s})=>r.length===0?s:{...s,contracts:r}).sort((r,s)=>r.canonical.localeCompare(s.canonical))}function W0(){return{create_string_options:M_,create_repeatable_options:P_,update_string_options:Ir,update_repeatable_options:$_,list_string_options:Zm,search_string_options:e_,calendar_string_options:t_,context_string_options:n_,activity_string_options:i_}}function af(e,t){let n=new Set(["title","type"]);if(t==="strict"){for(let o of e.required_create_fields)n.add(o);for(let o of e.required_create_repeatables)n.add(o)}let i=nn(e,"create",n),r=[...new Set(i.required)].sort((o,c)=>o.localeCompare(c)),s=[...new Set(r.map(o=>Te("create",o)))].sort((o,c)=>o.localeCompare(c)),a=[...new Set(e.options.filter(o=>o.required===!0).map(o=>o.key))].sort((o,c)=>o.localeCompare(c));return{required_option_keys:r,required_flags:s,required_type_options:a,policy_errors:[...new Set(i.errors)].sort((o,c)=>o.localeCompare(c))}}function B0(e){let t={},n={};for(let i of[...e.types].sort((r,s)=>r.localeCompare(s))){let r=e.by_type[i];t[i]=af(r,"strict"),n[i]=af(r,"progressive")}return{default_create_mode:"strict",by_create_mode:{strict:{by_type:t},progressive:{by_type:n}}}}function H0(e,t){let n=si(e);if(n.length===0)return e;let i=!1,r=n.map(s=>{let a=s.properties;if(typeof a!="object"||a===null)return s;let o=a.action;return typeof o!="object"||o===null||o.const!=="create"?s:(i=!0,{...s,"x-create-required-options":t})});return i?{...e,oneOf:r}:e}function V0(e){let t=$r(e.action)!==void 0||$r(e.command)!==void 0,n=e.schemaOnly===!0||e.flagsOnly===!0||e.availabilityOnly===!0,i=e.summary===!0||e.full!==!0&&e.runtimeOnly!==!0&&!t&&!n,r=e.schemaOnly===!0,s=e.flagsOnly===!0,a=e.availabilityOnly===!0,o=e.runtimeOnly===!0,c=e.full===!0,d=$r(e.action),l=$r(e.command),u=!i&&!c&&!r&&!s&&!a&&!d&&!l;return{selectedAction:d,selectedCommand:l,summary:i,schemaOnly:r,flagsOnly:s,availabilityOnly:a,runtimeOnly:o,fullOutput:c,omitUnfilteredSchema:u,omitUnfilteredCommandFlags:u,omitUnfilteredCommanderAliases:u||l!==void 0&&!c}}function Y0(e){if([e.summary,e.schemaOnly,e.flagsOnly,e.availabilityOnly].filter(t=>t).length>1)throw new _("Choose only one projection flag: --summary, --schema-only, --flags-only, or --availability-only.",m.USAGE)}async function J0(e,t=I){try{return await t(e)}catch{return structuredClone(Lt)}}async function X0(e,t,n){let i=await J0(t),r=await P0(e),s=F(i,r.registrations??P()),a=rn(i.schema),o=C0(r);return{settings:i,runtimeProbe:r,typeRegistry:s,statusRegistry:K(i.schema),runtimeFieldRegistry:a,runtimeFieldFlagMap:q0(a),createRequiredOptionContracts:B0(s),extensionContracts:o,mergedExtensionContracts:M0(o.filter(c=>jr(n,c.command,o))),extensionFlagMap:gf(r.flagRegistrations)}}function of(e){return e.availabilityOnly&&(e.selectedAction!==void 0&&Ur.has(e.selectedAction)||e.selectedCommand!==void 0&&Ut.has(H(e.selectedCommand)))}function Q0(e,t){let n=F0(t,{includePackageOwnedActions:of(e)});if(e.selectedAction===void 0&&e.selectedCommand===void 0){let i=new Set(Ml);return n.filter(r=>!i.has(r.action)&&(e.fullOutput||(t.find(s=>s.action===r.action)?.tier??yo(r.action))!=="internal"))}return of(e)&&e.selectedCommand!==void 0&&Ut.has(H(e.selectedCommand))&&!n.some(i=>i.command_path===e.selectedCommand)&&n.push({action:k0(H(e.selectedCommand)),provider:"extension",requires_extension:!0,command_path:e.selectedCommand}),n}function Z0(e,t){let n=new Set(t.map(i=>i.action));if(e.selectedAction&&!n.has(e.selectedAction))throw new _(`Unknown action: "${e.selectedAction}".`,m.USAGE)}function eE(e,t){return[...new Set([...Xe.filter(n=>!Ut.has(H(n))),...[...ri.keys()].filter(n=>!Ut.has(H(n))),...e.flatMap(n=>n.command_path?mt(n.command_path).filter(i=>n.provider==="extension"||!Ut.has(H(i))||t.some(r=>r.action===n.action)):[]),...t.flatMap(n=>n.command.split("|").flatMap(i=>{let r=Ye.find(s=>s.alias===i||s.canonical===i);return r===void 0?[i]:[r.alias,r.canonical]}))])].map(n=>be(n)).filter(n=>n.length>0).sort((n,i)=>n.localeCompare(i))}function tE(e,t){let n=t.slice(0,y0),i=t.length-n.length,r=i>0?`${n.join(", ")}, and ${i} more`:n.join(", "),s=t.slice(0,v0),a=t.slice(0,5).map(c=>`pm contracts --command "${c}" --flags-only --json`),o=t[0];return new _(`Command "${e}" is a command namespace. Choose a concrete child command: ${r}.`,m.USAGE,{code:"command_namespace",required:"Use a concrete child command path listed under this namespace.",why:"Command groups expose help at the namespace root, but command flag contracts belong to executable child commands.",examples:a,nextSteps:[`Retry with a child command, for example: ${a[0]}`],recovery:{suggested_retry:`pm contracts --command "${o}" --flags-only --json`,fallback_candidates:s.map(c=>({source:"command_namespace",command:`pm contracts --command "${c}" --flags-only --json`,reason:`Child command under ${e}`}))}})}function nE(e,t){return new _(`Unknown command: "${e}". Command "${e}" is provided by the optional "${t}" package. Run "pm install ${t} --project" and retry.`,m.USAGE,{code:"unknown_command",required:`Install the optional "${t}" package, or choose a command from pm contracts --flags-only --json.`,why:"Command contracts include core commands plus commands registered by active packages and extensions.",examples:[`pm install ${t} --project`,`pm contracts --command ${e} --flags-only --json`],nextSteps:[`Install the optional package first: pm install ${t} --project`],recovery:{suggested_retry:`pm install ${t} --project`}})}function iE(e){return new _(`Unknown command: "${e}".`,m.USAGE,{code:"unknown_command",required:"Use a command path listed by pm contracts --flags-only --json.",why:"Command contracts are generated from the active core, package, and extension command registry.",examples:["pm contracts --flags-only --json","pm --help"],nextSteps:["Verify spelling and active packages/extensions, then rerun with a known command path."],recovery:{suggested_retry:"pm contracts --flags-only --json"}})}function rE(e,t){if(!e.selectedCommand||new Set(t).has(e.selectedCommand))return;let n=t.filter(r=>r.startsWith(`${e.selectedCommand} `));if(n.length>0)throw tE(e.selectedCommand,n);let i=lf.get(H(e.selectedCommand));throw i?nE(e.selectedCommand,i):iE(e.selectedCommand)}function sE(e,t){let n=Q0(e,t.mergedExtensionContracts);Z0(e,n);let i=eE(n,t.mergedExtensionContracts);rE(e,i);let r=e.selectedCommand?mf.get(H(e.selectedCommand)):void 0,s=e.selectedCommand?n.filter(d=>r?d.action===r:E0(d,e.selectedCommand)):n;if(e.selectedCommand&&e.selectedAction&&!s.some(d=>d.action===e.selectedAction))throw new _(`Action "${e.selectedAction}" is not mapped to command "${e.selectedCommand}" in contracts output.`,m.USAGE);let a=e.selectedAction?s.filter(d=>d.action===e.selectedAction):s,o=[...new Map(a.map(d=>$0(d,t.runtimeProbe)).map(d=>[r?d.action:`${d.action}|${d.command_path??""}`,d])).values()],c=e.runtimeOnly&&!e.selectedAction&&!e.availabilityOnly?o.filter(d=>d.invocable):o;return{actionDescriptors:n,commandCatalog:i,commandScopedDescriptors:s,scopedActionDescriptors:a,selectedPackageOwnedAction:r,actionAvailability:c,actions:[...new Set(c.map(d=>d.action))]}}function aE(e){return new Set(si(e).map(t=>{let n=t.properties;if(typeof n!="object"||n===null)return null;let i=n.action;if(typeof i!="object"||i===null)return null;let r=i.const;return typeof r=="string"?r:null}).filter(t=>t!==null))}function oE(e){let t=D_,n=si(t),i=aE(t),r=e.filter(s=>!i.has(s.action)).map(s=>D0(s));return r.length>0?{...t,oneOf:[...n,...r]}:t}function cf(e,t,n){let i=new Set(t.actionDescriptors.map(s=>s.action)),r=e.selectedAction?T0(n,e.selectedAction):e.selectedCommand?Co(n,new Set(t.scopedActionDescriptors.map(s=>s.action))):Co(n,i);return e.runtimeOnly&&!e.selectedAction?Co(r,new Set(t.actions)):r}function cE(e,t,n){let i=oE(t.mergedExtensionContracts),r=!e.flagsOnly&&!e.availabilityOnly?H0(cf(e,n,i),t.createRequiredOptionContracts):cf(e,n,i);return{mergedSchema:i,filteredSchema:r}}function dE(e,t){return e.selectedCommand!==void 0?[e.selectedCommand]:e.selectedAction?S0(t.scopedActionDescriptors,t.commandCatalog):t.commandCatalog}function yf(e,t){return t.find(n=>H(n.command)===H(e))?.tier??yo(e)}function jr(e,t,n){return e.fullOutput||e.selectedCommand!==void 0||e.selectedAction!==void 0||yf(t,n)!=="internal"}function lE(e,t,n){if(e.selectedCommand!==void 0||e.selectedAction!==void 0)return t;let i=new Set(Ot.filter(r=>r.hidden&&(r.lifecycle==="deprecated"||!e.fullOutput&&!e.availabilityOnly)).map(r=>r.alias));if(e.summary&&!e.fullOutput)for(let r of Ro.keys())i.add(r);return t.filter(r=>!i.has(r)&&jr(e,r,n))}function vf(e){let t=Ye.find(i=>i.alias===e||i.canonical===e);if(t)return t.canonical;let n=e.split(" ")[0];return n.startsWith("list-")?"list":Ro.get(n)??n}var uE=new Map([["activate","Activate"],["adopt","Adopt"],["adopt-all","Adopt all"],["catalog","Catalog"],["complete","Complete"],["create","Create"],["deactivate","Deactivate"],["delete","Delete"],["describe","Describe"],["doctor","Diagnose"],["explore","Explore"],["init","Initialize"],["inspect","Inspect"],["install","Install"],["list","List"],["manage","Manage"],["migrate","Migrate"],["mutate","Mutate"],["reload","Reload"],["restore","Restore"],["run","Run"],["snapshot","Manage snapshots for"],["uninstall","Uninstall"],["upgrade","Upgrade"]]),mE=new Map([["extension adopt-all","extensions"],["package adopt-all","packages"],["workspace snapshot list","workspace snapshots"]]);function _E(e,t){let n=Zp.get(H(e))??(e.includes(" ")?void 0:Zp.get(vf(e)));if(n!==void 0)return{intent:n,intent_source:"command"};let i=t.find(d=>mt(d.command).some(l=>H(l)===H(e)));if(i?.intent!==null&&i?.intent!==void 0)return{intent:i.intent,intent_source:"command"};if(i?.description!==null&&i?.description!==void 0)return{intent:i.description,intent_source:"description"};let r=e.split(" "),s=r.at(-1),a=r.slice(0,-1).join(" "),o=uE.get(s),c=mE.get(e)??a;return{intent:o===void 0||a.length===0?`Run ${e}.`:`${o} ${c}.`,intent_source:"generated"}}function pE(e,t=[],n={}){let i=n.includeFormatBudgets??!0,r=n.includeIntentProvenance??!0;return[...new Set(e.map(be))].filter(s=>s.length>0).sort((s,a)=>s.localeCompare(a)).map(s=>{let a=qa(s,{generateFallback:!0}),o=s.split(" ")[0],c=Ro.get(o)??(o.startsWith("list-")?"list":o.startsWith("history-")?"history":o),d=new Set([...hf(s).map(p=>p.flag),...t.filter(p=>mt(p.command).some(g=>H(g)===H(s))).flatMap(p=>p.flags.map(g=>g.flag))]),l=(Qp.get(H(s))??Qp.get(c)??h0).filter(p=>d.has(p)),u=_E(s,t);return{command:s,intent:u.intent,...r||u.intent_source!=="command"?{intent_source:u.intent_source}:{},...l.length>0?{flags:l}:{},default_max_estimated_tokens:a.default_max_estimated_tokens,...i?{default_max_estimated_tokens_by_format:{...a.default_max_estimated_tokens_by_format}}:{}}})}function fE(e){return e.map(t=>({budget:qa(t,{generateFallback:!0}),envelope:Ip(t)}))}function gE(e){let t=new Map;for(let n of e){let i=Op(n),r=i===void 0?[m.SUCCESS,m.GENERIC_FAILURE,m.USAGE,m.NOT_FOUND,m.CONFLICT,m.DEPENDENCY_FAILED]:i.exit_codes,s=r.join(","),a=t.get(s)??{commands:[],exit_codes:r};a.commands.push(n),t.set(s,a)}return[...t.values()]}function hE(e,t,n){if(e.selectedCommand)return t.extensionContracts.filter(i=>mt(i.command).some(r=>H(r)===H(e.selectedCommand)));if(e.selectedAction){let i=new Set(n);return t.extensionContracts.filter(r=>mt(r.command).some(s=>i.has(s)))}return t.extensionContracts.filter(i=>jr(e,i.command,t.extensionContracts))}function yE(e,t,n,i){return{schema_version:typeof t.mergedSchema["x-schema-version"]=="string"?t.mergedSchema["x-schema-version"]:null,schema_id:typeof t.mergedSchema.$id=="string"?t.mergedSchema.$id:null,selected:{action:e.selectedAction??null,command:e.selectedCommand??null,summary:e.summary,schema_only:e.schemaOnly,flags_only:e.flagsOnly,availability_only:e.availabilityOnly,runtime_only:e.runtimeOnly,command_scoped:e.selectedCommand!==void 0},commands:e.summary?[]:i,...!e.summary&&!e.flagsOnly?{actions:n.actions,action_availability:n.actionAvailability}:{}}}function vE(e,t,n){(n.selectedCommand==="history"||n.fullOutput)&&!n.flagsOnly&&!n.schemaOnly&&!n.availabilityOnly&&(e.history_operations=tu);let i=n.selectedCommand;e.runtime_schema={statuses:t.statusRegistry.definitions.map(r=>r.id),open_status:t.statusRegistry.open_status,close_status:t.statusRegistry.close_status,canceled_status:t.statusRegistry.canceled_status,types:[...t.typeRegistry.types],fields_by_command:Object.fromEntries([...t.runtimeFieldRegistry.command_to_fields.entries()].filter(([r])=>i===void 0||r===i).map(([r,s])=>[r,[...new Set(s.map(a=>`--${a.cli_flag}`))].sort((a,o)=>a.localeCompare(o))]))},!(i!==void 0&&!n.fullOutput)&&(e.extension_contracts={capabilities:[...Il],services:[...Cl],policy_modes:[...xl],policy_mode_scope:"extensions.policy.mode",policy_surfaces:[...Ll],trust_modes:[...Rl],trust_mode_scope:"extensions.policy.trust_mode",sandbox_profiles:[...Ol],manifest_versions:[1,2],compatibility:{current:"v2",previous:["v1"],breaking_strategy:"versioned_breaking"}},e.governance_contracts={ownership_enforcement_modes:[...dl],create_modes:[...ll],close_validation_modes:[...ul],workflow_enforcement_modes:[...ml]},e.relationship_kind_contracts=[...Yd,...(t.runtimeProbe.registrations?.relationship_kinds??[]).flatMap(r=>r.definitions)].sort((r,s)=>r.kind.localeCompare(s.kind)).map(r=>({canonical:r.kind,aliases:[...r.aliases??[]],...r.inverse===void 0?{}:{inverse:r.inverse},ordering:r.ordering,hierarchy:r.hierarchy})))}function wE(e,t,n,i){if(!(t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredSchema){e.schema=n.filteredSchema,e.extension_commands=i;return}e.schema_omitted_reason="unfiltered_default_brief",e.extension_commands=i}}function bE(e,t,n,i,r){if(!(t.schemaOnly||t.availabilityOnly)){if(t.omitUnfilteredCommandFlags)e.command_flags_omitted_reason="unfiltered_default_brief";else{e.command_flags=K0(i,n.extensionFlagMap,n.runtimeFieldFlagMap,t.selectedCommand!==void 0,n.extensionContracts);let s=new Set(i);e.list_projections=Object.entries(V_).filter(([a])=>s.has(a)).map(([a,o])=>({command:a,default:o,brief_fields:[...H_],compact_fields:[...B_]}))}e.command_aliases=t.fullOutput?r:r.map(({canonical:s,aliases:a})=>({canonical:s,aliases:a})),t.fullOutput||(e.command_alias_contracts_omitted_reason="compact_projection; restore with --full")}}function kE(e,t){if(!(t.schemaOnly||t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredCommanderAliases){e.commander_aliases=W0();return}e.commander_aliases_omitted_reason=t.selectedCommand?"command_scoped":"unfiltered_default_brief"}}function EE(e,t,n,i){e.command_summaries=pE(t,n,{includeFormatBudgets:i.includeFormatBudgets,includeIntentProvenance:i.includeIntentProvenance}),e.output_policy={token_estimate:"ceil(utf8_bytes / 4)",degradation_ladder:[...Bl],allows_unbounded_opt_out:!0},e.output_projection_contracts={global_ladder_field:"output_policy.degradation_ladder",global_ladder_scope:"union_not_per_command",discovery:"pm contracts --command <command> --summary",...i.includeProjectionModeMatrix?{commands:[...new Set(t.map(be))].filter(r=>Yl(r)!==void 0).sort((r,s)=>r.localeCompare(s)).map(r=>({command:r,modes:[...Jl(r).keys()]}))}:{}},e.grammar_contracts={nouns:Pt.nouns,shared_verbs:Pt.shared_verbs,scope_before_verb:Pt.scope_before_verb,visible_top_level_ceiling:Pt.visible_top_level_ceiling,ceiling_raise_requires_pm_item:Pt.ceiling_raise_requires_pm_item,positional_shape_budget:Pt.positional_shape_budget,positional_shape_count:new Set(Va.map(({slots:r})=>Cu(r))).size,positional_action_count:Ha.length,positional_action_parents:[...new Set(Ha.map(({parent:r})=>r))].sort((r,s)=>r.localeCompare(s)),...i.includePositionalSignatures?{positional_signatures:Va}:{}}}async function p$(e,t){let n=V0(e);Y0(n);let i=x(process.cwd(),t.path),r=await X0(t,i,n),s=sE(n,r),a=cE(n,r,s),o=dE(n,s),c=lE(n,o,r.extensionContracts),d=yE(n,a,s,c),l=hE(n,r,c),u=n.fullOutput||n.selectedCommand!==void 0;if((n.summary||n.fullOutput)&&EE(d,c,l,{includeFormatBudgets:u,includeIntentProvenance:u,includePositionalSignatures:u,includeProjectionModeMatrix:u}),n.summary)return d;let p=z0(s.commandCatalog.filter(g=>jr(n,g,r.extensionContracts)));return n.flagsOnly&&!n.fullOutput||vE(d,r,n),wE(d,n,a,l),bE(d,n,r,c,p),kE(d,n),(n.selectedCommand==="assurance"||n.fullOutput)&&(d.assurance_contracts={measurement_source_kinds:[...ei],gate_triggers:[...lt]}),n.fullOutput&&d.grammar_contracts&&(d.grammar_contracts.destinations=Iu.map(g=>({...g,reason:g.reason??""}))),n.fullOutput&&!n.schemaOnly&&!n.flagsOnly&&!n.availabilityOnly&&(d.mcp_tools=Xp(),d.context_intents=Zl(),d.read_output_dimensions=Vl,d.error_codes=Tp,d.command_output_contracts=fE(c),d.diagnostic_output_contracts=Hl,d.command_exit_contracts={vocabulary:vo,command_sets:gE(c)}),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]="0f604cc2-c8cd-5c15-8fec-2243f64ef7d2")}catch{}})();var SE=Symbol("pm.mcp-mutation-transport"),TE=new Set(["activity","aggregate","context","contracts","deps","files-discover","files-lookup","get","graph","health","history","history-attest","list","next","search","stats","telemetry","validate"]);function qr(e){return SE in e}function Kr(e,t){return qr(e)?o_(t):Qe(e,t)}function Do(e,t,n=[]){let i=Qe(e,{...e,...t});for(let r of n)Reflect.deleteProperty(i,r);return i}function L(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n:void 0}function re(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 E$(e,t){let n=e[t];return typeof n=="string"?n:typeof n=="number"&&Number.isFinite(n)?String(n):void 0}function vn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function No(e,t){if(typeof e=="number"){if(!Number.isInteger(e))throw new _(`${t} must be a finite integer.`,m.USAGE);return e}if(typeof e=="string"&&e.trim().length>0){let n=Number(e);if(!Number.isInteger(n))throw new _(`${t} must be a finite integer.`,m.USAGE);return n}}function S$(e,t){return typeof e.limit=="number"&&Number.isFinite(e.limit)?e.limit:typeof t.limit=="number"&&Number.isFinite(t.limit)?t.limit:L(e,"limit")??L(t,"limit")}function T$(e){let t=L(e,"outputFormat");return{json:!0,quiet:!0,author:L(e,"author"),path:L(e,"path"),noExtensions:e.noExtensions===!0||e.no_extensions===!0,noPager:!0,outputInclude:L(e,"outputInclude"),outputLimit:re(e,"outputLimit"),outputBudget:re(e,"outputBudget"),outputSession:L(e,"outputSession"),outputCursor:L(e,"outputCursor"),outputFormat:t==="json"||t==="toon"?t:void 0}}var AE=new Set(["tags","blockedBy","blocked_by","skills","fields"]),bf=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"]),IE=new Set([...bf].filter(e=>e!=="file")),CE=new Set(["files","files-discover","docs","test","test-all"]),kf=new Set(["comments","notes","learnings"]);function xE(e,t){if(!(!kf.has(e)||!Object.prototype.hasOwnProperty.call(t,"file")))throw new _(`MCP ${e} does not accept options.file. Pass annotation text in options.add instead.`,m.USAGE,{code:"mcp_annotation_file_unavailable",required:"Pass annotation text as JSON data; MCP annotation actions cannot read server-local files."})}var RE=new Set(["claim","release","start-task","pause-task","close-task"]),OE={"history-attest":["verify","output","hashAlgorithm"],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","releaseAssignment"],claim:["start","next","ifAvailable"],release:["pause","handoff"],comments:["ifAbsent"],notes:["ifAbsent"],learnings:["ifAbsent"],extension:["dryRun","offline"],package:["dryRun","offline"],install:["dryRun"],upgrade:["scope","dryRun","cliOnly","packagesOnly","repair","tag","packageName"],append:["body"]},LE=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor"];function Ef(e,t=""){let n={},i=CE.has(t),r=t==="files"||t==="files-discover"||t==="docs",s=kf.has(t)?IE:bf;for(let[a,o]of Object.entries(e)){if(Array.isArray(o)&&AE.has(a)){n[a]=o.join(",");continue}if(a==="note"&&r){n[a]=o;continue}if(typeof o=="string"&&s.has(a)){n[a]=[o];continue}if(typeof o=="string"&&i&&(a==="add"||a==="remove")){n[a]=[o];continue}n[a]=o}return Object.assign(n,Object.fromEntries(Object.getOwnPropertySymbols(e).map(a=>[a,Reflect.get(e,a)]))),n}function DE(e,t,n){let i=L(e,"author");return i!==void 0?i:n!==void 0&&RE.has(n)?L(e,"assignee")??L(t,"assignee"):void 0}function NE(e,t){return t!==void 0&&e.author===void 0?{...e,author:t}:e}function A$(e,t){let n=vn(e.options)?e.options:void 0,i=ol(e.options),r={},s=c=>{i[c]!==void 0||e[c]===void 0||(r[c]=e[c])};for(let c of OE[t??""]??[])s(c);for(let c of LE)s(c);t!==void 0&&qr(e)&&xE(t,i);let a=Ef({...r,...i},t);if(t==="history-attest"&&qr(e)&&(a.output!==void 0||typeof a.verify=="string"))throw new _("MCP history attest does not accept server-local proof paths. Export the returned JSON bundle and pass that JSON object as verify.",m.USAGE);let o=qr(e)?e:n??e;return Kr(o,NE(a,DE(e,a,t)))}function I$(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 C$(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 ME(e){let t=[],n=!0;for(let i of e.trim().toLowerCase()){if(i>="a"&&i<="z"||i>="0"&&i<="9"){t.push(i),n=!1;continue}n||(t.push("-"),n=!0)}return t.at(-1)==="-"&&t.pop(),t.join("")}function x$(e){return!TE.has(ME(e))}function R$(e){return e.trim().toLowerCase().split(/\s+/).filter(Boolean).join(" ")}function Mo(e){return Array.isArray(e)?e.map(t=>String(t)).filter(t=>t.length>0):[]}function O$(e,t){let n=new Set(["action","args","author","cwd","fullChangedFields","id","options","path","query","reason","target"]),i={};for(let[s,a]of Object.entries(e))n.has(s)||(i[s]=a);let r={...i,...t};return delete r.args,r}function L$(e,t){let n=Kr(t??{},{...t});return{changedFields:e.fullChangedFields===!0?"full":"compact",idOnly:e.idOnly===!0,runnerOptions:n}}function Lo(e){return{type:re(e,"filterType"),tag:re(e,"filterTag"),priority:re(e,"filterPriority"),deadlineBefore:re(e,"filterDeadlineBefore"),deadlineAfter:re(e,"filterDeadlineAfter"),updatedAfter:re(e,"filterUpdatedAfter"),updatedBefore:re(e,"filterUpdatedBefore"),createdAfter:re(e,"filterCreatedAfter"),createdBefore:re(e,"filterCreatedBefore"),ids:to(e.ids),assignee:re(e,"filterAssignee"),assigneeFilter:re(e,"filterAssigneeFilter")??re(e,"filterAssignee_filter"),parent:re(e,"filterParent"),sprint:re(e,"filterSprint"),release:re(e,"filterRelease"),limit:re(e,"limit"),offset:re(e,"offset")}}function Oo(e){if(typeof e=="string"&&e.trim().length>0)return e;if(Array.isArray(e))return Mo(e)}function Gr(e){if(typeof e=="number"&&Number.isFinite(e)||typeof e=="string"&&e.trim().length>0)return e}function D$(e){let t=Oo(e.kind),n=Oo(e.exemptIsolate),i=Oo(e.exemptIsolateType);return{...t===void 0?{}:{kind:t},maxDepth:Gr(e.maxDepth),limit:Gr(e.limit),after:L(e,"after"),direction:L(e,"direction"),maxPaths:Gr(e.maxPaths),sample:Gr(e.sample),...n===void 0?{}:{exemptIsolate:n},...i===void 0?{}:{exemptIsolateType:i},saveBaseline:e.saveBaseline===!0,rebuild:e.rebuild===!0,clear:e.clear===!0,summary:e.summary===!0,...e.full===!0?{full:!0}:{}}}function Sf(e){let t=rp(e);return e.ids!==void 0&&(t.ids=to(e.ids)),t}function N$(e){return{status:L(e,"filterStatus"),list:vn(e.list)?Sf(e.list):Lo(e),reason:L(e,"reason"),resolution:L(e,"resolution"),expectedResult:L(e,"expectedResult")??L(e,"expected_result")??L(e,"expected"),actualResult:L(e,"actualResult")??L(e,"actual_result")??L(e,"actual"),validateClose:L(e,"validateClose")??L(e,"validate_close"),author:L(e,"author"),message:L(e,"message"),force:e.force===!0?!0:void 0,dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:L(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}var PE=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 wf(e){let t={};for(let[n,i]of Object.entries(e))PE.has(n)||(t[n]=i);return Tf(t)}function Tf(e){let t=Ef(e,"update-many");for(let n of Ir)for(let i of n.keys){let r=t[i];typeof r=="number"&&Number.isFinite(r)&&(t[i]=String(r))}return ip(t)}function M$(e){if(vn(e.list)||vn(e.update)){let t=vn(e.update)?e.update:wf(e),n=Kr(e,Tf(t));return{status:re(e,"filterStatus"),list:vn(e.list)?Sf(e.list):Lo(e),update:c_(t,n),dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:L(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}return{status:re(e,"filterStatus"),list:Lo(e),update:Kr(e,wf(e)),dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:L(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}import{readFile as FE}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="35773218-9c35-51d9-a19b-e9094bd23b66")}catch{}})();function X$(e){let t={...e,...e.full===!0?{fullHistory:!0}:{}};return delete t.full,Qe(e,t)}function Af(e,t){if(typeof e=="object"&&e!==null&&"format"in e&&e.format==="json")throw new _(`Structured context events are append-only and cannot be ${t}.`,m.USAGE,{code:"structured_event_immutable"})}function $E(e,t){return t===void 0?e:t===0?[]:e.slice(Math.max(0,e.length-t))}function jt(e,t){let n=e[t];return Array.isArray(n)?n:[]}function Q$(e,t={}){let n=e.trim();if(!n)return"";let i=/^(?:[-*+]\s*)?text\s*[:=]/i.exec(n);if(t.stripPlainTextPrefix===!0&&i&&!n.startsWith("```"))return n.slice(i[0].length).trim()||n;if(!(/^(?:[-*+]\s*)?text\s*[:=]/im.test(n)||n.startsWith("```")))return n;try{let r=Z(n,"--add");return Object.keys(r).map(s=>s.trim().toLowerCase()).some(s=>s!=="text")?n:r.text?.trim()||n}catch{return n}}function UE(e){return typeof e=="object"&&e!==null&&"code"in e}function If(e,t){if(!Ft(e))throw new _(`${t} cannot read process stdin through the MCP JSON-RPC transport. Pass annotation text in options.add instead.`,m.USAGE,{code:"mcp_stdin_unavailable",required:"Pass annotation text as JSON data; the MCP protocol already owns process stdin."})}async function jE(e,t){if(+(e.add!==void 0)+ +(e.stdin===!0)+ +(typeof e.file=="string")>1)throw new _(`Specify ${t} text using only one input source: --add, --stdin, or --file`,m.USAGE);let n=dn(),i=Ft(e);if(e.add!==void 0)return{value:await n.resolveValue(e.add,"--add",i)??"",rawValue:e.add,emptyFlag:"--add"};if(e.stdin===!0)return If(e,"--stdin"),{value:await n.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};if(typeof e.file!="string")return;let r=e.file.trim();if(!r)throw new _("--file path cannot be empty",m.USAGE);if(r==="-")return If(e,"--file -"),{value:await n.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await FE(r,"utf8"),emptyFlag:"--file"}}catch(s){if(UE(s)&&zi(s))throw new _(`--file path not found: ${r}. Use --file - to read stdin.`,m.USAGE);let a=s instanceof Error?s.message:String(s);throw new _(`Failed to read --file path "${r}": ${a}. Use --file - to read stdin.`,m.USAGE)}}async function Z$(e,t){if(e.edit!==void 0&&e.delete!==void 0)throw new _("Specify only one of --edit or --delete",m.USAGE);if(e.delete!==void 0){if(e.add!==void 0||e.stdin===!0||typeof e.file=="string")throw new _("--delete cannot be combined with replacement text",m.USAGE);if(!Number.isInteger(e.delete)||e.delete<1)throw new _("--delete must be a positive integer",m.USAGE);return{mode:"delete",index:e.delete}}if(e.edit!==void 0&&(!Number.isInteger(e.edit)||e.edit<1))throw new _("--edit must be a positive integer",m.USAGE);let n=await jE(e,t);if(e.edit!==void 0){if(!n)throw new _("--edit requires replacement text from --add, --stdin, or --file",m.USAGE);return{mode:"edit",index:e.edit,...n}}return n?{mode:"add",...n}:{mode:"list"}}function ai(e,t){throw e instanceof _&&e.exitCode===m.CONFLICT&&e.message.includes("is assigned to")&&e.message.includes("Use --force to override")?new _(e.message,e.exitCode,{code:"ownership_conflict",required:t.required,examples:t.examples,nextSteps:t.nextSteps}):e}function xf(e){return e==="comments"?"--stdin":"--add -"}function GE(e,t){if((t.input.emptyFlag??"--add")!=="--add")return;let n=e.trim();if(!/^-{1,2}[A-Za-z][\w-]*(?:=.*)?$/.test(n))return;let i=xf(t.collectionKey),r=t.input.mode==="edit"?`pm ${t.collectionKey} <id> --edit <index>`:`pm ${t.collectionKey} <id>`;throw new _(`--add value "${n}" looks like an option, not annotation text. Use ${i} to read stdin, or use text=${n} for literal dash-leading text.`,m.USAGE,{code:"annotation_flag_like_value",required:`Use ${i} for stdin input, pass plain text, or use text=${n} when the text really starts with "-".`,examples:[`${r} ${i}`,`${r} --add text=${n}`]})}function qE(e,t){if(t.ifAbsent===!0&&!["add","stdin","file"].includes(e.input.mode))throw new _(`--if-absent requires a ${e.collectionKey.replace(/s$/,"")} append`,m.USAGE,{code:"annotation_if_absent_without_append",required:"Combine --if-absent with one append text source; omit it for list, edit, and delete operations."});if(e.input.mode!=="list"||t.message===void 0)return;let n=e.collectionKey.replace(/s$/,"");throw new _(`--message labels a ${n} mutation but does not provide ${n} text. Pass text positionally or with --add, --stdin, or --file.`,m.USAGE,{code:"annotation_message_without_text",required:`Provide ${n} text through a content source; --message only annotates the history entry of a mutation.`,examples:[`pm ${e.collectionKey} <id> --add "text" --message "why"`,`pm ${e.collectionKey} <id> ${xf(e.collectionKey)}`]})}function KE(e,t,n,i,r,s){let a=jt(e.metadata,t),o=r?a.findIndex(c=>c.author===n&&c.text===i):-1;return o>=0?{changedFields:[],entryIndex:o+1}:(a.push(s({created_at:O(),author:n,text:i})),e.metadata[t]=a,{changedFields:[t],entryIndex:a.length})}async function e1(e,t,n,i){qE(i,t);let r=x(process.cwd(),n.path);await $(r);let s=await I(r),a=F(s,P()),o=Bn(t.limit);if(i.input.mode==="list"){let f=await Y(r,e,s.id_prefix,s.item_format,a.type_to_folder);if(!f)throw new _(`Item ${e} not found`,m.NOT_FOUND);let h=await he(f,{schema:s.schema}),y=jt(h.document.metadata,i.collectionKey);return zr(f.id,i.collectionKey,y,o,t.includeMeta===!0)}let c=U(t.author,s.author_default);if(i.input.mode==="delete"){let f=i.deleteOp??i.op,h;try{h=await se({pmRoot:r,settings:s,id:e,op:f,author:c,message:t.message,force:t.force,bypassAssigneeConflict:i.bypassOwnershipConflict,mutate(v){let w=jt(v.metadata,i.collectionKey),k=Cf(i.input.index,w.length,i.collectionKey);return Af(w[k],"deleted"),w.splice(k,1),v.metadata[i.collectionKey]=w,{changedFields:[i.collectionKey]}}})}catch(v){ai(v,i.conflictGuidance)}let y=jt(h.item,i.collectionKey);return zr(h.item.id,i.collectionKey,y,o,t.includeMeta===!0,{action:"delete",entryIndex:i.input.index},t.fullHistory===!0)}let d=i.input.rawValue??i.input.value??"";GE(d,i);let l=i.parseText(i.input.value??"");if(!l.trim())throw new _(`${i.input.emptyFlag??"--add"} text cannot be empty`,m.USAGE);if(i.input.mode==="edit"){let f=i.editOp??i.op,h;try{h=await se({pmRoot:r,settings:s,id:e,op:f,author:c,message:t.message,force:t.force,bypassAssigneeConflict:i.bypassOwnershipConflict,mutate(v){let w=jt(v.metadata,i.collectionKey),k=Cf(i.input.index,w.length,i.collectionKey),S=w[k];return Af(S,"edited"),w[k]={...S,text:l,edited_at:O()},v.metadata[i.collectionKey]=w,{changedFields:[i.collectionKey]}}})}catch(v){ai(v,i.conflictGuidance)}let y=jt(h.item,i.collectionKey);return zr(h.item.id,i.collectionKey,y,o,t.includeMeta===!0,{action:"edit",entryIndex:i.input.index,entry:y[i.input.index-1]},t.fullHistory===!0)}let u,p=0;try{u=await se({pmRoot:r,settings:s,id:e,op:i.op,author:c,message:t.message,force:t.force,bypassAssigneeConflict:i.bypassOwnershipConflict,skipNoop:t.ifAbsent===!0,mutate(f){let h=KE(f,i.collectionKey,c,l,t.ifAbsent===!0,i.createEntry);return p=h.entryIndex,{changedFields:h.changedFields}}})}catch(f){ai(f,i.conflictGuidance)}let g=jt(u.item,i.collectionKey);return zr(u.item.id,i.collectionKey,g,o,t.includeMeta===!0,{action:"add",entryIndex:p,entry:g[p-1],changedCount:t.ifAbsent===!0?Math.min(u.changedFields.length,1):void 0},t.fullHistory===!0)}function Cf(e,t,n){if(e===void 0||!Number.isInteger(e)||e<1||e>t){let i=n.replace(/s$/,""),r=`${i.charAt(0).toUpperCase()}${i.slice(1)}`,s=t===1?`1 ${i}`:`${t} ${n}`;throw new _(`${r} index ${e??"(missing)"} out of range (item has ${s})`,m.USAGE)}return e-1}function zE(e,t,n){return t===void 0?{}:{mutation_receipt:{action:t.action,entry_index:t.entryIndex,changed_count:t.changedCount??1,full_history_included:!n},omission_receipt:{has_omissions:n,omitted_field_group_count:n?1:0,omitted_field_groups:n?[{name:`${e}_history`,restore_with:{selector:"full_history",cli_flag:"--full-history",sdk_option:"fullHistory",mcp_option:"full"}}]:[]}}}function zr(e,t,n,i,r,s,a=!1){let o=s===void 0||a?$E(n,s!==void 0&&a?void 0:i):s.entry===void 0?[]:[s.entry],c=s!==void 0&&o.length<n.length;return{id:e,[t]:o,count:o.length,...s?.changedCount===void 0?{}:{changed:s.changedCount===1},...[r,s!==void 0].includes(!0)?{total_count:n.length,returned_count:o.length,has_more:c||o.length<n.length,...i!==void 0?{limit:i}:{}}:{},...zE(t,s,c)}}import{createHash as Of}from"node:crypto";import oi from"node:fs/promises";import ci 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]="69bf315a-01aa-56d9-bd56-196d6792dea2")}catch{}})();function Ue(e,t){throw new _(e,m.USAGE,t)}var WE="2026-07-15T06:22:12.276Z",BE=Date.parse(WE),HE=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],Rf=e=>typeof e=="string"?e:"",Lf=e=>{let t=e??{},n=Rf(t.author).trim().toLowerCase(),i=Number(["","unknown"].includes(n)),r=+(Date.parse(Rf(t.ts))>=BE);return HE[i][r]};function Df(e,t,n=20,i=new Set,r=!1){let s=[],a=[],o={legacy_unknown:0,actionable_unknown:0},c=Math.max(0,n),d=0,l=0,u=0;for(let[p,g]of t.split(/\r?\n/).entries()){let f;try{f=JSON.parse(g)}catch{continue}d+=1;let h=Lf(f);if(h!=="attributed"){if(l+=1,h==="actionable_unknown"&&i.has(`${e}:${p+1}`)){u+=1;continue}o[h]+=1,r&&h==="actionable_unknown"&&a.push({item_id:e,line:p+1}),s.length<c&&s.push({item_id:e,line:p+1})}}return{checked_events:d,unknown_event_count:l,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 l1=(e,t,n=20,i=new Set)=>Df(e,t,n,i);function Nf(e){let t=new Set;for(let n of e.split(/\r?\n/)){let i;try{i=JSON.parse(n)}catch{continue}let r=(typeof i=="object"&&i!==null&&typeof i.context=="object"&&i.context!==null?i.context:{}).author_acknowledgment;if(!(typeof r!="object"||r===null||!Array.isArray(r.events)))for(let s of r.events)typeof s=="object"&&s!==null&&typeof s.item_id=="string"&&Number.isSafeInteger(s.line)&&t.add(`${s.item_id}:${String(s.line)}`)}return t}var di=async(e,t=20,n=!1)=>{let i=ci.join(e,"history"),r;try{r=(await oi.readdir(i)).filter(v=>v.endsWith(".jsonl")).sort((v,w)=>v.localeCompare(w))}catch{r=[]}let s=new Set,a=[],o=[],c=0,d=0,l=0,u=0,p=0,g=0,f="_workspace.jsonl",h=new Set;if(r.includes(f))try{h=Nf(await oi.readFile(ci.join(i,f),"utf8"))}catch{h=new Set}for(let v of r){let w;try{w=await oi.readFile(ci.join(i,v),"utf8")}catch{continue}let k=v.slice(0,-6),S=Df(k,w,t-a.length,h,n);c+=1,d+=S.checked_events,l+=S.unknown_event_count,u+=S.legacy_unknown_event_count,p+=S.actionable_unknown_event_count,g+=S.acknowledged_actionable_event_count,S.unknown_event_count>0&&s.add(k),a.push(...S.samples),n&&o.push(...S.actionable_events)}let y=u+p;return{checked_streams:c,checked_events:d,unknown_event_count:l,legacy_unknown_event_count:u,actionable_unknown_event_count:p,acknowledged_actionable_event_count:g,affected_item_ids:[...s].sort((v,w)=>v.localeCompare(w)),samples:a,samples_truncated:y>a.length,...n?{actionable_events:o}:{}}};function VE(e){return[...new Map(e.map(t=>[`${t.item_id}:${t.line}`,{item_id:t.item_id,line:t.line}])).values()].sort((t,n)=>t.item_id.localeCompare(n.item_id)||t.line-n.line)}async function YE(e){try{return Nf(await oi.readFile(ci.join(e,"history","_workspace.jsonl"),"utf8"))}catch{return new Set}}function JE(e){return(e.item_id===Mt||/^[a-z0-9][a-z0-9-]*$/iu.test(e.item_id))&&Number.isSafeInteger(e.line)&&e.line>=1}function XE(e,t,n){let i=n[e.line-1]??"",r;try{r=JSON.parse(i)}catch{Ue(`Unknown-author acknowledgment target ${e.item_id}:${e.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}return Lf(r)!=="actionable_unknown"&&Ue(`Author acknowledgment target ${e.item_id}:${e.line} is not an actionable unknown-author event.`,{code:"history_author_acknowledge_target_not_actionable"}),{...e,source_event_hash:Of("sha256").update(i).digest("hex"),disposition:t.has(`${e.item_id}:${e.line}`)?"already_acknowledged":"actionable"}}async function Mf(e,t,n){let i=t.events??[],r=+(t.all_actionable===!0)+ +(i.length>0);r===0&&Ue("Specify exactly one selector: events or all_actionable.",{code:"history_author_acknowledge_selector_required"}),r>1&&Ue("Author acknowledgment accepts either explicit events or all_actionable, not both.",{code:"history_author_acknowledge_selector_conflict"}),(!Number.isSafeInteger(n)||n<0)&&Ue("Author acknowledgment coordinate_limit must be a non-negative integer.",{code:"history_author_acknowledge_preview_limit_invalid"});let s=VE(t.all_actionable===!0?(await di(e,0,!0)).actionable_events:i),a=await YE(e),o=new Map;for(let p of s)if(JE(p)||Ue(`Unknown-author acknowledgment target ${p.item_id}:${p.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"}),!o.has(p.item_id))try{o.set(p.item_id,(await oi.readFile(ci.join(e,"history",`${p.item_id}.jsonl`),"utf8")).split(/\r?\n/u))}catch{Ue(`Unknown-author acknowledgment target ${p.item_id}:${p.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}let c=s.map(p=>XE(p,a,o.get(p.item_id))),d=t.all_actionable===!0?"all_actionable":"events",l=Of("sha256").update(JSON.stringify({version:1,selection:d,coordinates:c})).digest("hex"),u=c.filter(({disposition:p})=>p==="actionable").length;return{plan:{selection:{kind:d},selected_count:c.length,actionable_count:u,already_acknowledged_count:c.length-u,omitted_count:Math.max(0,c.length-n),coordinates:c.slice(0,n),plan_fingerprint:l},completeCoordinates:c}}async function u1(e,t,n=50){return(await Mf(e,t,n)).plan}function QE(e,t){let n=e.length>0;return n&&t&&Ue("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&&Ue("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:ZE(e),all_actionable:t}}function ZE(e){return e.map(t=>{let n=t.lastIndexOf(":"),i=t.slice(0,n).trim(),r=Number(t.slice(n+1)),s=i===Mt||/^[a-z0-9][a-z0-9-]*$/iu.test(i);return(n<1||!s||!Number.isSafeInteger(r)||r<1)&&Ue(`history-author-acknowledge --event expects <item-id>:<one-based-line>, received "${t}".`,{code:"history_author_acknowledge_target_unreadable"}),{item_id:i,line:r}})}function m1(e,t){let n=QE(Mo(t.historyEvent),t.allActionable===!0||t.all_actionable===!0);return eS(e,{events:n.events,all_actionable:n.all_actionable,dry_run:t.dryRun===!0||t.dry_run===!0,plan_fingerprint:L(t,"planFingerprint")??L(t,"plan_fingerprint"),coordinate_limit:typeof t.limit=="number"?t.limit:typeof t.limit=="string"?Number(t.limit):void 0,attributed_author:L(t,"attributedAuthor")??L(t,"attributed_author")??void 0,reviewer:L(t,"reviewer"),reason:L(t,"reason")})}async function eS(e,t){let n=t.reviewer?.trim()??"",i=t.attributed_author?.trim()??"",r=t.reason?.trim()??"",s=await Mf(e,t,t.coordinate_limit??50);if(t.dry_run===!0)return{dry_run:!0,mutated:!1,acknowledged:0,outcome:"preview",exit_code:m.SUCCESS,plan:s.plan};if([n.length>0,n.toLowerCase()!=="unknown",i.length>0,i.toLowerCase()!=="unknown",r.length>0].includes(!1)&&Ue("Author acknowledgment requires events, reviewer, attributed_author, and reason.",{code:"history_author_acknowledge_required_values_missing"}),t.plan_fingerprint?.trim()||Ue("Author acknowledgment apply requires plan_fingerprint from a fresh dry-run preview.",{code:"history_author_acknowledge_plan_fingerprint_required",recovery:{suggested_retry:"Rerun history-author-acknowledge with --dry-run, then pass --plan-fingerprint <value>."}}),t.plan_fingerprint.trim()!==s.plan.plan_fingerprint)throw new _("Author acknowledgment selection changed after preview; no history was mutated.",m.CONFLICT,{code:"history_author_acknowledge_plan_conflict",recovery:{suggested_retry:"Rerun history-author-acknowledge with --dry-run and apply the fresh plan_fingerprint."}});let a=s.completeCoordinates.filter(({disposition:l})=>s.plan.selection.kind==="events"||l==="actionable").map(({item_id:l,line:u})=>({item_id:l,line:u}));if(a.length===0)return{dry_run:!1,mutated:!1,acknowledged:0,outcome:"no_effect",exit_code:m.NO_EFFECT,plan:s.plan};let o=await I(e),c=await an({pmRoot:e,op:"history:author-acknowledge",author:n,context:{author_acknowledgment:{events:a,attributed_author:i}},message:r,lockTtlSeconds:o.locks.ttl_seconds,lockWaitMs:o.locks.wait_ms}),d=s.plan.actionable_count>0&&s.plan.already_acknowledged_count>0?{outcome:"partial_effect",exit_code:m.PARTIAL_EFFECT}:{outcome:"effect",exit_code:m.SUCCESS};return{dry_run:!1,mutated:!0,acknowledged:a.length,...d,plan:s.plan,history_path:c.historyPath}}import nS from"node:fs/promises";import Ie from"node:path";import{glob as iS}from"tinyglobby";(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]="6f94fb3c-3d6c-5543-a2f0-e12680459e71")}catch{}})();var tS=/^[a-z][a-z0-9+.-]+:\/\//i;function li(e){return tS.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]="12655e94-6304-56cf-9f5d-387a26572db0")}catch{}})();var rS=["path","scope","note"],sS=["pattern","glob","path","scope","note"],aS=["path"],oS=["from","to"],cS=new Set(["note","scope"]);function Ff(e){let t=e??"project";if(!Pe.includes(t))throw new _(`Invalid scope "${e}". Valid scopes: ${Pe.join(", ")} (default: project).`,m.USAGE);return t}function Po(e){if(e.startsWith("```")||e.includes(`
|
|
6
|
-
`)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(e))return!0;let t=e.indexOf(","),n=e.slice(0,t>=0?t:e.length),i=n.indexOf("=");return i>=0&&!/\s/u.test(e)&&(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)||/^(?:[A-Za-z]:[\\/]|[\\/]{1,2}|\.\.?(?:[\\/]))/u.test(e)||[e.indexOf("/"),e.indexOf("\\")].some(r=>r>=0&&r<i))?!1:n.includes("=")||cn(e)}function dS(e){let t=0;for(let n of e)if(n==="("&&(t+=1),n===")"&&(t-=1),t<0)return!1;return t===0}function lS(e){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)&&!Po(e))return{path:e,scope:"project",note:void 0};let t=e.indexOf("](");if(e.startsWith("[")&&t>0&&e.endsWith(")")){let s=e.slice(t+2,-1).trim();if(s.length>0&&dS(s))return{path:s,scope:"project",note:e.slice(1,t).trim()||void 0}}let n=e.indexOf(",");if(n<0)return;let i=e.slice(0,n).trim(),r=e.slice(n+1).trim();if(!(i.length===0||!/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(r)))return{path:r,scope:"project",note:i}}function uS(e,t){return e?e.flatMap(n=>{let i=n.trim();if(t==="doc"){let s=lS(i);if(s!==void 0)return[s]}Wn(i,"--add",`${t} path`,Po(i));let r=Po(i)?Z(n,"--add"):{path:i};if(we(r,"--add",rS),!r.path)throw new _(`--add requires path=<value> or a bare ${t} path`,m.USAGE);return[{path:r.path,scope:Ff(r.scope),note:r.note?.trim()||void 0}]}):[]}function mS(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new _("--add-glob requires a glob pattern value",m.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(n)||n.startsWith("```")){let i=Z(n,"--add-glob");we(i,"--add-glob",sS);let r=i.pattern?.trim()||i.glob?.trim()||i.path?.trim();if(!r)throw new _("--add-glob key/value form requires pattern=<glob>",m.USAGE);return{pattern:r,scope:Ff(i.scope),note:i.note?.trim()||void 0}}return{pattern:n,scope:"project"}}):[]}function _S(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new _("--remove requires a path value",m.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(n)||n.startsWith("```")){let i=Z(n,"--remove"),r=Object.keys(i).filter(s=>cS.has(s.toLowerCase()));if(r.length>0)throw new _(`--remove identifies a linked artifact by path only and does not accept ${r.map(s=>`"${s}"`).join(", ")}. Pass just the path (path=<value>, path:<value>, or a bare path); record removal context with --message "<why removed>".`,m.USAGE);if(we(i,"--remove",aS),!i.path)throw new _("--remove key/value form requires path=<value>",m.USAGE);return i.path}return n}):[]}function pS(e){return e?e.map(t=>{let n=Z(t,"--migrate");we(n,"--migrate",oS);let i=n.from?.trim(),r=n.to?.trim();if(!i||!r)throw new _("--migrate requires from=<value> and to=<value>",m.USAGE);return{from:i,to:r}}):[]}function ui(e,t){let n=e;for(let i of t)n.startsWith(i.from)&&(n=`${i.to}${n.slice(i.from.length)}`);return n}function fS(e,t,n=[]){if(e.length===0||t.length===0)return;let i=new Set(e.map(s=>ui(s.path,n))),r=[...new Set(t.map(s=>ui(s,n)).filter(s=>i.has(s)))].sort((s,a)=>s.localeCompare(a));if(r.length!==0)throw new _(`Linked artifact mutation cannot add and remove the same normalized path in one transaction: ${r.join(", ")}. Split the replacement into separate commands so each history event has one unambiguous intent.`,m.USAGE,{code:"linked_artifact_mutation_conflict",reason:"same_path_added_and_removed",required:"Use distinct normalized paths for --add and --remove in one invocation.",why:"Conflicting batch intent cannot be applied deterministically without silently discarding metadata or a removal.",nextSteps:["Run the removal and addition as separate commands with a --message describing each intent."]})}function _t(e){return e.split(Ie.sep).join("/")}function Fo(e,t,n=process.cwd()){let i=e.trim();if(li(i))return i;if(Ie.isAbsolute(i)||/^[A-Za-z]:[\\/]/.test(i))return _t(i.replaceAll("\\",Ie.sep));let r=Ie.relative(t,n);return r.startsWith(`..${Ie.sep}`)||r===".."||Ie.isAbsolute(r)?_t(Ie.normalize(i)):_t(Ie.relative(t,Ie.resolve(n,i)))}async function gS(e,t=process.cwd(),n=process.cwd()){let i=[];for(let r of e){if(Ie.resolve(n,r.pattern)===Ie.resolve(n))continue;let s=Ie.isAbsolute(r.pattern),a=await iS(r.pattern,{cwd:n,absolute:s,onlyFiles:!0,dot:!0,expandDirectories:!1,followSymbolicLinks:!0}),o=[...new Set(a.map(c=>Fo(c,t,n)))].sort((c,d)=>c.localeCompare(d));for(let c of o)i.push({path:c,scope:r.scope,note:r.note})}return i}function hS(e,t,n){if(t===void 0)return e;if(!n)throw new _("--note requires --add or --add-glob in the same invocation (the note annotates the links being added)",m.USAGE);let i=t.trim();return i.length===0?e:e.map(r=>r.note===void 0?{...r,note:i}:r)}function yS(e){return`${e.path}::${e.scope}`}function $o(e){return[...e].sort((t,n)=>{let i=t.path.localeCompare(n.path);return i!==0?i:t.scope.localeCompare(n.scope)})}function Uo(e){return[...new Map(e.map(t=>[yS(t),t])).values()].map(t=>({...t,note:t.note?.trim()||void 0}))}async function vS(e,t=process.cwd()){let n=[...new Set(e)].sort((o,c)=>o.localeCompare(c)),i=[],r=[],s=[],a=[];for(let o of n){if(li(o)){a.push(o.trim());continue}let c=Ie.isAbsolute(o)?o:Ie.resolve(t,o);try{(await nS.stat(c)).isFile()?i.push(o):s.push(o)}catch(d){if(typeof d=="object"&&d!==null&&"code"in d&&zi(d)){r.push(o);continue}s.push(o)}}return{checked:n.length,existing_files:i,missing_paths:r,non_file_paths:s,remote_references:a}}function wS(e,t,n,i){let r=0;for(let s=0;s<e.length;s+=1){let a=ui(e[s].path,i);a!==e[s].path&&(e[s]={...e[s],path:a},r+=1)}return{adds:t.map(s=>{let a=ui(s.path,i);return a!==s.path&&(r+=1),{...s,path:a}}),removes:n.map(s=>ui(s,i)),count:r}}function bS(e,t,n,i){let r=Uo(e);for(let s of t){let a=r.findIndex(o=>o.path===s.path&&o.scope===s.scope);a<0?r.push(s):s.note!==void 0&&(r[a]={...r[a],note:s.note})}if(n.length>0)for(let s=r.length-1;s>=0;s-=1)n.includes(r[s].path)&&r.splice(s,1);return i?r:$o(r)}async function Pf(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||e.changed?await vS(t,e.workspaceRoot):void 0}}async function Wr(e,t,n,i){let{metadataKey:r}=i,s=dn(),a=x(process.cwd(),n.path),o=Je(a),c=process.cwd();await $(a);let d=await I(a),l=F(d,P()),u=await s.resolveList(t.add,"--add"),p=await s.resolveList(t.addGlob,"--add-glob"),g=await s.resolveList(t.remove,"--remove"),f=await s.resolveList(t.migrate,"--migrate"),h=uS(u,i.bareNoun).map(T=>({...T,path:Fo(T.path,o,c)})),y=mS(p),v=await gS(y,o,c),w=hS([...h,...v],t.note,h.length>0||y.length>0),k=_S(g).map(T=>Fo(T,o,c)),S=pS(f);if(fS(w,k,S),!(w.length>0||k.length>0||S.length>0)){let T=await Y(a,e,d.id_prefix,d.item_format,l.type_to_folder);if(!T)throw new _(`Item ${e} not found`,m.NOT_FOUND);let R=(await he(T,{schema:d.schema})).document.metadata[r]??[];return Pf({id:T.id,artifacts:R,changed:!1,options:t,workspaceRoot:o})}let A=U(t.author,d.author_default),C=await se({pmRoot:a,settings:d,id:e,op:i.op,author:A,message:t.message,force:t.force,skipNoop:!0,mutate(T){let R=T.metadata,G=R[r]??[],pe=[...G],ce=wS(pe,w,k,S),de=bS(pe,ce.adds,ce.removes,i.supportsAppendStable&&t.appendStable===!0);de.length>0?R[r]=de:delete R[r];let ue=!Fe(G,de);return{changedFields:ue?[r]:[],warnings:ue&&ce.count>0?[`path_migrations_applied:${ce.count}`]:[]}}}),b=C.item[r]??[],E=C.warnings.find(T=>T.startsWith("path_migrations_applied:")),N=E?Number(E.slice(24)):0;return Pf({id:C.item.id,artifacts:b,changed:C.changedFields.includes(r),migrationsApplied:N,options:t,workspaceRoot:o})}function Br(e,t){let n={};for(let[i,r]of Object.entries(e))n[i==="artifacts"?t:i]=r;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]="79f1acaf-8ef7-5725-900a-fbeced1c57e6")}catch{}})();async function $f(e,t,n){let i=await Wr(e,t,n,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return Br(i,"docs")}(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]="67d97df8-6551-52ed-9307-8b573a087831")}catch{}})();var Hr=1e6;function jo(e,t=Hr,n=.8,i=!1){let r=new Set,s=(l,u)=>{if(r.add(`${l}:${u}`),r.size>t)throw new _(`Duplicate sweep exceeded ${t} candidate pairs; narrow it with statuses or since.`,m.CONFLICT,{code:"duplicate_sweep_cost_limit",required:"Narrow the duplicate query or increase its similarity threshold. No partial result was returned."})};if(i||n===0){for(let l=0;l<e.length;l+=1)for(let u=0;u<l;u+=1)s(u,l);return r}let a=new Map;for(let{prepared:l}of e)for(let u of l.tokens)a.set(u,(a.get(u)??0)+1);let o=new Map,c=new Map,d=new Map;for(let[l,{prepared:u}]of e.entries()){let p=[...u.tokens].sort((h,y)=>a.get(h)-a.get(y)||h.localeCompare(y)),g=p.length-Math.ceil(n*p.length-1e-12)+1,f=[{index:o,keys:[u.normalized],lengthFilter:!1},{index:c,keys:n<=.99?u.issueCodes:[],lengthFilter:!1},{index:d,keys:p.length===0?[""]:p.slice(0,g),lengthFilter:!0}];for(let h of f)kS(e,l,h,n,s)}return r}function kS(e,t,n,i,r){let s=e[t].prepared.tokens.length;for(let a of n.keys){let o=n.index.get(a)??[];for(let c of o){let d=e[c].prepared.tokens.length;n.lengthFilter&&Math.min(d,s)/Math.max(d,s)+1e-12<i||r(c,t)}o.push(t),n.index.set(a,o)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a5f450bd-8970-5b1b-8250-b76b7818e6e1")}catch{}})();var ES=3,Uf=20,SS=.8,TS=100,jf=1e3;function Gf(e){return e===void 0?[]:[`likely_duplicates:${e.result.items.map(t=>t.id).join(",")}`,`likely_duplicate_recovery:${e.recovery.action}:${e.recovery.item_id}`]}async function AS(e,t){let n=e.items[0],i=x(t.cwd??process.cwd(),t.pmRoot),r=K((await I(i)).schema);return _e(n.status,r)?{action:"reopen",item_id:n.id,command:`pm item reopen ${n.id} "<recurrence reason>"`,args:["item","reopen",n.id,"<recurrence reason>"]}:{action:"reuse",item_id:n.id,command:`pm get ${n.id} --full`,args:["get",n.id,"--full"]}}function Go(e){let t=e.limit??ES,n=e.threshold??SS;if(!Number.isSafeInteger(t)||t<0||t>Uf)throw new _(`Similarity limit must be an integer from 0 to ${Uf}.`,m.USAGE);if(!Number.isFinite(n)||n<0||n>1)throw new _("Similarity threshold must be a number from 0 to 1.",m.USAGE);return{limit:t,threshold:n}}function qf(e){let t=e.limit??TS;if(!Number.isSafeInteger(t)||t<0||t>jf)throw new _(`Duplicate cluster limit must be an integer from 0 to ${jf}.`,m.USAGE);let n=e.since===void 0?void 0:new Date(e.since);if(n&&Number.isNaN(n.getTime()))throw new _("Duplicate cluster --since must be a valid ISO timestamp.",m.USAGE);return{limit:t,since:n}}async function IS(e,t){let n=x(e.cwd??process.cwd(),e.pmRoot),i=await I(n),r=F(i),s=e.statuses?.map(u=>u.trim().toLowerCase()).filter(Boolean);if(e.statuses!==void 0&&s?.length===0)throw new _("Duplicate cluster statuses must include at least one lifecycle status or all.",m.USAGE);let a=K(i.schema),o=s?.map(u=>{if(u==="all")return u;let p=me(u,a);if(!p)throw new _(`Unknown duplicate-cluster status "${u}". Allowed: all, ${a.definitions.map(g=>g.id).join(", ")}.`,m.USAGE);return p}),c=o?.includes("all")===!0;if(c&&o?.some(u=>u!=="all"))throw new _('The "all" status cannot be combined with other statuses.',m.USAGE);let d=c?void 0:o,l=d?new Set(d):void 0;return{items:(await Se(n,i.item_format,r.type_to_folder,void 0,i.schema)).filter(u=>(!l||l.has(u.status))&&(!t||new Date(u.created_at).getTime()>=t.getTime())),statuses:d}}var Z1={buildDuplicateClusters:zf,collectDuplicateCandidatePairs:jo,createDuplicateUnionFind:Kf};function Kf(e){let t=Array.from({length:e},(n,i)=>i);return{parent:t,findRoot:n=>{let i=n;for(;t[i]!==i;)i=t[i];for(;t[n]!==n;){let r=t[n];t[n]=i,n=r}return i}}}function CS(e,t,n,i){let r=[];for(let s of t){let[a,o]=s.split(":").map(u=>Number.parseInt(u,10)),c=oo(e[a].prepared,e[o].prepared);if(c.score<n)continue;let d=i.findRoot(a),l=i.findRoot(o);d!==l&&(i.parent[l]=d),r.push({left_id:e[a].item.id,right_id:e[o].item.id,...c})}return r}function zf(e,t,n,i){let r=new Map;for(let o of e.keys()){let c=n.findRoot(o),d=r.get(c)??[];d.push(o),r.set(c,d)}let s=new Map(e.map(({item:o},c)=>[o.id,n.findRoot(c)])),a=new Map;for(let o of t){let c=s.get(o.left_id),d=a.get(c)??[];d.push(o),a.set(c,d)}return[...r.values()].filter(o=>o.length>1).map(o=>{let c=(a.get(n.findRoot(o[0]))??[]).sort((d,l)=>l.score-d.score||d.left_id.localeCompare(l.left_id)||d.right_id.localeCompare(l.right_id));return{id:e[o[0]].item.id,items:o.map(d=>{let l=e[d].item;return{id:l.id,title:l.title,status:l.status,type:l.type}}),matches:c,max_score:c[0]?.score??0}}).sort((o,c)=>c.max_score-o.max_score||o.id.localeCompare(c.id)).slice(0,i)}function xS(e,t,n,i,r){return t.filter(s=>!n.has(s.id)).map(s=>({id:s.id,title:s.title,status:s.status,type:s.type,...ao(e,s.title)})).filter(s=>s.score>=i).sort((s,a)=>a.score-s.score||s.id.localeCompare(a.id)).slice(0,r)}async function RS(e,t={}){let n=e.title.trim();if(n.length===0)throw new _("Similarity candidate title must not be empty.",m.USAGE);let{limit:i,threshold:r}=Go(t),s=x(t.cwd??process.cwd(),t.pmRoot),a=await I(s),o=F(a),c=await ar(s,Object.values(o.type_to_folder)),d=ro(n),l=c&&d.length>0?await wu({pmRoot:s,expectedSourceCursor:c.source_cursor,query:d.map(g=>`"${g.replaceAll('"','""')}"`).join(" OR "),limit:Math.max(i*10,50)}):null,u=l===null?await Se(s,a.item_format,o.type_to_folder,void 0,a.schema):l.items,p=xS(n,u,new Set(e.excludeIds??[]),r,i);return{items:p,count:p.length,threshold:r,source:l?"persistent_index":"metadata_fallback"}}function OS(e,t={}){let{threshold:n}=Go({...t,limit:void 0}),{limit:i}=qf(t),r=new Set;for(let l of e){if(!l.id.trim()||r.has(l.id))throw new _("Duplicate analysis requires unique non-empty item ids.",m.USAGE);r.add(l.id)}let s=[...e].sort((l,u)=>l.id.localeCompare(u.id)).map(l=>({item:l,prepared:so(l.title)})),a=jo(s,Hr,n,t.exhaustive===!0),o=Kf(s.length),c=CS(s,a,n,o),d=zf(s,c,o,i);return{clusters:d,count:d.length,threshold:n,cost:{item_count:s.length,algorithm:t.exhaustive===!0||n===0?"exhaustive":"prefix_exact",possible_pairs:s.length*(s.length-1)/2,pair_limit:Hr,recall_guarantee:"exact",candidate_pairs:a.size,scored_pairs:a.size}}}async function Wf(e={}){Go({...e,limit:void 0});let{since:t}=qf(e),{items:n,statuses:i}=await IS(e,t);return{...OS(n,e),source:"metadata_scan",filters:{statuses:i??null,since:e.since??null}}}async function qo(e,t){if(t.mode==="off")return;let n=await RS(e,t);if(n.count===0)return;let i=await AS(n,t),r=t.mode==="strict"&&t.allowDuplicate===!0;if(t.mode==="strict"&&!r){let s=n.items.map(o=>`${o.id} (${o.status}): ${o.title}`).join("; "),a=i.action==="reopen"?"Reopen the canonical item":"Reuse the canonical item";throw new _(`Likely duplicate item(s) found: ${s}. ${a} or pass --allow-duplicate with explicit intent.`,m.CONFLICT,{code:"likely_duplicate",required:`${a}, or explicitly acknowledge the duplicate with --allow-duplicate.`,recovery:{suggested_flags:["--allow-duplicate"],suggested_retry:i.command,suggested_retry_args:i.args}})}return{mode:t.mode,bypassed:r,result:n,recovery:i}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="499dfc08-cf70-55fe-8868-65c3107e3a91")}catch{}})();async function iU(e,t={}){let n=await Wf({pmRoot:x(process.cwd(),e.path),exhaustive:t.exhaustive,...t.status===void 0?{}:{statuses:t.status.flatMap(i=>i.split(",").map(r=>r.trim()).filter(Boolean))},...t.since===void 0?{}:{since:t.since},...t.threshold===void 0?{}:{threshold:t.threshold},...t.limit===void 0?{}:{limit:t.limit}});return{...n,clusters:n.clusters.map(i=>{let r=i.id;return{...i,canonical_id:r,close_command:`pm close <duplicate-id> --duplicate-of ${r}`}}),guidance:{strategy:"review_then_close_duplicate",command:"pm close <duplicate-id> --duplicate-of <canonical-id>"}}}import{execFile as LS}from"node:child_process";import Bf 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]="3bb613e2-51f9-5947-8d92-d6207bb62cdc")}catch{}})();function Hf(e,t){return new Promise((n,i)=>{LS("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:4*1024*1024},(r,s)=>{r?i(r):n(s)})})}function Vf(e){if(e&&(!Number.isSafeInteger(e.start)||!Number.isSafeInteger(e.end)||e.start<1||e.end<e.start))throw new RangeError("Source line range must be inclusive positive integers with end >= start.")}function cU(e){let t=/^(\d+):(\d+)$/u.exec(e.trim()),n=t?{start:Number(t[1]),end:Number(t[2])}:void 0;if(Vf(n),!n)throw new RangeError("Source line range must use start:end.");return n}function DS(e){let t=new Map;for(let n of e.split(`
|
|
7
|
-
`)){let i=/^([0-9a-f^]{40,64}) \d+ \d+(?: \d+)?$/u.exec(n)?.[1];i&&t.set(i,(t.get(i)??0)+1)}return t}function NS(e){let t=e.split("\0"),n=new Map;for(let i=0;i+1<t.length;i+=2){let r=t[i]?.trim();if(!r)continue;let s=[...new Set(t[i+1]?.match(/\bpm-[a-z0-9][a-z0-9-]{2,63}\b/gu)??[])].sort((a,o)=>a.localeCompare(o));n.set(r,s)}return n}async function MS(e){let t=Bf.relative(e.workspaceRoot,Bf.resolve(e.workspaceRoot,e.sourcePath)),n=await Hf(e.workspaceRoot,["blame","--line-porcelain","-L",`${e.lineRange.start},${e.lineRange.end}`,"--",t]),i=await Hf(e.workspaceRoot,["log","-n","256","--format=%H%x00%B%x00","--",t]);return{commitLines:DS(n),commitItems:NS(i),available:!0}}function PS(e){let t=e.current.nodes.at(-1),n=e.current.kinds.length+1,i;for(let r of e.graph.incidentEdges(t)){let s=r.source===t,a=s?r.target:r.source;if((e.visitedDepth.get(a)??Number.POSITIVE_INFINITY)<n)continue;e.visitedDepth.set(a,n);let o=e.graph.registry().require(r.kind),c={nodes:[...e.current.nodes,a],kinds:[...e.current.kinds,s?r.kind:o.inverse??r.kind]};e.details.get(a)?.type?.toLowerCase()==="decision"?(i=n,e.found.push(c)):e.queue.push(c)}return i}function FS(e){let t=[{nodes:[e.itemId],kinds:[]}],n=new Map([[e.itemId,0]]),i=[],r;for(;t.length>0;){let s=t.shift(),a=s.kinds.length;r!==void 0&&a>=r||a>=e.maxDepth||(r=PS({current:s,graph:e.graph,details:e.details,visitedDepth:n,queue:t,found:i})??r)}return i.sort((s,a)=>s.nodes.join("\0").localeCompare(a.nodes.join("\0"))),i}function $S(e,t,n){let i=W_(t);if(!i.graph.hasNode(e))return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let r=FS({itemId:e,maxDepth:n,graph:i.graph,details:new Map(i.details.map(o=>[o.id,o]))}),s=r[0];if(!s)return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let a=[...new Set(r.map(o=>o.nodes.at(-1)))];return{status:a.length===1?"found":"ambiguous",nodes:s.nodes,kinds:s.kinds,alternative_decision_ids:a.slice(1)}}async function US(e){if(!e.lineRange)return{commitLines:new Map,commitItems:new Map,available:!0};try{return await MS({workspaceRoot:e.workspaceRoot,sourcePath:e.paths[0],lineRange:e.lineRange})}catch{return{commitLines:new Map,commitItems:new Map,available:!1}}}function jS(e){let t=[];return e.hasLineRange&&!e.attributionAvailable&&t.push("git_attribution_unavailable"),e.hasLineRange&&e.contributionLines===0&&t.push("line_attribution_unmapped"),e.decisionStatus==="ambiguous"&&t.push("multiple_governing_decisions"),e.decisionStatus==="not_found"&&t.push("governing_decision_not_found"),t}function GS(e){return[...e.commitLines.keys()].filter(t=>(e.commitItems.get(t)?.length??0)>0)}async function Yf(e){Vf(e.lineRange);let t=e.decisionDepth??8;if(!Number.isSafeInteger(t)||t<1||t>32)throw new RangeError("Decision path depth must be an integer from 1 to 32.");let n=await US(e),i=GS(n),r=new Map;for(let s of e.candidates){let a=[...n.commitLines.entries()].filter(([l])=>n.commitItems.get(l)?.includes(s.item.id)),o=a.reduce((l,[,u])=>l+u,0),c=$S(s.item.id,e.corpus,t),d=jS({hasLineRange:e.lineRange!==void 0,attributionAvailable:n.available,contributionLines:o,decisionStatus:c.status});r.set(s.item.id,{score:o*100+s.files.length*10+Math.max(0,9-Math.floor((Date.now()-Date.parse(s.item.updated_at))/(720*60*60*1e3))),contribution_lines:o,evidence:[...s.files.map(l=>({kind:"linked_file",reference:l.path})),...a.map(([l,u])=>({kind:"git_commit",reference:l.slice(0,12),contribution_lines:u}))],rationale:{value:s.item.value?.trim()||null,why_now:s.item.why_now?.trim()||null,outcome:s.item.outcome?.trim()||null,objective:s.item.objective?.trim()||null},decision_path:c,ambiguities:d})}return{explanations:r,receipt:{line_range:e.lineRange??null,blamed_commit_count:n.commitLines.size,mapped_commit_count:i.length,unmapped_commit_count:n.commitLines.size-i.length,decision_depth:t}}}import Jf from"node:fs/promises";import je 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]="06b0bd73-d282-5473-a1da-f11c61a0a086")}catch{}})();var qS=32768;function Ko(e){return _t(je.normalize(e))}async function Vr(e){try{return await Jf.realpath(e)}catch{return je.resolve(e)}}function wn(e,t){let n=je.isAbsolute(e.path)?je.resolve(e.path):je.resolve(t,e.path);return`${Ko(n)}::${e.scope}`}function Yr(e,t,n){if(typeof e=="string"){let i=e.trim();i.length>0&&n.push({field:t,value:i});return}if(Array.isArray(e)){e.forEach((i,r)=>Yr(i,`${t}[${r}]`,n));return}if(typeof e=="object"&&e!==null)for(let[i,r]of Object.entries(e))Yr(r,t?`${t}.${i}`:i,n)}function KS(e){let t=[];return Yr(e.metadata,"metadata",t),Yr(e.body,"body",t),t}function zS(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 WS(e){let t=[],n=/(?:[A-Za-z]:[\\/]|\/)[^\s"'`<>()[\]{},;]+/gu,i=/(?:\.{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 r of e){let s=new Set,a=r.value.slice(0,qS);for(let[o,c]of[[n,r.value],[i,a]]){o.lastIndex=0;for(let d of c.matchAll(o)){let l=zS(d[0]);!l||s.has(l)||(s.add(l),t.push({field:r.field,value:l}))}}}return t}async function BS(e,t,n=t){let i=je.isAbsolute(e)?je.resolve(e):je.resolve(n,e),r;try{r=await Jf.stat(i)}catch{return}if(!r.isFile())return;let[s,a]=await Promise.all([Vr(t),Vr(i)]);if(Na(s,a)){let o=je.relative(s,a);return!o||o.startsWith("..")||je.isAbsolute(o)?void 0:{path:Ko(o),scope:"project"}}return{path:Ko(i),scope:"global"}}async function HS(e,t,n=t){let i=new Set((e.metadata.files??[]).map(c=>wn(c,t))),r=new Map,s=WS(KS(e)),a=new Map;await Promise.all([...new Set(s.map(c=>c.value))].map(async c=>{a.set(c,await BS(c,t,n))}));let o=s.map(c=>({reference:c,resolved:a.get(c.value)}));for(let{reference:c,resolved:d}of o){if(!d)continue;let l=wn(d,t),u=r.get(l)??{path:d.path,scope:d.scope,sourceFields:new Set,originalPaths:new Set,sourceCount:0};u.sourceFields.add(c.field),u.originalPaths.add(c.value),u.sourceCount+=1,r.set(l,u)}return[...r.entries()].map(([c,d])=>({path:d.path,scope:d.scope,status:i.has(c)?"already_linked":"addable",source_count:d.sourceCount,source_fields:[...d.sourceFields].sort((l,u)=>l.localeCompare(u)),original_paths:[...d.originalPaths].sort((l,u)=>l.localeCompare(u))})).sort((c,d)=>{let l=c.status.localeCompare(d.status);if(l!==0)return l;let u=c.path.localeCompare(d.path);return u!==0?u:c.scope.localeCompare(d.scope)})}async function Xf(e,t,n){let i=await Wr(e,t,n,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return Br(i,"files")}async function VS(e,t){let n=await Vr(t),i=await Promise.all(e.map(async s=>{let a=s.trim();if(!a)throw new _("Files lookup paths must not be empty.",m.USAGE);if(!je.isAbsolute(a))return _t(a);let o=await Vr(a);return Na(n,o)?_t(je.relative(n,o)):_t(o)})),r=[...new Set(i)].sort((s,a)=>s.localeCompare(a));if(r.length===0)throw new _("Files lookup requires at least one path.",m.USAGE);return r}function YS(e){for(let[i,r]of[["limit",e.limit],["offset",e.offset]])if(r!==void 0&&(!Number.isInteger(r)||r<0))throw new _(`Files lookup ${i} must be a non-negative integer.`,m.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 Qf(e){return{id:e.id,title:e.title,type:e.type,status:e.status,priority:e.priority,updated_at:e.updated_at}}function Zf(e,t){let n=e.item.priority-t.item.priority;if(n!==0)return n;let i=t.item.updated_at.localeCompare(e.item.updated_at);return i===0?e.item.id.localeCompare(t.item.id):i}function JS(e){return e.metadata.map(t=>({item:t,files:(t.files??[]).filter(n=>e.paths.includes(_t(n.path))&&(e.scope===void 0||n.scope===e.scope)).sort((n,i)=>{let r=n.path.localeCompare(i.path);return r===0?n.scope.localeCompare(i.scope):r})})).filter(t=>t.files.length>0).sort(Zf)}async function XS(e){if(e.explain)return Yf({workspaceRoot:e.workspaceRoot,paths:e.paths,candidates:e.matching,corpus:e.metadata,...e.lineRange?{lineRange:e.lineRange}:{},...e.decisionDepth===void 0?{}:{decisionDepth:e.decisionDepth}})}async function QS(e){if([e.strictRead,e.noTruncate,e.explain,ql()].includes(!0))return null;let t=await ar(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]);return t?vu({pmRoot:e.pmRoot,expectedSourceCursor:t.source_cursor,paths:e.paths,scope:e.scope,limit:e.limit,offset:e.offset}):null}async function ZS(e){let t=[],n=await or(e.pmRoot,e.settings.item_format,e.typeToFolder,t,e.settings.schema),i=JS({metadata:n,paths:e.paths,scope:e.scope}),r=t.filter(o=>/^item_list_(?:item|directory)_read_failed:/u.test(o));if(e.strictRead&&r.length>0)throw new _(`Files lookup could not read every item: ${r.join("; ")}`,m.GENERIC_FAILURE);let s=await XS({explain:e.explain,workspaceRoot:e.workspaceRoot,paths:e.paths,matching:i,metadata:n,lineRange:e.lineRange,decisionDepth:e.decisionDepth}),a=(s?[...i].sort((o,c)=>{let d=s.explanations.get(c.item.id).score-s.explanations.get(o.item.id).score;return d!==0?d:Zf(o,c)}):i).slice(e.offset,e.limit===void 0?void 0:e.offset+e.limit);return{paths:e.paths,total:i.length,count:a.length,offset:e.offset,limit:e.limit??null,has_more:e.offset+a.length<i.length,truncated:e.offset+a.length<i.length,completeness:{status:r.length===0?"complete":"partial",source:"source_scan"},warnings:t,matches:a.map(o=>({item:Qf(o.item),files:o.files,...s?{traceability:s.explanations.get(o.item.id)}:{}})),...s?{traceability_receipt:s.receipt}:{}}}async function AU(e,t){let n=x(process.cwd(),t.path),i=Je(n);await $(n);let r=await VS(e.paths,i);if(e.lineRange&&r.length!==1)throw new _("Files lookup line attribution requires exactly one source path.",m.USAGE);let s=await I(n),a=F(s,P()),{offset:o,limit:c}=YS(e),d=await QS({pmRoot:n,typeToFolder:a.type_to_folder,paths:r,scope:e.scope,limit:c,offset:o,strictRead:e.strictRead===!0,noTruncate:e.noTruncate===!0,explain:e.explain===!0||e.lineRange!==void 0});return d?{paths:r,total:d.total,count:d.matches.length,offset:o,limit:c,has_more:o+d.matches.length<d.total,truncated:o+d.matches.length<d.total,completeness:{status:"unchecked",source:"index"},warnings:[],matches:d.matches.map(l=>({item:Qf(l.item),files:l.files}))}:ZS({pmRoot:n,settings:s,typeToFolder:a.type_to_folder,paths:r,scope:e.scope,limit:c,offset:o,strictRead:e.strictRead===!0,workspaceRoot:i,explain:e.explain===!0||e.lineRange!==void 0,lineRange:e.lineRange,decisionDepth:e.decisionDepth})}async function IU(e,t,n){let i=x(process.cwd(),n.path),r=Je(i);await $(i);let s=await I(i),a=F(s,P()),o=await Y(i,e,s.id_prefix,s.item_format,a.type_to_folder);if(!o)throw new _(`Item ${e} not found`,m.NOT_FOUND);let c=await he(o,{schema:s.schema}),d=await HS(c.document,r,process.cwd()),l=d.filter(E=>E.status==="addable"),u=d.filter(E=>E.status==="already_linked"),p=t.apply===!0,g=t.note?.trim()||"discovered from item text";if(!p||l.length===0){let E=c.document.metadata.files??[];return{id:o.id,files:E,changed:!1,apply:p,count:E.length,candidate_count:d.length,addable_count:l.length,added_count:0,skipped_existing_count:u.length,candidates:d,added:[],skipped_existing:u}}let f=U(t.author,s.author_default),h=l.map(E=>({path:E.path,scope:E.scope,note:g})),y=[],v=new Set,w=await se({pmRoot:i,settings:s,id:e,op:"files_discover",author:f,message:t.message??"Discover referenced file links",force:t.force,mutate(E){let N=[...E.metadata.files??[]],T=new Set(N.map(pe=>wn(pe,r)));y=[],v.clear();for(let[pe,ce]of h.entries()){let de=wn(ce,r);T.has(de)||(N.push(ce),T.add(de),y.push(ce),v.add(pe))}let R=Uo(N),G=t.appendStable?R:$o(R);return G.length>0?E.metadata.files=G:delete E.metadata.files,{changedFields:y.length>0?["files"]:[],warnings:y.length!==h.length?[`files_discover_skipped_existing:${h.length-y.length}`]:[]}}}),k=w.item.files??[],S=new Set(y.map(E=>wn(E,r))),A=k.filter(E=>S.has(wn(E,r))),C=l.filter((E,N)=>!v.has(N)),b=[...u,...C];return{id:w.item.id,files:k,changed:A.length>0,apply:!0,count:k.length,candidate_count:d.length,addable_count:l.length,added_count:A.length,skipped_existing_count:b.length,candidates:d,added:A,skipped_existing:b}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bee6d15d-ca4a-538c-bb70-fd3dc7e2a8ec")}catch{}})();var mi=["software-delivery","research","agent-evaluation","operations"];function eg(e,t,n,i,r){return{id:e,measurement_id:t,owner_item_id:n,scope:{kind:"active"},ceiling:i,lifetime:"hold",enforcement:r,negative_control:{cases:[{observed:i,expected:"pass"},{observed:i+1,expected:"fail"}]}}}function Jr(e,t,n,i,r){let s=`preset-${e}`,a=r.map(c=>({id:`${s}-missing-${c}`,description:`Active items missing ${c} evidence.`,source:{kind:"links",link:c,state:"missing"}})),o=a.map(c=>eg(`${c.id}-zero`,c.id,i,0,"warn"));return{id:e,title:t,description:n,declarations:{measurements:a,assertions:o,gates:[{id:`${s}-readiness`,description:n,assertion_ids:o.map(c=>c.id),triggers:["ci","scheduled"]}]}}}function Xr(e,t){return e==="software-delivery"?Jr(e,"Software delivery","Warn when active delivery work lacks executable tests or documentation.",t,["tests","docs"]):e==="research"?Jr(e,"Research","Warn when active research work lacks reproducibility files or documentation.",t,["files","docs"]):e==="agent-evaluation"?Jr(e,"Agent evaluation","Warn when active evaluation work lacks executable scenarios or recorded artifacts.",t,["tests","files"]):Jr(e,"Operations","Warn when active operational work lacks runbook documentation or repair evidence.",t,["docs","files"])}function tg(e,t,n,i={}){return Io(e,Xr(t,n).declarations,i)}async function ng(e,t){let n=new Set(e.terminal_statuses??["closed","canceled"]),i={...e,items:e.items.filter(r=>!n.has(r.status))};return await Promise.all(["files","tests","docs"].map(async r=>{let s={id:`derived-active-missing-${r}`,description:`Observed active items missing ${r} evidence.`,source:{kind:"links",link:r,state:"missing"}},a=(await To(s,i)).value,o=eg(`${s.id}-ceiling`,s.id,t,a,"observe"),c=`active-missing-${r}`;return{id:c,population_size:i.items.length,scope:{kind:"active"},observed:a,declarations:{measurements:[s],assertions:[o],gates:[{id:`derived-${c}`,description:`Observe the accepted ${r} evidence baseline.`,assertion_ids:[o.id],triggers:["ci","scheduled"]}]}}}))}function ig(e,t,n={}){return Io(e,{measurements:t.flatMap(i=>i.declarations.measurements),assertions:t.flatMap(i=>i.declarations.assertions),gates:t.flatMap(i=>i.declarations.gates)},n)}async function rg(e,t,n,i={}){let r=t.enforcement==="observe"?"warn":"block";if(t.enforcement==="block"||n!==r)throw new TypeError(`assurance assertion ${t.id} promotion must be ${t.enforcement} -> ${r}`);return Fr(e,"assertion",{...t,enforcement:n},{...i,message:i.message??`Promote assurance assertion ${t.id} from ${t.enforcement} to ${n}`})}import og from"node:fs/promises";import{createRequire as eT}from"node:module";import De 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]="32adaa7c-f0aa-5aff-8d88-d7c0ccfbd971")}catch{}})();function sg(e,t){let n=De.relative(t,e);if(n.length>0&&n!==".."&&!n.startsWith(`..${De.sep}`)&&!De.isAbsolute(n))return n.split(De.sep).join("/");let i=De.resolve(e),r=0xcbf29ce484222325n;for(let s=0;s<i.length;s+=1)r^=BigInt(i.charCodeAt(s)),r=BigInt.asUintN(64,r*0x100000001b3n);return`<external>/${r.toString(16).padStart(16,"0")}/${De.basename(De.dirname(e))}/package.json`}function tT(e){return e.includes(`${De.sep}.pnpm${De.sep}`)?"pnpm":e.includes(`${De.sep}node_modules${De.sep}`)?"npm":"other"}async function ag(e){try{let t=JSON.parse(await og.readFile(e,"utf8"));return t.name==="@unbrained/pm-cli"&&typeof t.version=="string"&&t.version.trim().length>0?t.version.trim():void 0}catch{return}}async function zo(e){try{return await og.realpath(e)}catch{return De.resolve(e)}}async function cg(e,t,n=sl(import.meta.url,["../../.."])){let i=await zo(t),r=await zo(De.join(n,"package.json")),s=await ag(r),a=new Map;s!==void 0&&a.set(r,{version:s,path:sg(r,i),layout:"host",consumers:["pm-cli-host"]});for(let d of e)try{let l=eT(d.entry_path).resolve("@unbrained/pm-cli/package.json"),u=await zo(l),p=await ag(u);if(p===void 0)continue;let g=u,f=a.get(g);if(f){f.consumers.includes(d.name)||(f.consumers.push(d.name),f.consumers.sort((h,y)=>h.localeCompare(y)));continue}a.set(g,{version:p,path:sg(u,i),layout:tT(u),consumers:[d.name]})}catch{}let o=[...a.values()].sort((d,l)=>d.path.localeCompare(l.path)),c=s===void 0?[]:o.filter(d=>d.version!==s);return{host_version:s??null,copies:o,mismatches:c,warnings:c.map(d=>`extension_host_pm_cli_version_skew:${s}:${d.version}:${d.consumers.join("+")}`)}}import{createHash as nT}from"node:crypto";import Qr 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]="36749195-9194-546a-bc3e-718f09c3b8d6")}catch{}})();var iT="2026-08-09T16:15:18.000Z",lg=Symbol("pre-durable-disposition-eligible");function pt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Wo(e){if(!Array.isArray(e)||e.length>256)return!1;let t=new Set;for(let n=0;n<e.length;n+=1){let i=e[n];if(!(n in e)||typeof i!="string"||i.length===0||i.length>256||i.includes("\0")||t.has(i))return!1;t.add(i)}return!0}function dg(e){return pt(e)?typeof e.field=="string"&&e.field.length>0&&e.field.length<=256&&!e.field.includes("\0")&&typeof e.retained_hash=="string"&&/^[a-f0-9]{64}$/u.test(e.retained_hash)&&typeof e.discarded_hash=="string"&&/^[a-f0-9]{64}$/u.test(e.discarded_hash):!1}function ug(e,t){if(typeof e!="string")return!1;let n=Qr.posix.normalize(e);return e.length<=4096&&!e.includes("\\")&&!e.includes("\0")&&!Qr.posix.isAbsolute(e)&&n===e&&!n.startsWith("../")&&(Qr.posix.basename(n)===`${t}.toon`||Qr.posix.basename(n)===`${t}.md`)}function rT(e,t){return typeof e.receipt_id=="string"&&Qn(e.receipt_id)&&(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0&&e.conflict_resolution===void 0&&e.item_id===t&&ug(e.item_path,t)}function mg(e){let t=e.conflict_fields,n=e.fields_from_theirs,i=e.union_fields,r=e.decisions,s=Array.isArray(r)?new Set(r.flatMap(a=>dg(a)?[a.field]:[])):new Set;return Wo(t)&&Wo(n)&&Wo(i)&&Array.isArray(r)&&r.length>0&&r.length<=256&&Object.keys(r).length===r.length&&r.every(dg)&&s.size===r.length&&t.length===s.size&&t.every(a=>s.has(a))}function sT(e,t){return rT(e,t)&&mg(e)}function aT(e,t){return typeof e.receipt_id=="string"&&Qn(e.receipt_id)&&(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0&&(e.conflict_resolution==="preferred_side"||e.conflict_resolution==="stable_value_order")&&e.item_id===t&&ug(e.item_path,t)&&mg(e)}function oT(e){return e[lg]===!0}function _g(e,t){if(!pt(e)||!pt(e.context))return[];let n=e.context.merge;return!pt(n)||!Array.isArray(n.receipts)?[]:n.receipts.flatMap(i=>!pt(i)||typeof i.receipt_id!="string"||i.receipt_id.trim().length===0?[]:[{receiptId:i.receipt_id,legacySummaryAccepted:sT(i,t),[lg]:aT(i,t),...typeof e.ts=="string"&&Ka(e.ts)?{eventTimestamp:e.ts}:{}}])}function pg(e,t,n){if(!pt(e)||e.op!=="merge_reconcile")return[];if(!pt(e.context)||!pt(e.context.merge))return[];let i=e.context.merge.missing_receipt_dispositions;return!Array.isArray(i)||i.length>256?[]:i.flatMap(r=>!pt(r)||typeof r.receipt_id!="string"||!Qn(r.receipt_id)||typeof r.original_history_line!="number"||!Number.isSafeInteger(r.original_history_line)||r.original_history_line<1||typeof r.original_event_ts!="string"||!Ka(r.original_event_ts)||r.reason!=="legacy_clone_local_only"?[]:[{itemId:t,receiptId:r.receipt_id,originalHistoryLine:r.original_history_line,originalEventTimestamp:r.original_event_ts,auditHistoryLine:n,reason:r.reason}])}function fg(e,t,n=[]){let i=new Map;for(let s of n){let a=`${s.itemId}\0${s.originalHistoryLine}\0${s.receiptId}\0${s.originalEventTimestamp}`;i.set(a,Math.max(i.get(a)??0,s.auditHistoryLine))}let r=s=>oT(s)&&s.eventTimestamp!==void 0&&Xi(s.eventTimestamp,iT)<0&&(i.get(`${s.itemId}\0${s.line}\0${s.receiptId}\0${s.eventTimestamp}`)??0)>s.line;return{missing:e.filter(s=>!s.legacySummaryAccepted&&!t.has(s.receiptId)&&!r(s)).map(s=>({item_id:s.itemId,history_line:s.line,...Qn(s.receiptId)?{receipt_id:s.receiptId}:{receipt_reference_hash:nT("sha256").update(s.receiptId).digest("hex")}})),acceptedLegacyCount:e.filter(s=>s.legacySummaryAccepted).length,acceptedDispositionCount:e.filter(r).length}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d8f1968e-a030-5a3c-b766-60a409163745")}catch{}})();function Zr(e,t,n=25){let i=e.definitions.filter(a=>a.roles.length===0).map(a=>a.id).sort((a,o)=>a.localeCompare(o)),r=new Set(i),s=t.filter(a=>{let o=Ke(a.status,e);return o!==void 0&&r.has(o)}).map(a=>a.id).sort((a,o)=>a.localeCompare(o));return{roleless_status_count:i.length,roleless_statuses:i.slice(0,n),roleless_statuses_truncated:i.length>n,affected_item_count:s.length,affected_item_ids:s.slice(0,n),affected_item_ids_truncated:s.length>n}}function es(e){return e.roleless_status_count===0?[]:[`schema_status_missing_lifecycle_role:${e.roleless_status_count}`]}import ft from"node:fs/promises";import Ce from"node:path";import _i from"node:fs/promises";import ts 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]="b5974276-3b45-5ad6-a7aa-e05a33807ee7")}catch{}})();function cT(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t,{id:i,owner:r,created_at:s,ttl_seconds:a}=n;return typeof i!="string"||typeof r!="string"||typeof s!="string"||typeof a!="number"||!Number.isFinite(a)?null:{id:i,owner:r,created_at:s,ttl_seconds:a}}function gg(e,t,n){let i=cT(t);if(i===null)return{detail:"unparseable_json",entry:{file:e,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"}};let r=Date.parse(i.created_at);if(!Number.isFinite(r))return{detail:"invalid_timestamp",entry:{file:e,id:i.id,owner:i.owner,created_at:i.created_at,ttl_seconds:i.ttl_seconds,age_seconds:null,stale:!1,reason:"unparseable"}};let s=n-r,a=Math.floor(s/1e3),o=s>i.ttl_seconds*1e3;return{detail:o?"expired":"active",entry:{file:e,id:i.id,owner:i.owner,created_at:i.created_at,ttl_seconds:i.ttl_seconds,age_seconds:a,stale:o,reason:o?"expired":"active"}}}async function hg(e,t){let n=t??Date.now(),i=ts.join(e,"locks"),r={scanned:0,active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0},s;try{s=(await _i.readdir(i)).filter(a=>a.endsWith(".lock")).sort()}catch(a){if(q(a))return r;throw a}for(let a of s){let o;try{o=await _i.readFile(ts.join(i,a),"utf8")}catch(d){if(q(d))continue;r.scanned+=1,r.unreadable_lock_count+=1;continue}r.scanned+=1;let{detail:c}=gg(a,o,n);c==="active"?r.active_lock_count+=1:c==="expired"?r.stale_lock_count+=1:r.unparseable_lock_count+=1}return r}async function yg(e,t){let{dryRun:n,hooks:i}=t,r=t.now??Date.now(),s=ts.join(e,"locks"),a={scanned:0,removed:[],retained:[],warnings:[],entries:[]},o;try{o=(await _i.readdir(s)).filter(c=>c.endsWith(".lock")).sort()}catch(c){if(q(c))return a;throw c}for(let c of o){a.scanned+=1;let d=ts.join(s,c),l=`locks/${c}`;if(i?.onRead){let g=await i.onRead(d);a.warnings.push(...g)}let u;try{u=await _i.readFile(d,"utf8")}catch(g){if(q(g)){a.scanned-=1;continue}a.warnings.push(`lock_unreadable:${c}`),a.retained.push(l),a.entries.push({file:c,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let p=gg(c,u,r);if(p.detail==="unparseable_json"){a.warnings.push(`lock_unparseable:${c}`),a.retained.push(l),a.entries.push(p.entry);continue}if(p.detail==="invalid_timestamp"){a.warnings.push(`lock_invalid_timestamp:${c}`),a.retained.push(l),a.entries.push(p.entry);continue}if(p.detail==="active"){a.retained.push(l),a.entries.push(p.entry);continue}if(!n){try{await _i.unlink(d)}catch(g){if(!q(g)){a.warnings.push(`lock_remove_failed:${c}`),a.retained.push(l),a.entries.push(p.entry);continue}}if(i?.onWrite){let g=await i.onWrite(d);a.warnings.push(...g)}}a.removed.push(l),a.entries.push(p.entry)}return 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]="270d544f-ac42-559f-ba6a-82f3d3b6c187")}catch{}})();var dT=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:"merge_driver_configuration_missing",command:"pm merge install",summary:"Install the clone-local Git drivers required by the tracker merge fence."},{code:"merge_driver_configuration_drift",command:"pm merge install",summary:"Reinstall clone-local Git drivers after runtime or package paths change."},{code:"merge_fence_missing",command:"pm merge install",summary:"Install the active tracker's committed Git merge attributes."},{code:"merge_fence_drift",command:"pm merge install",summary:"Restore the active tracker's merge mappings while retaining sibling tracker fences."},{code:"validate_merge_driver_configuration",command:"pm merge install",summary:"Restore missing or drifted clone-local Git merge driver commands."},{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 pending receipt summaries, re-apply intended discarded values, then run pm merge reconcile. If proof is unavailable or receipt decisions are lossy, explicit review authority is required for pm merge reconcile --force --message "<reviewed receipt disposition and rationale>"; this records acceptance rather than restoring discarded values.'},{code:"merge_receipts_pending",command:"pm merge reconcile",summary:'A lossless receipt is pending; preview with pm merge reconcile --dry-run, then apply. If no receipt set proves the snapshot, review the summaries and only with explicit authority run pm merge reconcile --force --message "<reviewed receipt disposition and rationale>" to record an audited acceptance.'},{code:"merge_receipt_evidence_invalid",command:"pm merge report --include-reconciled --json",summary:"One or more receipt candidates failed bounded-file, schema, identity, or copy-consistency validation; inspect the report's privacy-safe source, receipt id, and reason before repairing only the named evidence."},{code:"merge_receipt_history_reference_missing",command:"pm merge reconcile --dry-run",summary:"Review the bounded coordinates and recover available evidence first; for exact pre-durable clone-local-only references, rerun with --force so pm appends an audited disposition and proves the health finding is cleared without rewriting history."},{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_drift_version_skew",command:"npm install -g @unbrained/pm-cli@latest",summary:"A history stream declares an item hash version this runtime does not support; upgrade pm to verify the chain instead of re-anchoring it."},{code:"history_drift_merge_receipt",command:"pm merge reconcile",summary:"Canonical path, changed-field, and merged-value hash evidence attributes this drift to a pending receipt; run reconciliation (optionally preview first with --dry-run) instead of repairing history directly."},{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:"provenance_value_domain_invalid",command:"pm history-repair --all --normalize-provenance",summary:"Remove invalid bounded provenance observations from affected streams and append privacy-safe aggregate repair receipts."},{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_closed_at",command:"pm validate --check-metadata --auto-fix --fix-scope timestamps --dry-run",summary:"Preview closure dates proven by verified lifecycle history; inspect residuals and omit --dry-run to apply only proven dates."},{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_history_drift_version_skews",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more history streams declare an item hash version this runtime does not support; upgrade pm to verify the chains instead of re-anchoring them."},{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 Bo(e){if(typeof e!="string")return;let t=e.trim();for(let n of dT)if(t===n.code||t.startsWith(`${n.code}:`))return n}function Ho(e){let t={};for(let n of e){let i=Bo(n);i!==void 0&&!Object.prototype.hasOwnProperty.call(t,i.code)&&(t[i.code]=i.command)}return t}function vg(e){return Object.values(Ho(e))}import{execFile as lT}from"node:child_process";import{realpath as uT}from"node:fs/promises";import wg from"node:path";import{promisify as mT}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]="9af87d55-dbe2-561b-9f3f-6f12c0416147")}catch{}})();var _T=mT(lT),pT=32*1024*1024,fT=1e4,gT=["search/eval-queries.json"];function Vo(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}function hT(e){return`'${e.replaceAll("'","'\\''")}'`}async function yT(e,t=uT){return t(e).catch(()=>wg.resolve(e))}async function ns(e){let t=await Tt(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 yT(e),i=Vo(wg.relative(t,n));if(i.length===0)return{git_workspace_root:t,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let r=J_.map(s=>`${i}/${Vo(s)}`);try{let{stdout:s}=await _T("git",["ls-files","-z","--",...r.map(d=>`:(literal)${d}`)],{cwd:t,encoding:"utf8",maxBuffer:pT,windowsHide:!0,timeout:fT}),a=new Set(gT.map(d=>`${i}/${d}`)),o=[...new Set(s.split("\0").filter(d=>d.length>0&&!a.has(Vo(d))))].sort((d,l)=>d.localeCompare(l)),c=r.filter(d=>o.some(l=>l===d||l.startsWith(`${d}/`)));return{git_workspace_root:t,tracker_relative_root:i,tracked_paths:o,tracked_path_count:o.length,remediation_command:o.length===0?null:`git rm --cached -r -- ${c.map(d=>hT(`:(literal)${d}`)).join(" ")}`}}catch{return{git_workspace_root:t,tracker_relative_root:i,tracked_paths:[],tracked_path_count:0,remediation_command:null}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2e510b32-f27f-5ba5-94b2-8268343359dc")}catch{}})();async function bg(e,t,n,i){if(t===null)return{audit:null,count:0,warnings:[]};let r=await un(e,ln(n));if(r.status==="ok")return{audit:r,count:0,warnings:[]};let s=Math.max(1,r.missing_patterns.length+r.stale_patterns.length);return{audit:r,count:s,warnings:i?[`merge_fence_${r.status==="not_installed"?"missing":"drift"}:${s}`]:[]}}function kg(e){let t=[];return e.invalidEvidenceCount>0&&t.push(`merge_receipt_evidence_invalid:${e.invalidEvidenceCount}`),e.missingHistoryReferenceCount>0&&t.push(`merge_receipt_history_reference_missing:${e.missingHistoryReferenceCount}`),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]="8011ffaf-ce7a-5c0b-930d-ed538bde89f0")}catch{}})();var vT=new Set(v_),Sg=25,bn=8,Gt=100,wT=Ce.join("runtime","telemetry","events.jsonl"),bT=Ce.join("runtime","telemetry","state.json"),kT=2500,ET=500,Tg=E_-3,ST=["x-pm-telemetry-max-schema-version","x-pm-telemetry-max-version"];function ec(e,t=!1){return e.startsWith("agent_guidance_")||e.startsWith("telemetry_")||e.startsWith("history_stream_over_compact_threshold:")||e.startsWith("integrity_legacy_hierarchy_")||e.startsWith("stale_in_progress_items:")||e.startsWith("provenance_resolver_zero_success:")||e.startsWith("provenance_value_domain_invalid:")||!t&&e.startsWith("merge_driver_configuration_missing:")}function tc(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function kn(e){return e.trim().toLowerCase()}function Xo(e,t){let n=kn(e),i=kn(t);return n.startsWith("builtin-")?!0:i==="beads"||i==="todos"}async function nc(e){try{return(await ft.stat(e)).isDirectory()}catch{return!1}}async function TT(e){let t=(await ft.readdir(e,{withFileTypes:!0})).filter(i=>i.isDirectory()),n=await Promise.all(t.map(i=>ft.readdir(Ce.join(e,i.name),{withFileTypes:!0})));return new Set(n.flatMap(i=>i.filter(r=>r.isFile()).filter(r=>Dt.some(s=>r.name.endsWith(s))).map(r=>Ce.parse(r.name).name)))}async function AT(e,t,n,i){let r=await $e({path:e,scope:"project"}),s=t!=="_workspace"&&!i.has(t);if(!n.enabled&&!s)return{warnings:r,overThreshold:!1,classification:"live"};let a;try{a=await ft.readFile(e,"utf8")}catch{return{warnings:r,overThreshold:!1,classification:"unreadable"}}let o="live";if(s){let d=a.split(/\r?\n/).map(l=>l.trim()).filter(Boolean).at(-1);try{o=JSON.parse(d??"{}").op==="delete"?"tombstone":"orphaned"}catch{o="orphaned"}}let c=n.enabled?a.split(/\r?\n/).filter(d=>d.trim().length>0).length:0;return{warnings:r,overThreshold:n.enabled&&c>n.max_entries,classification:o}}async function IT(e,t,n){let i=Ce.join(e,"history");if(!await nc(i))return{count:0,warnings:[],over_threshold:[],max_entries:null,tombstones:[],orphaned:[]};let r=(await ft.readdir(i)).filter(l=>l.endsWith(".jsonl")).sort((l,u)=>l.localeCompare(u)),s=t.enabled?t.max_entries:null,a=[],o=[],c=[],d=[];for(let l of r){let u=Ce.join(i,l),p=l.slice(0,-6),g=await AT(u,p,t,n);a.push(...g.warnings),g.classification==="tombstone"&&c.push(p),g.classification==="orphaned"&&d.push(p),g.overThreshold&&o.push(p)}return{count:r.length,warnings:[...a,...o.map(l=>`history_stream_over_compact_threshold:${l}`),...d.map(l=>`history_orphaned_stream:${l}`)],over_threshold:o,max_entries:s,tombstones:c,orphaned:d}}function Qo(e,t){return Ce.relative(e,t).replaceAll("\\","/")}async function Ag(e,t){let n=[...new Set(Object.values(t))].sort((r,s)=>r.localeCompare(s)),i=[];for(let r of n){let s=Ce.join(e,r),a=[];try{a=await ft.readdir(s)}catch(o){if(typeof o=="object"&&o!==null&&"code"in o&&q(o))continue;continue}for(let o of a)Dt.some(c=>o.toLowerCase().endsWith(c))&&i.push(Ce.join(s,o))}return i.sort((r,s)=>Qo(e,r).localeCompare(Qo(e,s))),i}function CT(e){return!(typeof e=="object"&&e!==null&&"code"in e&&q(e))}async function xT(e,t,n){let i=await Ag(e,t),r=[],s=[],a=[],o=[],c=Et(P());for(let d of i){let l=Qo(e,d),u;try{u=await ft.readFile(d,"utf8")}catch{r.push(l);continue}let p=sn(u);if(p){s.push({path:l,...p});continue}try{let g=nr(u,{format:gl(d),schema:n,extensionFieldNames:c});o.push({ref:l,version:er(g.metadata)})}catch{a.push(l)}}return{paths:i,unreadable:r,conflictMarkers:s,parseFailures:a,formatVersions:o}}async function RT(e){let t=Ce.join(e,"history"),n=[],i=[],r=[],s=[],a=[],o=[];try{o=(await ft.readdir(t)).filter(c=>c.endsWith(".jsonl")).sort((c,d)=>c.localeCompare(d))}catch(c){CT(c)&&n.push("history")}for(let c of o){let d=c.slice(0,-6),l;try{l=await ft.readFile(Ce.join(t,c),"utf8")}catch{n.push(d);continue}let u=sn(l);if(u){i.push({id:d,...u});continue}l.split(/\r?\n/).forEach((p,g)=>{if(p.trim())try{let f=JSON.parse(p);s.push(..._g(f,d).map(h=>({itemId:d,line:g+1,...h}))),a.push(...pg(f,d,g+1))}catch{r.push({id:d,line:g+1})}})}return{files:o,unreadable:n,conflictMarkers:i,invalidJson:r,mergeReceiptReferences:s,mergeReceiptDispositions:a}}function Ig(e){return[...e.cycles.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_cycle:${t.item_ids.join(",")}`:`integrity_hierarchy_cycle:${t.item_ids.join(",")}`),...e.cardinality_violations.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_cardinality:${t.child_id}`:`integrity_hierarchy_cardinality:${t.child_id}`),...e.divergences.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_divergence:${t.child_id}`:`integrity_hierarchy_divergence:${t.child_id}`)]}async function OT(e,t,n,i,r,s){let a=await xT(e,t,n),o=await RT(e),c=tr(a.formatVersions,jn,Zi),d=K(n),l=xr(s,T=>_e(T,d),ae()),u=await ns(e),p=await Tt(e),g=await bg(e,p,i,r),f=p===null?null:await mn(p),h=await _n(p??e,{includeReconciled:!0,includeLossless:!0,pmRoot:e}),y=new Set(h.receipts.map(T=>T.id)),v=fg(o.mergeReceiptReferences,y,o.mergeReceiptDispositions),w=v.missing,k=h.receipts.filter(T=>T.state==="pending"),{pendingDecisions:S,lossless:A}=pn(k),C=f?.status==="missing"&&f.missing_keys.length===5&&f.drifted_keys.length===0,b=[...a.unreadable.map(T=>`integrity_item_unreadable:${T}`),...a.conflictMarkers.map(T=>`integrity_item_conflict_marker:${T.path}:L${T.line}`),...a.parseFailures.map(T=>`integrity_item_parse_failed:${T}`),...o.unreadable.map(T=>`integrity_history_unreadable:${T}`),...o.conflictMarkers.map(T=>`integrity_history_conflict_marker:${T.id}:L${T.line}`),...o.invalidJson.map(T=>`integrity_history_invalid_json:${T.id}:L${T.line}`),...c.outdated.map(T=>`integrity_item_outdated_format_version:${T}`),...c.ahead.map(T=>`integrity_item_ahead_format_version:${T}`),...Ig(l),...u.tracked_path_count>0?[`tracked_runtime_cache_files:${u.tracked_path_count}`]:[],...f!==null&&f.status!=="ok"?[`merge_driver_configuration_${C?"missing":"drift"}:${f.missing_keys.length+f.drifted_keys.length}`]:[],...g.warnings,...S.length>0?[`merge_decisions_unreviewed:${S.length}`]:[],...A.length>0?[`merge_receipts_pending:${A.length}`]:[],...kg({invalidEvidenceCount:h.invalid_evidence_count,missingHistoryReferenceCount:w.length})],E=[...new Set(b)].sort((T,R)=>T.localeCompare(R)),N=E.filter(T=>!T.startsWith("integrity_legacy_hierarchy_"));return{check:{name:"integrity",status:N.length===0?"ok":"warn",ok:N.length===0,details:{checked_item_files:a.paths.length,checked_history_streams:o.files.length,counts:{item_unreadable:a.unreadable.length,item_conflict_markers:a.conflictMarkers.length,item_parse_failures:a.parseFailures.length,history_unreadable:o.unreadable.length,history_conflict_markers:o.conflictMarkers.length,history_invalid_json:o.invalidJson.length,item_outdated_format_version:c.outdated.length,item_ahead_format_version:c.ahead.length,hierarchy_cycles:l.cycles.length,hierarchy_cardinality_violations:l.cardinality_violations.length,hierarchy_parent_divergences:l.divergences.length,tracked_runtime_cache_files:u.tracked_path_count,merge_driver_configuration:f===null||f.status==="ok"?0:f.missing_keys.length+f.drifted_keys.length,merge_fence:g.count,pending_merge_decisions:S.length,lossless_merge_receipts:A.length,invalid_merge_receipt_evidence:h.invalid_evidence_count,missing_merge_receipt_history_references:w.length,accepted_legacy_merge_receipt_references:v.acceptedLegacyCount,accepted_missing_merge_receipt_dispositions:v.acceptedDispositionCount},item_unreadable:a.unreadable,item_conflict_markers:a.conflictMarkers,item_parse_failures:a.parseFailures,item_outdated_format_version:c.outdated,item_ahead_format_version:c.ahead,hierarchy_integrity:{...l,relations:et(l.relations,bn)},history_unreadable:o.unreadable,history_conflict_markers:o.conflictMarkers,history_invalid_json:o.invalidJson,tracked_runtime_cache:{tracker_relative_root:u.tracker_relative_root,tracked_paths:u.tracked_paths,tracked_path_count:u.tracked_path_count,remediation_command:u.remediation_command},merge_driver_configuration:f===null?null:{...f,required:r},merge_fence:g.audit,pending_merge_decision_items:[...new Set(S.map(T=>T.item_id))].sort((T,R)=>T.localeCompare(R)),lossless_merge_receipt_items:[...new Set(A.map(T=>T.item_id))].sort((T,R)=>T.localeCompare(R)),invalid_merge_receipt_evidence_details:h.invalid_evidence,invalid_merge_receipt_evidence_details_truncated:h.invalid_evidence_truncated,missing_merge_receipt_history_reference_details:w.slice(0,Gt),missing_merge_receipt_history_reference_details_truncated:w.length>Gt}},warnings:E,gitWorkspaceRoot:p,pendingMergeReceipts:k}}function LT(e){if(typeof e.activate=="function")return!0;let t=e.default;return typeof t!="object"||t===null?!1:typeof t.activate=="function"}function DT(e){let t={layer:e.layer,directory:e.directory,manifest_path:e.manifest_path,name:e.name,version:e.version,entry:e.entry,priority:e.priority,entry_path:e.entry_path,has_activate:LT(e.module)};return Array.isArray(e.capabilities)&&(t.capabilities=[...e.capabilities]),t}function NT(e,t){return ne(e.id)||`migration-${String(t+1).padStart(3,"0")}`}function MT(e){let t=ne(e.status)?.toLowerCase();return t==="failed"?"failed":t==="applied"?"applied":"pending"}function PT(e){return ne(e.reason)??ne(e.error)??ne(e.message)}function Yo(e,t){let n=(e.layer??"").localeCompare(t.layer??"");if(n!==0)return n;let i=(e.name??"").localeCompare(t.name??"");return i!==0?i:(e.id??"").localeCompare(t.id??"")}function FT(e){let t=[],n=[],i=[];e.forEach((s,a)=>{let o=NT(s.definition,a),c=MT(s.definition);if(c==="applied"){t.push({layer:s.layer,name:s.name,id:o,status:c});return}if(c==="failed"){i.push({layer:s.layer,name:s.name,id:o,status:c,reason:PT(s.definition)});return}n.push({layer:s.layer,name:s.name,id:o,status:c})}),t.sort(Yo),n.sort(Yo),i.sort(Yo);let r=[...i.map(s=>`extension_migration_failed:${s.layer}:${s.name}:${s.id}`),...n.map(s=>`extension_migration_pending:${s.layer}:${s.name}:${s.id}`)];return{summary:{applied:t,pending:n,failed:i,applied_count:t.length,pending_count:n.length,failed_count:i.length},warnings:r}}function Cg(e,t,n,i,r,s,a,o,c){let d=[...new Set(e)].sort((y,v)=>y.localeCompare(v)),l=[...new Set(d.map(y=>tc(y)))].sort((y,v)=>y.localeCompare(v)),u=d.filter(y=>y.startsWith("extension_capability_unknown:")).length,p=c.length>0,g=p?"partial":"full",f=[],h=Z_(d,{deactivate:"pm extension --deactivate <name> --project/--global",doctor:"pm extension --doctor --project/--global --detail deep --trace"});return h&&f.push(h),t>0&&f.push("Run pm extension --explore --project and pm extension --explore --global to inspect load failures."),n>0&&f.push("Review checks[name=extensions].details.activation.failed in pm health --json for activation error details."),(i.failed_count>0||i.pending_count>0)&&f.push("Resolve pending/failed extension migrations before write commands; use --force only when policy allows."),r>0&&f.push("Run pm extension --manage --project and pm extension --manage --global to refresh managed-state diagnostics."),u>0&&f.push(`Unknown extension capabilities detected. Allowed capabilities: ${Qd.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`),d.some(y=>y.startsWith("extension_capability_legacy_alias:"))&&f.push("Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema)."),d.some(y=>y.startsWith("extension_command_definition_legacy_handler_alias:"))&&f.push("Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."),p?f.push("Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via pm extension --manage --project/--global --fix-managed-state, pm extension --adopt-all --project/--global, or pm extension --adopt <name>."):a.length>0&&f.push("Loaded unmanaged extensions are currently treated as informational. Use pm extension --manage --project/--global --fix-managed-state to adopt them for update checks."),f.length===0&&f.push("No immediate action required. Re-run pm health after extension configuration changes."),{status:d.length===0?"ok":"warn",warning_count:d.length,warning_codes:l,load_failure_count:t,activation_failure_count:n,migration_failed_count:i.failed_count,migration_pending_count:i.pending_count,managed_state_warning_count:r,managed_extension_entries_count:s,unmanaged_loaded_extension_count:a.length,unmanaged_loaded_extensions:a,unmanaged_expected_extension_count:o.length,unmanaged_expected_extensions:o,unmanaged_action_required_extension_count:c.length,unmanaged_action_required_extensions:c,update_health_coverage:g,update_health_partial:p,unknown_capability_count:u,top_warnings:d.slice(0,8),remediation:f}}async function $T(e,t,n){let i=await ep(Je(e)),r=await Yi({pmRoot:e,settings:t,cwd:process.cwd(),noExtensions:n}),s=r.loaded.map(b=>DT(b)),a=await cg(r.loaded,Je(e)),o=await Ji({...r,loaded:r.loaded}),[c,d]=await Promise.all([_o(r.roots.project),_o(r.roots.global)]);await Tu(e,o.registrations.migrations);let l=FT(o.registrations.migrations),u={failed:o.failed,warnings:o.warnings,hook_counts:o.hook_counts,command_override_count:o.command_override_count,command_handler_count:o.command_handler_count,parser_override_count:o.parser_override_count,preflight_override_count:o.preflight_override_count,service_override_count:o.service_override_count,renderer_override_count:o.renderer_override_count,registration_counts:o.registration_counts,registrations:o.registrations,migration_status:l.summary,managed_extensions:{project:{path:c.path,count:c.state.entries.length,entries:c.state.entries},global:{path:d.path,count:d.state.entries.length,entries:d.state.entries}}},p=new Set(c.state.entries.map(b=>kn(b.name))),g=new Set(d.state.entries.map(b=>kn(b.name))),f=[...new Map(r.loaded.filter(b=>!(b.layer==="project"?p:g).has(kn(b.name))).map(b=>[`${b.layer}:${b.name}`,{layer:b.layer,name:b.name,directory:b.directory}])).values()].sort((b,E)=>{let N=`${b.layer}:${b.name}`,T=`${E.layer}:${E.name}`;return N.localeCompare(T)}),h=f.map(b=>`${b.layer}:${b.name}`).sort((b,E)=>b.localeCompare(E)),y=f.filter(b=>Xo(b.name,b.directory)).map(b=>`${b.layer}:${b.name}`).sort((b,E)=>b.localeCompare(E)),v=f.filter(b=>!Xo(b.name,b.directory)).map(b=>`${b.layer}:${b.name}`).sort((b,E)=>b.localeCompare(E)),w=v.length>0?[`extension_update_health_partial_coverage:skipped_unmanaged:${v.length}`]:[],k=[...i.warnings,...r.warnings,...u.warnings,...l.warnings,...c.warnings,...d.warnings,...w,...a.warnings],S=po(k),A=fo(),C=Cg(k,r.failed.length,o.failed.length,l.summary,c.warnings.length+d.warnings.length,c.state.entries.length+d.state.entries.length,h,y,v);return{check:{name:"extensions",status:k.length===0?"ok":"warn",ok:k.length===0,details:{...r,loaded:s,warnings:k,activation:u,author_manifest:i,triage:C,...l.summary.pending_count>0?{remediation_map:{extension_migration_pending:"pm extension migrate --project"}}:{},capability_contract:A,capability_guidance:S,host_version_census:a}},warnings:k}}function UT(e,t){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function et(e,t){return Array.isArray(e)?{count:e.length,sample:e.slice(0,t),truncated:e.length>t}:{count:0,sample:[],truncated:!1}}function jT(e){if(typeof e!="object"||e===null||Array.isArray(e))return{};let t=e;return{layer:t.layer,directory:t.directory,name:t.name,version:t.version,enabled:t.enabled,status:t.status,has_activate:t.has_activate,capabilities:t.capabilities}}function is(e,t){let n=et(e,t);return{...n,sample:n.sample.map(i=>jT(i))}}function W(e,t){if(!Array.isArray(e))return{count:0,sample:[],truncated:!1};let n=e.filter(i=>typeof i=="string");return{count:n.length,sample:n.slice(0,t),truncated:n.length>t}}function GT(e){if(typeof e!="object"||e===null)return null;let t=e;return{applied_count:t.applied_count,pending_count:t.pending_count,failed_count:t.failed_count}}var qT={settings:(e,t)=>({version:e.version,id_prefix:e.id_prefix,locks_ttl_seconds:e.locks_ttl_seconds,warnings:W(e.warnings,t)}),directories:(e,t)=>({required_count:Array.isArray(e.required)?e.required.length:0,optional_count:Array.isArray(e.optional)?e.optional.length:0,missing_required:W(e.missing_required,t),missing_optional:W(e.missing_optional,t),missing:W(e.missing,t),strict_directories:e.strict_directories}),settings_values:(e,t)=>({warnings:W(e.warnings,t)}),telemetry:e=>({enabled:e.enabled,capture_level:e.capture_level,endpoint:e.endpoint,queue_exists:e.queue_exists,queue_entries:e.queue_entries,queue_draining:e.queue_draining,queue_invalid_rows:e.queue_invalid_rows,queue_rows_total:e.queue_rows_total,last_successful_flush_at:e.last_successful_flush_at,last_failed_flush_at:e.last_failed_flush_at,endpoint_probe:e.endpoint_probe,env_overrides:e.env_overrides}),extensions:(e,t)=>{let n=typeof e.activation=="object"&&e.activation!==null?e.activation:{};return{disabled_by_flag:e.disabled_by_flag,discovered:is(e.discovered,t),effective:is(e.effective,t),loaded:is(e.loaded,t),failed:et(e.failed,t),warnings:W(e.warnings,t),activation:{failed:et(n.failed,t),warnings:W(n.warnings,t),hook_counts:n.hook_counts,command_handler_count:n.command_handler_count,service_override_count:n.service_override_count,renderer_override_count:n.renderer_override_count,registration_counts:n.registration_counts,migration_status:GT(n.migration_status)},author_manifest:e.author_manifest,triage:e.triage,capability_contract:e.capability_contract,capability_guidance:et(e.capability_guidance,t),host_version_census:e.host_version_census}},storage:(e,t)=>{let n=typeof e.author_attribution=="object"&&e.author_attribution!==null?e.author_attribution:void 0;return{...e,...n?{author_attribution:{...n,affected_item_ids:W(n.affected_item_ids,t),samples:et(n.samples,t)}}:{}}},locks:e=>({active_lock_count:e.active_lock_count,stale_lock_count:e.stale_lock_count,unreadable_lock_count:e.unreadable_lock_count,unparseable_lock_count:e.unparseable_lock_count}),integrity:(e,t)=>{let n=typeof e.tracked_runtime_cache=="object"&&e.tracked_runtime_cache!==null?e.tracked_runtime_cache:void 0;return{checked_item_files:e.checked_item_files,checked_history_streams:e.checked_history_streams,counts:e.counts,item_unreadable:W(e.item_unreadable,t),item_conflict_markers:et(e.item_conflict_markers,t),item_parse_failures:W(e.item_parse_failures,t),tracked_runtime_cache:n===void 0?e.tracked_runtime_cache:{...n,tracked_paths:W(n.tracked_paths,t)},history_unreadable:W(e.history_unreadable,t),history_conflict_markers:et(e.history_conflict_markers,t),history_invalid_json:et(e.history_invalid_json,t),skipped:e.skipped}},history_drift:(e,t)=>{let n=typeof e.cache_confirmation=="object"&&e.cache_confirmation!==null?e.cache_confirmation:void 0;return{checked_items:e.checked_items,cache_hit_verification:e.cache_hit_verification,cache_confirmation:n===void 0?e.cache_confirmation:{...n,candidate_items:W(n.candidate_items,t),confirmed_items:W(n.confirmed_items,t),resolved_false_positive_items:W(n.resolved_false_positive_items,t)},counts:e.counts,drifted_items:W(e.drifted_items,t),merge_receipt_attributed_items:W(e.merge_receipt_attributed_items,t),missing_streams:W(e.missing_streams,t),unreadable_streams:W(e.unreadable_streams,t),hash_mismatches:W(e.hash_mismatches,t),chain_mismatches:W(e.chain_mismatches,t),version_skews:W(e.version_skews,t),workspace_state_mismatches:W(e.workspace_state_mismatches,t),workspace_state_missing:W(e.workspace_state_missing,t),workspace_state_unreadable:W(e.workspace_state_unreadable,t),skipped:e.skipped}},vectorization:(e,t)=>({semantic_runtime_available:e.semantic_runtime_available,compatibility_mode_auto_defaults:e.compatibility_mode_auto_defaults,auto_ollama_defaults_applied:e.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:e.auto_ollama_defaults_skipped_reason,auto_ollama_defaults_remediation:e.auto_ollama_defaults_remediation,refresh_policy:e.refresh_policy,provider_active:e.provider_active,vector_store_active:e.vector_store_active,items:e.items,ledger_entries_before:e.ledger_entries_before,stale_items_before_total:e.stale_items_before_total,stale_items_before:W(e.stale_items_before,t),refresh_attempted:e.refresh_attempted,refresh_skipped_reason:e.refresh_skipped_reason,refresh_result:e.refresh_result,ledger_entries_after:e.ledger_entries_after,stale_items_after_total:e.stale_items_after_total,stale_items_after:W(e.stale_items_after,t),skipped:e.skipped})};function xg(e,t){let n=qT[e.name];return n?n(e.details,t):e.details}function KT(e){let t=W(e.warnings,bn);return{ok:e.ok,...e.verdict?{verdict:e.verdict}:{},checks:e.checks.map(n=>({name:n.name,status:n.status,ok:n.ok,details:xg(n,bn)})),warnings:t.sample,findings:e.findings.filter(n=>t.sample.includes(n.warning)||e.failed_because.includes(n.warning)),failed_because:e.failed_because,projection:{mode:"brief",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:bn},generated_at:e.generated_at}}function Eg(e){return e.details.skipped===!0}function zT(e){let t=W(e.warnings,bn),n=e.checks.filter(Eg).map(i=>i.name);return{ok:e.ok,...e.verdict?{verdict:e.verdict}:{},checks:e.checks.filter(i=>!Eg(i)).map(i=>({name:i.name,status:i.status,ok:i.ok,details:{}})),warning_count:t.count,warnings:t.sample,findings:e.findings.filter(i=>t.sample.includes(i.warning)||e.failed_because.includes(i.warning)),failed_because:e.failed_because,projection:{mode:"summary",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:bn,omitted_checks:n},generated_at:e.generated_at}}function Zo(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=UT(e,Sg);return{values:n.values,truncated:n.truncated,total:e.length}}function rs(e){let t=(process.env[e]??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function WT(){let e=(process.env.PM_TELEMETRY_SOURCE_CONTEXT??"").trim().toLowerCase();return vT.has(e)?e:null}function ss(e){let t=e.trim();if(t.length===0)return"";try{let n=new URL(t);return n.username="",n.password="",n.search="",n.hash="",n.toString()}catch{return t}}function Rg(e){let t=0,n=0,i=0,r=0,s=0;for(let a of e.split(`
|
|
8
|
-
`)){let o=a.trim();if(o.length!==0){i+=1;try{let c=JSON.parse(o);if(typeof c=="object"&&c!==null&&typeof c.attempts=="number"&&Number.isFinite(c.attempts)){let d=Math.max(0,Math.trunc(c.attempts));t+=1,s=Math.max(s,d),d>=Tg&&(r+=1)}else n+=1}catch{n+=1}}}return{validEntries:t,invalidRows:n,totalRows:i,highRetryEntries:r,maxAttempts:s}}function BT(){return{validEntries:0,invalidRows:0,totalRows:0,highRetryEntries:0,maxAttempts:0}}function HT(e){if(!e||e.trim().length===0)return{runtimeState:{},stateParseFailed:!1};try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)?{runtimeState:t,stateParseFailed:!1}:{runtimeState:{},stateParseFailed:!0}}catch{return{runtimeState:{},stateParseFailed:!0}}}async function VT(e,t){let n=e.telemetry.endpoint.trim();return!t||!e.telemetry.enabled||n.length===0||$t().telemetry_disabled?void 0:{attempted:!0,...await Og(n)}}function YT(e,t,n){let i=[];if(t.invalidRows>0&&i.push(`telemetry_queue_invalid_rows:${t.invalidRows}`),!e.telemetry.enabled||t.validEntries===0)return i;let r=n.last_successful_flush_at,s=n.last_failed_flush_at,a=s&&(!r||s>r),o=!r,c=t.validEntries>=ET;return(a||o||c)&&i.push(`telemetry_queue_pending:${t.validEntries}`),t.highRetryEntries>0&&i.push(`telemetry_queue_high_retries:${t.highRetryEntries}`),i}function JT(e){return!e||e.ok!==!1?[]:typeof e.status=="number"?[`telemetry_endpoint_probe_http_status:${e.status}`]:["telemetry_endpoint_probe_failed"]}function XT(e){let t=Number.parseInt(e?.max_schema_version??"",10);return e?.ok===!0&&Number.isInteger(t)&&t>k_?[`telemetry_schema_version_behind:${t}`]:[]}function QT(e,t){let n=typeof t.pending_otel_spans=="number"?t.pending_otel_spans:0,i=t.last_otel_success_at,r=t.last_otel_failure_at;return e.telemetry.enabled&&n>0&&r&&(!i||r>=i)?[`telemetry_otel_export_failing:${n}`]:[]}function ZT(){return{...$t(),pm_no_telemetry:rs("PM_NO_TELEMETRY"),telemetry_otel_disabled:rs("PM_TELEMETRY_OTEL_DISABLED"),telemetry_inline_flush:rs("PM_TELEMETRY_INLINE_FLUSH"),telemetry_source_context:WT()}}function eA(e,t){return e.telemetry.enabled&&t.validEntries>0}function tA(e,t){return e&&t.every(n=>!n.startsWith("telemetry_queue_pending:")&&!n.startsWith("telemetry_queue_high_retries:"))}async function Og(e){let t=e;try{let n=new URL(e);n.pathname="/healthz",n.search="",n.hash="",t=n.toString()}catch{}try{let n=await fetch(t,{method:"GET",signal:AbortSignal.timeout(kT)});return{probe_url:ss(t),ok:n.ok,status:n.status,max_schema_version:(()=>{for(let i of ST){let r=n.headers.get(i)?.trim();if(r&&r.length>0)return r}})()}}catch(n){return{probe_url:ss(t),ok:!1,error:n instanceof Error?n.message:"probe_failed"}}}async function nA(e,t){let n=qe(process.cwd()),i=Ce.join(n,wT),r=Ce.join(n,bT),s=await Q(i),a=s!==null,o=s?Buffer.byteLength(s,"utf8"):0,c=s?Rg(s):BT(),d=await Q(r),{runtimeState:l,stateParseFailed:u}=HT(d),p=e.telemetry.endpoint.trim(),g=ss(p),f=await VT(e,t.checkTelemetry),h=[];u&&h.push("telemetry_state_invalid_json"),h.push(...YT(e,c,l),...JT(f),...XT(f),...QT(e,l));let y=eA(e,c),v=typeof l.pending_otel_spans=="number"?l.pending_otel_spans:0;return{check:{name:"telemetry",status:h.length===0?"ok":"warn",ok:h.length===0,details:{enabled:e.telemetry.enabled,capture_level:e.telemetry.capture_level,endpoint:g,global_pm_root:n,queue_path:i,queue_exists:a,queue_entries:c.validEntries,queue_draining:tA(y,h),queue_invalid_rows:c.invalidRows,queue_rows_total:c.totalRows,queue_size_bytes:o,queue_high_retry_entries:c.highRetryEntries,queue_high_retry_threshold:Tg,queue_max_attempts:c.maxAttempts,runtime_state_path:r,last_attempted_flush_at:l.last_attempted_flush_at??null,last_successful_flush_at:l.last_successful_flush_at??null,last_failed_flush_at:l.last_failed_flush_at??null,last_failed_flush_error:l.last_failed_flush_error??null,pending_otel_spans:v,last_otel_attempt_at:l.last_otel_attempt_at??null,last_otel_success_at:l.last_otel_success_at??null,last_otel_failure_at:l.last_otel_failure_at??null,last_otel_failure_error:l.last_otel_failure_error??null,endpoint_probe:f??{attempted:!1},env_overrides:ZT()}},warnings:h}}async function iA(e){let t;try{t=await hg(e)}catch(i){let r=i instanceof Error?i.message:String(i);return{check:{name:"locks",status:"warn",ok:!1,details:{active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0,scan_failed:!0,error:r,pm_root:e}},warnings:[`locks_scan_failed:${r}`]}}let n=[];return t.stale_lock_count>0&&n.push(`locks_stale_count:${t.stale_lock_count}`),t.unreadable_lock_count>0&&n.push(`locks_unreadable:${t.unreadable_lock_count}`),{check:{name:"locks",status:n.length===0?"ok":"warn",ok:n.length===0,details:{active_lock_count:t.active_lock_count,stale_lock_count:t.stale_lock_count,unreadable_lock_count:t.unreadable_lock_count,unparseable_lock_count:t.unparseable_lock_count}},warnings:n}}async function rA(e){let t="metadata",n=e.items,i=await Xn(e.pmRoot,n,{cacheHitVerification:t}),r=[...new Set([...i.hashMismatches,...i.chainMismatches,...i.versionSkews])].sort((v,w)=>v.localeCompare(w)),s=[],a=[];if(r.length>0){n=await dt(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema,{forceSourceScan:!0}),i=await Xn(e.pmRoot,n),s=[...new Set([...i.hashMismatches,...i.chainMismatches,...i.versionSkews])].sort((w,k)=>w.localeCompare(k));let v=new Set(s);a=r.filter(w=>!v.has(w))}let{missingStreams:o,unreadableStreams:c,hashMismatches:d,chainMismatches:l,versionSkews:u,driftedItems:p,workspaceStateMismatches:g,workspaceStateMissing:f,workspaceStateUnreadable:h}=i,y=[...o.map(v=>`history_drift_missing_stream:${v}`),...c.map(v=>`history_drift_unreadable_stream:${v}`),...d.map(v=>`history_drift_hash_mismatch:${v}`),...l.map(v=>`history_drift_chain_mismatch:${v}`),...u.map(v=>`history_drift_version_skew:${v}`),...g.map(v=>`history_drift_workspace_state_mismatch:${v}`),...f.map(v=>`history_drift_workspace_state_missing:${v}`),...h.map(v=>`history_drift_workspace_state_unreadable:${v}`)];return{check:{name:"history_drift",status:y.length===0?"ok":"warn",ok:y.length===0,details:{checked_items:n.length,cache_hit_verification:r.length>0?"metadata_then_content_hash":t,cache_confirmation:{triggered:r.length>0,reason:r.length>0?"cached_corruption_candidate":null,candidate_items:r,confirmed_items:s,resolved_false_positive_items:a,authoritative_item_source:r.length>0},drifted_items:p,counts:{drifted:p.length,missing_streams:o.length,unreadable_streams:c.length,hash_mismatches:d.length,chain_mismatches:l.length,version_skews:u.length,workspace_state_mismatches:g.length,workspace_state_missing:f.length,workspace_state_unreadable:h.length},missing_streams:o,unreadable_streams:c,hash_mismatches:d,chain_mismatches:l,version_skews:u,workspace_state_mismatches:g,workspace_state_missing:f,workspace_state_unreadable:h}},warnings:y}}function sA(e,t){let n=__(e),i=p_(n.settings),r=f_(n.settings,t),s=i.active?g_(i.active.name,i.active.model):null;return{runtimeDefaults:n,providerResolution:i,vectorStoreResolution:r,runtimeEmbeddingIdentity:s,semanticRuntimeAvailable:!!(i.active&&r.active)}}function aA(){return{refreshed:[],skipped:[],warnings:[]}}async function oA(e){return!e.refreshPolicy.enabled||!e.snapshot.semanticRuntimeAvailable||e.staleBefore.length===0?aA():y_(e.pmRoot,e.staleBefore,{settings:e.snapshot.runtimeDefaults.settings,apply_runtime_defaults:!1})}function cA(e){return e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&!!(e.ledgerBefore.embedding&&e.runtimeEmbeddingIdentity&&h_(e.ledgerBefore.embedding,e.runtimeEmbeddingIdentity))}function dA(e){let t=new Set([...e.ledgerBefore.warnings,...e.ledgerAfter.warnings]);if(e.strictVectorizationWarnings)for(let n of e.refreshResult.warnings)t.add(n);return e.embeddingIdentityChanged&&t.add("vectorization_embedding_identity_changed"),e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&e.staleAfter.length>0&&t.add(`vectorization_stale_items_remaining:${e.staleAfter.length}`),[...t].sort((n,i)=>n.localeCompare(i))}function lA(e,t,n){return e.enabled&&t&&n.length>0?null:e.enabled?t?"no_stale_items":"semantic_runtime_unavailable":"refresh_disabled"}function Lg(e,t){let n=t.providerResolution.active?.name??null,i=t.vectorStoreResolution.active?.name??null;return{provider_active:n,provider_configured:typeof e.search?.provider=="string"?e.search.provider:null,provider_source:no(n,e.search?.provider??null),vector_store_active:i,vector_store_configured:typeof e.vector_store?.adapter=="string"?e.vector_store.adapter:null,vector_store_source:no(i,e.vector_store?.adapter??null)}}function uA(e){return{enabled:e.enabled,check_only:e.checkOnly,no_refresh:e.noRefresh,refresh_vectors:e.refreshVectors}}function mA(e,t,n){return e.enabled&&n.length>0&&t}async function _A(e,t,n,i,r){let s=sA(t,e),a=await io(e),o=s.semanticRuntimeAvailable?ho(n,a.entries):[],c=await oA({pmRoot:e,snapshot:s,refreshPolicy:i,staleBefore:o}),d=await io(e),l=s.semanticRuntimeAvailable?ho(n,d.entries):[],u=!s.runtimeDefaults.auto_ollama_defaults_applied,p=cA({strictVectorizationWarnings:u,semanticRuntimeAvailable:s.semanticRuntimeAvailable,ledgerBefore:a,runtimeEmbeddingIdentity:s.runtimeEmbeddingIdentity}),g=dA({ledgerBefore:a,ledgerAfter:d,refreshResult:c,strictVectorizationWarnings:u,semanticRuntimeAvailable:s.semanticRuntimeAvailable,embeddingIdentityChanged:p,staleAfter:l}),f=Zo(o,r),h=Zo(l,r),y=mA(i,s.semanticRuntimeAvailable,o);return{check:{name:"vectorization",status:g.length===0?"ok":"warn",ok:g.length===0,details:{semantic_runtime_available:s.semanticRuntimeAvailable,compatibility_mode_auto_defaults:s.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_applied:s.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:s.runtimeDefaults.auto_ollama_defaults_skipped_reason??null,auto_ollama_defaults_remediation:s.runtimeDefaults.auto_ollama_defaults_remediation??null,refresh_policy:uA(i),...Lg(t,s),embedding_identity_changed:p,embedding_identity_before:a.embedding??null,embedding_identity_runtime:s.runtimeEmbeddingIdentity??null,items:n.length,ledger_entries_before:Object.keys(a.entries).length,stale_items_detail_mode:r?"full":"summary",stale_items_summary_limit:Sg,stale_items_before_total:f.total,stale_items_before:f.values,stale_items_before_truncated:f.truncated,refresh_attempted:y,refresh_skipped_reason:lA(i,s.semanticRuntimeAvailable,o),refresh_result:c,ledger_entries_after:Object.keys(d.entries).length,stale_items_after_total:h.total,stale_items_after:h.values,stale_items_after_truncated:h.truncated}},warnings:g}}function pA(e){let t=[];return e.id_prefix.trim().length===0&&t.push("settings:id_prefix_empty"),e.locks.ttl_seconds<=0&&t.push("settings:locks_ttl_non_positive"),t}function Dg(e){let t=e.checkOnly===!0,n=e.refreshVectors===!0;if(n&&t)throw new _("--check-only cannot be combined with --refresh-vectors",m.USAGE);if(n&&e.noRefresh===!0)throw new _("--no-refresh cannot be combined with --refresh-vectors",m.USAGE);return{enabled:n,checkOnly:t,noRefresh:!n,refreshVectors:n}}var fA=new Set(["extensions","locks","search"]);function gA(e){let t=new Set(tl.filter(r=>r.length>0)),n=new Set,i=new Set(Object.values(nl));for(let r of e.folders)t.has(r)&&!i.has(r)||(t.delete(r),n.add(r));for(let r of fA)t.delete(r),n.add(r);return{requiredDirs:[...t].sort((r,s)=>r.localeCompare(s)),optionalDirs:[...n].sort((r,s)=>r.localeCompare(s)),optionalDirSet:n}}async function hA(e,t,n){let{requiredDirs:i,optionalDirs:r,optionalDirSet:s}=gA(t),a=[],o=[],c=[];for(let d of[...i,...r]){let l=Ce.join(e,d);c.push(...await $e({path:l,scope:"project"})),!await nc(l)&&(s.has(d)?o.push(d):a.push(d))}return{requiredDirs:i,optionalDirs:r,missingRequiredDirs:a,missingOptionalDirs:o,missingDirs:n?[...a,...o]:[...a],hookWarnings:c}}function Ng(e){let t=e.checkOnly===!0&&e.brief!==!0&&e.summary!==!0&&e.full!==!0,n=(e.summary===!0||t)&&e.full!==!0,i=e.checkOnly===!0&&(e.brief===!0||e.summary===!0)&&e.full!==!0;return{summaryMode:n,skipIntegrity:(e.skipIntegrity===!0||i)&&e.full!==!0,skipDrift:(e.skipDrift===!0||i)&&e.full!==!0,skipVectors:(e.skipVectors===!0||i)&&e.full!==!0}}async function yA(e){return e.skipPolicy.skipDrift&&e.skipPolicy.skipVectors?Se(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema):dt(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema)}function Jo(e){return{check:{name:e,status:"ok",ok:!0,details:{skipped:!0}},warnings:[]}}function vA(e,t,n){return{name:"settings",status:n.length===0?"ok":"warn",ok:n.length===0,details:{path:e,version:t.version,id_prefix:t.id_prefix,locks_ttl_seconds:t.locks.ttl_seconds,warnings:n}}}function wA(e,t){return{name:"directories",status:e.missingDirs.length===0?"ok":"warn",ok:e.missingDirs.length===0,details:{required:e.requiredDirs,optional:e.optionalDirs,missing_required:e.missingRequiredDirs,missing_optional:e.missingOptionalDirs,missing:e.missingDirs,strict_directories:t}}}function bA(e,t){return{name:"settings_values",status:e.length===0?"ok":"warn",ok:e.length===0,details:{warnings:e,...t.roleless_status_count>0?{lifecycle_status_roles:t}:{}}}}var ic=e=>e.unknown_event_count??0,rc=e=>e.actionable_unknown_event_count??ic(e);function kA(e,t,n,i,r,s){let a=ic(i),o=rc(i),c=a>0,d=o>0,l=r.count>0;return{name:"storage",status:n.over_threshold.length===0&&n.orphaned.length===0&&!d&&!l?"ok":"warn",ok:n.over_threshold.length===0&&n.orphaned.length===0&&!d&&!l,details:{items:e.length,history_streams:n.count,tombstones:{retention_policy:"retain_append_only",gc_enabled:!1,count:n.tombstones.length,ids:n.tombstones.slice(0,25),truncated:n.tombstones.length>25},orphaned_history_streams:{count:n.orphaned.length,ids:n.orphaned.slice(0,25),truncated:n.orphaned.length>25},...c?{author_attribution:i}:{},...l?{stale_in_progress:r}:{},...s.outcomes.length>0?{provenance_resolver_outcomes:s.outcomes}:{},...s.invalid_values.length>0?{provenance_invalid_values:s.invalid_values}:{},provenance_sample:s.sample,...n.max_entries!==null?{compact_policy:{enabled:t.history.compact_policy.enabled,max_entries:n.max_entries,trigger:t.history.compact_policy.trigger,over_threshold_count:n.over_threshold.length,over_threshold:n.over_threshold}}:{}}}}function Mg(e){let t=e.count===0?[]:[`stale_in_progress_items:${e.count}`];return{scan:e,warnings:t}}function EA(e){let t=[...e.directoryState.missingDirs.map(n=>`missing_directory:${n}`),...e.normalizedSettingsReadWarnings,...e.settingWarnings,...e.normalizedItemReadWarnings,...e.telemetryCheck.warnings,...e.extensionCheck.warnings,...e.historyPolicyWarnings,...e.historySummary.warnings,...e.authorAttributionWarnings,...e.staleInProgressWarnings,...e.provenanceWarnings,...e.locksCheck.warnings,...e.integrityCheck.warnings,...e.historyDriftCheck.warnings,...e.vectorizationCheck.warnings,...e.directoryState.hookWarnings];return[...new Set(t)]}function SA(e){let t=e.check.details.counts;return typeof t?.drifted=="number"?t.drifted:0}function TA(e){return{settings:e.normalizedSettingsReadWarnings,directories:e.directoryState.missingDirs.map(t=>`missing_directory:${t}`).concat(e.directoryState.hookWarnings),settings_values:e.settingWarnings,telemetry:e.telemetryCheck.warnings,extensions:e.extensionCheck.warnings,storage:[...e.historyPolicyWarnings,...e.historySummary.warnings,...e.authorAttributionWarnings,...e.staleInProgressWarnings,...e.provenanceWarnings],locks:e.locksCheck.warnings,integrity:[...e.normalizedItemReadWarnings,...e.integrityCheck.warnings],history_drift:e.historyDriftCheck.warnings,vectorization:e.vectorizationCheck.warnings}}function Pg(e){let t=new Map;for(let[i,r]of Object.entries(e.remediationSources))for(let s of r)t.has(s)||t.set(s,i);let n=new Map(e.checks.map(i=>[i.name,i]));return e.warnings.map(i=>{let r=t.get(i)??"integrity",s=Bo(i)?.code??tc(i),a=n.get(r)?.details,o=typeof a?.remediation_map=="object"&&a.remediation_map!==null?a.remediation_map:{},c=s==="agent_guidance_outdated"?"pm init --agent-guidance add":s==="agent_guidance_unreadable"?"Check AGENTS.md and CLAUDE.md read permissions and file types, then retry pm health.":o[s],d=ec(i,e.requireMergeDrivers)?"advisory":"gate_failing";return{warning:i,code:s,check:r,severity:d,...typeof c=="string"?{remediation:c}:d==="gate_failing"?{disposition:"no_safe_automatic_remediation"}:{}}})}function AA(e){if(e.check.name==="history_drift"&&e.historyDriftedCount>1)for(let t of Object.keys(e.remediationMap))t!=="history_drift_merge_receipt"&&t!=="history_drift_version_skew"&&(e.remediationMap[t]="pm history-repair --all");if(e.check.name==="storage"&&e.overThresholdCount>1)for(let t of Object.keys(e.remediationMap))e.remediationMap[t]="pm history-compact --all-streams"}function IA(e){for(let t of e.checks){let n=Ho(e.remediationSources[t.name]);AA({check:t,remediationMap:n,historyDriftedCount:e.historyDriftedCount,overThresholdCount:e.overThresholdCount}),Object.keys(n).length>0&&(t.details={...t.details,remediation_map:n})}}async function CA(e){if(e.gitWorkspaceRoot===null||e.pendingMergeReceipts.length===0)return[];let t=e.historyDriftCheck.check.details,n=Array.isArray(t.hash_mismatches)?t.hash_mismatches.filter(a=>typeof a=="string"):[],i=new Set([t.missing_streams,t.unreadable_streams,t.chain_mismatches].flatMap(a=>Array.isArray(a)?a:[])),r=new Map;for(let a of e.pendingMergeReceipts){let o=r.get(a.item_id)??[];o.push(a),r.set(a.item_id,o)}let s=[];for(let a of n){if(i.has(a))continue;let o=r.get(a);if(!(!o||o.length===0))try{await lp(a,{dryRun:!0,mergeReceiptProof:{gitWorkspaceRoot:e.gitWorkspaceRoot,receipts:o}},e.global),s.push(a)}catch{}}return[...new Set(s)].sort((a,o)=>a.localeCompare(o))}function xA(e,t){let n=new Set(t);e.warnings=[...e.warnings.filter(i=>i.startsWith("history_drift_hash_mismatch:")?!n.has(i.slice(i.indexOf(":")+1)):!0),...t.map(i=>`history_drift_merge_receipt:${i}`)].sort((i,r)=>i.localeCompare(r)),e.check.details={...e.check.details,merge_receipt_attributed_items:t}}function Fg(e,t,n){let i=e.warning_count??e.warnings.length,r={...e,warning_count:i,warning_limit:Gt,warnings_truncated:i>Gt,warnings:e.warnings.slice(0,Gt),findings:(e.findings??[]).filter(a=>e.warnings.slice(0,Gt).includes(a.warning)||e.failed_because.includes(a.warning))},s=n?zT(r):t.brief===!0?KT(r):r;return{...s,warning_count:i,warning_limit:Gt,warnings_truncated:i>s.warnings.length,...s.projection?{projection:{...s.projection,warning_count:i,warnings_truncated:i>s.warnings.length}}:{}}}async function $g(e,t={}){let n=x(process.cwd(),e.path);await $(n);let i=Ae(n),{settings:r,warnings:s}=await pu(n),a=[...new Set(s)],o=F(r,P()),c=t.strictDirectories===!0,d=t.strictExit===!0||t.failOnWarn===!0,l=t.requireMergeDrivers===!0||d,u=Dg(t),p=await hA(n,o,c),g=pA(r),f=await nA(r,{checkTelemetry:t.checkTelemetry===!0}),h=await $T(n,r,!!e.noExtensions),y=Ng(t),v=[],w=await yA({pmRoot:n,settings:r,typeRegistry:o,skipPolicy:y,itemReadWarnings:v}),k=w,S=Zr(K(r.schema),w),A=[...(await tp({pm_root:n,cwd:process.cwd(),mode:"status",interactive:!1,settings:r}).catch(()=>({warnings:["agent_guidance_unreadable:AGENTS.md,CLAUDE.md"]}))).warnings.filter(V=>V.startsWith("agent_guidance_")),...g,...es(S)],C=y.skipDrift?{warnings:[]}:await sr({pmRoot:n,settings:r,itemIds:w.map(V=>V.id),commandLabel:"health"}),b=await IT(n,r.history.compact_policy,await TT(n)),E=await di(n,20,t.verboseAuthorEvents===!0),N=rc(E),T=N>0?[`history_unknown_author_events:${N}`]:[],R=Mg(await w_(n,w,{in_progress_status:r.schema.workflow.in_progress_status,threshold_hours:r.mutation_guard.stale_in_progress_hours})),G=await dp(n),pe=G.warnings,ce=await iA(n),de=y.skipIntegrity&&!l?{...Jo("integrity"),gitWorkspaceRoot:null,pendingMergeReceipts:[]}:await OT(n,o.type_to_folder,r.schema,r,l,w),ue=y.skipDrift?Jo("history_drift"):await rA({pmRoot:n,items:k,settings:r,typeRegistry:o,itemReadWarnings:v}),tn=[...new Set(v)],Pn=await CA({gitWorkspaceRoot:de.gitWorkspaceRoot,pendingMergeReceipts:de.pendingMergeReceipts,historyDriftCheck:ue,global:e});xA(ue,Pn);let it=y.skipVectors?Jo("vectorization"):await _A(n,r,k,u,t.verboseStaleItems===!0),Ne=[vA(i,r,a),wA(p,c),bA(A,S),f.check,h.check,kA(w,r,b,E,R.scan,G),ce.check,de.check,ue.check,it.check],ht=EA({directoryState:p,normalizedSettingsReadWarnings:a,settingWarnings:A,normalizedItemReadWarnings:tn,telemetryCheck:f,extensionCheck:h,historyPolicyWarnings:C.warnings,historySummary:b,authorAttributionWarnings:T,staleInProgressWarnings:R.warnings,provenanceWarnings:pe,locksCheck:ce,integrityCheck:de,historyDriftCheck:ue,vectorizationCheck:it}),Ee=TA({directoryState:p,normalizedSettingsReadWarnings:a,settingWarnings:A,normalizedItemReadWarnings:tn,telemetryCheck:f,extensionCheck:h,historyPolicyWarnings:C.warnings,historySummary:b,authorAttributionWarnings:T,staleInProgressWarnings:R.warnings,provenanceWarnings:pe,locksCheck:ce,integrityCheck:de,historyDriftCheck:ue,vectorizationCheck:it});IA({checks:Ne,remediationSources:Ee,historyDriftedCount:SA(ue),overThresholdCount:b.over_threshold.length});let Me=ht.filter(V=>!ec(V,l)),yt=Pg({warnings:ht,checks:Ne,remediationSources:Ee,requireMergeDrivers:l}),D=new Set(yt.filter(V=>V.severity==="gate_failing").map(V=>V.check)),rt=new Set(yt.map(V=>V.check));for(let V of Ne)V.ok=!D.has(V.name),rt.has(V.name)&&(V.status="warn");let vt={ok:Me.length===0,verdict:{authority:"ok",...d?{strict_exit:!0}:{},...l?{require_merge_drivers:!0}:{},exit_code:d&&Me.length>0?m.GENERIC_FAILURE:0},checks:Ne,warnings:ht,findings:yt,failed_because:Me,generated_at:O()};return Fg(vt,t,y.summaryMode)}var Zj={buildHierarchyIntegrityWarnings:Ig,buildExtensionHealthTriageSummary:Cg,buildHealthFindings:Pg,buildCapabilityContractMetadata:fo,buildStaleInProgressHealthSummary:Mg,buildVectorizationProviderDetails:Lg,collectUnknownCapabilityGuidance:po,isAdvisoryHealthWarning:ec,isDirectory:nc,isExpectedUnmanagedExtension:Xo,listItemDocumentPaths:Ag,normalizeEndpointForDisplay:ss,normalizeExtensionNameForMatch:kn,parseTelemetryQueue:Rg,probeTelemetryEndpointHealth:Og,projectHealthResult:Fg,resolveActionableUnknownAuthorEventCount:rc,resolveHealthSkipPolicy:Ng,resolveUnknownAuthorEventCount:ic,resolveVectorRefreshPolicy:Dg,selectStaleItemDetail:Zo,summarizeHealthCheckDetails:xg,summarizeExtensionList:is,summarizeRecordList:et,summarizeStringList:W,telemetryEnvFlagEnabled:rs,warningCode:tc};(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]="a07d2f98-7c1d-5d0a-be70-5181ed0f7b4f")}catch{}})();function Ug(e,t,n){if(!n.has(t.metadata.status))return{reason:"not_terminal"};if(e.length===0)return{reason:"missing_history"};if(!Su(e,t).ok)return{reason:"unverified_history"};let i=mu(),r={reason:"no_proven_transition"};for(let[s,a]of e.entries()){let o=n.has(String(i.metadata.status));i=gu(i,a.patch,s+1,a.op),n.has(String(i.metadata.status))?o||(r=["create","close","cancel","update","update_audit"].includes(a.op)&&Ql(a.ts)?{timestamp:a.ts,source_index:s+1}:{reason:"no_proven_transition"}):r={reason:"no_proven_transition"}}return r}function jg(e){return new Set([...e.terminal_statuses,...[...e.alias_to_id].filter(([,t])=>e.terminal_statuses.has(t)).map(([t])=>t)])}async function Gg(e,t,n,i,r){let s=jg(n),a=t.filter(d=>s.has(d.status)&&!d.closed_at),o=[],c=[];for(let d of i?a:[]){let l;try{let u=await ct(at(e,d.id),d.id),{body:p,...g}=d;l=Ug(u,{metadata:g,body:p},s)}catch{c.push({id:d.id,reason:"unreadable_history"});continue}if("reason"in l){c.push({id:d.id,reason:l.reason});continue}o.push({item_id:d.id,check:"metadata",field:"closed_at",kind:"set_closed_at",value:l.timestamp,gate:"timestamps",command:"pm validate --check-metadata --auto-fix --fix-scope timestamps"})}return{details:{missing_closed_at_count:a.length,missing_closed_at_item_ids:a.slice(0,r).map(d=>d.id),missing_closed_at_item_ids_truncated:a.length>r,closure_history_inspected:i,closure_timestamp_derivable_count:o.length,closure_timestamp_residual_count:c.length,closure_timestamp_residual:c.slice(0,r),closure_timestamp_residual_truncated:c.length>r,...a.length>0?{closure_timestamp_fix_hint:"pm validate --check-metadata --auto-fix --fix-scope timestamps --dry-run"}:{}},fixes:o,warnings:a.length>0?[`validate_metadata_missing_closed_at:${a.length}`]:[]}}async function qg(e,t){let n=x(process.cwd(),t.path),i=await I(n),r=K(i.schema);await se({pmRoot:n,settings:i,id:e.item_id,op:"update",author:U(t.author,i.author_default),message:"Backfill closed_at from verified lifecycle history",skipNoop:!0,async mutate(s){if(s.metadata.closed_at)return{changedFields:[]};let a=await ct(at(n,s.metadata.id),s.metadata.id),o=jg(r),c=Ug(a,s,o);if(!("timestamp"in c)||c.timestamp!==e.value)throw new _("Closure timestamp evidence changed or cannot be verified; rerun the timestamp repair preview.",m.GENERIC_FAILURE);return s.metadata.closed_at=c.timestamp,{changedFields:["closed_at"]}}})}(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]="34d28b31-b098-5ffd-b39b-2e11de150ac1")}catch{}})();function RA(e,t){return e==="malformed"||t==="malformed"?"malformed":e==="moved"||t==="moved"?"moved":"deleted"}function Kg(e){return`${e.item_id} ${e.link_kind}`}function zg(e,t){let n=new Map;for(let i of e){let r=n.get(i.path);r?(r.classification=RA(r.classification,i.classification),r.owners.set(Kg(i),i)):n.set(i.path,{classification:i.classification,owners:new Map([[Kg(i),i]])})}return[...n.entries()].sort(([i],[r])=>i.localeCompare(r)).map(([i,r])=>({path:i,classification:r.classification,items:[...r.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(){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]="00f8052d-480b-5e38-86cf-4574a8ad1e92")}catch{}})();function Wg(e,t,n,i,r=40){let s=r===1/0?1/0:Number.isFinite(r)?Math.max(0,Math.floor(r)):40,a=new Map(t.map(d=>[d.path,d])),o={missing_linked_path_rows_count:0,missing_linked_path_rows:[],missing_linked_path_rows_truncated:!1,missing_linked_links_count:0,active_missing_linked_links_count:0,legacy_closed_missing_linked_links_count:0,legacy_terminal_missing_linked_links_count:0,active_missing_linked_paths_count:0},c=zg(e,n).map(d=>{let l=[],u=[];for(let g of d.items){let f=me(g.status,i)??g.status;i.terminal_statuses.has(f)?(u.push(g),f===i.close_status&&(o.legacy_closed_missing_linked_links_count+=1)):l.push(g)}o.missing_linked_links_count+=d.items.length,o.active_missing_linked_links_count+=l.length,o.legacy_terminal_missing_linked_links_count+=u.length,l.length>0&&(o.active_missing_linked_paths_count+=1);let p=a.get(d.path);return{...d,candidates:p?.candidates??[],candidates_truncated:p?.candidates_truncated??!1,link_count:d.items.length,active_link_count:l.length,items:[...l,...u].slice(0,s),items_truncated:d.items.length>s}});return c.sort((d,l)=>+(l.active_link_count>0)-+(d.active_link_count>0)||d.path.localeCompare(l.path)),o.missing_linked_path_rows_count=c.length,o.missing_linked_path_rows=c.slice(0,s),o.missing_linked_path_rows_truncated=c.length>s,o}import En from"node:fs/promises";import Sn 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]="7ff2e182-d84c-5e1c-8b63-daea17d55af4")}catch{}})();async function OA(e,t){let n=[...new Set(Object.values(t))],i=[];return await Promise.all(n.map(async r=>{let s;try{s=await En.readdir(Sn.join(e,r))}catch{return}for(let a of s)for(let o of Dt)if(a.toLowerCase().endsWith(o)){i.push({relativePath:`${r}/${a}`,id:a.slice(0,-o.length)});break}})),i.sort((r,s)=>r.relativePath.localeCompare(s.relativePath))}function LA(e,t){let{id:n,relativePath:i,liveItemIds:r,out:s}=e,a=sn(t);if(a){s.conflictMarkers.push({id:n,path:i,line:a.line,detail:`unresolved merge conflict marker ${a.marker}`});return}let o=DA(e,t);o!==null&&(o.op==="delete"&&r.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 DA(e,t){let{id:n,relativePath:i,out:r}=e,s=null,a=!1,o=t.split(/\r?\n/).map((c,d)=>({content:c.trim(),number:d+1})).filter(c=>c.content.length>0);for(let c of o){try{let d=JSON.parse(c.content);if(typeof d!="object"||d===null||Array.isArray(d))throw new TypeError("history entry must be an object");s=d}catch{return r.unparseable.push({id:n,path:i,line:c.number,detail:"history line is not a valid JSON object"}),null}if(s.op==="create"){if(a)return r.unparseable.push({id:n,path:i,line:c.number,detail:"duplicate item identity: more than one create event in one history stream"}),null;a=!0}}return s}function sc(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 NA(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},i;try{i=await En.readdir(Sn.join(e,"history"))}catch{return n}for(let r of i.sort((s,a)=>s.localeCompare(a))){if(!r.endsWith(".jsonl"))continue;n.scanned+=1;let s;try{s=await En.readFile(Sn.join(e,"history",r),"utf8")}catch(a){n.unparseable.push({id:r.slice(0,-6),path:`history/${r}`,detail:sc("history stream",a)});continue}LA({id:r.slice(0,-6),relativePath:`history/${r}`,liveItemIds:t,out:n},s)}return n}function Bg(e){let t=sn(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 MA(e){let t=[],n=0,i=null;try{i=await Q(Ae(e))}catch(s){n+=1,t.push({path:"settings.json",detail:sc("configuration file",s)})}if(i!==null){n+=1;let s=Bg(i);s!==null&&t.push({path:"settings.json",detail:s})}let r;try{r=await En.readdir(Sn.join(e,"schema"))}catch{return{scanned:n,unparseable:t}}for(let s of r.sort((a,o)=>a.localeCompare(o))){if(!s.endsWith(".json"))continue;n+=1;let a;try{a=await En.readFile(Sn.join(e,"schema",s),"utf8")}catch(c){t.push({path:`schema/${s}`,detail:sc("configuration file",c)});continue}let o=Bg(a);o!==null&&t.push({path:`schema/${s}`,detail:o})}return{scanned:n,unparseable:t}}async function Hg(e,t,n,i={}){let r=await OA(e,n),s=new Set(r.map(u=>u.id)),a=new Map;for(let u of r){let p=a.get(u.id);p===void 0?a.set(u.id,[u.relativePath]):p.push(u.relativePath)}let o=[...a.entries()].filter(([,u])=>u.length>1).map(([u,p])=>({id:u,paths:[...p].sort((g,f)=>g.localeCompare(f))})).sort((u,p)=>u.id.localeCompare(p.id)),c=(await Promise.all(r.map(async u=>{if(!t.has(u.id))return{path:u.relativePath,id:u.id};try{let p=Sn.join(e,u.relativePath);return nr(await En.readFile(p,"utf8"),{format:p.toLowerCase().endsWith(".md")?"json_markdown":"toon",schema:i.schema,extensionFieldNames:i.extensionFieldNames}),null}catch{return{path:u.relativePath,id:u.id}}}))).filter(u=>u!==null),d=await NA(e,s),l=await MA(e);return{item_files_on_disk:r.length,item_ids_on_disk:s.size,parsed_items:t.size,unreadable_item_files:c,duplicate_item_ids:o,history_streams_scanned:d.scanned,history_conflict_marker_streams:d.conflictMarkers,history_unparseable_streams:d.unparseable,resurrected_items:d.resurrected,history_repair_reconciliations:d.repairReconciliations,config_files_scanned:l.scanned,unparseable_config_files:l.unparseable}}import{readFileSync as PA}from"node:fs";import as 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]="597a781e-a00d-5083-8d57-3fae870f9ccd")}catch{}})();var FA=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),ac=new Set(["--pm-path","--path","--author"]),$A={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"])},UA=new Set(["-p","--package"]),jA=new Set(["-c","--call"]),oc=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),cc=new Set(["-C","--prefix","--userconfig","--cache"]),Vg=new Set(["--cwd"]),Yg=new Set(["--cwd"]),GA=new Set(["exec","x"]),Jg=new Set(["run","run-script"]),Xg=new Set(["-C","--dir","--cwd","-w","--workspace","--filter"]);function qt(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function os(e,t=process.cwd()){let n=cs(e.split(" ").filter(a=>a.length>0));if(n.length===0)return null;let[i,...r]=n;if(pi(i)||fi(i,t))return r;if(i==="node"&&r[0]&&fi(r[0],t))return r.slice(1);let s=i==="npx"||i==="bunx"?Kt(r):i==="pnpm"?ls(r):i==="npm"?us(r):null;return s&&(pi(s.command)||lc(s.command))?s.args:null}var dc=(e,t="pm")=>{let n=t.trim().toLowerCase(),i=n.length;for(;i>0&&n[i-1]==="-";)i-=1;let r=n.slice(0,i);if(r.length===0)return[];let s=e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase(),a=new Set;for(let o of qt(s)){let c=os(o),d=c?uc(c):null,l=d&&FA.has(d.subcommand)?KA(d.remaining,$A[d.subcommand]):void 0,u=l?.trim().toLowerCase();u?.startsWith(`${r}-`)===!0&&u.length>r.length+1&&a.add(l)}return[...a].sort((o,c)=>o.localeCompare(c))};function cs(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 ds(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(ac.has(n)){t+=2;continue}t+=1;continue}return n}}function pi(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function qA(e){let t=e.trim();if(!t.startsWith("@")){let r=t.indexOf("@");return r===-1?t:t.slice(0,r)}let n=t.indexOf("/");if(n===-1)return t;let i=t.indexOf("@",n+1);return i===-1?t:t.slice(0,i)}function lc(e){let t=qA(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function fi(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 i=as.resolve(t,e);try{return JSON.parse(PA(as.join(as.dirname(as.dirname(i)),"package.json"),"utf8")).name==="@unbrained/pm-cli"}catch{return!1}}function Kt(e){let t=0;for(;t<e.length;){let i=e[t];if(i==="--"){t+=1;break}if(!i.startsWith("-"))break;let r=/^(?:-c|--call)=(.*)$/.exec(i);if(r){let s=r[1];return s?{command:s,args:e.slice(t+1)}:null}if(jA.has(i)){t+=1;break}t+=UA.has(i)&&!i.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function It(e,t){let n=0;for(;n<e.length;){let i=e[n];if(i==="--"){n+=1;continue}if(i.startsWith("-")){if(i.includes("=")){n+=1;continue}if(t.has(i)){n+=2;continue}n+=1;continue}return{subcommand:i,args:e.slice(n+1)}}return null}function ls(e){let t=It(e,oc);return t?.subcommand!=="dlx"?null:Kt(t.args)}function us(e){let t=It(e,cc);return!t||!GA.has(t.subcommand)?null:Kt(t.args)}function uc(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(ac.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function KA(e,t=new Set){for(let n=0;n<e.length;n+=1){let i=e[n];if(i==="--")return e[n+1];if(!i.startsWith("-"))return i;!i.includes("=")&&(ac.has(i)||t.has(i))&&(n+=1)}}import{execFile as WA}from"node:child_process";import{readFile as BA}from"node:fs/promises";import eh from"node:path";import{promisify as HA}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]="4025e3fb-f2f2-57f1-a981-5bbb2381fe67")}catch{}})();function ms(e){if(!(e.pm_context_mode!=="none"||e.workspace_context_mode==="isolated"||e.workspace_context_mode==="snapshot"))throw new _("pm_context_mode=none requires workspace_context_mode=isolated or snapshot so implicit tracker discovery cannot reach the source workspace.",m.USAGE,{code:"linked_test_context_invalid",required:"Set workspace_context_mode to isolated or snapshot when pm_context_mode is none.",examples:[fe(["test","<id>","--add-json",JSON.stringify({command:e.command,pm_context_mode:"none",workspace_context_mode:"isolated"})])]})}var Ge=["command","cmd","path","scope","timeout","timeout_seconds","pm_context_mode","workspace_context_mode","env_set","env_clear","shared_host_safe","assert_stdout_contains","assert_stdout_regex","assert_stderr_contains","assert_stderr_regex","assert_stdout_min_lines","assert_json_field_equals","assert_json_field_gte","note"],zA=new Set(Ge);function Qg(e){return lr(e,Ge)}function _s(e,t){let n={},i=[];for(let[r,s]of Object.entries(e)){let a=r.toLowerCase();if(!zA.has(a)){i.push(r);continue}if(Object.hasOwn(n,a))throw new _(`${t} provides key "${r}" more than once after case normalization`,m.USAGE);n[a]=s}if(i.length>0)throw new _(`${t} does not recognize key${i.length>1?"s":""} ${i.map(r=>`"${r}"`).join(", ")}. Allowed keys: ${Ge.join(", ")}.`,m.USAGE);if(n.cmd!==void 0){if(n.command!==void 0&&n.command.trim()!==n.cmd.trim())throw new _(`${t} command and cmd must match when both are provided`,m.USAGE);let{cmd:r,...s}=n;return{...s,command:s.command??r}}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]="8f1a3301-8938-5208-9177-72ee29f3d174")}catch{}})();var VA=HA(WA),mc=1,YA="linked-test-trust.json";function _c(e){return eh.join(hl(e),YA)}function Zg(){return{version:mc,acknowledged:{}}}async function pc(e){try{let t=JSON.parse(await BA(_c(e),"utf8"));return t.version!==mc||typeof t.acknowledged!="object"||t.acknowledged===null||Array.isArray(t.acknowledged)?Zg():{version:mc,acknowledged:t.acknowledged}}catch{return Zg()}}async function hi(e=process.cwd()){let t=process.env.GITHUB_HEAD_REF?.trim()||process.env.GITHUB_REF_NAME?.trim();if(t&&t!=="merge")return t;try{let{stdout:n}=await VA("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),i=n.trim();return i.length===0?void 0:i}catch{return}}function yi(e=process.cwd()){return process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||e}function JA(e){return e===null||typeof e!="object"?!1:typeof e.author=="string"&&e.author.trim().length>0&&typeof e.created_at=="string"&&Xl(e.created_at)&&(e.source_kind==="local_mutation"||e.source_kind==="merge_union")}function gi(e,t){return{...e?{source_ref:e}:{},...t?{current_source_ref:t}:{}}}function XA(e,t,n,i){return e?.map(r=>r.command&&!r.provenance?{...r,provenance:{author:t,created_at:n,source_kind:"local_mutation",...i?{source_ref:i}:{}}}:r)}async function Tn(e,t,n){if(!e||e.length===0)return e;for(let r of e)ms(r);let i=yi();return XA(e,t,n,await hi(i))}function th(e){return Tl(ie({command:e.command??null,path:e.path??null,scope:e.scope,pm_context_mode:e.pm_context_mode??null,workspace_context_mode:e.workspace_context_mode??null,env_set:e.env_set??null,env_clear:e.env_clear??null,shared_host_safe:e.shared_host_safe??null,provenance:e.provenance??null,provenance_invalid:e.provenance_invalid??null}))}async function fc(e,t,n){let i=await pc(e);return nh(t,n,i)}function nh(e,t,n){let i=th(e),r=e.provenance?.source_ref;if(e.provenance===void 0&&e.provenance_invalid!==!0)return{fingerprint:i,trusted:!0,reason:"legacy"};let s=Object.hasOwn(n.acknowledged,i);return e.provenance_invalid===!0||!JA(e.provenance)?s?{fingerprint:i,trusted:!0,reason:"acknowledged",...gi(void 0,t)}:{fingerprint:i,trusted:!1,reason:"invalid_provenance",...gi(void 0,t)}:e.provenance.source_kind==="local_mutation"&&r===void 0?{fingerprint:i,trusted:!0,reason:"local_mutation",...gi(void 0,t)}:e.provenance.source_kind==="local_mutation"&&r!==void 0&&r===t?{fingerprint:i,trusted:!0,reason:"local_source_ref",source_ref:r,current_source_ref:t}:s?{fingerprint:i,trusted:!0,reason:"acknowledged",...gi(r,t)}:{fingerprint:i,trusted:!1,reason:"foreign_source_ref",...gi(r,t)}}async function ih(e,t,n){let i=await pc(e);return t.map(r=>nh(r,n,i))}async function rh(e,t,n){let i=await pc(e),r=t.filter(s=>typeof s.command=="string"&&s.command.length>0).map(th);for(let s of r)i.acknowledged[s]={acknowledged_at:n};return await wt(eh.dirname(_c(e))),await Oe(_c(e),`${JSON.stringify(i,null,2)}
|
|
9
|
-
`),{acknowledged:r.length,fingerprints:r}}import xc from"node:fs/promises";import{realpathSync as oI}from"node:fs";import{execFile as cI}from"node:child_process";import xe from"node:path";import{promisify as dI}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]="8c3bbe6d-dcce-5b1a-8352-1472ab1ed6e2")}catch{}})();var QA=["metadata","resolution"],gc=["metadata","resolution","estimates","timestamps","lifecycle"],ZA="completed";function hc(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function sh(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function ah(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let i=sh(n.close_reason)??ZA;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:i,command:`pm update ${n.id} --resolution ${hc(i)}`,gate:"resolution"})}return t}function oh(e){let t=[];for(let n of e){let i=sh(n.resolution);i!==void 0&&t.push({item_id:n.id,check:"metadata",field:"close_reason",kind:"set_close_reason",value:i,command:`pm update ${n.id} --close-reason ${hc(i)}`,gate:"metadata"})}return t}function ch(e,t){return e.map(n=>{let i=_u(n.type,t);return{item_id:n.id,check:"metadata",field:"estimated_minutes",kind:"set_estimate",value:String(i),command:`pm update ${n.id} --estimate ${i}`,gate:"estimates"}})}function dh(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 lh(e){let t=[];for(let n of e){if(n.classification!=="deleted")continue;let i=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 ${i} ${n.item_id} --remove ${hc(n.path)}`})}return t}function uh(e){let t=(e??[]).flatMap(i=>i.split(",")).map(i=>i.trim()).filter(i=>i.length>0);if(t.length===0){if(e!==void 0&&e.length>0)throw new _(`--fix-scope values must not be empty. Supported values: ${gc.join(", ")}.`,m.USAGE);return new Set(QA)}let n=new Set;for(let i of t){let r=i.toLowerCase().replaceAll("-","_");if(gc.includes(r)){n.add(r);continue}throw new _(`Unknown --fix-scope value "${i}". Supported values: ${gc.join(", ")}.`,m.USAGE)}return n}function mh(e,t){let n=[],i=[];for(let r of e)r.gate!==void 0&&!t.has(r.gate)?i.push(r):n.push(r);return{applicable:n,gated:i}}function vi(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]="e93db1eb-e524-58bf-af2e-cb5f22f3047b")}catch{}})();var eI=/^([A-Z][A-Z0-9]*-\d+)\b/iu;function tI(e,t={}){if(typeof e!="string")return null;let n=e.trim();if(n.length===0)return null;let i=eI.exec(n);if(!i)return null;let r=i[1],s=r.toUpperCase(),a=r.slice(0,r.lastIndexOf("-")),o=new Set((t.configuredPrefixes??[]).map(u=>u.trim().replace(/-+$/u,"").toUpperCase())),c=n.slice(r.length),d=t.evidenceText?.toUpperCase()??"",l=d.includes(`ISSUE CODE: ${s}`)||d.includes(`ISSUE CODE \`${s}\``)||d.includes(`\`${s}\``)||d.includes(`[${s}]`);return a===a.toUpperCase()||/^\s*(?::|—|–|\])/u.test(c)||o.has(a.toUpperCase())||l?s:null}function _h(e){return typeof e=="string"&&e.trim().length>0}function nI(e){let t=new Set(e.map(a=>a.id.toLowerCase())),n=new Map,i=new Map;for(let a of e){let o=a.id.toLowerCase(),c=new Set([...a.parent===null?[]:[a.parent.toLowerCase()],...a.derivations].filter(d=>d!==o&&t.has(d)));n.set(o,c);for(let d of c){let l=i.get(d)??[];l.push(o),i.set(d,l)}}let r=[...[...n].filter(([,a])=>a.size===0).map(([a])=>a)],s=new Set;for(let a=0;a<r.length;a+=1)for(let o of i.get(r[a])??[]){let c=n.get(o);c.delete(r[a]),c.size===0&&(s.add(o),r.push(o))}return e.filter(a=>!s.has(a.id.toLowerCase()))}function ph(e,t={}){let n=new Map;for(let r of e){if(typeof r.title!="string"||_h(r.duplicate_of))continue;let s=tI(r.title,{...t,evidenceText:r.body});if(s===null)continue;let a=n.get(s);a||(a=[],n.set(s,a)),a.some(o=>o.id===r.id)||a.push({id:r.id,title:r.title,parent:_h(r.parent)?r.parent.trim():null,derivations:(r.dependencies??[]).filter(o=>["discovered_from","supersedes","incident_from"].includes(o.kind)).map(o=>o.id.trim().toLowerCase()).filter(o=>o!==r.id.toLowerCase())})}let i=[];for(let[r,s]of n){if(s.length<2)continue;let a=nI(s);if(a.length<2)continue;let o=[...a].sort((c,d)=>c.id.localeCompare(d.id));i.push({code:r,count:o.length,ids:o.map(c=>c.id),titles:o.map(c=>c.title)})}return i.sort((r,s)=>r.code.localeCompare(s.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]="3c32504d-254c-5156-a41f-8ffd8e49107f")}catch{}})();function fh(e){let t=new Map;for(let i of e){let r=t.get(i.item_type);r||(r=new Map,t.set(i.item_type,r)),r.set(i.field,(r.get(i.field)??0)+1)}let n={};for(let i of[...t.keys()].sort((r,s)=>r.localeCompare(s))){let r=t.get(i),s={};for(let a of[...r.keys()].sort((o,c)=>o.localeCompare(c)))s[a]=r.get(a);n[i]=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]="c577e41b-6642-554a-bc4d-0c22170c1e24")}catch{}})();function gh(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function hh(e,t,n=3){let i=Number.isFinite(n)&&n>=1?Math.floor(n):3,r=new Map;for(let s of t){let a=gh(s);if(a.length===0)continue;let o=r.get(a);o?o.push(s):r.set(a,[s])}return e.map(s=>{if(s.includes(",")||s.replace(/^[a-z]:[\\/]/i,"").includes(":"))return{path:s,classification:"malformed",candidates:[],candidates_truncated:!1};let a=(r.get(gh(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,i),candidates_truncated:a.length>i}})}function yh(e){return e.map(t=>t.classification==="moved"?`${t.path}:moved:${t.candidates[0]}`:`${t.path}:${t.classification}`)}(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]="8cca9707-86a7-5ab5-8c7b-92be560254d0")}catch{}})();async function ps(e){return e.includeBody?dt(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema,{forceSourceScan:!0}):or(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]="6322c4ff-92bd-59e5-aa64-ef8d3ef4b57f")}catch{}})();var iI=5;async function rI(e,t){let n=t.hashMismatches.filter(s=>s!==Mt);if(n.length===0)return;let i=await I(e),r=F(i,P());for(let s of n){let a=await bt(e,s,i.locks.ttl_seconds,"history-drift-read",!1,!0,i.locks.wait_ms);try{let o=await Y(e,s,i.id_prefix,i.item_format,r.type_to_folder);if(o===null)throw new _(`Item ${s} not found`,m.NOT_FOUND,{code:"item_not_found",required:"Repeat validation after writers finish; each item-hash discrepancy requires readable canonical source."});let{document:c}=await he(o,{schema:i.schema});if(c.metadata.id!==s)throw new _(`Item identity changed while validating ${s}`,m.CONFLICT,{code:"item_identity_conflict",required:"Restore the canonical item identity and validate storage integrity before retrying history validation."});let d=await cp(e,{...c.metadata,body:c.body});for(let u of["missingStreams","unreadableStreams","hashMismatches","chainMismatches","versionSkews","driftedItems"])t[u]=[...t[u].filter(p=>p!==s),...d[u].filter(p=>p===s)].sort((p,g)=>p.localeCompare(g));let l=[...(t.identityDiscontinuities??[]).filter(u=>u.item_id!==s),...(d.identityDiscontinuities??[]).filter(u=>u.item_id===s)];l.length>0?t.identityDiscontinuities=l:delete t.identityDiscontinuities}finally{await a()}}}async function fs(e,t,n){let i=await Xn(e,t);await rI(e,i);let r=[["validate_history_drift_missing_streams",i.missingStreams.length],["validate_history_drift_unreadable_streams",i.unreadableStreams.length],["validate_history_drift_hash_mismatches",i.hashMismatches.length],["validate_history_drift_chain_mismatches",i.chainMismatches.length],["validate_history_drift_version_skews",i.versionSkews.length],["validate_history_drift_workspace_state_mismatches",i.workspaceStateMismatches.length],["validate_history_drift_workspace_state_missing",i.workspaceStateMissing.length],["validate_history_drift_workspace_state_unreadable",i.workspaceStateUnreadable.length]].filter(([,c])=>c>0).map(([c,d])=>`${c}:${d}`),s=n?Number.POSITIVE_INFINITY:iI,a=i.driftedItems.slice(0,s),o=i.identityDiscontinuities??[];return{check:{name:"history_drift",status:o.length>0?"error":r.length===0?"ok":"warn",ok:o.length===0&&r.length===0,details:{identity_discontinuities:o.slice(0,s),identity_discontinuities_count:o.length,identity_discontinuities_truncated:o.length>s,checked_items:t.length,drifted_items_count:i.driftedItems.length,drifted_items:a,drifted_items_truncated:a.length<i.driftedItems.length,counts:{missing_streams:i.missingStreams.length,unreadable_streams:i.unreadableStreams.length,hash_mismatches:i.hashMismatches.length,chain_mismatches:i.chainMismatches.length,version_skews:i.versionSkews.length,workspace_state_mismatches:i.workspaceStateMismatches.length,workspace_state_missing:i.workspaceStateMissing.length,workspace_state_unreadable:i.workspaceStateUnreadable.length},workspace_state_mismatches:i.workspaceStateMismatches,workspace_state_missing:i.workspaceStateMissing,workspace_state_unreadable:i.workspaceStateUnreadable,version_skews:i.versionSkews.slice(0,s)}},warnings: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]="3caaa82b-d8c7-5bc4-94e5-6699da27fa3c")}catch{}})();function gs(e,t){let n=e[0];if(e.length===1)return[n,n];let i=new Set(e),r=[n],s=new Set([n]),a=o=>{for(let c of(t.get(o)??[]).filter(d=>i.has(d))){if(c===n&&r.length>1)return r.push(n),!0;if(!s.has(c)){if(s.add(c),r.push(c),a(c))return!0;r.pop(),s.delete(c)}}return!1};return a(n)?[...r]:[...e,n]}function sI(e,t){if(typeof e!="string")return;let n=e.trim().toLowerCase();return n.length>0?t.get(n):void 0}function aI(e,t,n,i){for(let r of e.dependencies??[]){if(typeof r!="object"||r===null||typeof r.id!="string")continue;let s=i.resolve(r.kind);if(!s?.hierarchy)continue;let a=n.get(r.id.toLowerCase());a&&(s.hierarchyDirection==="source_parent"?t.get(a).push(e.id):t.get(e.id).push(a))}}function yc(e,t=ae()){let n=new Map(e.map(r=>[r.id.toLowerCase(),r.id])),i=new Map(e.map(r=>[r.id,[]]));for(let r of[...e].sort((s,a)=>s.id.localeCompare(a.id))){let s=i.get(r.id),a=sI(r.parent,n);a&&s.push(a),aI(r,i,n,t)}for(let[r,s]of i)i.set(r,[...new Set(s)].sort());return i}function vc(e,t,n=ae()){let i=xr(e,a=>t?Nt(a,t):a==="closed"||a==="canceled",n),r=yc(e,n),s=i.cycles.map(a=>a.item_ids);return{cycle_count:s.length,active_cycle_count:i.cycles.filter(a=>!a.legacy_terminal).length,legacy_cycle_count:i.cycles.filter(a=>a.legacy_terminal).length,cycle_item_ids:[...new Set(s.flat())].sort(),cycle_sample_paths:s.map(a=>gs(a,r).join("->")),cardinality_violation_count:i.cardinality_violations.length,active_cardinality_violation_count:i.cardinality_violations.filter(a=>!a.legacy_terminal).length,legacy_cardinality_violation_count:i.cardinality_violations.filter(a=>a.legacy_terminal).length,cardinality_violation_rows:i.cardinality_violations.map(a=>`${a.child_id}:${a.parent_ids.join(",")}:${a.legacy_terminal?"legacy":"active"}`),parent_divergence_count:i.divergences.length,active_parent_divergence_count:i.divergences.filter(a=>!a.legacy_terminal).length,legacy_parent_divergence_count:i.divergences.filter(a=>a.legacy_terminal).length,parent_divergence_rows:i.divergences.map(a=>`${a.child_id}:scalar=${a.scalar_parent_id}:dependencies=${a.dependency_parent_ids.join(",")}:${a.legacy_terminal?"legacy":"active"}`)}}(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]="f2840c80-38f5-5563-b2c0-ef5596cf8f62")}catch{}})();function Ct(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function wc(e){return Ct(e).replace(/\/+$/,"")}function ze(e){let t=ne(e);if(!t)return;let n=t.toLowerCase();if(!(n==="none"||n==="null"||n==="n/a"||n==="na"))return t}function bc(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length>120?`${t.slice(0,117)}...`: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]="9ef196b2-3eef-5bac-b949-bcb3e947c44d")}catch{}})();var lI=["src","tests","docs"],uI=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],mI=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),_I=["resolution","expected_result","actual_result"],pI=["default","tracked-all","tracked-all-strict"],vh=["core","strict","custom"],vs=["off","warn","error"],Sc=["author","acceptance_criteria","estimated_minutes","close_reason"],kh=[...Sc,"reviewer","risk","confidence","sprint","release"],Tc=Array.from(new Set(kh)),fI={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"},gI={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"},hI={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"},yI={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"},vI={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"},wI=32*1024*1024,bI=1e4,Ac=40,We=5,kI=4096,EI=255,SI=dI(cI);function Eh(e){let t={};for(let[n,i]of Object.entries(e))Array.isArray(i)||i===!1&&n.endsWith("_truncated")||(t[n]=typeof i=="object"&&i!==null?Eh(i):i);return t}function TI(e){return{...e,checks:e.checks.map(t=>({...t,details:Eh(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 bs(e,t){return me(e,t)??e}function wi(e,t){return t.terminal_statuses.has(bs(e,t))}function xt(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function hs(e,t){return e.length!==t.length?!1:e.every((n,i)=>n===t[i])}function AI(e){let t=xt(il),n={blocked_reason:xt(Ki.blocked_reason),resolution:xt(Ki.resolution),actual_result:xt(Ki.actual_result)},i=xt(e.validation.lifecycle_stale_blocker_reason_patterns),r={blocked_reason:xt(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:xt(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:xt(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:i,stale_blocker_reason_pattern_source:hs(i,t)?"default":"settings",closure_like_metadata_field_patterns:r,closure_like_metadata_field_pattern_sources:{blocked_reason:hs(r.blocked_reason,n.blocked_reason)?"default":"settings",resolution:hs(r.resolution,n.resolution)?"default":"settings",actual_result:hs(r.actual_result,n.actual_result)?"default":"settings"}}}function Sh(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(vh.includes(t))return t;throw new _(`Unknown --metadata-profile value "${e}". Supported values: ${vh.join(", ")}.`,m.USAGE)}function Th(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(vs.includes(t))return t;throw new _(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${vs.join(", ")}.`,m.USAGE)}function Ah(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(vs.includes(t))return t;throw new _(`Unknown --parent-cycle-severity value "${e}". Supported values: ${vs.join(", ")}.`,m.USAGE)}function II(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase().replaceAll("-","_")))].map(t=>fI[t]).filter(t=>t!==void 0).sort((t,n)=>t.localeCompare(n))}function CI(e,t,n){let i=II(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...Sc],configured_custom_fields:i,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...kh],configured_custom_fields:i,fallback_to_core:!1,warnings:[]}:i.length>0?{profile:e,profile_source:t,required_fields:i,configured_custom_fields:i,fallback_to_core:!1,warnings:[]}:{profile:e,profile_source:t,required_fields:[...Sc],configured_custom_fields:i,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var xI=new Set(["acceptance_criteria","estimated_minutes"]);function Ih(e,t,n,i){return!i&&xI.has(t)&&wi(e.status,n)?!1:t==="author"?!ne(e.author):t==="acceptance_criteria"?!ne(e.acceptance_criteria):t==="estimated_minutes"?!Number.isFinite(e.estimated_minutes):t==="close_reason"?bs(e.status,n)===n.close_status&&!ne(e.close_reason):t==="reviewer"?!ne(e.reviewer):t==="risk"?!ne(e.risk):t==="confidence"?typeof e.confidence=="number"?!Number.isFinite(e.confidence):!ne(e.confidence):t==="sprint"?!ne(e.sprint):!ne(e.release)}function Ch(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 _(`Unknown --scan-mode value "${e}". Supported values: ${pI.join(", ")}.`,m.USAGE)}function xh(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim();if(t)return xe.resolve(t);let n=xe.resolve(e);if(n.replaceAll("\\","/").endsWith("/.agents/pm"))return xe.dirname(xe.dirname(n));let i=xe.resolve(process.cwd()),r=wh(n),s=wh(i),a=xe.relative(r,s);return a.length===0||!a.startsWith("..")&&!xe.isAbsolute(a)?n:i}function wh(e){try{return oI.native(e)}catch{return xe.resolve(e)}}function RI(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function Rc(e,t,n){let i=t.length>0?xe.join(e,t):e,r;try{r=await xc.readdir(i,{withFileTypes:!0})}catch(s){if(q(s))return;throw s}for(let s of r){if(s.name.startsWith("."))continue;let a=t.length>0?xe.join(t,s.name):s.name;if(s.isDirectory()){if(mI.has(s.name))continue;await Rc(e,a,n);continue}s.isFile()&&n.push(Ct(a))}}async function Ic(e){let t=[];for(let n of lI)await Rc(e,n,t);for(let n of uI){let i=xe.join(e,n);try{(await xc.stat(i)).isFile()&&t.push(Ct(n))}catch{}}return[...new Set(t)].sort((n,i)=>n.localeCompare(i))}async function Rh(e){try{let{stdout:t}=await SI("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:wI,windowsHide:!0,timeout:bI}),n=t.split("\0").map(i=>Ct(i)).filter(i=>i.length>0);return[...new Set(n)].sort((i,r)=>i.localeCompare(r))}catch{return null}}function OI(e,t){let n=new Set,i=wc(el);i.length>0&&n.add(i);let r=wc(xe.relative(t,e));return r.length>0&&!r.startsWith("..")&&n.add(r),[...n].sort((s,a)=>s.localeCompare(a))}function bh(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function LI(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let i=await Rh(e);if(i)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:i,candidateTotal:i.length,candidateScanned:i.length};let r=await Ic(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length}}let n=await Ic(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function ee(e,t=We){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function zt(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=ee(e,Ac);return{values:n.values,truncated:n.truncated,total:e.length}}var DI={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},NI={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function MI(e){let t=e.missing_fields.map(n=>`${DI[n]} "${NI[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function Oh(e,t){let n=e.details?.missing_resolution_remediation_hints,i=Array.isArray(n)&&n.length>0,r=i?n.filter(a=>typeof a=="string"):vg(t);if(r.length===0)return;let s=i&&e.details?.missing_resolution_remediation_hints_truncated===!0;e.details={...e.details,fix_hints:r,...s?{fix_hints_truncated:!0}:{}}}function Lh(e){let t=new Set;return e.checkCompleteness&&t.add("completeness"),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("completeness"),t.add("storage_integrity")),t):(e.pruneMissing&&t.add("files"),t)}var PI="validate_metadata_duplicate_issue_codes";function Dh(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:We,i=e.slice(0,n);return{rows:i.map(r=>({code:r.code,count:r.count,ids:r.ids,titles:r.titles,remediation_hint:`Items ${r.ids.join(", ")} share issue code "${r.code}"; rename or merge so each logical code maps to one item.`})),truncated:i.length<e.length,warnings:[`${PI}:${e.length}`]}}function FI(e,t,n){let i=Object.fromEntries(Tc.map(r=>[r,[]]));for(let r of e)for(let s of Tc)Ih(r,s,t,n)&&i[s].push(r.id);return i}function $I(e,t,n){let i=[...e.warnings];for(let r of e.required_fields){let s=t[r];s.length>0&&i.push(`${gI[r]}:${s.length}`)}return i.push(...n),i}function Nh(e,t){let n={};for(let i of e.required_fields){let r=t[i],s=r?r.length:0,a=hI[i];n[a]=s}return n}function Mh(e,t,n){let i=[];for(let r of e.required_fields){let s=t[r];if(s)for(let a of s){let o=n.get(a)?.type,c=typeof o=="string"&&o.length>0?o:"Unknown";i.push({item_type:c,field:r})}}return i}function UI(e,t,n,i){for(let r of t.required_fields){let s=n[r];if(!s||s.length===0)continue;let a=yI[r],o=vI[r];if(!a||!o)continue;let c=ee(s,i?s.length:We);e[a]=c.values,e[o]=c.truncated}}function Ph(e,t,n){if(!e.required_fields.includes("close_reason"))return[];let i=t.close_reason;return i?i.map(r=>({id:r,resolution:ne(n.get(r)?.resolution)})):[]}function Fh(e,t,n){if(!e.required_fields.includes("estimated_minutes"))return[];let i=t.estimated_minutes;return i?i.map(r=>({id:r,type:ne(n.get(r)?.type)})):[]}function jI(e,t,n,i,r){let s=new Map(e.map(v=>[v.id,v])),a=t.profile==="strict",o=FI(e,n,a),c=ph(e,{configuredPrefixes:r}),d=Dh(c,i),l=$I(t,o,d.warnings),u=Nh(t,o),p=Mh(t,o,s),g=fh(p),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:[...Tc],counts:u,missing_by_type:g,duplicate_issue_codes_count:c.length,duplicate_issue_codes:d.rows,duplicate_issue_codes_truncated:d.truncated};t.configured_custom_fields.length>0&&(f.configured_custom_required_fields=[...t.configured_custom_fields]),UI(f,t,o,i);let h=Ph(t,o,s),y=Fh(t,o,s);return{check:{name:"metadata",status:l.length===0?"ok":"warn",ok:l.length===0,details:f},warnings:l,closeReasonBackfillRows:h,estimateBackfillRows:y}}function GI(e,t,n){let i=new Set(t.terminal_done_statuses);i.add(t.close_status);let r=e.filter(p=>i.has(bs(p.status,t))),s=[],a=[];for(let p of r){let g=_I.filter(f=>!ne(p[f]));g.length!==0&&(s.push({id:p.id,missing_fields:g}),a.push({id:p.id,missing_fields:g,close_reason:ne(p.close_reason)}))}let o=s.length>0?[`validate_resolution_missing_fields:${s.length}`]:[],c=n?Number.POSITIVE_INFINITY:We,d=ee(s.map(p=>`${p.id}:${p.missing_fields.join(",")}`),c),l=s.map(p=>MI(p)),u=ee(l,c);return{check:{name:"resolution",status:o.length===0?"ok":"warn",ok:o.length===0,details:{checked_closed_items:r.length,missing_resolution_items:s.length,missing_resolution_rows:d.values,missing_resolution_rows_truncated:d.truncated,missing_resolution_remediation_hints:u.values,missing_resolution_remediation_hints_truncated:u.truncated}},warnings:o,resolutionBackfillRows:a}}function $h(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Uh(e,t="pm",n=Jd()){let i=new Set(e.map(s=>s.id)),r=[...e].sort((s,a)=>s.id.localeCompare(a.id));return new Map(r.map(s=>{let a=new Set,o=ze(s.blocked_by);o&&i.has(o)&&a.add(o),(s.dependencies??[]).filter(d=>{let l=ze(d.kind);return l!==void 0&&n.resolve(l)?.ordering===!0}).map(d=>ze(d.id)).filter(d=>d!==void 0&&i.has(d)).forEach(d=>a.add(d));let c=ze(s.definition_of_ready);return Gh(c??"",t).filter(d=>i.has(d)).forEach(d=>a.add(d)),[s.id,[...a].sort((d,l)=>d.localeCompare(l))]}))}function jh(e,t,n){let i=z_(e,n?l=>wi(l,n):void 0),r=i.active.map(l=>`${l.holder_id}:${l.target_id}:${l.kind}`),s=i.legacy_terminal.map(l=>`${l.holder_id}:${l.target_id}:${l.kind}:${l.holder_status}`),a=t?Number.POSITIVE_INFINITY:We,o=ee(r,a),c=ee(s,a),d=ee(i.active.map(l=>l.source==="parent"?`pm update ${l.holder_id} --unset parent`:l.source==="blocked_by"?`pm update ${l.holder_id} --unset blocked_by`:`pm update ${l.holder_id} --replace-deps '<correct dependency edges>'`),a);return{check:{name:"dependency_references",status:r.length===0?"ok":"warn",ok:r.length===0,details:{checked_items:e.length,dangling_reference_count:r.length+s.length,active_dangling_reference_count:r.length,dangling_reference_rows:o.values,dangling_reference_rows_truncated:o.truncated,legacy_terminal_dangling_reference_count:s.length,legacy_closed_dangling_reference_count:i.legacy_terminal.filter(l=>l.holder_status==="closed").length,legacy_terminal_dangling_reference_rows:c.values,legacy_terminal_dangling_reference_rows_truncated:c.truncated,no_active_blocker_sentinel_count:i.no_active_blocker_sentinels.length,remediation_hints:d.values,remediation_hints_truncated:d.truncated}},warnings:r.length>0?[`validate_dangling_dependency_references:${r.length}`]:[]}}function Gh(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),i=new RegExp(`(?:^|[^a-z0-9-])(${$h(n)}-[a-z0-9][a-z0-9-]*)`,"gi");return[...new Set([...e.matchAll(i)].map(r=>r[1].toLowerCase()))].sort((r,s)=>r.localeCompare(s))}function qh(e){let t=0,n=new Map,i=new Map,r=[],s=new Set,a=[],o=d=>{n.set(d,t),i.set(d,t),t+=1,r.push(d),s.add(d);for(let u of e.get(d)??[])n.has(u)?s.has(u)&&i.set(d,Math.min(i.get(d),n.get(u))):(o(u),i.set(d,Math.min(i.get(d),i.get(u))));if(i.get(d)!==n.get(d))return;let l=[];for(;r.length>0;){let u=r.pop();if(s.delete(u),l.push(u),u===d)break}l.sort((u,p)=>u.localeCompare(p)),a.push(l)},c=[...e.keys()].sort((d,l)=>d.localeCompare(l));for(let d of c)n.has(d)||o(d);return a.filter(d=>{if(d.length>1)return!0;let l=d[0];return(e.get(l)??[]).includes(l)}).sort((d,l)=>d[0].localeCompare(l[0])||d.length-l.length||d.join(",").localeCompare(l.join(",")))}function Kh(e,t="pm"){let n=Uh(e,t),i=qh(n),r=[...new Set(i.flat())].sort((a,o)=>a.localeCompare(o)),s=i.map(a=>gs(a,n).join("->"));return{cycle_count:i.length,cycle_item_ids:r,cycle_sample_paths:s}}function zh(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 ws(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function Wh(e,t){let n=ws(e).split("/").filter(Boolean),i=ws(t).split("/").filter(Boolean),r=0;for(;r<n.length&&r<i.length&&n[r]===i[r];)r+=1;return r}function qI(e,t){let n=ws(t),i=ws(e),r=t.endsWith("/")?t:`${t}/`,s=e.startsWith(r),a=n.length>0&&n===i,o=Wh(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 KI(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function zI(e,t,n){let i=t==="docs_unowned"?"docs":"files",r;return n.flatMap(s=>(i==="docs"?s.docs??[]:s.files??[]).map(a=>({item:s,link:a}))).forEach(({item:s,link:a})=>{if(a.scope!=="project")return;let o=Ct(a.path);if(o.length===0||o===e)return;let c=qI(e,o);c!==null&&KI(r,s,c.score)&&(r={item:s,score:c.score,confidence:c.confidence})}),r?{id:r.item.id,type:r.item.type,title:r.item.title,status:r.item.status,confidence:r.confidence}:null}function Bh(e,t){return e.map(n=>{let i=zh(n),r=i==="docs_unowned"?"docs":"files",s=zI(n,i,t),a=s?.id??"<id>";return{path:n,classification:i,owner_candidate:s,remediation_hint:`pm ${r} ${a} --add path=${n},scope=project,note="<why this artifact belongs to the item>"`}})}function Hh(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function WI(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,i])=>{let r=ze(e[n]);return r?i.some(s=>r.toLowerCase().includes(s)):!1}).map(([n])=>n).sort((n,i)=>n.localeCompare(i))}function BI(e,t,n,i,r){let s=ze(t.parent),a=s?n.get(i.get(s.toLowerCase())??s):void 0;return{id:e.id,parent_id:t.id,grandparent_id:a?.id,grandparent_active:a!==void 0&&!wi(a.status,r)}}function HI(e,t,n,i){let r=ze(e.blocked_by),s=ze(e.blocked_reason),a=s?.toLowerCase(),o=bs(e.status,n),c=[];return t.has(o)?(!r&&!s&&c.push("blocked_status_missing_blocker_context"),a?.includes("no active blocker")&&c.push("blocked_status_reason_reports_no_active_blocker"),a&&i.stale_blocker_reason_patterns.some(d=>a.includes(d))&&c.push("blocked_status_reason_matches_stale_pattern"),c):(r&&c.push("non_blocked_status_has_blocked_by"),s&&c.push("non_blocked_status_has_blocked_reason"),c)}function VI(e,t,n,i){let r=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=>!wi(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of o.activeItems){let d=WI(c,i);d.length>0&&o.closureLikeRows.push({id:c.id,fields:d});let l=ze(c.parent),u=l?r.get(s.get(l.toLowerCase())??l):void 0;if(u&&wi(u.status,n)&&(o.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),o.terminalParentFixRows.push(BI(c,u,r,s,n))),t){let p=HI(c,a,n,i);p.length>0&&o.staleBlockerRows.push({id:c.id,status:c.status,reasons:[...new Set(p)].sort((g,f)=>g.localeCompare(f))})}}return o}function YI(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 ys(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function kc(e,t,n){return n>0&&t!=="off"?`${e}:${n}`:null}function JI(e,t,n,i,r){let s=[];e.closureLikeRows.length>0&&s.push(`validate_lifecycle_active_closure_like_metadata:${e.closureLikeRows.length}`),e.terminalParentRows.length>0&&s.push(`validate_lifecycle_active_terminal_parent:${e.terminalParentRows.length}`),t&&e.staleBlockerRows.length>0&&s.push(`validate_lifecycle_stale_blockers:${e.staleBlockerRows.length}`);let a=ys("validate_lifecycle_dependency_cycles",n,r.dependencyCycles),o=ys("validate_hierarchy_parent_cycle",i,r.activeHierarchyCycles),c=ys("validate_hierarchy_cardinality_violation",i,r.activeHierarchyCardinality),d=ys("validate_hierarchy_parent_divergence",i,r.activeHierarchyDivergence),l=kc("validate_legacy_hierarchy_parent_cycle",i,r.legacyHierarchyCycles),u=kc("validate_legacy_hierarchy_cardinality_violation",i,r.legacyHierarchyCardinality),p=kc("validate_legacy_hierarchy_parent_divergence",i,r.legacyHierarchyDivergence);return[...s,...a?[a]:[],...o?[o]:[],...c?[c]:[],...d?[d]:[],...l?[l]:[],...u?[u]:[],...p?[p]:[]]}function Vh(e){let t=Ct(e);return t.length>kI||t.split(/[\\/]/).some(n=>n.length>EI)}async function XI(e,t){let n=xe.isAbsolute(t)?t:xe.resolve(e,t);if(Vh(n))return!1;try{let i=await xc.stat(n);return!i.isFile()&&!i.isDirectory()}catch(i){return RI(i,["ENOENT","ENOTDIR"])}}async function QI(e,t){let n={linkedProjectPaths:new Set,remoteLinkedPaths:new Set,missingLinkedPaths:[],staleLinkRows:[]},i=e.flatMap(r=>[...(r.files??[]).map(s=>({item:r,artifact:s,link_kind:"files"})),...(r.docs??[]).map(s=>({item:r,artifact:s,link_kind:"docs"}))]);for(let{item:r,artifact:s,link_kind:a}of i){if(s.scope!=="project")continue;if(li(s.path)){n.remoteLinkedPaths.add(s.path.trim());continue}let o=Ct(s.path);o.length!==0&&(n.linkedProjectPaths.add(o),await XI(t,s.path)&&(n.missingLinkedPaths.push(o),n.staleLinkRows.push({item_id:r.id,path:o,link_kind:a})))}return n}function ZI(e,t,n,i,r,s){let a=i==="tracked-all-strict",o=a&&!r,c=r||a,d=c?[]:OI(t,n),l=d.length===0?[]:e.candidateFiles.filter(g=>bh(g,d)),u=d.length===0?e.candidateFiles:e.candidateFiles.filter(g=>!bh(g,d)),p={};if(l.length>0){let g=zt(l,s);p.pm_internals={count:l.length,paths:g.values,paths_truncated:g.truncated,paths_total:g.total}}return{strictTrackedAllMode:a,strictModeForcesPmInternals:o,includePmInternalsEffective:c,pmInternalCandidatePrefixes:d,excludedPmInternalPaths:l,candidateFiles:u,excludedByReason:p}}function Yh(e,t,n,i,r,s,a,o="pm"){let c=VI(e,t,r,s);YI(c);let d=Kh(c.activeItems,o),l=vc(e,r),u=Zr(r,e,a?Number.POSITIVE_INFINITY:We),p=[...JI(c,t,n,i,{dependencyCycles:d.cycle_count,activeHierarchyCycles:l.active_cycle_count,activeHierarchyCardinality:l.active_cardinality_violation_count,activeHierarchyDivergence:l.active_parent_divergence_count,legacyHierarchyCycles:l.legacy_cycle_count,legacyHierarchyCardinality:l.legacy_cardinality_violation_count,legacyHierarchyDivergence:l.legacy_parent_divergence_count}),...es(u)],g=a?Number.POSITIVE_INFINITY:We,f=ee(c.closureLikeRows.map(E=>`${E.id}:${E.fields.join(",")}`),g),h=ee(c.terminalParentRows.map(E=>`${E.id}:${E.parent_id}:${E.parent_status}`),g),y=ee(c.staleBlockerRows.map(E=>`${E.id}:${E.status}:${E.reasons.join(",")}`),g),v=ee(d.cycle_item_ids,g),w=ee(d.cycle_sample_paths,g),k=ee(l.cycle_item_ids,g),S=ee(l.cycle_sample_paths,g),A=ee(l.cardinality_violation_rows,g),C=ee(l.parent_divergence_rows,g),b=d.cycle_count>0&&n==="error"||(l.active_cycle_count>0||l.active_cardinality_violation_count>0||l.active_parent_divergence_count>0)&&i==="error";return{check:{name:"lifecycle",status:b?"error":p.length===0?"ok":"warn",ok:!b&&p.length===0,details:{checked_active_items:c.activeItems.length,lifecycle_status_roles:u,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:h.values,active_terminal_parent_rows_truncated:h.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:d.cycle_count,dependency_cycle_item_count:d.cycle_item_ids.length,dependency_cycle_item_ids:v.values,dependency_cycle_item_ids_truncated:v.truncated,dependency_cycle_sample_paths:w.values,dependency_cycle_sample_paths_truncated:w.truncated,parent_cycle_severity_policy:i,parent_cycle_count:l.cycle_count,active_parent_cycle_count:l.active_cycle_count,legacy_parent_cycle_count:l.legacy_cycle_count,parent_cycle_item_count:l.cycle_item_ids.length,parent_cycle_item_ids:k.values,parent_cycle_item_ids_truncated:k.truncated,parent_cycle_sample_paths:S.values,parent_cycle_sample_paths_truncated:S.truncated,hierarchy_cardinality_violation_count:l.cardinality_violation_count,active_hierarchy_cardinality_violation_count:l.active_cardinality_violation_count,legacy_hierarchy_cardinality_violation_count:l.legacy_cardinality_violation_count,hierarchy_cardinality_violation_rows:A.values,hierarchy_cardinality_violation_rows_truncated:A.truncated,hierarchy_parent_divergence_count:l.parent_divergence_count,active_hierarchy_parent_divergence_count:l.active_parent_divergence_count,legacy_hierarchy_parent_divergence_count:l.legacy_parent_divergence_count,hierarchy_parent_divergence_rows:C.values,hierarchy_parent_divergence_rows_truncated:C.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:p,terminalParentFixRows:c.terminalParentFixRows}}async function Jh(e,t,n,i,r,s,a=K(Lt.schema)){let o=await QI(e,t),c=new Map(e.map(R=>[R.id,R])),d=[...new Set(o.missingLinkedPaths)].sort((R,G)=>R.localeCompare(G)),l=await LI(t,i),u=ZI(l,n,t,i,r,s),p=u.candidateFiles.filter(R=>!o.linkedProjectPaths.has(R)),g=Bh(p,e),f=hh(d,u.candidateFiles),h=new Map(f.map(R=>[R.path,R.classification])),y=f.filter(R=>R.classification==="moved").length,v=o.staleLinkRows.map(R=>({...R,classification:h.get(R.path)??"deleted"})).sort((R,G)=>R.item_id.localeCompare(G.item_id)||R.path.localeCompare(G.path)||R.link_kind.localeCompare(G.link_kind)),w=[];u.strictModeForcesPmInternals&&w.push("validate_files_tracked_all_strict_forces_pm_internals"),p.length>0&&w.push(`validate_files_orphaned_paths:${p.length}`);let k=[...o.remoteLinkedPaths].sort((R,G)=>R.localeCompare(G)),S=zt(k,s),A=zt(d,s),C=zt(p,s),b=zt(g.map(R=>`${R.path}:${R.classification}:owner_candidate=${R.owner_candidate?.id??"unowned"}`),s),E=s?g:zt(Hh(g),!1).values,N=zt(yh(f),s),T=Wg(v,f,R=>c.get(R),a,s?1/0:Ac);return T.active_missing_linked_paths_count>0&&w.push(`validate_files_missing_linked_paths:${T.active_missing_linked_paths_count}`),{check:{name:"files",status:w.length===0?"ok":"warn",ok:w.length===0,details:{workspace_root:t,scan_mode_requested:l.requestedMode,scan_mode_applied:l.appliedMode,strict_tracked_all_mode:u.strictTrackedAllMode,strict_mode_forces_pm_internals:u.strictModeForcesPmInternals,strict_mode_forces_pm_internals_notice:u.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:Ac,candidate_scan_source:l.source,include_pm_internals:u.includePmInternalsEffective,include_pm_internals_requested:r,pm_internal_candidate_prefixes:u.pmInternalCandidatePrefixes,pm_internal_excluded_count:u.excludedPmInternalPaths.length,excluded_total:u.excludedPmInternalPaths.length,excluded_by_reason:u.excludedByReason,linked_project_paths:o.linkedProjectPaths.size,remote_linked_paths_count:k.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:u.candidateFiles.length,candidate_scanned:u.candidateFiles.length,scanned_candidate_files:u.candidateFiles.length,missing_linked_paths_count:d.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:f.filter(R=>R.classification==="deleted").length,missing_linked_paths_malformed_count:f.filter(R=>R.classification==="malformed").length,missing_linked_path_classifications:N.values,missing_linked_path_classifications_truncated:N.truncated,...T,orphaned_paths_count:p.length,orphaned_paths_total:C.total,orphaned_paths:C.values,orphaned_paths_truncated:C.truncated,orphaned_path_classifications:b.values,orphaned_path_classifications_truncated:b.truncated,orphaned_path_rows_count:g.length,orphaned_path_rows:E}},warnings:w,staleLinkPruneRows:v}}function eC(e,t){let n=[];return e.forEach(({item:i,linkedTest:r},s)=>{let a=t[s];if(a.trusted)return;let o=bc(r.command??"");n.push(`${i.id}:${a.source_ref??"unknown"}->${a.current_source_ref??"unknown"}:${o}`)}),n}async function Xh(e,t,n,i){let r=new Set(e.map(A=>A.id.toLowerCase())),s=0,a=0,o=new Set,c=[],d=e.flatMap(A=>(A.tests??[]).map(C=>({item:A,linkedTest:C}))),l=await hi(yi()),u=await ih(i,d.map(({linkedTest:A})=>A),l),p=eC(d,u);for(let{item:A,linkedTest:C}of d){if(typeof C.command!="string"||C.command.trim().length===0)continue;s+=1;let b=dc(C.command,t);if(b.length!==0){a+=b.length;for(let E of b)o.add(E),r.has(E.toLowerCase())||c.push(`${A.id}:${E}:${bc(C.command)}`)}}let g=[...new Set(c)].sort((A,C)=>A.localeCompare(C)),f=[...new Set(g.map(A=>A.split(":")[1]??""))].filter(A=>A.length>0).sort((A,C)=>A.localeCompare(C)),h=[];g.length>0&&h.push(`validate_command_references_stale_pm_ids:${g.length}`),p.length>0&&h.push(`validate_linked_test_trust_unacknowledged:${p.length}`);let y=n?Number.POSITIVE_INFINITY:We,v=ee(g,y),w=ee(f,y),k=ee([...o].sort((A,C)=>A.localeCompare(C)),y),S=ee(p,y);return{check:{name:"command_references",status:h.length===0?"ok":"warn",ok:h.length===0,details:{checked_items:e.length,linked_commands_scanned:s,referenced_pm_ids_count:a,unique_referenced_pm_ids_count:o.size,unique_referenced_pm_ids:k.values,unique_referenced_pm_ids_truncated:k.truncated,linked_test_trust_current_source_ref:l??null,untrusted_linked_tests_count:p.length,untrusted_linked_tests:S.values,untrusted_linked_tests_truncated:S.truncated,stale_pm_id_references_count:g.length,stale_pm_ids_count:f.length,stale_pm_ids:w.values,stale_pm_ids_truncated:w.truncated,stale_pm_id_reference_rows:v.values,stale_pm_id_reference_rows_truncated:v.truncated}},warnings:h}}function tC(e,t){let n=tr(e.map(c=>({ref:c.id,version:er(c)})),jn,Zi),i=[];n.outdated.length>0&&i.push(`validate_format_version_outdated_items:${n.outdated.length}`),n.ahead.length>0&&i.push(`validate_format_version_ahead_items:${n.ahead.length}`);let r=t?Number.POSITIVE_INFINITY:We,s=ee(n.outdated,r),a=ee(n.ahead,r),o=n.ahead.length>0?"error":n.outdated.length>0?"warn":"ok";return{check:{name:"format_version",status:o,ok:o==="ok",details:{checked_items:e.length,current_format_version:jn,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:i}}var Cc="pm validate auto-fix";async function Qh(e,t,n){switch(e.kind){case"set_closed_at":await qg(e,t);return;case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let i={message:Cc};if(e.kind==="set_resolution"?i.resolution=e.value:e.kind==="set_close_reason"?i.closeReason=e.value:e.kind==="set_estimate"?i.estimatedMinutes=e.value:e.kind==="reparent"?i.parent=e.parent_id:i.unset=["parent"],!n.runUpdate)throw new _("Applying validate metadata/lifecycle fixes requires a runUpdate mutation service.",m.USAGE);await n.runUpdate(e.item_id,i,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 Ec(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function Zh(e,t,n){let i=[],r=[],s=new Map;for(let a of e.filter(o=>Ec(o)===null))try{await Qh(a,t,n),i.push(a)}catch(o){r.push({fix:a,error:o})}for(let a of e.filter(o=>Ec(o)!==null)){let o=Ec(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(d=>d.path).filter(d=>typeof d=="string"&&d.length>0);try{o.kind==="prune_file_link"?await Xf(o.item_id,{remove:c,message:Cc},t):await $f(o.item_id,{remove:c,message:Cc},t),i.push(...a)}catch(d){r.push(...a.map(l=>({fix:l,error:d})))}}return{applied:i,failed:r}}var iK={applyValidateFix:Qh,applyValidateFixes:Zh,attachValidateFixHints:Oh,buildCommandReferencesCheck:Xh,buildDependencyReferencesCheck:jh,buildCloseReasonBackfillRows:Ph,buildFilesCheck:Jh,buildLifecycleCheck:Yh,buildLifecycleDependencyGraph:Uh,buildLifecycleParentGraph:yc,buildEstimateBackfillRows:Fh,buildMetadataCounts:Nh,buildMissingFieldOccurrences:Mh,buildOrphanedPathRows:Bh,classifyOrphanedPath:zh,collectDefaultProjectFileCandidates:Ic,collectTrackedGitFileCandidates:Rh,detectLifecycleDependencyCycles:Kh,detectLifecycleParentCycles:vc,escapeRegExp:$h,extractItemIds:Gh,findLifecycleDependencyCycleComponents:qh,isMetadataFieldMissing:Ih,linkedArtifactPathExceedsFilesystemLimits:Vh,listFilesRecursive:Rc,resolveDependencyCycleSeverity:Th,resolveParentCycleSeverity:Ah,resolveFileScanMode:Ch,resolveLifecycleDependencyCycleSamplePath:gs,resolveRequestedChecks:Lh,resolveValidateMetadataProfile:Sh,resolveWorkspaceRoot:xh,sharedDirectoryPrefixLength:Wh,summarizeOrphanedPathRows:Hh,summarizeDuplicateIssueCodes:Dh,toMeaningfulString:ze};function nC(e,t){t>0&&e.push(`merge_receipt_evidence_invalid:${t}`)}async function iC(e,t,n,i){let r=await Hg(e,new Set(t.map(y=>y.id)),n,{schema:i.schema,extensionFieldNames:Et(P())}),s=[];r.unreadable_item_files.length>0&&s.push(`validate_storage_unreadable_items:${r.unreadable_item_files.length}`),r.duplicate_item_ids.length>0&&s.push(`validate_storage_duplicate_item_ids:${r.duplicate_item_ids.length}`),r.history_conflict_marker_streams.length>0&&s.push(`validate_storage_history_conflict_markers:${r.history_conflict_marker_streams.length}`),r.history_unparseable_streams.length>0&&s.push(`validate_storage_unparseable_history:${r.history_unparseable_streams.length}`),r.resurrected_items.length>0&&s.push(`validate_storage_resurrected_items:${r.resurrected_items.length}`),r.unparseable_config_files.length>0&&s.push(`validate_storage_unparseable_config:${r.unparseable_config_files.length}`);let a=s.length,o=await ns(e);o.tracked_path_count>0&&s.push(`validate_storage_tracked_runtime_cache_files:${o.tracked_path_count}`);let c=await un(e,ln(i));c.status==="drift"&&s.push(`validate_merge_fence_drift:${c.missing_patterns.length+c.stale_patterns.length}`);let d=await Tt(e),l=d===null?null:await mn(d);l!==null&&l.status!=="ok"&&s.push(`validate_merge_driver_configuration:${l.missing_keys.length+l.drifted_keys.length}`);let u=await _n(d??e,{includeLossless:!0,pmRoot:e}),p=u.receipts,{pendingDecisions:g,lossless:f}=pn(p);g.length>0&&s.push(`validate_merge_decisions_unreviewed:${g.length}`),nC(s,u.invalid_evidence_count);let h=a>0?"error":s.length>0?"warn":"ok";return{check:{name:"storage_integrity",status:h,ok:h==="ok",details:{...r,merge_fence:c,merge_driver_configuration:l,pending_merge_decision_count:g.length,pending_merge_decision_items:[...new Set(g.map(y=>y.item_id))].sort((y,v)=>y.localeCompare(v)),lossless_merge_receipt_count:f.length,invalid_merge_receipt_evidence_count:u.invalid_evidence_count,invalid_merge_receipt_evidence_details:u.invalid_evidence,invalid_merge_receipt_evidence_details_truncated:u.invalid_evidence_truncated,lossless_merge_receipt_items:[...new Set(f.map(y=>y.item_id))].sort((y,v)=>y.localeCompare(v)),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 tt(e,t,n){n&&Oh(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function rC(e){let t={closureTimestampFixes:[],checks:[],warnings:[...e.initialWarnings],closeReasonBackfillRows:[],estimateBackfillRows:[],resolutionBackfillRows:[],terminalParentFixRows:[],staleLinkPruneRows:[]},n=e.options.fixHints===!0,i=e.options.verboseDiagnostics===!0||e.options.allAffectedIds===!0||e.global.json===!0;if(e.requestedChecks.has("completeness")){let r=await Q_(e.pmRoot,e.items,i?1/0:We,e.sourceIncomplete);tt(t,r,n)}if(e.requestedChecks.has("metadata")){let r=jI(e.items,e.metadataPolicy,e.statusRegistry,i,[e.settings.id_prefix]);t.closeReasonBackfillRows=r.closeReasonBackfillRows,t.estimateBackfillRows=r.estimateBackfillRows;let s=await Gg(e.pmRoot,e.items,e.statusRegistry,e.options.autoFix===!0||n,i?1/0:We);t.closureTimestampFixes=s.fixes,Object.assign(r.check.details,s.details),r.warnings.push(...s.warnings),r.check.ok=r.warnings.length===0,r.check.status=r.check.ok?"ok":"warn",tt(t,r,n)}if(e.requestedChecks.has("resolution")){let r=GI(e.items,e.statusRegistry,i);t.resolutionBackfillRows=r.resolutionBackfillRows,tt(t,r,n)}if(e.requestedChecks.has("lifecycle")){let r=Yh(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,i,e.settings.id_prefix);t.terminalParentFixRows=r.terminalParentFixRows,tt(t,r,n),tt(t,jh(e.items,i,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let r=await Jh(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists,e.statusRegistry);t.staleLinkPruneRows=r.staleLinkPruneRows,tt(t,r,n)}return e.requestedChecks.has("command_references")&&tt(t,await Xh(e.items,e.settings.id_prefix,i,e.pmRoot),n),e.requestedChecks.has("history_drift")&&tt(t,await fs(e.pmRoot,e.items,i),n),e.requestedChecks.has("format_version")&&tt(t,tC(e.items,i),n),e.requestedChecks.has("storage_integrity")&&tt(t,await iC(e.pmRoot,e.items,F(e.settings,P()).type_to_folder,e.settings),n),t}function sC(e,t,n){let i=[];return e.autoFix===!0&&(i.push(...t.closureTimestampFixes),i.push(...oh(t.closeReasonBackfillRows)),i.push(...ah(t.resolutionBackfillRows)),i.push(...ch(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),i.push(...dh(t.terminalParentFixRows))),e.pruneMissing===!0&&i.push(...lh(t.staleLinkPruneRows)),i}async function aC(e,t,n,i,r,s){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let a=sC(e,t,n),{applicable:o,gated:c}=mh(a,i),d=e.dryRun===!0,l=[],u=[];if(!d){let p=await Zh(o,r,s);l.push(...p.applied.map(vi)),u.push(...p.failed.map(({fix:g,error:f})=>({...vi(g),error:f instanceof Error?f.message:String(f)})))}return{mode:d?"dry_run":"apply",auto_fix:e.autoFix===!0,prune_missing:e.pruneMissing===!0,granted_fix_scopes:[...i].sort((p,g)=>p.localeCompare(g)),planned_count:a.length,applied_count:l.length,gated_count:c.length,failed_count:u.length,planned_fixes:a.map(vi),applied_fixes:l,gated_fixes:c.map(p=>({...vi(p),gate_hint:`Withheld: re-run with --fix-scope ${p.gate} to apply.`})),failed_fixes:u}}async function ey(e,t,n={}){Wl(e.counts===!0,e.full===!0,"--counts");let i=e.autoFix===!0||e.pruneMissing===!0;if(e.dryRun===!0&&!i)throw new _("--dry-run requires --auto-fix or --prune-missing (there is nothing to preview otherwise).",m.USAGE);if(e.fixScope!==void 0&&e.fixScope.length>0&&e.autoFix!==!0)throw new _("--fix-scope requires --auto-fix.",m.USAGE);let r=uh(e.fixScope),s=x(process.cwd(),t.path);await $(s);let a=await I(s),o=K(a.schema),c=F(a,P()),d=Lh(e),l=[],u=await ps({includeBody:["history_drift","metadata","completeness"].some(N=>d.has(N)),pmRoot:s,settings:a,typeToFolder:c.type_to_folder,warnings:l}),p=l.length>0;if(d.has("history_drift")){let N=await di(s);N.actionable_unknown_event_count>0&&l.push(`validate_history_unknown_author_events:${N.actionable_unknown_event_count}`)}let g=typeof e.metadataProfile=="string"?"option":"settings",f=Sh(typeof e.metadataProfile=="string"?e.metadataProfile:a.validation.metadata_profile),h=CI(f,g,a.validation.metadata_required_fields),y=AI(a),v=Th(e.dependencyCycleSeverity),w=Ah(e.parentCycleSeverity),k=Ch(e.scanMode),S=xh(s),A=await rC({requestedChecks:d,options:e,global:t,pmRoot:s,workspaceRoot:S,settings:a,items:u,statusRegistry:o,metadataPolicy:h,lifecyclePatternPolicy:y,dependencyCycleSeverity:v,parentCycleSeverity:w,fileScanMode:k,initialWarnings:[...new Set(l)],sourceIncomplete:p}),C=i?await aC(e,A,a,r,t,n):void 0,b=[...new Set(A.warnings)].sort((N,T)=>N.localeCompare(T)),E={ok:!A.checks.some(N=>N.status==="error"),has_warnings:b.length>0,checks:A.checks,warnings:b,...C!==void 0?{fixes:C}:{},generated_at:O(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return e.counts!==!0?E:{...TI(E),projection:{mode:"counts",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:[]}}}import{execFile as oC}from"node:child_process";import{promisify as cC}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]="d50f9868-5c11-51dc-967e-61ce41225ef1")}catch{}})();var dC=cC(oC),lC=16,uC=3e4;function mC(e,t,n){if(!(e.keys[t].value_type==="number"?typeof n.value=="number"&&Number.isFinite(n.value):Array.isArray(n.value)&&n.value.every(i=>typeof i=="string")))throw new TypeError(`assurance provider ${e.id} key ${t} returned the wrong value type`);if(!Number.isInteger(n.population_size)||n.population_size<0||!Number.isFinite(n.cost)||n.cost<0)throw new TypeError(`assurance provider ${e.id} returned an invalid population or cost`);return n}function _C(e,t){let n=e.keys[t.key];if(!n)throw new TypeError(`assurance provider ${e.id} does not declare key ${t.key}`);let i=t.parameters??{},r=n.parameters??{};for(let s of Object.entries(r).filter(([,a])=>a.required===!0).map(([a])=>a))if(!Object.hasOwn(i,s))throw new TypeError(`assurance provider ${e.id} key ${t.key} requires parameter ${s}`);for(let[s,a]of Object.entries(i)){let o=r[s];if(!o)throw new TypeError(`assurance provider ${e.id} key ${t.key} does not declare parameter ${s}`);if(a===null||typeof a!==o.type)throw new TypeError(`assurance provider ${e.id} parameter ${s} must be ${o.type}`)}return{...i}}async function pC(e,t,n,i){let r=_C(e,t),s=Promise.resolve().then(()=>e.resolve({provider:e.id,key:t.key,parameters:r,trigger:i,pm_root:n,...$l(n)}));s.catch(()=>{});let a;try{let o=await Promise.race([s,new Promise((c,d)=>{a=setTimeout(()=>d(new TypeError(`assurance provider ${e.id} timed out`)),e.timeout_ms??uC),a.unref?.()})]);return mC(e,t.key,o)}finally{clearTimeout(a)}}function ny(e,t,n,i){let r=e;for(let s of t.split(".")){if(typeof r!="object"||r===null||Array.isArray(r))throw new Ze(`assurance field ${t} is not present`,{source_kind:n,field:t,...i?{check:i}:{}});r=r[s]}if(typeof r=="number"&&Number.isFinite(r)||Array.isArray(r)&&r.every(s=>typeof s=="string"))return r;throw new Ze(`assurance field ${t} must resolve to a finite number or string array`,{source_kind:n,field:t,...i?{check:i}:{}})}function ty(e,t,n,i){let r=e.checks.find(s=>s.name===t);if(!r)throw new Ze(`assurance check ${t} is not present`,{source_kind:i,field:n,check:t});return{value:n==="status"||n==="ok"?r.ok?0:1:ny(r.details,n,i,t),population_size:1,cost:e.checks.length}}async function fC(e,t){if(t?.trim())return t.trim();try{let{stdout:n}=await dC("git",["rev-parse","HEAD^{commit}"],{cwd:e,encoding:"utf8",timeout:5e3,windowsHide:!0});return n.trim()}catch{return"working-copy"}}async function gC(e,t){let n=new Array(t.length),i=0,r=Array.from({length:Math.min(lC,t.length)},async()=>{for(;i<t.length;){let s=i;i+=1;let a=t[s],o=await ct(at(e,a.id),a.id);n[s]=o.map(c=>({op:c.op,author:c.author,agent_harness:c.agent_harness,agent_model:c.agent_model}))}});return await Promise.all(r),n.flat()}async function bi(e,t={}){let n=await I(e),i=F(n),r=K(n.schema),s=(t.strict_read===!0?(await Y_(void 0,{status:"all",full:!0,includeBody:!0,noTruncate:!0,strictRead:!0},{path:e})).items:await dt(e,n.item_format,i.type_to_folder,void 0,n.schema)).map(p=>({...p,id:p.id,status:p.status,type:p.type})),a={path:e},o=P(),c=Object.fromEntries((o?.assurance_providers??[]).map(p=>[p.definition.id,{cost_class:p.runtime_definition.cost_class,network:p.runtime_definition.network}])),d=new Map,l,u;return{tree_id:t.resolve_tree===!1?t.tree_id??"working-copy":await fC(e,t.tree_id),items:s,history:t.include_history===!1?[]:await gC(e,s),terminal_statuses:[...r.terminal_statuses],provider_capabilities:{...c,...t.provider_capabilities},external:async p=>{if(p.kind==="graph"){let h=ie({operation:p.operation,parameters:p.parameters??{}}),y=d.get(h);y===void 0&&(y=op(p.operation,void 0,void 0,{...p.parameters,full:!0},a),d.set(h,y));let v=await y;return{value:ny(v,p.field,p.kind),population_size:s.length,cost:s.length}}if(p.kind==="validate"){l??=ey({counts:!0},a);let h=await l;return ty(h,p.check,p.field,p.kind)}if(p.kind==="health"){u??=$g(a,{checkOnly:!0,full:!0});let h=await u;return ty(h,p.check,p.field,p.kind)}let g=t.providers?.[p.provider];if(g)return g(p);let f=r_(o,p.provider);if(!f)throw new TypeError(`assurance provider ${p.provider} is not registered`);return pC(f.runtime_definition,p,e,t.trigger??"sdk")}}}import{createHash as hC}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]="c72d246d-a7ff-5c9d-8c36-4ebd45b8a69f")}catch{}})();function iy(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new TypeError("recurrence coverage request must be an object");let t=e;if(Object.hasOwn(t,"change"))throw new TypeError("recurrence coverage request does not accept change");if(t.uncoveredOnly!==void 0&&typeof t.uncoveredOnly!="boolean")throw new TypeError("recurrence coverage request.uncoveredOnly must be a boolean");let{policy:n,cursor:i,limit:r}=Ar({...t,change:{}});return{policy:n,...i===void 0?{}:{cursor:i},...r===void 0?{}:{limit:r},...t.uncoveredOnly===void 0?{}:{uncoveredOnly:t.uncoveredOnly}}}function yC(e,t){if(e===void 0)return 0;let n;try{n=JSON.parse(Buffer.from(e,"base64url").toString("utf8"))}catch{throw new TypeError("recurrence coverage cursor is invalid")}if(typeof n!="object"||n===null||Array.isArray(n))throw new TypeError("recurrence coverage cursor is invalid");let i=n;if(i.fingerprint!==t||typeof i.offset!="number"||!Number.isSafeInteger(i.offset)||i.offset<0)throw new TypeError("recurrence coverage cursor does not match this evidence and filter");return i.offset}function vC(e,t,n,i,r,s){let a=Object.fromEntries(lo.map(g=>[g,0])),o=0,c=0,d=0,l=0,u=[],p=hC("sha256").update(r);for(let g of i){let f=e.membership.get(g),h=n.has(g),y=f.family_ids.length>0;y&&h&&(o+=1),y||(c+=1),h||(d+=1);let v=t.get(g)?.escape_class;v!==void 0&&lo.includes(v)&&(a[v]+=1,l+=1),p.update(ie([g,h,t.get(g)??null,f.id,f.family_ids])),(!s||!y||!h)&&u.push(g)}return{classCounts:a,coveredCount:o,uncoveredCount:c,missingCount:d,classifiedCount:l,selected:u,fingerprint:p.digest("hex")}}function ry(e,t,n={}){O_(e);let i=n.limit??25;if(!Number.isSafeInteger(i)||i<1||i>100)throw new TypeError("recurrence coverage limit must be an integer from 1 through 100");let r=new Set,s=new Map;for(let S of t){if(r.has(S.id))throw new TypeError(`Duplicate recurrence item ${S.id}`);r.add(S.id);let A=Tr(S);A!==void 0&&s.set(S.id,A)}let a=I_(e.families,s),o=[...a.membership.keys()].sort(),c=ie({policy:e,uncoveredOnly:n.uncoveredOnly===!0}),{classCounts:d,coveredCount:l,uncoveredCount:u,missingCount:p,classifiedCount:g,selected:f,fingerprint:h}=vC(a,s,r,o,c,n.uncoveredOnly===!0),y=yC(n.cursor,h);if(y>f.length)throw new TypeError("recurrence coverage cursor offset exceeds the selected population");let v=f.slice(y,y+i).map(S=>{let A=a.membership.get(S),C=r.has(S);return{item_id:S,lineage_id:A.id,lineage_item_count:A.item_ids.length,family_ids:A.family_ids,present:C,...C?A.family_ids.length===0?{finding:"unregistered_recurrence_item"}:{}:{finding:"missing_recurrence_item"}}}),w=y+v.length,k=o.length===0?null:d.production_defect/o.length;return{ok:u===0&&p===0,fingerprint:h,items:v,total:f.length,has_more:w<f.length,...w<f.length?{next_cursor:Buffer.from(JSON.stringify({fingerprint:h,offset:w})).toString("base64url")}:{},population:{scope:"all_recorded_recurrence_items",item_count:o.length,lineage_count:a.lineages.length,edge_count:a.edge_count,covered_item_count:l,uncovered_item_count:u,missing_item_count:p,classified_item_count:g,unclassified_item_count:o.length-g,class_counts:d,escape_rate:g===o.length?k:null,escape_rate_lower_bound:k},budget_scope:"registered_families_only",cost:{items_scanned:t.length,edges_scanned:a.edge_count,row_limit:i},row_contract:{row_keys:["items"],jq_selector:".items[]"}}}import{createHash as wC}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]="676125a5-e16e-5fa2-819f-f4028dc0c3c2")}catch{}})();var Oc,sy=["list","show","put","remove","run","verdicts","presets","apply","derive","promote","risk","lineages"],Lc=["measurement","assertion","gate"];function bC(e){if(sy.includes(e))return e;throw dr({command_path:"assurance",token:e,allowed:sy,display_name:"assurance action"})}function An(e,t,n){throw new _(t,m.USAGE,{code:"missing_required_argument",required:`Provide the missing assurance operand: ${e}.`,examples:[n],recovery:{missing:[e]}})}function kC(e){if(!e)return An("kind",`Assurance declaration kind is required. Expected: ${Lc.join(", ")}`,"pm assurance list measurement");if(Lc.includes(e))return e;throw new _(`Assurance declaration kind is required. Expected: ${Lc.join(", ")}`,m.USAGE)}function ay(e){if(!e)return An("preset",`Assurance preset is required. Expected: ${mi.join(", ")}`,"pm assurance apply software-delivery --owner <pm-item-id>");if(mi.includes(e))return e;throw new _(`Assurance preset is required. Expected: ${mi.join(", ")}`,m.USAGE)}function Dc(e){return e.owner?.trim()?e.owner.trim():An("owner","assurance preset and derivation actions require --owner <pm-item-id>","pm assurance apply software-delivery --owner <pm-item-id>")}function EC(e,t){let n=t;if(typeof t=="string")if(!t.trim())n=void 0;else try{n=JSON.parse(t)}catch(i){throw new _("assurance definition must be valid JSON",m.USAGE,{reason:i instanceof Error?i.message:"invalid_json"})}if(typeof n!="object"||n===null||Array.isArray(n))throw new _("assurance put requires a JSON object definition",m.USAGE);return n}async function SC(e){let[t,n,i]=await Promise.all([ii(e,"measurement"),ii(e,"assertion"),ii(e,"gate")]);return{version:1,measurements:t.items,assertions:n.items,gates:i.items}}function oy(e,t){return t===!0?{id:e.id}:e}async function TC(e,t){let n=t.authorization_decision;if(!n)return[];let i=await bi(e,{include_history:!1,resolve_tree:!1}),r=i.items.find(a=>a.id===n),s=new Set(i.terminal_statuses);if(!r||r.type.toLowerCase()!=="decision"||!s.has(r.status))throw new _(`Assurance authorization ${n} must name a terminal Decision item`,m.USAGE);return[r.id]}async function AC(e,t){let n=No(e.limit,"assurance verdict limit");if(n!==void 0&&(n<1||n>hn))throw new _(`assurance verdict limit must be an integer from 1 through ${hn}`,m.USAGE);let i=await Vp(t,{gate_id:e.id??e.gate,limit:n});return{items:i,count:i.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function IC(e,t,n){if(e==="presets"){if(t.preset??t.id)return Xr(ay(t.preset??t.id),Dc(t));let r=mi.map(s=>{let a=Xr(s,"pm-owner");return{id:s,title:a.title,description:a.description}});return{items:r,count:r.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}if(e==="apply")return gn(()=>tg(n,ay(t.preset??t.id),Dc(t),{author:t.author,message:t.message}));if(e==="derive"){let r=await ng(await bi(n,{resolve_tree:!1,trigger:"derive"}),Dc(t)),s=t.apply?await gn(()=>ig(n,r,{author:t.author,message:t.message??"Accept observation-derived assurance proposals"})):void 0;return{items:r,count:r.length,...s?{applied:s}:{}}}if(!t.id)return An("assertion-id","assurance promote requires an assertion id","pm assurance promote <assertion-id> --enforcement warn");if(t.enforcement!=="warn"&&t.enforcement!=="block")throw new _("assurance promote requires --enforcement warn|block",m.USAGE);let i=await Ao(n,"assertion",t.id);return gn(()=>rg(n,i,t.enforcement,{author:t.author,message:t.message}))}async function CC(e,t,n){if(!e.id)return An("gate-id","assurance run requires a gate id","pm assurance run <gate-id> --trigger ci --dry-run");let i=e.id;if(!e.trigger)throw new _("assurance run requires a trigger",m.USAGE);if(!lt.includes(e.trigger))throw new _(`Unknown assurance trigger ${e.trigger}. Expected: ${lt.join(", ")}`,m.USAGE);let r=e.trigger,[s,a]=await Promise.all([SC(t),bi(t,{...n.workspace,tree_id:e.tree,trigger:r})]),o=await Lp(()=>zp(i,s,a,{trigger:r,dry_run:e.dry_run===!0}));return o.dry_run||await Hp(t,o,{author:e.author,message:e.message}),o}function cy(e){throw e instanceof _?e:new _(e instanceof Error?e.message:"assurance risk request is invalid",m.USAGE)}function xC(e){if(e.limit!==void 0)throw new _(`assurance ${e.action} does not accept --limit; set limit inside the definition`,m.USAGE);let t=e.definition;if(typeof t=="string")try{t=JSON.parse(t)}catch(n){throw new _(`assurance ${e.action} definition must be valid JSON`,m.USAGE,{reason:n instanceof Error?n.message:"invalid_json"})}try{return e.action==="lineages"?iy(t):Ar(t)}catch(n){if(e.action==="risk"&&n instanceof R_)throw new _(n.message,m.USAGE,{required:"Supply definition.policy with the project's declared recurrence policy and definition.change with the proposed change; no policy is inferred.",recovery:{suggested_retry:`pm assurance ${e.action} --help`,suggested_retry_args:["assurance",e.action,"--help"]}});return cy(n)}}function RC(e,t){let n=new Set;for(let[i,r]of t)e.item_fingerprints.get(i)!==r&&n.add(i);for(let i of e.item_fingerprints.keys())t.has(i)||n.add(i);return n}function OC(e,t,n){let i=ie(t.policy),r=Oc?.pm_root===e?Oc:void 0,s=new Map(n.map(d=>[d.id,wC("sha256").update(ie([T_(d),Tr(d)])).digest("hex")])),a=r?.policy_serialized===i?r:void 0,o=a?RC(a,s):new Set,c=C_(t.policy,a?n.filter(d=>o.has(d.id)):n,a?{previous_index:a.index,changed_item_ids:[...o]}:{});return Oc={pm_root:e,policy_serialized:i,item_fingerprints:s,index:c},c}async function LC(e,t){let n=xC(e),i=await bi(t,{strict_read:!0,include_history:!1,resolve_tree:!1});try{return"change"in n?x_(OC(t,n,i.items),n.change,{cursor:n.cursor,limit:n.limit}):ry(n.policy,i.items,n)}catch(r){return cy(r)}}async function DC(e,t={},n={}){let i=bC(e.action),r=x(process.cwd(),t.path);if(i==="presets"||i==="apply"||i==="derive"||i==="promote")return IC(i,e,r);if(i==="verdicts")return AC(e,r);if(i==="run")return CC(e,r,n);if(["risk","lineages"].includes(i))return LC(e,r);let s=kC(e.kind);if(i==="list")return ii(r,s);if(!e.id)return An("id",`assurance ${i} requires an id`,`pm assurance ${i} ${s} <id>`);let a=e.id;if(i==="show")return Ao(r,s,a);if(i==="remove"){let l=await gn(()=>Bp(r,s,a,{author:e.author,message:e.message}));return oy(l,e.idOnly)}let o=EC(s,e.definition);if(o.id!==a)throw new _(`Assurance definition id ${o.id} does not match requested id ${a}`,m.USAGE);let c={author:e.author,message:e.message,...s==="assertion"?{authorized_decision_ids:await TC(r,o)}:{}},d=await gn(()=>Fr(r,s,o,c));return oy(d,e.idOnly)}function UK(e,t,n){let i={...e,...t};return DC({action:L(i,"subcommand")??L(i,"assuranceAction")??L(i,"operation")??"",kind:L(i,"kind"),id:L(i,"id"),definition:i.definition,trigger:L(i,"trigger"),tree:L(i,"treeId")??L(i,"tree"),gate:L(i,"gate"),limit:No(i.limit,"assurance verdict limit"),dry_run:i.dryRun===!0||i.dry_run===!0,fullChangedFields:i.fullChangedFields===!0,idOnly:i.idOnly===!0,author:L(i,"author"),message:L(i,"message"),preset:L(i,"preset"),owner:L(i,"owner"),apply:i.apply===!0,enforcement:L(i,"enforcement")},n)}import Nc from"node:fs/promises";import dy 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]="9c0640f0-505c-5f4a-bb7a-daa3cc775239")}catch{}})();var NC=1440*60*1e3,MC=new Set(["committed","compensated"]);function PC(e){let t;try{t=JSON.parse(e)}catch{return{status:null,updatedAt:null}}if(typeof t!="object"||t===null||Array.isArray(t))return{status:null,updatedAt:null};let n=t;return{status:typeof n.status=="string"?n.status:null,updatedAt:typeof n.updatedAt=="string"?n.updatedAt:null}}function FC(e,t,n,i,r){let s=n===null?Number.NaN:Date.parse(n);if(t===null||!Number.isFinite(s))return{entry:{file:e,status:t,age_seconds:null,stale:!1,reason:"unparseable"},remove:!1};let a=i-s;return MC.has(t)?a>r?{entry:{file:e,status:t,age_seconds:Math.floor(a/1e3),stale:!0},remove:!0}:{entry:{file:e,status:t,age_seconds:Math.floor(a/1e3),stale:!1,reason:"fresh"},remove:!1}:{entry:{file:e,status:t,age_seconds:Math.floor(a/1e3),stale:!1,reason:"active"},remove:!1}}async function $C(e,t,n,i){let r=i.hooks?.onRead?await i.hooks.onRead(e):[],s=PC(await Nc.readFile(e,"utf8")),a=FC(t,s.status,s.updatedAt,i.nowMs,i.retentionMs);return a.entry.reason==="unparseable"&&r.push(`transaction_journal_unparseable:${n}`),a.remove&&!i.dryRun&&(await Nc.rm(e,{force:!0}),i.hooks?.onWrite&&r.push(...await i.hooks.onWrite(e))),{decision:a,warnings:r}}async function ly(e,t){let{dryRun:n,hooks:i}=t,r=t.now??Date.now(),s=Math.max(0,t.retentionDays)*NC,a=dy.join(e,"transactions","sdk"),o={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c;try{c=(await Nc.readdir(a)).filter(d=>d.endsWith(".json")).sort((d,l)=>d.localeCompare(l))}catch(d){if(q(d))return o;throw d}for(let d of c){let l=dy.join(a,d),u=`transactions/sdk/${d}`,p=await $C(l,u,d,{dryRun:n,hooks:i,nowMs:r,retentionMs:s});o.warnings.push(...p.warnings),o.scanned+=1;let{decision:g}=p;if(!g.remove){o.retained.push(u),o.entries.push(g.entry);continue}o.removed.push(u),o.entries.push(g.entry)}return o}import In from"node:fs/promises";import Es from"node:path";import ks from"node:fs/promises";import Mc 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]="4fe37a62-2d0f-55f6-bb98-7162e7e8b8fe")}catch{}})();var UC=864e5;function jC(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t.created_at;return typeof n=="string"?n:null}async function GC(e,t){let n;try{n=await ks.readdir(e,{withFileTypes:!0})}catch(r){if(q(r))return[];throw r}let i=[];for(let r of n)if(r.isDirectory()){let s=Mc.join(e,r.name),a;try{a=await ks.readdir(s)}catch(o){q(o)||t.push(`checkpoint_subdir_unreadable:${r.name}`);continue}for(let o of a)o.endsWith(".json")&&i.push(`${r.name}/${o}`)}else r.name.endsWith(".json")&&i.push(r.name);return i.sort()}async function uy(e,t){let{dryRun:n,hooks:i}=t,r=t.now??Date.now(),s=Math.max(0,t.retentionDays)*UC,a=Mc.join(e,"checkpoints"),o={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c=await GC(a,o.warnings);for(let d of c){let l=Mc.join(a,d),u=`checkpoints/${d}`;o.scanned+=1,i?.onRead&&o.warnings.push(...await i.onRead(l));let p;try{p=await ks.readFile(l,"utf8")}catch(v){if(q(v)){o.scanned-=1;continue}o.warnings.push(`checkpoint_unreadable:${d}`),o.retained.push(u),o.entries.push({file:u,created_at:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let g=jC(p),f=g===null?Number.NaN:Date.parse(g);if(!Number.isFinite(f)){o.warnings.push(`checkpoint_unparseable:${d}`),o.retained.push(u),o.entries.push({file:u,created_at:g,age_seconds:null,stale:!1,reason:"unparseable"});continue}let h=r-f,y={file:u,created_at:g,age_seconds:Math.floor(h/1e3),stale:h>s,reason:h>s?"expired":"active"};if(!y.stale){o.retained.push(u),o.entries.push(y);continue}if(!n){try{await ks.unlink(l)}catch(v){if(!q(v)){o.warnings.push(`checkpoint_remove_failed:${d}`),o.retained.push(u),o.entries.push(y);continue}}i?.onWrite&&o.warnings.push(...await i.onWrite(l))}o.removed.push(u),o.entries.push(y)}return o}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="38736716-2644-5166-bfec-4ed4bca951b9")}catch{}})();var ki=["index","embeddings","runtime","locks","checkpoints","transactions"],qC=1440*60*1e3,KC=[{scope:"index",relativePath:"index/manifest.json",kind:"file"},{scope:"embeddings",relativePath:"search/embeddings.jsonl",kind:"file"},{scope:"embeddings",relativePath:"search/vectorization-status.json",kind:"file"},{scope:"embeddings",relativePath:"search/lancedb",kind:"directory"},{scope:"embeddings",relativePath:"search/pending-refresh.json",kind:"file"},{scope:"embeddings",relativePath:"search/pending-refresh.gate.lock",kind:"directory"},{scope:"runtime",relativePath:"runtime/test-runs",kind:"directory"},{scope:"runtime",relativePath:"runtime/history-drift-cache.json",kind:"file"}];async function zC(e,t,n){let i=t.relativePath,r=Es.join(e,i),s=await $e({path:r,scope:"project"});try{let a=await In.stat(r);if(t.kind==="file"&&!a.isFile())return{removed:!1,warnings:[...s,`not_a_file:${i}`]};if(t.kind==="directory"&&!a.isDirectory())return{removed:!1,warnings:[...s,`not_a_directory:${i}`]};if(n)return{removed:!0,warnings:s};t.kind==="file"?await In.unlink(r):await In.rm(r,{recursive:!0,force:!0});let o=await ot({path:r,scope:"project",op:"gc:remove"});return{removed:!0,warnings:[...s,...o]}}catch(a){if(q(a))return{removed:!1,warnings:s};throw a}}async function WC(e,t){let n=[{relativePath:"runtime/workspace-snapshots/objects",prefix:".create-"},{relativePath:"runtime/workspace-snapshots/refs",prefix:".ref-"}],i=[],r=[],s=[],a=Date.now()-qC;for(let o of n){let c=Es.join(e,o.relativePath);if(!await te(c))continue;let d=(await In.readdir(c)).filter(l=>l.startsWith(o.prefix)).sort();for(let l of d){let u=Es.posix.join(o.relativePath,l),p=Es.join(c,l);s.push(...await $e({path:p,scope:"project"}));let g=await In.stat(p).catch(f=>{if(!q(f))throw f});if(g){if(g.mtimeMs>a){r.push(u);continue}i.push(u),!t&&(await In.rm(p,{recursive:!0,force:!0}),s.push(...await ot({path:p,scope:"project",op:"gc:workspace_snapshot_temp_remove"})))}}}return{removed:i,retained:r,warnings:s}}function BC(e){if(!e||e.length===0)return[...ki];let t=e.flatMap(i=>i.split(",")).map(i=>i.trim().toLowerCase()).filter(i=>i.length>0);if(t.length===0)throw new _(`--scope requires at least one value (${ki.join(",")})`,m.USAGE);let n=new Set;for(let i of t){if(!ki.includes(i))throw new _(`Invalid --scope value "${i}". Expected one or more of: ${ki.join(", ")}`,m.USAGE);n.add(i)}return ki.filter(i=>n.has(i))}function HC(e){let t=[];e.dryRun&&t.push("Dry-run preview only: no cache artifacts were deleted.");let n=e.scopes.includes("index")||e.scopes.includes("embeddings"),i=e.removed.some(r=>r==="index/manifest.json"||r==="search/embeddings.jsonl"||r==="search/vectorization-status.json"||r==="search/lancedb"||r==="search/pending-refresh.json"||r==="search/pending-refresh.gate.lock");return n&&i&&t.push('Search artifacts were removed; the semantic index (including any queued background refresh) is invalidated. Run "pm install search-advanced --project" if reindex is unavailable, then "pm reindex --mode keyword" (and "--mode semantic" when semantic search is enabled) before search-heavy workflows.'),e.removed.includes("runtime/history-drift-cache.json")&&t.push('History drift cache was removed; the next "pm health" run performs a full history-drift re-scan.'),!e.dryRun&&e.removed.some(r=>r.startsWith("checkpoints/"))&&t.push('Aged rollback checkpoints were removed; their "pm update-many"/"pm close-many --rollback" windows are no longer recoverable.'),!e.dryRun&&e.removed.some(r=>r.startsWith("transactions/"))&&t.push("Aged terminal workspace-transaction journals were removed; replaying those transactionIds re-executes their idempotent steps instead of short-circuiting."),t}async function cz(e,t={}){let n=x(process.cwd(),e.path);await $(n);let i=await I(n),r=t.dryRun===!0,s=BC(t.scope),a=KC.filter(f=>s.includes(f.scope)),o=[],c=[],d=[];for(let f of a){let h=await zC(n,f,r);h.removed?o.push(f.relativePath):c.push(f.relativePath),d.push(...h.warnings)}if(s.includes("runtime")){let f=await WC(n,r);o.push(...f.removed),c.push(...f.retained),d.push(...f.warnings)}let l;if(s.includes("locks")){let f=await yg(n,{dryRun:r,hooks:{onRead:h=>$e({path:h,scope:"project"}),onWrite:h=>ot({path:h,scope:"project",op:"gc:lock_remove"})}});o.push(...f.removed),c.push(...f.retained),d.push(...f.warnings),l={scanned:f.scanned,removed:f.removed.length,retained:f.retained.length}}let u;if(s.includes("transactions")){let f=i.checkpoints.retention_days,h=await ly(n,{dryRun:r,retentionDays:f,hooks:{onRead:y=>$e({path:y,scope:"project"}),onWrite:y=>ot({path:y,scope:"project",op:"gc:transaction_journal_remove"})}});o.push(...h.removed),c.push(...h.retained),d.push(...h.warnings),u={scanned:h.scanned,removed:h.removed.length,retained:h.retained.length,retention_days:f}}let p;if(s.includes("checkpoints")){let f=i.checkpoints.retention_days,h=await uy(n,{dryRun:r,retentionDays:f,hooks:{onRead:y=>$e({path:y,scope:"project"}),onWrite:y=>ot({path:y,scope:"project",op:"gc:checkpoint_remove"})}});o.push(...h.removed),c.push(...h.retained),d.push(...h.warnings),p={scanned:h.scanned,removed:h.removed.length,retained:h.retained.length,retention_days:f}}d.push(...await Kl({mode:r?"gc:dry-run":"gc",total_items:a.length}));let g=HC({dryRun:r,scopes:s,removed:o});return{ok:d.length===0,dry_run:r,scope:s,removed:o,retained:c,warnings:d,...l?{locks:l}:{},...p?{checkpoints:p}:{},...u?{transactions:u}:{},guidance:g,generated_at:O()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8e07b07a-fde3-5173-bb7c-7e8ade88570c")}catch{}})();var mz=Object.freeze({requireCloseReason:!0,orderingEdges:"preserve"});function VC(e){let t=[{source:"explicit",value:e.explicit},{source:"duplicate",value:e.duplicateOf===void 0?void 0:`Duplicate of ${e.duplicateOf}`},{source:"resolution",value:e.resolution},{source:"message",value:e.message}];for(let n of t){let i=n.value?.trim();if(i)return{closeReason:i,source:n.source}}return{source:"none"}}function my(e,t){return Pc(e,t,{operation:"close"})}function Pc(e,t,n){let i=VC(e);if(!t||i.closeReason!==void 0)return i;let r=n.operation==="create"?[`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --close-reason "<closing summary>"`,`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --resolution "<resolution summary>"`,"pm create --stdin-json < item.json"]:['pm close <id> "Done: <what changed and why>"','pm close <id> --reason "<closing summary>"','pm close <id> -m "<closing summary>"',"pm close <id> --duplicate-of <canonical-id>"];throw new _("Close reason text is required because governance.require_close_reason is enabled",m.USAGE,{code:"close_reason_required",required:"Provide an author-controlled closing summary as the reason, message, resolution, or duplicate target.",why:"governance.require_close_reason is enabled, so tools must not invent immutable closure evidence.",examples:r,nextSteps:[`Re-run the ${n.operation} operation with a closing summary.`,"To stop requiring reasons, run: pm config set governance-require-close-reason --policy disabled"]})}function _y(e,t){let n=typeof e.blocked_by=="string"?e.blocked_by.trim():"",i=e.blocked_by!==void 0,r=e.dependencies??[],s=r.filter(d=>d.kind==="blocked_by"),a=e.blocked_reason!==void 0,o=[];if(i&&(delete e.blocked_by,o.push("blocked_by")),a&&(delete e.blocked_reason,o.push("blocked_reason")),t.orderingEdges==="remove"&&s.length>0){let d=new Set(s),l=r.filter(u=>!d.has(u));l.length>0?e.dependencies=l:delete e.dependencies,o.push("dependencies")}if(t.orderingEdges==="remove")return{changedFields:o,warnings:[...n?[`closed_cleared_blocked_by:${e.id}:${n}`]:[],...s.length>0?[`closed_removed_predecessors:${e.id}:${s.map(d=>d.id).join(",")}`,`closed_removed_predecessors_count:${e.id}:${s.length}`]:[]]};let c=[...new Set([...n?[n]:[],...s.map(d=>d.id)])];return c.length===0?{changedFields:o,warnings:[]}:{changedFields:o,warnings:[`closed_preserved_predecessors:${e.id}:${c.join(",")}`]}}(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]="6b7f5ee8-94ca-574f-b660-963eb574d571")}catch{}})();var YC=[{key:"resolution",label:"resolution (--resolution)"},{key:"expected_result",label:"expected_result (--expected-result)"},{key:"actual_result",label:"actual_result (--actual-result)"}];function JC(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0||t==="warn")return"warn";if(t==="off"||t==="none"||t==="disabled")return"off";if(t==="strict")return"strict";throw new _(`Invalid --validate-close mode "${e}" (expected "off", "warn", or "strict")`,m.USAGE)}function fy(e){let t=[];for(let n of YC){let i=e[n.key];(typeof i!="string"||i.trim().length===0)&&t.push(n)}return t}function gy(e,t,n={}){let i=fy(e);if(i.length===0)return;let r={resolution:n.resolution,expected_result:n.expectedResult,actual_result:n.actualResult},s=i.map(o=>`--${o.key.replaceAll("_","-")}`),a=["--pm-path",t,"update",e.id,...i.flatMap((o,c)=>[s[c],r[o.key]?.trim()||"<value>"])];return{missing:s,suggested_retry:fe(a),suggested_retry_args:a}}async function XC(e,t,n){let i=new Set,r=t;for(;typeof r=="string"&&r.trim().length>0;){let s=r.trim();if(s===n)return!0;if(i.has(s))return!1;i.add(s),r=(await e(s))?.duplicate_of}return!1}function QC(e){return typeof e!="string"||e.trim().length===0}async function ZC(e,t,n,i){let r=n?.trim();if(!r)return;if(r===i)throw new _("An item cannot be closed as a duplicate of itself.",m.USAGE,{code:"duplicate_target_self",why:"--duplicate-of must identify the canonical item that should remain open or already represent the work."});let s=F(t,P()),a=new Map,o=async d=>{if(a.has(d))return a.get(d)??null;let l=await Y(e,d,t.id_prefix,t.item_format,s.type_to_folder);if(!l)return a.set(d,null),null;let{document:u}=await he(l,{schema:t.schema});return a.set(d,u.metadata),u.metadata},c=await o(r);if(!c)throw new _(`Duplicate target "${r}" was not found. Create or locate the canonical item first.`,m.USAGE,{code:"duplicate_target_missing",why:"Duplicate closure should point at a real canonical pm item so future dedupe and changelog tooling can trace the relationship.",examples:[`pm close ${i} "Duplicate of ${r}" --duplicate-of ${r}`],nextSteps:["Run pm search/list to find the canonical item, then retry with --duplicate-of <id>."]});if(await XC(o,c.duplicate_of,i))throw new _(`Circular duplicate reference detected. Target "${r}" points back to "${i}".`,m.USAGE,{code:"duplicate_target_circular",why:"Circular duplicate relationships create loops for dedupe and status propagation tooling.",nextSteps:["Choose the existing canonical item, or clear the target duplicate_of metadata before closing this item as a duplicate."]});if(typeof c.duplicate_of=="string"&&c.duplicate_of.trim().length>0)throw new _(`Duplicate target "${r}" is already marked as a duplicate of "${c.duplicate_of.trim()}".`,m.USAGE,{code:"duplicate_target_is_duplicate",why:"Duplicate closure should point directly at the canonical item, not another duplicate.",examples:[`pm close ${i} "Duplicate of ${c.duplicate_of.trim()}" --duplicate-of ${c.duplicate_of.trim()}`],nextSteps:["Use the canonical item referenced by duplicate_of as the --duplicate-of target."]});return c.id}function ex(e,t,n){return e.filter(i=>i.parent===t&&!_e(i.status,n)).map(i=>i.id).sort((i,r)=>i.localeCompare(r))}function tx(e,t,n){let i=new Map(e.map(o=>[o.id.trim().toLowerCase(),o])),r=U_(e),s=t.trim().toLowerCase(),a=n.blocked_statuses;return e.filter(o=>a.has(o.status)).map(o=>({item:o,blockerIds:r.get(o.id.trim().toLowerCase())})).filter(({blockerIds:o})=>o.includes(s)).filter(({blockerIds:o})=>o.every(c=>{if(c===s)return!0;let d=i.get(c);return d!==void 0&&_e(d.status,n)})).map(({item:o,blockerIds:c})=>({id:o.id,blocker_ids:c})).sort((o,c)=>o.id.localeCompare(c.id))}async function nx(e,t,n,i,r,s){let a=tx(n,i,s),o=[];for(let c of a)try{let d=await se({pmRoot:e,settings:t,id:c.id,op:"update",author:r,message:`Auto-unblocked after blocker ${i} closed`,mutate(l){let u=l.metadata.dependencies??[],p=u.filter(f=>{let h=f.id.trim().toLowerCase();return f.kind!=="blocked_by"||!c.blocker_ids.includes(h)});l.metadata.status=s.open_status,delete l.metadata.blocked_by,delete l.metadata.blocked_reason,l.metadata.unblock_note=`Auto-unblocked after blocker ${i} closed; all blockers resolved (${c.blocker_ids.join(", ")}).`,p.length>0?l.metadata.dependencies=p:delete l.metadata.dependencies;let g=["status","blocked_by","blocked_reason","unblock_note"];return p.length!==u.length&&g.push("dependencies"),{changedFields:g}}});o.push(`auto_unblocked:${d.item.id}:resolved_blockers=${c.blocker_ids.join(",")}`)}catch(d){let l=d instanceof Error?d.message.replace(/\s+/g," ").trim():"unknown";o.push(`auto_unblock_failed:${c.id}:${l}`)}return o}function ix(e,t){let n=[],i=[{option:t.resolution,key:"resolution"},{option:t.expectedResult,key:"expected_result"},{option:t.actualResult,key:"actual_result"}];for(let{option:r,key:s}of i){if(typeof r!="string")continue;let a=r.trim();a.length!==0&&(e[s]=a,n.push(s))}return n}function rx(e,t){if(t===void 0)return[];e.duplicate_of=t;let n=[],i=[{key:"resolution",value:`Duplicate of ${t}`},{key:"expected_result",value:`Canonical item ${t} tracks the work.`},{key:"actual_result",value:`Closed as duplicate of ${t}.`}];for(let{key:r,value:s}of i)QC(e[r])&&(e[r]=s,n.push(r));return n}function sx(e,t,n,i){let r=[];if(t!=="off"){let s=fy(e);if(s.length>0){let a=s.map(o=>o.label);if(t==="strict"){let o=s.map(d=>`--${d.key.replaceAll("_","-")}`),c=["--pm-path",i,"update",e.id,...o.flatMap(d=>[d,"<value>"])];throw new _(`Cannot close item ${e.id}: missing ${a.join(", ")}. Populate fields or use --validate-close warn.`,m.USAGE,{code:"close_validation_missing_fields",recovery:{missing:o,suggested_retry:fe(c)},nextSteps:["Run the suggested pm update, then retry the original pm close invocation.","Use --validate-close warn only when governance permits an evidenced exception."]})}r.push(`close_validation_missing_fields:${e.id}:${a.join(",")}`)}if(n.length>0){if(t==="strict")throw new _(`Cannot close item ${e.id}: active child items remain open (${n.join(", ")}). Close, cancel, or re-parent them first, or use --validate-close warn.`,m.USAGE);r.push(`close_validation_active_children:${e.id}:${n.join(",")}`)}return r}return n.length>0&&r.push(`closed_with_active_children:${e.id}:${n.join(",")}`),r}function ax(e,t){return t!==void 0?(e.close_reason=t,["close_reason"]):[]}function ox(e){return e.assignee===void 0?[]:(delete e.assignee,["assignee"])}function cx(e,t){if(_e(e.status,t.statusRegistry)&&!t.force)throw new _(`Item ${e.id} is already terminal; use pm update to append acceptance evidence, or --force only for an intentional repeat closure.`,m.CONFLICT,{recovery:gy(e,t.pmRoot,t.options)});let n=ix(e,t.options),i=rx(e,t.duplicateOf),r=sx(e,t.validateCloseMode,t.activeChildIds,t.pmRoot);e.status=t.statusRegistry.close_status,e.closed_at=t.closedAt;let s=t.options.completedAt!==void 0||e.completed_at===void 0;s&&(e.completed_at=t.completedAt);let a=["status","closed_at",...s?["completed_at"]:[],...ax(e,t.closeReason),...n];if(b_(e)&&(e.plan_mode="completed",a.push("plan_mode")),t.duplicateOf!==void 0){a.push("duplicate_of");for(let c of i)a.includes(c)||a.push(c)}a.push(...ox(e));let o=_y(e,t.lifecyclePolicy);return a.push(...o.changedFields),r.push(...o.warnings),{changedFields:a,...r.length>0?{warnings:r}:{}}}async function dx(e,t,n,i){let r=x(process.cwd(),i.path);await $(r);let s=await I(r),a=K(s.schema),o=U(n.author,s.author_default),c=F(s,P()).type_to_folder,d=await Y(r,e,s.id_prefix,s.item_format,c);if(!d)throw await zn(r,e,s.id_prefix,c);let l=await ZC(r,s,n.duplicateOf,d.id),u={requireCloseReason:n.lifecyclePolicy?.requireCloseReason??s.governance.require_close_reason,orderingEdges:n.lifecyclePolicy?.orderingEdges??"preserve"},p=my({explicit:t,duplicateOf:l,resolution:n.resolution,message:n.message},u.requireCloseReason).closeReason,g=JC(n.validateClose)??s.governance.close_validation_default,f=await Se(r,s.item_format,c,void 0,s.schema),h=ex(f,d.id,a),y=O(),v=n.completedAt===void 0?y:ge(n.completedAt,new Date(y),"completed-at"),w=await se({pmRoot:r,settings:s,id:d.id,op:"close",author:o,message:n.message,force:n.force,mutate(S){return cx(S.metadata,{pmRoot:r,statusRegistry:a,force:n.force,options:n,duplicateOf:l,validateCloseMode:g,activeChildIds:h,closeReason:p,closedAt:y,completedAt:v,lifecyclePolicy:u})}}),k=g==="warn"?gy(w.item,r):void 0;return{item:w.item,changed_fields:w.changedFields,...k?{follow_up:{kind:"complete_close_evidence",missing:k.missing,suggested_command:k.suggested_retry,suggested_command_args:k.suggested_retry_args}}:{},warnings:[...w.warnings,...await nx(r,s,f,d.id,o,a)]}}function Ss(e,t,n,i){return dx(e,t,n,i)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="73852fdf-f072-51ab-9449-d7922712eeb4")}catch{}})();function hy(e){return[...e].sort().join("\0")}function lx(e,t,n){let i=e.successors.get(t);i?i.push(n):e.successors.set(t,[n]);let r=e.predecessors.get(n);r?r.push(t):e.predecessors.set(n,[t])}function yy(e,t,n,i,r){let s=t.resolve(r);if(s?.ordering!==!0)return;let a=K_(i),o=a===void 0?void 0:e.canonicalIds.get(a.toLowerCase());if(o===void 0)return;let c=(s.precedence??"source_before_target")==="source_before_target";lx(e,c?n:o,c?o:n)}function ux(e,t){let n={successors:new Map,predecessors:new Map,canonicalIds:new Map},i=e.filter(r=>typeof r?.id=="string"&&r.id.trim().length>0);for(let r of i){let s=r.id.trim();n.canonicalIds.set(s.toLowerCase(),s)}for(let r of i){let s=r.id.trim();yy(n,t,s,r.blocked_by,"blocked_by");for(let a of r.dependencies??[])typeof a!="object"||a===null||yy(n,t,s,a.id,typeof a.kind=="string"?a.kind:"related")}for(let r of[n.successors,n.predecessors])for(let s of r.values())s.sort();return n}function mx(e,t){let n=new Set([t]),i=[t];for(;i.length>0;){let r=i.pop();for(let s of[e.successors,e.predecessors])for(let a of s.get(r)??[])n.has(a)||(n.add(a),i.push(a))}return n}function _x(e,t){let n=new Map;for(let i of t){let r=(e.successors.get(i)??[]).filter(s=>t.has(s));r.length>0&&n.set(i,r)}return n}function vy(e,t,n){let i=ux(e,t),r=i.canonicalIds.get(n.trim().toLowerCase());if(r===void 0)return{cycles:[],successors:new Map,canonical:n};let s=_x(i,mx(i,r));return{cycles:sp(s).filter(a=>a.includes(r)),successors:s,canonical:r}}function px(e,t,n){let i=new Set(t),r=i.has(n)?n:t[0];if(e.get(r)?.includes(r))return[r,r];for(let s of e.get(r)??[]){if(!i.has(s))continue;let a=fx(e,i,r,s);if(a)return a}return[...t,t[0]]}function fx(e,t,n,i){let r=[[i]],s=new Set([n,i]);for(;r.length>0;){let a=r.shift(),o=a.at(-1);for(let c of e.get(o)??[]){if(c===n)return[n,...a,n];!t.has(c)||s.has(c)||(s.add(c),r.push([...a,c]))}}}function Ts(e,t,n){let i=ae(),r=vy(e,i,n),s=vy(t,i,n),a=new Set(r.cycles.map(hy)),o=new Set(mo(e,void 0,i).map(c=>`${c.holder_id.toLowerCase()}\0${c.target_id.toLowerCase()}\0${c.dependency_kind}`));return[...mo(t,void 0,i).filter(c=>c.holder_id.toLowerCase()===n.trim().toLowerCase()&&!o.has(`${c.holder_id.toLowerCase()}\0${c.target_id.toLowerCase()}\0${c.dependency_kind}`)).map(c=>`ordering_storage_contradiction_created:${ap(c)}:remove_contradicting_dependency_row:run_pm_graph_audit`),...s.cycles.filter(c=>!a.has(hy(c))).map(c=>`ordering_cycle_created:${px(s.successors,c,s.canonical).join(" -> ")}:items_will_not_be_ready:run_pm_graph_audit`)]}(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]="5f2ca18e-450d-5b6e-9e07-7bbf080764f9")}catch{}})();function As(e,t){let n=t.resolve(e);return n?.hierarchy===!0||n?.outgoing==="one"||n?.incoming==="one"}function wy(e,t,n,i,r){let s=JSON.stringify([t,n,i]),a=e.get(s);a===void 0&&(a={kind:t,direction:n,node_id:i,endpoints:new Set},e.set(s,a)),a.endpoints.add(r)}function by(e,t){let n=new Map;for(let i of e)for(let r of i.dependencies??[]){let s=t.resolve(r.kind);s===void 0||s.hierarchy||(s.outgoing==="one"&&wy(n,s.kind,"outgoing",i.id,r.id),s.incoming==="one"&&wy(n,s.kind,"incoming",r.id,i.id))}return n}function Is(e,t,n=ae()){let i=by(e,n),r=by(t,n);for(let s of[...r.keys()].sort()){let a=r.get(s);if(a.endpoints.size<=1)continue;let o=i.get(s);if(![...a.endpoints].every(c=>o?.endpoints.has(c)))throw new _(`Relationship ${a.kind} permits only one ${a.direction} endpoint for ${a.node_id}.`,m.USAGE,{code:"dependency_cardinality_created",field:"dependencies",value:a.kind,relationship_cardinality:{kind:a.kind,direction:a.direction,node_id:a.node_id,endpoint_ids:[...a.endpoints].sort()},required:"The final dependency set must satisfy the active relationship kind's one-edge cardinality.",nextSteps:["Drop extra --dep seeds, or remove conflicting rows with update --dep-remove before adding another edge.","Choose another kind only when its declared semantics match the intended relationship."]})}}(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]="1ce8c06c-cdc7-57bb-b4c3-477b2e07d71c")}catch{}})();var Ht=new Set(["PM_PATH","PM_GLOBAL_PATH","PM_SOURCE_PM_PATH","PM_SOURCE_WORKSPACE_ROOT","PM_BUILD_CONSUMER_LEASE","PM_BUILD_CONSUMER_LEASE_ROOT",Jn,X_,"FORCE_COLOR"]),Rs=/^[A-Za-z_][A-Za-z0-9_]*$/,Bt=["schema","tracker","auto","none"],ky=["source","isolated","snapshot"];function Ei(e,t){if(!e)return;let n=e.split(/[;\n]/).map(r=>r.trim()).filter(r=>r.length>0);if(n.length===0)throw new _(`${t} env_set must include at least one KEY=VALUE assignment`,m.USAGE);let i=Object.create(null);for(let r of n){let s=r.indexOf("=");if(s<=0)throw new _(`${t} env_set entries must use KEY=VALUE and be separated by semicolons. Example: env_set=PORT=0;PLAYWRIGHT_BASE_URL=http://127.0.0.1:4173`,m.USAGE);let a=r.slice(0,s).trim(),o=r.slice(s+1);if(!Rs.test(a))throw new _(`${t} env_set key "${a}" is invalid`,m.USAGE);if(Ht.has(a.toUpperCase()))throw new _(`${t} env_set key "${a}" is reserved for sandbox safety`,m.USAGE);i[a]=o}return Object.keys(i).length>0?i:void 0}function Si(e,t){if(!e)return;let n=co(e,{separators:/[;,\n]/});if(n.length===0)throw new _(`${t} env_clear must include at least one environment variable name`,m.USAGE);for(let i of n){if(!Rs.test(i))throw new _(`${t} env_clear key "${i}" is invalid`,m.USAGE);if(Ht.has(i.toUpperCase()))throw new _(`${t} env_clear key "${i}" is reserved for sandbox safety`,m.USAGE)}return n}function Os(e,t,n){if(!e)return;let i=e.trim().toLowerCase();if(i==="true"||i==="1"||i==="yes")return!0;if(i==="false"||i==="0"||i==="no")return!1;throw new _(`${t} ${n} must be one of true|false|1|0|yes|no`,m.USAGE)}function Ls(e,t){if(!e)return;let n=e.trim().toLowerCase();if(Bt.includes(n))return n;throw new _(`${t} pm_context_mode must be one of: ${Bt.join(", ")}`,m.USAGE)}function Vt(e,t){if(!e)return;let n=e.trim().toLowerCase();if(ky.includes(n))return n;throw new _(`${t} workspace_context_mode must be one of: ${ky.join(", ")}`,m.USAGE)}function Yt(e){if(!e)return;let t=co(e,{separators:/[;\n]/});return t.length>0?t:void 0}function Cn(e,t,n){let i=Yt(e);if(!(!i||i.length===0)){for(let r of i)try{new RegExp(r,"m")}catch(s){throw new _(`${t} ${n} includes invalid regex "${r}": ${s instanceof Error?s.message:String(s)}`,m.USAGE)}return i}}function Ds(e,t){if(!e)return;let n=ye(e,"assert_stdout_min_lines");if(!Number.isInteger(n)||n<0)throw new _(`${t} assert_stdout_min_lines must be an integer >= 0`,m.USAGE);return n}function Ns(e,t){if(!e)return;let n=e.split(/[;\n]/).map(r=>r.trim()).filter(r=>r.length>0);if(n.length===0)throw new _(`${t} assert_json_field_equals must include at least one path=value assignment`,m.USAGE);let i=Object.create(null);for(let r of n){let s=r.indexOf("=");if(s<=0)throw new _(`${t} assert_json_field_equals entries must use path=value and be separated by semicolons`,m.USAGE);let a=r.slice(0,s).trim(),o=r.slice(s+1).trim();if(a.length===0||o.length===0)throw new _(`${t} assert_json_field_equals entries must include non-empty path and value`,m.USAGE);i[a]=o}return Object.keys(i).length>0?i:void 0}function Ms(e,t){if(!e)return;let n=e.split(/[;\n]/).map(r=>r.trim()).filter(r=>r.length>0);if(n.length===0)throw new _(`${t} assert_json_field_gte must include at least one path=value assignment`,m.USAGE);let i=Object.create(null);for(let r of n){let s=r.indexOf("=");if(s<=0)throw new _(`${t} assert_json_field_gte entries must use path=value and be separated by semicolons`,m.USAGE);let a=r.slice(0,s).trim(),o=r.slice(s+1).trim();if(a.length===0||o.length===0)throw new _(`${t} assert_json_field_gte entries must include non-empty path and value`,m.USAGE);let c=Number(o);if(!Number.isFinite(c))throw new _(`${t} assert_json_field_gte value for "${a}" must be numeric`,m.USAGE);i[a]=c}return Object.keys(i).length>0?i:void 0}var gx=new Set(Ge);function Ps(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function hx(e,t){let n={},i=[];for(let[r,s]of Object.entries(e)){let a=r.toLowerCase();if(!gx.has(a)){i.push(r);continue}if(Object.hasOwn(n,a))throw t(`provides key "${r}" more than once after case normalization`);n[a]=s}if(i.length>0)throw t(`does not recognize key${i.length>1?"s":""} ${i.map(r=>`"${r}"`).join(", ")}. Allowed keys: ${Ge.join(", ")}.`);return n}function Wt(e,t,n){if(!Object.hasOwn(e,t))return;let i=e[t];if(i!==void 0){if(typeof i!="string")throw n(`field "${t}" must be a JSON string`);return i}}function Cs(e,t,n){if(!Object.hasOwn(e,t))return;let i=e[t];if(i===void 0)return;let r=typeof i=="string"?[i]:i;if(!Array.isArray(r)||r.some(a=>typeof a!="string"))throw n(`field "${t}" must be a string or an array of strings`);let s=r.filter(a=>a.length>0);return s.length>0?s:void 0}function Ey(e,t,n){let i=Cs(e,t,n);if(i){for(let r of i)try{new RegExp(r,"m")}catch(s){throw n(`field "${t}" includes invalid regex "${r}": ${s instanceof Error?s.message:String(s)}`)}return i}}function xs(e,t,n){let i=typeof e=="number"?e:typeof e=="string"&&e.trim().length>0?Number(e.trim()):Number.NaN;if(typeof e=="boolean"||!Number.isFinite(i))throw n(`field "${t}" must be a finite number (or numeric string)`);return i}function yx(e,t){let n=e.timeout_seconds,i=e.timeout;if(n===void 0&&i===void 0)return;let r=n===void 0?void 0:xs(n,"timeout_seconds",t),s=i===void 0?void 0:xs(i,"timeout",t);if(r!==void 0&&s!==void 0&&r!==s)throw t("timeout and timeout_seconds must match when both are provided");let a=r??s;if(!Number.isInteger(a)||a<=0)throw t("timeout_seconds must be a positive integer");return a}function vx(e,t){let n=Wt(e,"scope",t);if(n===void 0)return"project";if(!Pe.includes(n))throw t(`field "scope" must be one of: ${Pe.join(", ")}`);return n}function wx(e,t){if(!Object.hasOwn(e,"env_set"))return;let n=e.env_set;if(n===void 0)return;if(!Ps(n))throw t('field "env_set" must be a JSON object mapping environment names to string values');let i=Object.create(null);for(let[r,s]of Object.entries(n)){if(typeof s!="string")throw t(`field "env_set" value for "${r}" must be a string`);if(!Rs.test(r))throw t(`field "env_set" key "${r}" is invalid`);if(Ht.has(r.toUpperCase()))throw t(`field "env_set" key "${r}" is reserved for sandbox safety`);i[r]=s}return Object.keys(i).length>0?i:void 0}function bx(e,t){let n=Cs(e,"env_clear",t);if(n){for(let i of n){if(!Rs.test(i))throw t(`field "env_clear" key "${i}" is invalid`);if(Ht.has(i.toUpperCase()))throw t(`field "env_clear" key "${i}" is reserved for sandbox safety`)}return n}}function kx(e,t,n){if(!Object.hasOwn(e,t))return;let i=e[t];if(i!==void 0){if(typeof i!="boolean")throw n(`field "${t}" must be a JSON boolean (true or false)`);return i}}function Ex(e,t){if(!Object.hasOwn(e,"assert_stdout_min_lines"))return;let n=e.assert_stdout_min_lines;if(n===void 0)return;let i=xs(n,"assert_stdout_min_lines",t);if(!Number.isInteger(i)||i<0)throw t('field "assert_stdout_min_lines" must be an integer >= 0');return i}function Sx(e,t){if(!Object.hasOwn(e,"assert_json_field_equals"))return;let n=e.assert_json_field_equals;if(n===void 0)return;if(!Ps(n))throw t('field "assert_json_field_equals" must be a JSON object mapping field paths to expected values');let i=Object.create(null);for(let[r,s]of Object.entries(n)){if(r.trim().length===0)throw t('field "assert_json_field_equals" keys must be non-empty field paths');if(typeof s!="string"&&typeof s!="number"&&typeof s!="boolean")throw t(`field "assert_json_field_equals" value for "${r}" must be a string, number, or boolean`);i[r]=String(s)}return Object.keys(i).length>0?i:void 0}function Tx(e,t){if(!Object.hasOwn(e,"assert_json_field_gte"))return;let n=e.assert_json_field_gte;if(n===void 0)return;if(!Ps(n))throw t('field "assert_json_field_gte" must be a JSON object mapping field paths to numeric minimums');let i=Object.create(null);for(let[r,s]of Object.entries(n)){if(r.trim().length===0)throw t('field "assert_json_field_gte" keys must be non-empty field paths');i[r]=xs(s,`assert_json_field_gte.${r}`,t)}return Object.keys(i).length>0?i:void 0}function Ax(e,t,n){let i=p=>new _(`${n} ${t} ${p}`,m.USAGE);if(!Ps(e))throw i(`must be a JSON object with linked-test fields. Allowed keys: ${Ge.join(", ")}.`);let r=hx(e,i),s=Wt(r,"command",i),a=Wt(r,"cmd",i);if(s!==void 0&&a!==void 0&&s!==a)throw i("command and cmd must match when both are provided");let o=s??a;if(o===void 0||o.trim().length===0)throw i('requires a non-empty "command" string');let c=Wt(r,"path",i),d=Wt(r,"pm_context_mode",i);if(d!==void 0&&!Bt.includes(d))throw i(`field "pm_context_mode" must be one of: ${Bt.join(", ")}`);let l=Vt(Wt(r,"workspace_context_mode",i),`${n} ${t}`),u=Wt(r,"note",i);return{command:o,path:c!==void 0&&c.length>0?c:void 0,scope:vx(r,i),timeout_seconds:yx(r,i),pm_context_mode:d,workspace_context_mode:l,env_set:wx(r,i),env_clear:bx(r,i),shared_host_safe:kx(r,"shared_host_safe",i),assert_stdout_contains:Cs(r,"assert_stdout_contains",i),assert_stdout_regex:Ey(r,"assert_stdout_regex",i),assert_stderr_contains:Cs(r,"assert_stderr_contains",i),assert_stderr_regex:Ey(r,"assert_stderr_regex",i),assert_stdout_min_lines:Ex(r,i),assert_json_field_equals:Sx(r,i),assert_json_field_gte:Tx(r,i),note:u!==void 0&&u.trim().length>0?u.trim():void 0}}function Fs(e,t){let n=e.trim();if(n.length===0)throw new _(`${t} requires a JSON object or array of objects describing linked-test entries`,m.USAGE);let i;try{i=JSON.parse(n)}catch(s){throw new _(`${t} value is not valid JSON: ${s instanceof Error?s.message:String(s)}. Provide a JSON object or array of objects, e.g. '{"command":"node scripts/check.js --flag value, with commas","timeout_seconds":120}'.`,m.USAGE)}let r=Array.isArray(i)?i:[i];if(r.length===0)throw new _(`${t} array must include at least one linked-test entry object`,m.USAGE);return r.map((s,a)=>Ax(s,r.length>1?`entry ${a+1}`:"entry",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]="a9b9f4df-2129-5230-af20-16bef3754d39")}catch{}})();var Ix={comment:"--clear-comments",dep:"--clear-deps",doc:"--clear-docs",event:"--clear-events",file:"--clear-files",learning:"--clear-learnings",note:"--clear-notes",reminder:"--clear-reminders",test:"--clear-tests",typeOption:"--clear-type-options"};function Cx(e){return Ix[e]}function Fc(e){return Cx(e)!==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]="1e808776-dd0e-507f-9214-e3f5fa846874")}catch{}})();var xx="hierarchy-integrity";async function $s(e){let t=e.required?await bt(e.pmRoot,xx,e.ttlSeconds,e.author,!1,!1,e.waitMs):async()=>{},n=!1;return async()=>{n||(n=!0,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]="01a312de-88fc-514f-b37b-2e717222a8ed")}catch{}})();function Us(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function js(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function Gs(e){let t=e.trim().toLowerCase();if(t==="med")return"medium";if(cl.includes(t))return t;let n=ye(e,"confidence");if(!Number.isInteger(n)||n<0||n>100)throw new _("Confidence must be an integer 0..100 or one of low|med|medium|high",m.USAGE);return n}function qs(e){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1;throw new _("Regression must be one of true|false|1|0",m.USAGE)}(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]="6ccfe6c7-3911-5623-aa29-5eff0293f816")}catch{}})();var Sy=[["dependencies","dep",["id","kind","created_at","author","source_kind"]],["comments","comment",["text","created_at","author"]],["notes","note",["text","created_at","author"]],["learnings","learning",["text","created_at","author"]],["files","file",["path","scope","note"]],["tests","test",["command","scope","timeout_seconds"]],["docs","doc",["path","scope","note"]],["reminders","reminder",["at","text","created_at"]],["events","event",["start_at","end_at","title","location"]],["type_options","typeOption",["key","value"]]];(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]="2167160d-d7ba-5096-b0b5-7e9e795af0a6")}catch{}})();function Ks(e){let t=Sy.find(([i])=>i===e)?.[1]??e.replaceAll(/_([a-z])/gu,(i,r)=>r.toUpperCase()),n=[["update",F_],["create",N_]].flatMap(([i,r])=>r.flatMap(s=>{if(s.target!==t)return[];let a=s.option.match(/--[a-z][a-z0-9-]*/u)[0];return[{command:i,flag:a}]}));return{recovery:{provided_fields:[e],...n.length>0?{suggested_flags:[...new Set(n.map(i=>i.flag))]}:{}},nextSteps:n.length>0?n.map(({command:i,flag:r})=>`Use the declared core mutation: pm ${i}${i==="update"?" <id>":""} ${r} <value>; inspect its help for other required options.`):[`No dedicated create/update CLI mutation flag is declared for "${e}". Use its owning lifecycle, evidence, or importer API; --field cannot mutate core metadata.`]}}(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]="c22dc1f8-285a-5858-9087-17a8deed6db8")}catch{}})();var Rx=new Set(["none","null"]);function zs(e={}){return[{optionKey:"dep",clearFlagKey:"clearDeps",valueFlag:"--dep",clearFlag:"--clear-deps",...e.depDisableFlagKey===void 0?{}:{disableFlagKey:e.depDisableFlagKey}},{optionKey:"comment",clearFlagKey:"clearComments",valueFlag:"--comment",clearFlag:"--clear-comments"},{optionKey:"note",clearFlagKey:"clearNotes",valueFlag:"--note",clearFlag:"--clear-notes"},{optionKey:"learning",clearFlagKey:"clearLearnings",valueFlag:"--learning",clearFlag:"--clear-learnings"},{optionKey:"file",clearFlagKey:"clearFiles",valueFlag:"--file",clearFlag:"--clear-files",...e.fileDisableFlagKey===void 0?{}:{disableFlagKey:e.fileDisableFlagKey}},{optionKey:"test",clearFlagKey:"clearTests",valueFlag:"--test",clearFlag:"--clear-tests",...e.testDisableFlagKey===void 0?{}:{disableFlagKey:e.testDisableFlagKey}},{optionKey:"doc",clearFlagKey:"clearDocs",valueFlag:"--doc",clearFlag:"--clear-docs",...e.docDisableFlagKey===void 0?{}:{disableFlagKey:e.docDisableFlagKey}},{optionKey:"reminder",clearFlagKey:"clearReminders",valueFlag:"--reminder",clearFlag:"--clear-reminders"},{optionKey:"event",clearFlagKey:"clearEvents",valueFlag:"--event",clearFlag:"--clear-events"},{optionKey:"typeOption",clearFlagKey:"clearTypeOptions",valueFlag:"--type-option",clearFlag:"--clear-type-options"}]}function Be(e){return e===void 0?!1:Rx.has(e.trim().toLowerCase())}function Ws(e,t,n){if(!Be(e))return;let i=n?` ${n}`:"";throw new _(`${t} no longer accepts "none" or "null".${i}`.trim(),m.USAGE)}function Re(e,t,n){if(!e||e.length===0||!e.some(r=>Be(r)))return;let i=n?` ${n}`:"";throw new _(`${t} no longer accepts "none" or "null".${i}`.trim(),m.USAGE)}function Bs(e,t){for(let n of t){let i=e[n.optionKey];if(!Array.isArray(i)||i.length===0)continue;if(!i.every(s=>typeof s=="string"))throw new _(`${n.valueFlag} entries must be strings.`,m.USAGE);let r=i;if(r.some(s=>Be(s))){if(r.filter(s=>!Be(s)).length>0)throw new _(`Cannot mix legacy clear token "none"/"null" with concrete ${n.valueFlag} entries. Use ${n.clearFlag} to clear or provide explicit entries.`,m.USAGE);e[n.optionKey]=void 0,e[n.clearFlagKey]=!0,n.disableFlagKey&&(e[n.disableFlagKey]=!1)}}return e}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="daa816a5-05d4-5e0a-90aa-9d96afdb2117")}catch{}})();var Ox=new Set(["event","meeting","reminder","milestone","decision","adr"]);function Ty(e,t,n,i){if(Ox.has(t.trim().toLowerCase())||n!==i.open_status)return;let r=Ke("in_progress",i);if(!(r===void 0||r===i.open_status))return{command:`pm claim ${e} --start`,to_status: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]="1ffee31a-c272-5494-a04a-01a17b78dd2d")}catch{}})();var $c=[{canonical:"tags",aliases:["tags"],optionKey:"tags",metadataKey:"tags"}],Uc=[{canonical:"deadline",aliases:["deadline"],optionKey:"deadline",metadataKey:"deadline"},{canonical:"estimate",aliases:["estimate","estimated_minutes","estimated-minutes"],optionKey:"estimatedMinutes",metadataKey:"estimated_minutes"},{canonical:"acceptance-criteria",aliases:["acceptance_criteria","acceptance-criteria","ac"],optionKey:"acceptanceCriteria",metadataKey:"acceptance_criteria"},{canonical:"definition-of-ready",aliases:["definition_of_ready","definition-of-ready"],optionKey:"definitionOfReady",metadataKey:"definition_of_ready"},{canonical:"order",aliases:["order","rank"],optionKey:"order",metadataKey:"order"},{canonical:"goal",aliases:["goal"],optionKey:"goal",metadataKey:"goal"},{canonical:"objective",aliases:["objective"],optionKey:"objective",metadataKey:"objective"},{canonical:"value",aliases:["value"],optionKey:"value",metadataKey:"value"},{canonical:"impact",aliases:["impact"],optionKey:"impact",metadataKey:"impact"},{canonical:"outcome",aliases:["outcome"],optionKey:"outcome",metadataKey:"outcome"},{canonical:"why-now",aliases:["why_now","why-now"],optionKey:"whyNow",metadataKey:"why_now"}],Ay=[...$c,...Uc],Hs=[{canonical:"assignee",aliases:["assignee"],optionKey:"assignee",metadataKey:"assignee"},{canonical:"parent",aliases:["parent"],optionKey:"parent",metadataKey:"parent"},{canonical:"reviewer",aliases:["reviewer"],optionKey:"reviewer",metadataKey:"reviewer"},{canonical:"risk",aliases:["risk"],optionKey:"risk",metadataKey:"risk"},{canonical:"confidence",aliases:["confidence"],optionKey:"confidence",metadataKey:"confidence"},{canonical:"sprint",aliases:["sprint"],optionKey:"sprint",metadataKey:"sprint"},{canonical:"release",aliases:["release"],optionKey:"release",metadataKey:"release"},{canonical:"blocked-by",aliases:["blocked_by","blocked-by"],optionKey:"blockedBy",metadataKey:"blocked_by"},{canonical:"blocked-reason",aliases:["blocked_reason","blocked-reason"],optionKey:"blockedReason",metadataKey:"blocked_reason"},{canonical:"unblock-note",aliases:["unblock_note","unblock-note"],optionKey:"unblockNote",metadataKey:"unblock_note"},{canonical:"reporter",aliases:["reporter"],optionKey:"reporter",metadataKey:"reporter"},{canonical:"severity",aliases:["severity"],optionKey:"severity",metadataKey:"severity"},{canonical:"environment",aliases:["environment"],optionKey:"environment",metadataKey:"environment"},{canonical:"repro-steps",aliases:["repro_steps","repro-steps"],optionKey:"reproSteps",metadataKey:"repro_steps"},{canonical:"resolution",aliases:["resolution"],optionKey:"resolution",metadataKey:"resolution"},{canonical:"expected-result",aliases:["expected_result","expected-result"],optionKey:"expectedResult",metadataKey:"expected_result"},{canonical:"actual-result",aliases:["actual_result","actual-result"],optionKey:"actualResult",metadataKey:"actual_result"},{canonical:"affected-version",aliases:["affected_version","affected-version"],optionKey:"affectedVersion",metadataKey:"affected_version"},{canonical:"fixed-version",aliases:["fixed_version","fixed-version"],optionKey:"fixedVersion",metadataKey:"fixed_version"},{canonical:"component",aliases:["component"],optionKey:"component",metadataKey:"component"},{canonical:"regression",aliases:["regression"],optionKey:"regression",metadataKey:"regression"},{canonical:"customer-impact",aliases:["customer_impact","customer-impact"],optionKey:"customerImpact",metadataKey:"customer_impact"}];function Vs(e){let t=new Set,n=new Set;if(!e.raw||e.raw.length===0)return{metadataKeys:t,optionKeys:n};for(let i of e.raw){let r=i.trim().toLowerCase();if(!r)throw new _("--unset values must not be empty",m.USAGE);if(Be(r))throw new _('--unset no longer accepts "none" or "null". Specify concrete field names such as --unset deadline',m.USAGE);let s=e.resolveDefinition(r);if(!s)throw new _(`Unsupported --unset field "${i}". Supported fields: ${e.supportedFields}`,m.USAGE);t.add(s.metadataKey),n.add(s.optionKey)}return{metadataKeys:t,optionKeys:n}}function Ys(e,t,n){let i=e.trim().toLowerCase();if(!n)return;let r=n.command_to_fields?.get(t)??[];for(let s of r){if(s.allow_unset===!1)continue;let a=new Set;if(typeof s.key=="string"&&s.key.length>0&&a.add(s.key.toLowerCase()),typeof s.metadata_key=="string"&&s.metadata_key.length>0&&a.add(s.metadata_key.toLowerCase()),typeof s.cli_flag=="string"&&s.cli_flag.length>0&&(a.add(s.cli_flag.replaceAll("-","_").toLowerCase()),a.add(s.cli_flag.toLowerCase())),Array.isArray(s.cli_aliases))for(let o of s.cli_aliases)typeof o!="string"||o.length===0||(a.add(o.replaceAll("-","_").toLowerCase()),a.add(o.toLowerCase()));if(a.has(i))return{optionKey:s.key,metadataKey:s.metadata_key}}}(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]="48975dc8-636f-51a1-858a-f97c7a037688")}catch{}})();function Cy(e,t){let n=e.trim().toLowerCase();if(n==="true"||n==="1"||n==="yes")return!0;if(n==="false"||n==="0"||n==="no")return!1;throw new _(`${t} must be one of true|false|1|0|yes|no`,m.USAGE)}function jc(e){return e?e.split("|").map(t=>t.trim()).filter(t=>t.length>0):[]}function He(e,t,n,i=n){if(!t.includes(e))throw new _(`Invalid ${n} value "${e}". Allowed: ${t.join(", ")}`,m.USAGE,{field:i,value:e,recovery:{allowed_values:[...t]},required:`${n} must be one of: ${t.join(", ")}.`,nextSteps:[`Choose an allowed ${n} and retry the mutation.`]});return e}var xy=["recur_freq","recur_interval","recur_count","recur_until","recur_by_weekday","recur_by_month_day","recur_exdates"];function Lx(e,t){return t==="defined"?e!==void 0:!!e}function Iy(e,t,n){if(!Lx(e,n))return;let i=ye(e,`event ${t}`);if(!Number.isInteger(i)||i<1)throw new _(`--event ${t} must be an integer >= 1`,m.USAGE);return i}function Dx(e,t,n){let i=e?ge(e,n,"event.recur_until"):void 0;if(i&&i<t)throw new _("--event recur_until must be at or after start",m.USAGE);return i}function Nx(e){return Array.from(new Set(jc(e).map(t=>He(t.toLowerCase(),pl,"event weekday")))).sort((t,n)=>Fa(t)-Fa(n))}function Mx(e){return Array.from(new Set(jc(e).map(t=>{let n=ye(t,"event recur_by_month_day");if(!Number.isInteger(n)||n<1||n>31)throw new _("--event recur_by_month_day values must be integers 1..31",m.USAGE);return n}))).sort((t,n)=>t-n)}function Px(e,t){return Array.from(new Set(jc(e).map(n=>ge(n,t,"event.recur_exdates")))).sort((n,i)=>n.localeCompare(i))}function Ry(e,t,n,i){let r=e.recur_freq?.trim(),s=e.recur_interval?.trim(),a=e.recur_count?.trim(),o=e.recur_until?.trim(),c=e.recur_by_weekday?.trim(),d=e.recur_by_month_day?.trim(),l=e.recur_exdates?.trim();if(![r,s,a,o,c,d,l].some(w=>w!==void 0))return;if(!r)throw new _("--event recurrence fields require recur_freq=<daily|weekly|monthly|yearly>",m.USAGE);let u=He(r.toLowerCase(),_l,"event recurrence frequency"),p=Iy(s,"recur_interval",i),g=Iy(a,"recur_count",i),f=Dx(o,t,n),h=Nx(c),y=Mx(d),v=Px(l,n);return{freq:u,interval:p,count:g,until:f,by_weekday:h.length>0?h:void 0,by_month_day:y.length>0?y:void 0,exdates:v.length>0?v: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]="414326ff-8d4d-577d-b724-ab32b3f311ac")}catch{}})();function Ti(e,t=ae()){let n=t.resolve(e);if(n)return n.kind;let i=new Set(Pa),r=[...Pa,...t.list().filter(({kind:s})=>!i.has(s)).flatMap(({kind:s,aliases:a})=>[s,...a])];throw new _(`Invalid dependency kind value "${e}". Allowed: ${r.join(", ")}`,m.USAGE,{field:"kind",value:e,recovery:{allowed_values:r},required:`dependency kind must be one of: ${r.join(", ")}.`,nextSteps:["Choose a registered kind, or install and enable the extension that registers this kind before retrying."]})}function Ai(e,t,n="--dep"){if(!t&&/[:,=]/.test(e))throw new _(`Invalid ${n} value "${e}". Use a bare item id or id=<id>,kind=<kind>.`,m.USAGE,{code:"dependency_flag_value_invalid",reason:"malformed_dependency_shorthand",flag:n,value:e,required:"Use a bare item id or an explicit id=<id>,kind=<kind> entry."})}function Ii(e,t,n=ae()){for(let i of t??[])try{Xd(e,i.id,i.kind,n)}catch(r){throw new _(al(r),m.USAGE,{code:"dependency_edge_not_allowed",why:`${e} -> ${i.id} (${i.kind}) violates the active relationship-kind policy`})}}async function Oy(e,t){return(await he(e,{schema:t})).document.metadata.created_at}async function Fx(e,t){if(e.createdAt!==void 0)return e.createdAt;let n=await Y(t.pmRoot,e.id,t.idPrefix,t.itemFormat,t.typeToFolder);return n===null?void 0:Oy(n,t.schema)}function $x(e){let t=e.registry.require(e.dependency.kind);return new _(`${t.kind} requires source ${e.holder.id} to be created after target ${e.dependency.id}`,m.USAGE,{code:"dependency_temporal_order_invalid",reason:"source_not_after_target",required:`${e.holder.id}.created_at must be later than ${e.dependency.id}.created_at for ${t.kind}.`,why:"Chronological recurrence direction must be validated before the relationship is persisted.",source_id:e.holder.id,source_created_at:e.sourceCreatedAt,target_id:e.dependency.id,target_created_at:e.targetCreatedAt,temporal_order:t.temporalOrder})}async function Ux(e){let t=e.dependencies.filter(r=>e.registry.resolve(r.kind)?.temporalOrder==="source_after_target"&&!e.missingTargets.includes(r.id));if(t.length===0||e.holders.length===0)return;let n=new Map(e.resolutions.flatMap(({target:r,located:s})=>s===null?[]:[[r,s]])),i=new Map(await Promise.all([...new Set(t.map(({id:r})=>r))].map(async r=>[r,await Oy(n.get(r),e.context.schema)])));for(let r of e.holders){let s=await Fx(r,e.context);if(s!==void 0)for(let a of t){let o=i.get(a.id),c=Date.parse(s),d=Date.parse(o);if(!(Number.isFinite(c)&&Number.isFinite(d)&&c>d))throw $x({holder:r,dependency:a,sourceCreatedAt:s,targetCreatedAt:o,registry:e.registry})}}}async function Js(e){let t=e.registry??ae(),n=(e.dependencies??[]).filter(a=>!A_(a.source_kind)),i=[...new Set(n.map(a=>a.id))],r=await Promise.all(i.map(async a=>({target:a,located:await Y(e.pmRoot,a,e.idPrefix,e.itemFormat,e.typeToFolder)}))),s=r.filter(({located:a})=>a===null).map(({target:a})=>a).sort((a,o)=>a<o?-1:1);if(s.length>0&&e.allowUnresolved!==!0)throw new _(`Dependency target${s.length===1?"":"s"} not found: ${s.join(", ")}`,m.NOT_FOUND,{code:"dependency_target_not_found",reason:"unresolved_local_dependency",required:"Every local dependency target must exist before the edge is committed.",why:"Fail-fast target resolution prevents dangling graph nodes and preserves reliable traversal semantics.",unresolved_targets:s,examples:["--dep id=<existing-item-id>,kind=related","--dep id=<external-id>,kind=related,source_kind=external","--allow-unresolved-deps --dep id=<future-item-id>,kind=related"],nextSteps:[`Create or correct ${s.length===1?"the target":"the targets"}, then retry the mutation.`,"Use source_kind=external for a cross-workspace reference.","Use --allow-unresolved-deps only when the dangling local edge is intentional."],recovery:{recovery_mode:"compact",missing:s,suggested_flags:["--allow-unresolved-deps"],suggested_retry:`pm search "${s[0]}" --limit 10`}});return await Ux({dependencies:n,missingTargets:s,resolutions:r,holders:e.holders??[],registry:t,context:e}),s.map(a=>`dependency_target_unresolved:${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]="3950ef46-cc2b-5b8e-97d6-34c739bd816e")}catch{}})();var Ly="--event end must be strictly after start. Equal start/end timestamps are treated as an instant event (end is dropped); an end earlier than start is rejected. Omit end for an instant event or set end later than start.",jx="--event end and duration are mutually exclusive; provide only one (use duration=<relative> like duration=2h, duration=30min, or duration=PT30M, or set an explicit end).",Gx=/^([+-]?)(\d+)(min|mins|minute|minutes)$/i,qx=/^([+-]?)[Pp][Tt](?:(\d+)[Hh])?(?:(\d+)[Mm])?(?:(\d+)[Ss])?$/,Ny=1e3,Gc=60*Ny,Kx=60*Gc;function Dy(e,t){let n=new Date(e);if(!Number.isFinite(n.getTime()))throw new _(`Invalid event.duration value "${t}". Duration is out of supported timestamp range.`,m.USAGE);return n.toISOString()}function zx(e,t){let n=new Date(e),i=t.trim();if(/^[+-]?\d+m$/i.test(i))throw new _(`Event duration "${i}" is ambiguous. Use min for minutes or mo for months (for example 5min or 5mo).`,m.USAGE);let r=i.replace(/^([+-]?\d+)mo$/i,"$1m"),s=Gx.exec(i);if(s){let c=s[1]==="-"?-1:1,d=Number.parseInt(s[2],10)*c;return Dy(n.getTime()+d*Gc,i)}let a=qx.exec(i);if(a){let[,c,d,l,u]=a;if(d||l||u){let p=c==="-"?-1:1,g=Number.parseInt(d??"0",10),f=Number.parseInt(l??"0",10),h=Number.parseInt(u??"0",10),y=g*Kx+f*Gc+h*Ny;return Dy(n.getTime()+p*y,i)}}let o=r.startsWith("+")||r.startsWith("-")?r:`+${r}`;return ge(o,n,"event.duration")}function My(e,t,n,i){if(t&&n)throw new _(jx,m.USAGE);if(n){let s=zx(e,n);if(s<e)throw new _(Ly,m.USAGE);return s===e?void 0:s}if(!t)return;let r=ge(t,i,"event.end");if(r<e)throw new _(Ly,m.USAGE);if(r!==e)return r}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8288d6e7-a027-5bfa-9b4a-3c8b581f31ce")}catch{}})();var Wx=["at","date","text","title"],Bx=["start","date","end","duration","title","description","location","timezone","all_day",...xy],Hx=["key","value"];function Py(e,t){return t==="trimmed"?e?.trim():e}function Vx(e,t){return t==="defined"?e!==void 0:!!e}function Xs(e,t,n){return e.map(i=>{let r=Z(i,"--reminder");we(r,"--reminder",Wx);let s=Py(r.at??r.date,n.valueMode),a=Py(r.text??r.title,n.valueMode);if(!s||!a)throw new _("--reminder requires at=<iso|relative> or date=<iso|relative>, plus text=<value> or title=<value>",m.USAGE);let o=a.trim();if(!o)throw new _("--reminder text must not be empty",m.USAGE);return{at:ge(s,t,"reminder.at"),text:o}})}function Qs(e,t,n){return e.map(i=>{let r=Z(i,"--event");we(r,"--event",Bx);let s=(r.start??r.date)?.trim();if(!s)throw new _("--event requires start=<iso|relative> or date=<iso|relative>",m.USAGE);let a=ge(s,t,"event.start"),o=r.end?.trim(),c=r.duration?.trim(),d=My(a,o,c,t),l=r.title,u=r.description,p=r.location,g=r.timezone,f=l?.trim(),h=u?.trim(),y=p?.trim(),v=g?.trim(),w=[["title",l,f],["description",u,h],["location",p,y],["timezone",g,v]];for(let[C,b,E]of w)if(b!==void 0&&!E)throw new _(`--event ${C} must not be empty`,m.USAGE);let k=r.all_day?.trim(),S=Ry(r,a,t,n.recurrenceEmptyNumericGuard),A=Vx(k,n.allDayEmptyGuard)?Cy(k,"--event all_day"):void 0;return{start_at:a,end_at:d,title:f,description:h,location:y,all_day:A,timezone:v,recurrence:S}})}function Zs(e){let t={};for(let n of e){let i=n.trim();if(i.length===0)throw new _("--type-option values must not be empty",m.USAGE);let r,s;if(i.includes(",")||i.includes(`
|
|
10
|
-
`)||i.startsWith("```")||/^(?:[-*+]\s+)?(?:key|value)\s*[:=]/i.test(i)){let a=Z(i,"--type-option");we(a,"--type-option",Hx),r=a.key?.trim(),s=a.value?.trim()}else{let a=i.indexOf("="),o=i.indexOf(":"),c=a;if(a<=0&&o>0&&(c=o),c<=0||c===i.length-1)throw new _("--type-option requires key=value or key=<name>,value=<value> entries",m.USAGE);r=i.slice(0,c).trim(),s=i.slice(c+1).trim()}if(!r||!s)throw new _("--type-option requires key and value",m.USAGE);t[r]=s}return Object.fromEntries(Object.entries(t).sort((n,i)=>n[0].localeCompare(i[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]="2eb7f7bc-c23a-5ea2-a050-c81c2fa88456")}catch{}})();var Yx=["strict","progressive"],Jx=["lightweight"],jy=new Set(["Reminder","Meeting","Event"]),Xx=new Set(["author","created_at","text"]),Kc=[...Ay,{canonical:"author",aliases:["author"],optionKey:"author",metadataKey:"author"},...Hs],Qx=(()=>{let e=new Map;for(let t of Kc)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),ea=new Map(Kc.map(e=>[e.optionKey,e.canonical])),Zx=Kc.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", ");function eR(e,t){let n=me(e,t);if(!n){let i=t.definitions.map(r=>r.id);throw new _(`Invalid status value "${e}". Allowed: ${i.join(", ")}`,m.USAGE)}return n}function tR(e,t){let n=e.default_status;if(n!==void 0){let i=me(n,t);if(i)return i}return t.open_status}function qc(e,t){if(!e||e.trim()===""||e.trim().toLowerCase()==="now")return t;let n=Date.parse(e);if(!Number.isFinite(n))throw new _(`Invalid created_at timestamp "${e}"`,m.USAGE);return new Date(n).toISOString()}var nR=zs();function Gy(e){let t={...e,unset:e.unset?[...e.unset]:void 0},n=r=>{let s=t.unset?[...t.unset]:[];s.includes(r)||s.push(r),t.unset=s};Be(t.template)&&(t.template=void 0);let i=new Set([...ea.keys(),"rank"]);for(let r of i){let s=t[r];if(typeof s!="string"||!Be(s))continue;let a=r==="rank"?"order":ea.get(r)??r;n(a),t[r]=void 0}return Qe(e,Bs(t,nR))}function ke(e){if(e!==void 0)return e}function iR(e,t){return Vs({raw:e,supportedFields:Zx,resolveDefinition:n=>Qx.get(n)??Ys(n,"create",t)})}var Fy=["id","kind","type","author","created_at","source_kind"],ta=["path","scope","note"];function rR(e,t,n,i){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Re(e,"--dep","Use --clear-deps to clear dependencies."),{values:e.map(r=>{let s=r.trim(),a=na(s,Fy);Ai(s,a);let o=a?Z(r,"--dep"):{id:s,kind:"related"};a&&we(o,"--dep",Fy);let c=ke(o.id),d=sR(ke(o.kind??o.type));if(!c||!d)throw new _("--dep requires id and kind, or a bare item id to create a related dependency",m.USAGE);if(c.trim().toLowerCase()==="undefined")throw new _(`--dep id must not use placeholder token "${c}". Use --clear-deps to clear dependencies.`,m.USAGE);let l=Vn(ke(o.source_kind)),u=ke(o.author);return{id:Yn(c,n,l),kind:Ti(d),created_at:qc(o.created_at,t),author:u??i,source_kind:l??"cli:create:dep",author_source:u?"asserted":"detected"}}),explicitEmpty:!1})}function sR(e){return typeof e=="string"?ae().resolve(e)?.kind??e.trim():e}function na(e,t){return lr(e,t)?!0:cn(e)}function Xt(e,t,n,i){return!t||t.length===0?{values:void 0,explicitEmpty:!1}:(Re(t,e,e==="--comment"?"Use --clear-comments to clear comments.":e==="--note"?"Use --clear-notes to clear notes.":"Use --clear-learnings to clear learnings."),{values:t.map(r=>{let s=r.trim(),a=()=>{if(s.length===0)throw new _(`${e} requires text=<value>`,m.USAGE);return{created_at:n,author:i,text:s}},o;try{o=Z(r,e)}catch(d){if(e==="--comment"||e==="--note"||e==="--learning")return a();throw d}if(Object.keys(o).filter(d=>!Xx.has(d)).length>0)return{created_at:qc(o.created_at,n),author:ke(o.author)??i,text:s};let c=o.text??"";if(c==="")throw new _(`${e} requires text=<value>`,m.USAGE);return{created_at:qc(o.created_at,n),author:ke(o.author)??i,text:c}}),explicitEmpty:!1})}function zc(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Re(e,"--file","Use --clear-files to clear linked files."),{values:e.map(t=>{let n=t.trim(),i=na(n,ta);Wn(n,"--file","file path",i);let r=i?Z(t,"--file"):{path:n};if(i&&we(r,"--file",ta),!r.path)throw new _("--file requires path=<value> or a bare file path",m.USAGE);return{path:r.path,scope:He(r.scope??"project",Pe,"file scope"),note:ke(r.note)}}),explicitEmpty:!1})}function Wc(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Re(e,"--test","Use --clear-tests to clear linked tests."),{values:e.map(t=>{let n=t.trim(),i=na(n,Ge);Wn(n,"--test","test command",i);let r=i?_s(Z(t,"--test"),"--test"):{command:n},s=ke(r.command),a=ke(r.path);if(!s)throw new _("--test requires command=<value> or a bare command (path=<value> is optional metadata)",m.USAGE);let o=ke(r.timeout_seconds),c=ke(r.timeout);if(o&&c&&o!==c)throw new _("--test timeout and timeout_seconds must match when both are provided",m.USAGE);let d=o??c;return{command:s,path:a,scope:He(r.scope??"project",Pe,"test scope"),timeout_seconds:d?ye(d,"timeout_seconds"):void 0,pm_context_mode:Ls(r.pm_context_mode,"--test"),workspace_context_mode:Vt(r.workspace_context_mode,"--test"),env_set:Ei(r.env_set,"--test"),env_clear:Si(r.env_clear,"--test"),shared_host_safe:Os(r.shared_host_safe,"--test","shared_host_safe"),assert_stdout_contains:Yt(r.assert_stdout_contains),assert_stdout_regex:Cn(r.assert_stdout_regex,"--test","assert_stdout_regex"),assert_stderr_contains:Yt(r.assert_stderr_contains),assert_stderr_regex:Cn(r.assert_stderr_regex,"--test","assert_stderr_regex"),assert_stdout_min_lines:Ds(r.assert_stdout_min_lines,"--test"),assert_json_field_equals:Ns(r.assert_json_field_equals,"--test"),assert_json_field_gte:Ms(r.assert_json_field_gte,"--test"),note:ke(r.note)}}),explicitEmpty:!1})}function Bc(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Re(e,"--doc","Use --clear-docs to clear linked docs."),{values:e.map(t=>{let n=t.trim(),i=na(n,ta),r=i?Z(t,"--doc"):{path:n};if(i&&we(r,"--doc",ta),!r.path)throw new _("--doc requires path=<value> or a bare doc path",m.USAGE);return{path:r.path,scope:He(r.scope??"project",Pe,"doc scope"),note:ke(r.note)}}),explicitEmpty:!1})}function aR(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Re(e,"--reminder","Use --clear-reminders to clear reminders."),{values:Xs(e,new Date(t),{valueMode:"raw"}),explicitEmpty:!1})}function oR(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Re(e,"--event","Use --clear-events to clear linked events."),{values:Qs(e,new Date(t),{allDayEmptyGuard:"defined",recurrenceEmptyNumericGuard:"defined"}),explicitEmpty:!1})}function cR(e,t,n,i=[]){let r=[...Zd.filter(s=>e[s]!==void 0),...i.filter(s=>e[s]!==void 0),...t.length>0?["body"]:[],...n.map(s=>`unset:${s}`)];return Array.from(new Set(r))}function dR(e,t){let n=e??"";if(t.length===0)return n;let i=`explicit_unset=${t.join(",")}`;return n?`${n} | ${i}`:i}function $y(e,t,n){let i=Fn("create",e);if(!i)throw new _(`Unsupported ${n} entry "${e}" for type "${t}"`,m.CONFLICT);return i}function lR(e){return{scalarValues:{title:e.title,description:e.description,type:e.type,status:e.status,priority:e.priority,tags:e.tags,body:e.body,deadline:e.deadline,estimatedMinutes:e.estimatedMinutes,acceptanceCriteria:e.acceptanceCriteria,definitionOfReady:e.definitionOfReady,order:e.order??e.rank,goal:e.goal,objective:e.objective,value:e.value,impact:e.impact,outcome:e.outcome,whyNow:e.whyNow,author:e.author,message:e.message,assignee:e.assignee,parent:e.parent,reviewer:e.reviewer,risk:e.risk,confidence:e.confidence,sprint:e.sprint,release:e.release,blockedBy:e.blockedBy,blockedReason:e.blockedReason,unblockNote:e.unblockNote,reporter:e.reporter,severity:e.severity,environment:e.environment,reproSteps:e.reproSteps,resolution:e.resolution,expectedResult:e.expectedResult,actualResult:e.actualResult,affectedVersion:e.affectedVersion,fixedVersion:e.fixedVersion,component:e.component,regression:e.regression,customerImpact:e.customerImpact},repeatableValues:{dep:e.dep,comment:e.comment,note:e.note,learning:e.learning,file:e.file,test:e.test,doc:e.doc,reminder:e.reminder,event:e.event,typeOption:e.typeOption,field:e.field},addTags:e.addTags}}function qy(e,t){if(t==="tags")return e.scalarValues.tags!==void 0||Array.isArray(e.addTags)&&e.addTags.length>0;if(Object.prototype.hasOwnProperty.call(e.scalarValues,t))return e.scalarValues[t]!==void 0;if(Object.prototype.hasOwnProperty.call(e.repeatableValues,t)){let n=e.repeatableValues[t];return Array.isArray(n)&&n.length>0}return!1}function uR(e,t){let n=new Set(["title","type"]);if(t!=="strict")return n;for(let i of e.required_create_fields)n.add($y(i,e.name,"required_create_fields"));for(let i of e.required_create_repeatables)n.add($y(i,e.name,"required_create_repeatables"));return n}function mR(e,t,n,i){for(let r of e)if(!(!qy(t,r)&&!n.has(r)))throw new _(`Option ${Te("create",r)} is disabled for type "${i}" by command_option_policies`,m.USAGE)}function _R(e,t,n){if(t!=="strict")return;let i=e.filter(s=>n.has(s)&&!Fc(s));if(i.length===0)return;let r=[...new Set(i.map(s=>Te("create",s)))].sort((s,a)=>s.localeCompare(a));throw new _(`Strict create mode requires concrete values for ${r.join(", ")}; --unset/--clear-* directives cannot satisfy required options`,m.USAGE)}function pR(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Re(e,"--type-option","Use --clear-type-options to clear existing type options."),{values:Zs(e),explicitEmpty:!1})}async function fR(e){return await pr(e,[["body","--body"],["description","--description"]],[["dep","--dep"],["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"],["field","--field"]])}async function gR(e){return Ft(e)?await fR(e):e}function hR(e,t){if(e===void 0)return t;let n=e.trim().toLowerCase();if(n.length===0)return t;if(n==="strict"||n==="progressive")return n;throw new _(`Invalid --create-mode value "${e}". Allowed: ${Yx.join(", ")}`,m.USAGE)}function yR(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)throw new _("--schedule-preset must not be empty",m.USAGE);if(t==="lightweight"||t==="lite"||t==="schedule-lite")return"lightweight";throw new _(`Invalid --schedule-preset value "${e}". Allowed: ${Jx.join(", ")}`,m.USAGE)}function vR(e,t,n){let i=hR(e,n);if(t===void 0)return i;if(typeof e=="string"&&e.trim().length>0&&i==="strict")throw new _("--schedule-preset lightweight cannot be combined with --create-mode strict. Use --create-mode progressive or omit --create-mode.",m.USAGE);return"progressive"}function wR(e,t,n,i,r){let s=e.name,a=lR(t),o=uR(e,n),c=nn(e,"create",o);if(c.errors.length>0)throw new _(c.errors.join("; "),m.CONFLICT);mR(c.disabled,a,i,s),_R(c.required,n,i);let d=u=>u==="author"&&r!=="unknown"||u==="status"&&e.default_status!==void 0||i.has(u)&&Fc(u)?!0:qy(a,u),l=c.required.filter(u=>!d(u));return[...new Set(l.map(u=>Te("create",u)))].sort((u,p)=>u.localeCompare(p))}var Ky=/^Missing required type option "([^"]+)" for type "([^"]+)"$/;function bR(e,t){let n=[];for(let i of e){let r=i.match(Ky);r&&r[2]===t&&n.push(r[1])}return[...new Set(n)].sort((i,r)=>i.localeCompare(r))}function kR(e,t){return e.filter(n=>{let i=n.match(Ky);return!i||i[2]!==t})}function ER(e,t,n,i){let r=kR(e,t);if(r.length===0)return;let s=zy(n,[],[],i.open_status);throw new _(r.join("; "),m.USAGE,{code:"invalid_argument_value",required:`Provide valid --type-option key/value pairs for type "${t}".`,examples:[s],nextSteps:[`Run "pm create --help --type ${t}" to review allowed type-option keys and values.`]})}function SR(e,t){let n=e.options.find(i=>i.key===t)?.values[0];return typeof n=="string"&&n.trim().length>0?n:"<value>"}function TR(e,t,n){let i=e.split("/")[0];switch(i){case"--title":return["--title",`"${t} example title"`];case"--description":return["--description",`"${t} example description"`];case"--type":return["--type",t];case"--status":return["--status",n];case"--priority":return["--priority","1"];case"--message":return["--message",`"Create ${t} item"`];case"--comment":return["--comment",'"author=maintainer,created_at=now,text=Implementation context"'];default:return[i,'"<value>"']}}function zy(e,t,n,i){let r=["pm","create","--title",`"${e.name} example title"`,"--description",`"${e.name} example description"`,"--type",e.name],s=["--status","--priority","--message"],a=[...new Set([...s,...t])],o=new Set(["--title","--description","--type"]);for(let c of a){if(o.has(c))continue;let d=By[c];r.push(...d?[d]:TR(c,e.name,i)),o.add(c)}for(let c of n){let d=SR(e,c);r.push("--type-option",`${c}=${d}`)}return r.join(" ")}function Hc(e,t){let n=e?.trim();if(!n)throw t==="--title"?e!==void 0?new _("Title cannot be empty or whitespace-only. Retry: pass a non-empty title with --title.",m.USAGE):new _('Missing required option --title. Why required: every item needs a human-readable title for lookup, search, and reporting. Retry: pass the title as the first positional argument (example: pm create "Fix login bug" --type Issue) or with --title.',m.USAGE):new _(`Missing required option ${t}`,m.USAGE);return n}function AR(e,t){let n={};for(let[i,r]of Object.entries(e))n[i]=Array.isArray(r)?[...r]:r;for(let[i,r]of Object.entries(t))r!==void 0&&(n[i]=Array.isArray(r)?[...r]:r);return n}function IR(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function CR(){let e=P();return e?e.commands.some(t=>t.action==="templates-show"||IR(t.command)==="templates show"):!1}function xR(e,t){if(typeof e!="object"||e===null||!("options"in e))throw new _(`Templates package returned invalid payload for template "${t}". Expected an options object.`,m.GENERIC_FAILURE);let n=e.options;if(typeof n!="object"||n===null||Array.isArray(n))throw new _(`Templates package returned invalid options for template "${t}".`,m.GENERIC_FAILURE);let i={};for(let[r,s]of Object.entries(n)){if(typeof s=="string"||typeof s=="number"||typeof s=="boolean"){i[r]=s;continue}if(Array.isArray(s)&&s.every(a=>typeof a=="string")){i[r]=[...s];continue}throw new _(`Templates package returned unsupported option value for "${r}" in template "${t}".`,m.GENERIC_FAILURE)}return i}async function RR(e,t,n){if(!CR())throw new _("--template requires the templates package. Install it first (for example: pm install templates --project).",m.USAGE);let i=await zl({command:"templates show",args:[e],options:{},global:t,pm_root:n});if(!i.handled){let r=i.warnings.length>0?` (${i.warnings.join(", ")})`:"";throw new _(`Unable to resolve template "${e}" via templates package. Run "pm templates show ${e}" for details.${r}`,m.USAGE)}return xR(i.result,e)}function J(e,t,n){return e.has(t)||n===void 0?void 0:ke(n)}function Jt(e,t,n,i){return e.has(t)||n===void 0?void 0:i(n)}var OR=new Set(["milestone","meeting","reminder","event"]);function Wy(e,t,n,i){let r=t!==void 0,s=n!==void 0&&n.length>0,a=i!==void 0&&i.length>0;return OR.has(e.toLowerCase())&&!r&&!s&&!a}function LR(e,t,n,i,r){let s=[];return e.toLowerCase()==="event"&&(r===void 0||r.length===0)&&s.push(`event_without_schedule:${t}:no_time_set`),Wy(e,n,i,r)&&s.push(`calendar_item_without_schedule:${t}:no_deadline_or_reminder_or_event (hint: set --deadline <ISO> or --reminder "<when>", or link an Event via --event "start=<ISO>,end=<ISO>"; otherwise this item never appears on pm calendar)`),s}async function DR(e,t,n,i){if(e!==void 0||n.has("parent")||t.parent!==void 0)return{parent:e,parentSource:void 0};let r=await cu(i);return r===void 0?{parent:e,parentSource:void 0}:{parent:r,parentSource:"focus"}}async function NR(e,t,n,i,r,s){let a=Cr(gr(r),t.id_prefix);if(Sr(a))return{parent:a,warnings:[]};if(yr(i,a,t.id_prefix),await Y(e,a,t.id_prefix,t.item_format,n.type_to_folder))return{parent:a,warnings:[]};let o=kt(a,t.id_prefix);return{parent:a,warnings:hr(o,s).warnings}}async function MR(e){return e.parent===void 0?{parent:void 0,warnings:[]}:await NR(e.pmRoot,e.settings,e.typeRegistry,e.itemId,e.parent,e.policy)}async function PR(e){if(e.explicitId===void 0)return hu(e.pmRoot,e.settings.id_prefix,{tokenLength:e.settings.ids.token_length,typeToFolder:e.typeRegistry.type_to_folder,probeExisting:!1});if(typeof e.explicitId!="string")throw new _("--id must be a string",m.USAGE);let t=e.explicitId.trim();if(t.length===0||d_(t))throw new _("--id must not be empty or use a placeholder token",m.USAGE);let n=kt(t,e.settings.id_prefix);if(!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(n))throw new _("--id must contain only letters, numbers, and dashes after normalization",m.USAGE);return n}function Uy(e,t,n,i,r){let s=J(e,t,n);if(s===void 0)return{value:void 0,warnings:[]};let a=wr(i,s,r);return{value:a.value,warnings:a.warnings}}async function FR(e){let{pmRoot:t,settings:n,typeRegistry:i,statusRegistry:r,blockedBy:s,status:a,statusExplicit:o,nowValue:c,author:d}=e,l=e.dependencyValues;if(s===void 0)return{dependencyValues:l,status:a};let u=kt(s,n.id_prefix),p=await Y(t,u,n.id_prefix,n.item_format,i.type_to_folder);if(!p)return{dependencyValues:l,status:a};if((l??[]).some(f=>f.id===p.id&&f.kind==="blocked_by")||(l=[...l??[],{id:p.id,kind:"blocked_by",created_at:c,author:d,source_kind:"cli:create:blocked_by",author_source:"detected"}]),o)return{dependencyValues:l,status:a};let g=r.blocked_statuses.has("blocked")?"blocked":[...r.blocked_statuses].sort((f,h)=>f.localeCompare(h))[0]??r.open_status;return{dependencyValues:l,status:g}}function $R(e,t,n){if(typeof e.createMode=="string"&&e.createMode.trim().toLowerCase()==="strict")return;let i=t.governance.create_default_type?.trim();if(i&&i.length>0&&st(i,n)){e.type=i;return}st("Task",n)&&(e.type="Task")}function UR(e,t){return e.options.filter(n=>Fn("create",n.key)===void 0).flatMap(n=>{let i=t[n.key];if(i===void 0)return[];if(typeof i=="string"||typeof i=="number"||typeof i=="boolean")return[n];throw new _(`Template custom type option "${n.key}" must be a string, number, or boolean value`,m.USAGE)})}async function jR(e,t,n,i,r){let s=e,a=[];if(s.template!==void 0){let f=s.template.trim();if(f.length===0)throw new _("--template must not be empty. Omit --template to disable template usage.",m.USAGE);let h=await RR(f,t,n);s=Gy(AR(h,s))}if(s.type===void 0&&$R(s,i,r),s.type===void 0)throw new _("Missing required option --type <value>",m.USAGE);let o=st(s.type,r);if(!o){let f=l_(s.type),h=f?st(f,r):void 0;if(h)a.push(`type_coercion:${s.type.trim()}:${h}`),s.type=h,o=h;else throw new _(br(s.type,r.types,Qi(n,i.schema)),m.USAGE)}let c=Hi(o,r);if(!c)throw new _(`Invalid type value "${s.type}"`,m.USAGE);let d=c.name,l=UR(c,s),u=l.map(f=>`${f.key}=${String(s[f.key])}`);if(u.length>0){s.typeOption=[...u,...s.typeOption??[]];for(let f of l)delete s[f.key]}let p=yR(s.schedulePreset);if(p!==void 0&&!jy.has(d))throw new _(`--schedule-preset ${p} is only supported for Reminder, Meeting, or Event types`,m.USAGE);let g=vR(s.createMode,p,i.governance.create_mode_default);return{resolvedOptions:s,typeDefinition:c,type:d,schedulePreset:p,createMode:g,warnings:a}}function GR(e,t){let n=new Set(t.metadataKeys),i=new Set(t.optionKeys),r=[{enabled:e.clearDeps,optionKey:"dep",clearFlag:"--clear-deps",valueFlag:"--dep",values:e.dep,metadataKey:"dependencies"},{enabled:e.clearComments,optionKey:"comment",clearFlag:"--clear-comments",valueFlag:"--comment",values:e.comment,metadataKey:"comments"},{enabled:e.clearNotes,optionKey:"note",clearFlag:"--clear-notes",valueFlag:"--note",values:e.note,metadataKey:"notes"},{enabled:e.clearLearnings,optionKey:"learning",clearFlag:"--clear-learnings",valueFlag:"--learning",values:e.learning,metadataKey:"learnings"},{enabled:e.clearFiles,optionKey:"file",clearFlag:"--clear-files",valueFlag:"--file",values:e.file,metadataKey:"files"},{enabled:e.clearTests,optionKey:"test",clearFlag:"--clear-tests",valueFlag:"--test",values:e.test,metadataKey:"tests"},{enabled:e.clearDocs,optionKey:"doc",clearFlag:"--clear-docs",valueFlag:"--doc",values:e.doc,metadataKey:"docs"},{enabled:e.clearReminders,optionKey:"reminder",clearFlag:"--clear-reminders",valueFlag:"--reminder",values:e.reminder,metadataKey:"reminders"},{enabled:e.clearEvents,optionKey:"event",clearFlag:"--clear-events",valueFlag:"--event",values:e.event,metadataKey:"events"},{enabled:e.clearTypeOptions,optionKey:"typeOption",clearFlag:"--clear-type-options",valueFlag:"--type-option",values:e.typeOption,metadataKey:"type_options"}];for(let s of r)if(s.enabled){if(s.values&&s.values.length>0)throw new _(`Cannot combine ${s.clearFlag} with ${s.valueFlag}`,m.USAGE);n.add(s.metadataKey),i.add(s.optionKey)}return{explicitUnsets:n,clearOptionKeys:i}}function qR(e,t){let n={tags:e.tags!==void 0,deadline:e.deadline!==void 0,estimatedMinutes:e.estimatedMinutes!==void 0,acceptanceCriteria:e.acceptanceCriteria!==void 0,definitionOfReady:e.definitionOfReady!==void 0,order:e.order!==void 0||e.rank!==void 0,goal:e.goal!==void 0,objective:e.objective!==void 0,value:e.value!==void 0,impact:e.impact!==void 0,outcome:e.outcome!==void 0,whyNow:e.whyNow!==void 0,author:e.author!==void 0,assignee:e.assignee!==void 0,parent:e.parent!==void 0,reviewer:e.reviewer!==void 0,risk:e.risk!==void 0,confidence:e.confidence!==void 0,sprint:e.sprint!==void 0,release:e.release!==void 0,blockedBy:e.blockedBy!==void 0,blockedReason:e.blockedReason!==void 0,unblockNote:e.unblockNote!==void 0,reporter:e.reporter!==void 0,severity:e.severity!==void 0,environment:e.environment!==void 0,reproSteps:e.reproSteps!==void 0,resolution:e.resolution!==void 0,expectedResult:e.expectedResult!==void 0,actualResult:e.actualResult!==void 0,affectedVersion:e.affectedVersion!==void 0,fixedVersion:e.fixedVersion!==void 0,component:e.component!==void 0,regression:e.regression!==void 0,customerImpact:e.customerImpact!==void 0};for(let[i,r]of Object.entries(n)){if(!r||!t.optionKeys.has(i))continue;let s=ea.get(i)??i;throw new _(`Cannot combine --unset ${s} with ${Te("create",i)}`,m.USAGE)}}function KR(e){let t=(n,i)=>{let r=ea.get(i),s=r?`Use --unset ${r} to clear this field.`:void 0;Ws(n,Te("create",i),s)};t(e.tags,"tags"),t(e.deadline,"deadline"),t(e.estimatedMinutes,"estimatedMinutes"),t(e.acceptanceCriteria,"acceptanceCriteria"),t(e.definitionOfReady,"definitionOfReady"),t(e.order??e.rank,"order"),t(e.goal,"goal"),t(e.objective,"objective"),t(e.value,"value"),t(e.impact,"impact"),t(e.outcome,"outcome"),t(e.whyNow,"whyNow"),t(e.author,"author"),t(e.assignee,"assignee"),t(e.parent,"parent"),t(e.reviewer,"reviewer"),t(e.risk,"risk"),t(e.confidence,"confidence"),t(e.sprint,"sprint"),t(e.release,"release"),t(e.blockedBy,"blockedBy"),t(e.blockedReason,"blockedReason"),t(e.unblockNote,"unblockNote"),t(e.reporter,"reporter"),t(e.severity,"severity"),t(e.environment,"environment"),t(e.reproSteps,"reproSteps"),t(e.resolution,"resolution"),t(e.expectedResult,"expectedResult"),t(e.actualResult,"actualResult"),t(e.affectedVersion,"affectedVersion"),t(e.fixedVersion,"fixedVersion"),t(e.component,"component"),t(e.regression,"regression"),t(e.customerImpact,"customerImpact")}function zR(e,t,n){for(let i of Object.keys(e))if(n.metadataKeys.has(i))throw new _(`Cannot combine --unset ${i.replaceAll("_","-")} with --field ${i}=...`,m.USAGE);for(let i of Object.keys(t.values??{}))if(n.metadataKeys.has(i))throw new _(`Cannot combine --unset ${i.replaceAll("_","-")} with its value flag`,m.USAGE)}var By={"--comment":"--clear-comments","--dep":"--clear-deps","--doc":"--clear-docs","--event":"--clear-events","--file":"--clear-files","--learning":"--clear-learnings","--note":"--clear-notes","--reminder":"--clear-reminders","--test":"--clear-tests","--type-option":"--clear-type-options"};function WR(e){let{combinedMissingFlags:t,typeDefinition:n,missingRequiredCreateFlags:i,missingRequiredTypeOptionKeys:r,openStatus:s,type:a,createMode:o,missingRequiredRuntimeFields:c}=e;if(t.length===0)return;let d=c.map(f=>{let h=f.type==="boolean"?"<true|false>":f.type==="array"?"<json-array>":f.type==="object"?"<json-object>":f.type==="number"?"<number>":f.type==="string_array"||f.repeatable?"<value>":"<string>";return{example:`--${f.cli_flag} ${h}`,description:`--${f.cli_flag} maps to ${f.metadata_key} (${f.type}${f.repeatable?", repeatable":""})`}}),l=[zy(n,i,r,s),...d.map(f=>f.example)].join(" "),u=[`Run "pm create --help --type ${a}" for type-aware required option guidance.`,...t.filter(f=>f==="--title").map(()=>'Title can also be passed as the first positional argument (example: pm create "Your title" --type '+a+").")];o==="strict"&&(u.push('For staged onboarding, retry with "--create-mode progressive".'),jy.has(a)&&u.push('For minimal scheduling inputs, try "--schedule-preset lightweight".')),d.length>0&&u.push(`Required custom field formats: ${d.map(f=>f.description).join("; ")}.`);let p=[...new Set(t.flatMap(f=>{let h=f.split(" ",1)[0],y=By[h];return y?[y]:[]}))];p.length>0&&u.push(`If the truthful value is an empty collection, use ${p.join(", ")} instead of inventing metadata.`);let g=t.length===1?`Missing required option ${t[0]} for type "${a}"`:`Missing required options ${t.join(", ")} for type "${a}"`;throw new _(g,m.USAGE,{code:"missing_required_option",required:`Provide all required create options and type options for type "${a}" in one invocation.`,examples:[...p.map(f=>`pm create --type ${a} ${f} ...`),l],nextSteps:u,recovery:o==="strict"?{recovery_mode:"compact",missing_required_fields:t,suggested_flags:[...p,...t,"--create-mode progressive"]}:void 0})}function BR(e,t){if(e.has("tags")&&Array.isArray(t.addTags)&&t.addTags.length>0)throw new _("Cannot combine --unset tags with --add-tags",m.USAGE);let n=e.has("tags")?[]:t.tags!==void 0?ur(t.tags):[];return _r(n,t.addTags)}function HR(e,t){if(t.order!==void 0&&t.rank!==void 0&&t.order!==t.rank)throw new _("--order and --rank must match when both are provided",m.USAGE);let n=t.order??t.rank,i=Jt(e,"order",n,r=>ye(r,"order"));if(i!==void 0&&!Number.isInteger(i))throw new _("Order must be an integer",m.USAGE);return i}function VR(e,t,n,i,r,s){if(i.completedAt!==void 0&&e!==t.close_status)throw new _("--completed-at requires a terminal create status.",m.USAGE);let a=e!==t.close_status?void 0:i.completedAt===void 0?s:ge(i.completedAt,new Date(s),"completed-at");if(e!==t.close_status)return{closeReason:void 0,completedAt:a,warnings:[]};let o=n.governance.require_close_reason?{explicit:i.closeReason??i.message,resolution:r}:{explicit:i.closeReason};return{closeReason:Pc(o,n.governance.require_close_reason,{operation:"create",status:e}).closeReason,completedAt:a,warnings:[]}}async function YR(e){let{pmRoot:t,type:n,id:i,settings:r,typeRegistry:s,author:a,extensionFieldNames:o,afterDocument:c,beforeDocument:d,historyMessage:l,changedFields:u,nowValue:p,similarityCandidate:g,allowDuplicate:f}=e,h=fl(t,n,i,r.item_format,s.type_to_folder),y=at(t,i),v=ae(),w=c.metadata.parent!==void 0||(c.metadata.dependencies??[]).some(C=>As(C.kind,v)),k=await $s({pmRoot:t,author:a,ttlSeconds:r.locks.ttl_seconds,waitMs:r.locks.wait_ms,required:w}),S=w,A=[];try{let C=await bt(t,i,r.locks.ttl_seconds,a,!1,r.governance.force_required_for_stale_lock,r.locks.wait_ms);try{let b=c.metadata.parent!==void 0||c.metadata.dependencies!==void 0&&c.metadata.dependencies.length>0?await Se(t,r.item_format,s.type_to_folder,void 0,r.schema):void 0,E=await Y(t,i,r.id_prefix,r.item_format,s.type_to_folder);if(E)throw new _(`Item "${i}" already exists`,m.CONFLICT,{code:"item_already_exists",id:E.id,path:E.itemPath,required:"Read the existing item before deciding whether to update it or create a different ID.",nextSteps:[`Inspect the existing item with pm get ${E.id}.`]});if(b){Is(b,[...b,c.metadata],v);let G=K(r.schema);Rr(b,[...b,c.metadata],i,pe=>_e(pe,G),v)}let N=await yu({pmRoot:t,settings:r,operation:"create",author:a,before:null,after:c});await Gl({pm_root:t,operation:"create",before:null,after:c,changed_fields:u,sdk:Eu({pmRoot:t,settings:r,typeToFolder:s.type_to_folder})});let T=await bu(t,a,{required:r.governance.duplicate_detection_mode==="strict"&&f!==!0}),R=[];try{r.governance.duplicate_detection_mode==="strict"&&f!==!0&&await qo(g,{pmRoot:t,mode:"strict",threshold:r.governance.duplicate_detection_threshold,limit:r.governance.duplicate_detection_limit,allowDuplicate:!1}),await Oe(h,au(c,{format:r.item_format,schema:r.schema,extensionFieldNames:o}));try{let G=lu({nowIso:p,author:a,op:"create",before:d,after:c,message:l,context:N.decisions.length===0?void 0:{workflow_policies:N.decisions}});await uu(y,G)}catch(G){throw await rl(h),G}S&&(await k(),S=!1),R=await ku({pmRoot:t,preferredFormat:r.item_format,typeToFolder:s.type_to_folder,schema:r.schema,itemPath:h,document:c})}finally{await T()}A=[...N.warnings,...b?Ts(b,[...b,c.metadata],i):[],...R,...await ot({path:h,scope:"project",op:"create",item_id:c.metadata.id,item_type:c.metadata.type,before:d,after:c,changed_fields:u}),...await ot({path:y,scope:"project",op:"create:history",item_id:c.metadata.id,item_type:c.metadata.type,before:d,after:c,changed_fields:u})],Ul({id:c.metadata.id,op:"create",item_type:c.metadata.type,status:c.metadata.status,current:jl(c.metadata,u),changed_fields:u})}finally{await C()}}finally{S&&await k()}return A}async function zW(e,t){let n=Gy(await gR(e)),i=x(process.cwd(),t.path);await $(i);let r=await I(i),s=K(r.schema),a=rn(r.schema),o=F(r,P()),c=await jR(n,t,i,r,o);n=c.resolvedOptions;let{typeDefinition:d,type:l,createMode:u}=c,p=iR(n.unset,a),{explicitUnsets:g,clearOptionKeys:f}=GR(n,p);qR(n,p),KR(n);let h=U(ke(n.author),r.author_default),y=wR(d,n,u,f,h),v=O(),w=rR(n.dep,v,r.id_prefix,h),k=Xt("--comment",n.comment,v,h),S=Xt("--note",n.note,v,h),A=Xt("--learning",n.learning,v,h),C=zc(n.file),b=Wc(n.test);b.values=await Tn(b.values,h,v);let E=Bc(n.doc),N=aR(n.reminder,v),T=oR(n.event,v),R=pR(n.typeOption),G=$n(l,R.values,o),pe=P(),ce=Et(pe),de=ir(n.field,pe,Ks),ue=nu(n,a,l),tn=new Set(ue.missing_required_flags),Pn=a.definitions.filter(X=>tn.has(`--${X.cli_flag}`));zR(de,ue,p);let it=bR(G.errors,l),Ne=it.map(X=>`--type-option ${X}=<value>`),ht=[...new Set([...y,...Ne,...ue.missing_required_flags])].sort((X,La)=>X.localeCompare(La));WR({combinedMissingFlags:ht,typeDefinition:d,missingRequiredCreateFlags:y,missingRequiredTypeOptionKeys:it,openStatus:s.open_status,type:l,createMode:u,missingRequiredRuntimeFields:Pn}),ER(G.errors,l,d,s);let Ee=await PR({pmRoot:i,settings:r,typeRegistry:o,explicitId:n.id}),Me=n.status!==void 0?eR(n.status,s):tR(d,s),yt=n.priority!==void 0?vr(n.priority):2,D=p.metadataKeys,rt=BR(D,n),vt=Jt(D,"deadline",n.deadline,X=>ge(X,new Date(v),"deadline")),V=Jt(D,"estimated_minutes",n.estimatedMinutes,X=>fr(X,"estimated-minutes")),Ta=J(D,"acceptance_criteria",n.acceptanceCriteria),Ve=J(D,"definition_of_ready",n.definitionOfReady),Aa=HR(D,n),Ui=J(D,"goal",n.goal),db=J(D,"objective",n.objective),lb=J(D,"value",n.value),ub=J(D,"impact",n.impact),mb=J(D,"outcome",n.outcome),_b=J(D,"why_now",n.whyNow),pb=J(D,"assignee",n.assignee),fb=D.has("author")?void 0:ke(n.author)??h,gb=J(D,"parent",n.parent),Fd=await DR(gb,n,D,i),Ia=Fd.parent,hb=Fd.parentSource,yb=J(D,"reviewer",n.reviewer),vb=Jt(D,"risk",n.risk,X=>He(Us(X),Wi,"risk")),wb=Jt(D,"confidence",n.confidence,X=>Gs(X)),bb=n.allowMissingParent===!0&&r.validation.parent_reference==="strict_error"?"warn":r.validation.parent_reference,$d=r.validation.sprint_release_format,Rt=[...c.warnings,...LR(l,Ee,vt,N.values,T.values)],Ud=await MR({itemId:Ee,parent:Ia,pmRoot:i,settings:r,typeRegistry:o,policy:bb});Ia=Ud.parent,Rt.push(...Ud.warnings);let jd=Uy(D,"sprint",n.sprint,"sprint",$d),kb=jd.value;Rt.push(...jd.warnings);let Gd=Uy(D,"release",n.release,"release",$d),Eb=Gd.value;Rt.push(...Gd.warnings);let qd=J(D,"blocked_by",n.blockedBy),Kd=await FR({pmRoot:i,settings:r,typeRegistry:o,statusRegistry:s,blockedBy:qd,dependencyValues:w.values,status:Me,statusExplicit:n.status!==void 0,nowValue:v,author:h}),Ca=Kd.dependencyValues;Ii(Ee,Ca),Rt.push(...await Js({pmRoot:i,dependencies:Ca,idPrefix:r.id_prefix,itemFormat:r.item_format,typeToFolder:o.type_to_folder,allowUnresolved:n.allowUnresolvedDeps,holders:[{id:Ee,createdAt:v}],schema:r.schema})),Me=Kd.status;let Sb=J(D,"blocked_reason",n.blockedReason),Tb=J(D,"unblock_note",n.unblockNote),Ab=J(D,"reporter",n.reporter),Ib=Jt(D,"severity",n.severity,X=>He(js(X),Bi,"severity")),Cb=J(D,"environment",n.environment),xb=J(D,"repro_steps",n.reproSteps),zd=J(D,"resolution",n.resolution),Rb=J(D,"expected_result",n.expectedResult),Ob=J(D,"actual_result",n.actualResult),Lb=J(D,"affected_version",n.affectedVersion),Db=J(D,"fixed_version",n.fixedVersion),Nb=J(D,"component",n.component),Mb=Jt(D,"regression",n.regression,X=>qs(X)),Pb=J(D,"customer_impact",n.customerImpact),xa=Hc(n.title,"--title"),Ra=n.description??"",ji=n.body??"",Wd=await qo({title:xa,description:Ra,body:ji},{pmRoot:i,mode:r.governance.duplicate_detection_mode,threshold:r.governance.duplicate_detection_threshold,limit:r.governance.duplicate_detection_limit,allowDuplicate:n.allowDuplicate});Rt.push(...Gf(Wd));let Oa=VR(Me,s,r,n,zd,v),Fb=Oa.closeReason,$b=Me===s.close_status?v:void 0,Ub=Oa.completedAt;Rt.push(...Oa.warnings);let Gi=su({id:Ee,title:xa,description:Ra,type:l,type_options:G.normalized,status:Me,closed_at:$b,completed_at:Ub,close_reason:Fb,priority:yt,tags:rt,created_at:v,updated_at:v,deadline:vt,assignee:pb,author:fb,estimated_minutes:V,acceptance_criteria:Ta,definition_of_ready:Ve,order:Aa,goal:Ui,objective:db,value:lb,impact:ub,outcome:mb,why_now:_b,parent:Ia,reviewer:yb,risk:vb,confidence:wb,sprint:kb,release:Eb,blocked_by:qd,blocked_reason:Sb,unblock_note:Tb,reporter:Ab,severity:Ib,environment:Cb,repro_steps:xb,resolution:zd,expected_result:Rb,actual_result:Ob,affected_version:Lb,fixed_version:Db,component:Nb,regression:Mb,customer_impact:Pb,dependencies:Ca,comments:k.values,notes:S.values,learnings:A.values,files:C.values,tests:b.values,docs:E.values,reminders:N.values,events:T.values,...de,...ue.values});try{rr(Gi,pe)}catch(X){throw new _(X instanceof Error?X.message:"Invalid extension item field values",m.USAGE)}let jb=ou({metadata:Gi,body:ji},{schema:r.schema,extensionFieldNames:ce}),Gb={metadata:{},body:""},Bd=[...g].sort((X,La)=>X.localeCompare(La)),qb=dR(n.message,Bd),Hd=cR(Gi,ji,Bd,[...Object.keys(de),...Object.keys(ue.values??{})]),Kb=await YR({pmRoot:i,type:l,id:Ee,settings:r,typeRegistry:o,author:h,extensionFieldNames:ce,afterDocument:jb,beforeDocument:Gb,historyMessage:qb,changedFields:Hd,nowValue:v,similarityCandidate:{title:xa,description:Ra,body:ji},allowDuplicate:n.allowDuplicate}),Vd=structuredClone(Gi);u==="strict"&&g.has("dependencies")&&(Vd.dependencies=[]);let zb=Ty(Ee,l,Me,s);return Wy(l,vt,N.values,T.values)&&eu(`[pm] warning: ${l} '${Ee}' has no deadline/reminder/event \u2014 it will not appear on the calendar. Add one via 'pm update ${Ee} --deadline <ISO>' or 'pm update ${Ee} --event "start=<ISO>,end=<ISO>"'.`),{item:Vd,changed_fields:Hd,warnings:[...Rt,...Kb],...Object.fromEntries([["parent_source",hb],["next_transition",zb],["similarity_advisory",Wd]].filter(X=>X[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]="961c1918-75f9-5e5d-bbae-b333ca29534f")}catch{}})();function Hy(e){return Ke("in_progress",e)??e.open_status}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4790c318-c305-53d4-895c-e9ac90665376")}catch{}})();function ia(e){if(e.enforcement==="off"||e.typeWorkflows.length===0)return;let t=u_({typeName:e.typeName,fromStatus:e.fromStatus,toStatus:e.toStatus,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry});if(!t.hasRule||t.allowed)return;let n=Ke(e.fromStatus,e.statusRegistry)??e.fromStatus,i=Ke(e.toStatus,e.statusRegistry)??e.toStatus,r=`Disallowed transition for type "${e.typeName}": ${n} -> ${i}. Allowed transitions: ${m_(t.allowedTransitions)}.`;if(e.enforcement==="strict")throw new _(r,m.USAGE);return`workflow_transition_not_allowed: ${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]="f93d880f-109a-51b7-8572-d03841e35803")}catch{}})();var Xc=[...$c,{canonical:"close-reason",aliases:["close_reason","close-reason"],optionKey:"closeReason",metadataKey:"close_reason"},...Uc,...Hs],JR=(()=>{let e=new Map;for(let t of Xc)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),ra=new Map(Xc.map(e=>[e.optionKey,e.canonical])),XR=Xc.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", "),QR=new Set(["close_reason","assignee","parent","blocked_by","blocked_reason","unblock_note","dependencies","comments","notes","learnings","files","tests","docs","reminders","events"]),ZR=zs({depDisableFlagKey:"replaceDeps",fileDisableFlagKey:"replaceFiles",testDisableFlagKey:"replaceTests",docDisableFlagKey:"replaceDocs"});function tv(e){let t={...e,unset:e.unset?[...e.unset]:void 0},n=r=>{let s=t.unset?[...t.unset]:[];s.includes(r)||s.push(r),t.unset=s},i=new Set([...ra.keys(),"rank"]);for(let r of i){let s=t[r];if(typeof s!="string"||!Be(s))continue;let a=r==="rank"?"order":ra.get(r)??r;n(a),t[r]=void 0}return Qe(e,Bs(t,ZR))}function nv(e,t,n=[]){return Vs({raw:e,supportedFields:XR,resolveDefinition:i=>{let r=n.find(s=>{let a=s.toLowerCase();return a===i||a.replaceAll("_","-")===i||a.replaceAll("-","_")===i});return JR.get(i)??Ys(i,"update",t)??(r?{optionKey:"field",metadataKey:r}:void 0)}})}var Vy=new Map([["--comment",e=>`pm comments ${e} --add "<text>" --force`],["--file",e=>`pm files ${e} --add "path=<path>,scope=<scope>,note=<note>" --force`],["--doc",e=>`pm docs ${e} --add "path=<path>,scope=<scope>,note=<note>" --force`]]);function Yy(e){let t=e.disallowedFlags.flatMap(i=>{let r=Vy.get(i);return r?[r(e.id)]:[]}),n=e.disallowedFlags.flatMap(i=>{let r=Vy.get(i);return r?[`Replace ${i} with: ${r(e.id)}`]:[]});return new _(e.message,m.USAGE,{code:e.code,required:e.required,why:e.why,...t.length>0?{examples:t}:{},nextSteps:[`Re-run without: ${e.disallowedFlags.join(", ")}`,...n]})}function eO(e,t,n){let i=t.ownershipMetadataBypass===!0,r=t.ownershipDependencyBypass===!0;if(!i&&!r)return;if(i&&r)throw new _("Choose only one package-provided ownership bypass mode.",m.USAGE);let s=(c,d,l)=>{c&&l.push(d)};if(r){let c=[];if(s(t.title!==void 0,"--title",c),s(t.description!==void 0,"--description",c),s(t.body!==void 0,"--body",c),s(t.status!==void 0,"--status",c),s(t.closeReason!==void 0,"--close-reason",c),s(t.priority!==void 0,"--priority",c),s(t.type!==void 0,"--type",c),s(t.tags!==void 0,"--tags",c),s(Array.isArray(t.addTags)&&t.addTags.length>0,"--add-tags",c),s(Array.isArray(t.removeTags)&&t.removeTags.length>0,"--remove-tags",c),s(t.deadline!==void 0,"--deadline",c),s(t.estimatedMinutes!==void 0,"--estimate",c),s(t.acceptanceCriteria!==void 0,"--acceptance-criteria",c),s(Array.isArray(t.addAc)&&t.addAc.length>0,"--add-ac",c),s(Array.isArray(t.removeAc)&&t.removeAc.length>0,"--remove-ac",c),s(t.definitionOfReady!==void 0,"--definition-of-ready",c),s(t.order!==void 0||t.rank!==void 0,"--order/--rank",c),s(t.goal!==void 0,"--goal",c),s(t.objective!==void 0,"--objective",c),s(t.value!==void 0,"--value",c),s(t.impact!==void 0,"--impact",c),s(t.outcome!==void 0,"--outcome",c),s(t.whyNow!==void 0,"--why-now",c),s(t.assignee!==void 0,"--assignee",c),s(t.parent!==void 0,"--parent",c),s(t.reviewer!==void 0,"--reviewer",c),s(t.risk!==void 0,"--risk",c),s(t.confidence!==void 0,"--confidence",c),s(t.sprint!==void 0,"--sprint",c),s(t.release!==void 0,"--release",c),s(t.blockedBy!==void 0,"--blocked-by",c),s(t.blockedReason!==void 0,"--blocked-reason",c),s(t.unblockNote!==void 0,"--unblock-note",c),s(t.reporter!==void 0,"--reporter",c),s(t.severity!==void 0,"--severity",c),s(t.environment!==void 0,"--environment",c),s(t.reproSteps!==void 0,"--repro-steps",c),s(t.resolution!==void 0,"--resolution",c),s(t.expectedResult!==void 0,"--expected-result",c),s(t.actualResult!==void 0,"--actual-result",c),s(t.affectedVersion!==void 0,"--affected-version",c),s(t.fixedVersion!==void 0,"--fixed-version",c),s(t.component!==void 0,"--component",c),s(t.regression!==void 0,"--regression",c),s(t.customerImpact!==void 0,"--customer-impact",c),s(t.depRemove!==void 0,"--dep-remove",c),s(t.replaceDeps===!0,"--replace-deps",c),s(t.replaceTests===!0,"--replace-tests",c),s(t.replaceFiles===!0,"--replace-files",c),s(t.replaceDocs===!0,"--replace-docs",c),s(t.comment!==void 0,"--comment",c),s(t.note!==void 0,"--note",c),s(t.learning!==void 0,"--learning",c),s(t.file!==void 0,"--file",c),s(t.test!==void 0,"--test",c),s(t.doc!==void 0,"--doc",c),s(t.reminder!==void 0,"--reminder",c),s(t.event!==void 0,"--event",c),s(t.typeOption!==void 0,"--type-option",c),s(t.clearDeps===!0,"--clear-deps",c),s(t.clearComments===!0,"--clear-comments",c),s(t.clearNotes===!0,"--clear-notes",c),s(t.clearLearnings===!0,"--clear-learnings",c),s(t.clearFiles===!0,"--clear-files",c),s(t.clearTests===!0,"--clear-tests",c),s(t.clearDocs===!0,"--clear-docs",c),s(t.clearReminders===!0,"--clear-reminders",c),s(t.clearEvents===!0,"--clear-events",c),s(t.clearTypeOptions===!0,"--clear-type-options",c),s(t.force===!0,"--force",c),s(n.size>0,"--unset",c),t.dep===void 0||t.dep.length===0)throw new _("The dependency ownership bypass requires at least one --dep value",m.USAGE);if(c.length>0)throw Yy({id:e,code:"ownership_dependency_bypass_restricted_options",message:`The dependency ownership bypass supports append-only dependency additions via --dep. Remove restricted options: ${c.join(", ")}`,required:"Pass only --dep additions (plus --message/--author) with the dependency ownership bypass.",why:"the dependency ownership bypass is a narrow non-owner override scoped to append-only dependency additions; every other mutation keeps its normal ownership rules.",disallowedFlags:c});return}let a=[];s(t.status!==void 0,"--status",a),s(t.closeReason!==void 0,"--close-reason",a),s(t.assignee!==void 0,"--assignee",a),s(t.parent!==void 0,"--parent",a),s(t.blockedBy!==void 0,"--blocked-by",a),s(t.blockedReason!==void 0,"--blocked-reason",a),s(t.unblockNote!==void 0,"--unblock-note",a),s(t.dep!==void 0,"--dep",a),s(t.depRemove!==void 0,"--dep-remove",a),s(t.replaceDeps===!0,"--replace-deps",a),s(t.replaceTests===!0,"--replace-tests",a),s(t.replaceFiles===!0,"--replace-files",a),s(t.replaceDocs===!0,"--replace-docs",a),s(t.note!==void 0,"--note",a),s(t.learning!==void 0,"--learning",a),s(t.test!==void 0,"--test",a),s(t.reminder!==void 0,"--reminder",a),s(t.event!==void 0,"--event",a),s(t.clearDeps===!0,"--clear-deps",a),s(t.clearComments===!0,"--clear-comments",a),s(t.clearNotes===!0,"--clear-notes",a),s(t.clearLearnings===!0,"--clear-learnings",a),s(t.clearFiles===!0,"--clear-files",a),s(t.clearTests===!0,"--clear-tests",a),s(t.clearDocs===!0,"--clear-docs",a),s(t.clearReminders===!0,"--clear-reminders",a),s(t.clearEvents===!0,"--clear-events",a);let o=[...n].filter(c=>QR.has(c)).sort((c,d)=>c.localeCompare(d)).map(c=>`--unset ${c.replaceAll("_","-")}`);if(a.push(...o),a.length>0)throw Yy({id:e,code:"ownership_metadata_bypass_restricted_options",message:`The metadata ownership bypass only supports non-lifecycle metadata fields and evidence appends. Remove restricted options: ${a.join(", ")}`,required:"Limit the metadata ownership bypass to non-lifecycle metadata fields plus append-only --comment/--file/--doc evidence; route restricted appends and lifecycle changes through their dedicated commands.",why:"the metadata ownership bypass is a non-owner override scoped to metadata maintenance and append-only evidence; lifecycle, ownership, dependency mutations, restricted append fields, and clear/replace operations keep their normal ownership rules.",disallowedFlags:a})}function tO(e,t){let n=me(e,t);if(!n){let i=t.definitions.map(r=>r.id);throw new _(`Invalid --status value "${e}". Allowed: ${i.join(", ")}`,m.USAGE)}return n}function nO(e,t){return!e||e.trim()===""||e.trim().toLowerCase()==="now"?t:iv(e)}function iv(e){let t=Date.parse(e);if(!Number.isFinite(t))throw new _(`Invalid dependency created_at timestamp "${e}"`,m.USAGE);return new Date(t).toISOString()}function xn(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}var iO=["id","kind","type","author","created_at","source_kind"],rO=["id","kind","type","author","created_at","source_kind"];function rv(e){return e.startsWith("```")||e.includes(`
|
|
11
|
-
`)||/^(?:[-*+]\s+)?(?:id|kind|type|author|created_at|source_kind)\s*[:=]/i.test(e)?!0:cn(e)}function sv(e){return typeof e=="string"?ae().resolve(e)?.kind??e.trim():e}function sO(e,t,n,i){return e?(Re(e,"--dep","Use --clear-deps to clear dependencies."),{additions:e.map(r=>{let s=r.trim(),a=rv(s);Ai(s,a);let o=a?Z(r,"--dep"):{id:s,kind:"related"};a&&we(o,"--dep",iO);let c=o.id?.trim(),d=sv((o.kind??o.type)?.trim());if(!c||!d)throw new _("--dep requires id and kind, or a bare item id to add a related dependency",m.USAGE);if(c.toLowerCase()==="undefined")throw new _(`--dep id must not use placeholder token "${c}". Use --clear-deps to clear dependencies.`,m.USAGE);let l=Vn(xn(o.source_kind)),u=xn(o.author);return{id:Yn(c,t,l),kind:Ti(d),created_at:nO(o.created_at,n),author:u??i,source_kind:l??"cli:update:dep",author_source:u?"asserted":"detected"}})}):{additions:[]}}function aO(e,t){return e?(Re(e,"--dep-remove"),e.map(n=>{let i=n.trim();if(!i)throw new _("--dep-remove requires id or key/value selectors",m.USAGE);let r=rv(i);if(Ai(i,r,"--dep-remove"),r){let s=Z(i,"--dep-remove");we(s,"--dep-remove",rO);let a=s.id?.trim();if(!a)throw new _("--dep-remove key/value form requires id=<value>",m.USAGE);if(a.toLowerCase()==="undefined")throw new _(`--dep-remove id must not use placeholder token "${a}"`,m.USAGE);let o=sv(xn(s.kind??s.type)),c=Vn(xn(s.source_kind)),d=xn(s.author),l=xn(s.created_at);return{id:Yn(a,t,c),kind:o?Ti(o):void 0,source_kind:c,author:d,created_at:l?iv(l):void 0}}if(i.toLowerCase()==="undefined")throw new _(`--dep-remove id must not use placeholder token "${i}"`,m.USAGE);return{id:kt(i,t)}})):[]}function sa(e){let t=e.source_kind?.trim().toLowerCase()??"";return[e.id.trim().toLowerCase(),e.kind,t].join("\0")}function oO(e){let t=e.source_kind?.trim().toLowerCase()??"",n=e.author?.trim().toLowerCase()??"",i=e.created_at?.trim()??"",r=Date.parse(i),s=Number.isFinite(r)?new Date(r).toISOString():i;return[e.id.trim().toLowerCase(),e.kind,t,n,s].join("\0")}function cO(e,t,n,i){let r=[...e??[]],s=!1;if(t===void 0){let a=r.filter(o=>o.kind!=="blocked_by");return a.length!==r.length&&(r=a,s=!0),s?{dependencies:r.length>0?r:void 0,changed:!0}:{dependencies:e,changed:!1}}return r.some(a=>a.kind==="blocked_by"&&a.id===t)||(r.push({id:t,kind:"blocked_by",created_at:n,author:i,source_kind:"cli:update:blocked_by",author_source:"detected"}),s=!0),s?{dependencies:r.length>0?r:void 0,changed:!0}:{dependencies:e,changed:!1}}async function dO(e,t,n,i,r,s){if(e===void 0||t)return{};let a=e.trim();if(a.length===0)return{};let o=await Y(n,kt(a,i),i,r,s);return o?{id:o.id}:{unresolved:a}}function lO(e,t,n,i,r){let s=cO(e.dependencies,t,n,i);s.changed&&(s.dependencies===void 0?delete e.dependencies:e.dependencies=s.dependencies,r.includes("dependencies")||r.push("dependencies"))}function uO(e){return`${e.path}::${e.scope}`}function mO(e){return`${e.path}::${e.scope}`}function _O(e){return`${e.command}::${e.path??""}::${e.scope}::${e.pm_context_mode??""}::${e.workspace_context_mode??""}`}function av(e,t){return!(e.id.trim().toLowerCase()!==t.id.trim().toLowerCase()||t.kind&&e.kind!==t.kind||t.source_kind!==void 0&&e.source_kind?.trim().toLowerCase()!==t.source_kind.trim().toLowerCase()||t.author!==void 0&&e.author?.trim().toLowerCase()!==t.author.trim().toLowerCase()||t.created_at!==void 0&&(e.created_at===void 0||!Number.isFinite(Date.parse(e.created_at))||new Date(Date.parse(e.created_at)).toISOString()!==t.created_at))}function Jy(e,t){let n=Fn("update",e);if(!n)throw new _(`Unsupported command_option_policies option "${e}" for update command on type "${t}"`,m.CONFLICT);return n}function pO(e,t,n){let i=new Set,r=(s,a)=>{a&&i.add(s)};if(r("title",e.title!==void 0),r("description",e.description!==void 0),r("body",e.body!==void 0),r("status",e.status!==void 0),r("closeReason",e.closeReason!==void 0),r("priority",e.priority!==void 0),r("type",e.type!==void 0),r("tags",e.tags!==void 0||Array.isArray(e.addTags)&&e.addTags.length>0||Array.isArray(e.removeTags)&&e.removeTags.length>0),r("deadline",e.deadline!==void 0),r("estimatedMinutes",e.estimatedMinutes!==void 0),r("acceptanceCriteria",e.acceptanceCriteria!==void 0||Array.isArray(e.addAc)&&e.addAc.length>0||Array.isArray(e.removeAc)&&e.removeAc.length>0),r("definitionOfReady",e.definitionOfReady!==void 0),r("order",e.order!==void 0||e.rank!==void 0),r("goal",e.goal!==void 0),r("objective",e.objective!==void 0),r("value",e.value!==void 0),r("impact",e.impact!==void 0),r("outcome",e.outcome!==void 0),r("whyNow",e.whyNow!==void 0),r("author",e.author!==void 0),r("message",e.message!==void 0),r("assignee",e.assignee!==void 0),r("parent",e.parent!==void 0),r("reviewer",e.reviewer!==void 0),r("risk",e.risk!==void 0),r("confidence",e.confidence!==void 0),r("sprint",e.sprint!==void 0),r("release",e.release!==void 0),r("blockedBy",e.blockedBy!==void 0),r("blockedReason",e.blockedReason!==void 0),r("unblockNote",e.unblockNote!==void 0),r("reporter",e.reporter!==void 0),r("severity",e.severity!==void 0),r("environment",e.environment!==void 0),r("reproSteps",e.reproSteps!==void 0),r("resolution",e.resolution!==void 0),r("expectedResult",e.expectedResult!==void 0),r("actualResult",e.actualResult!==void 0),r("affectedVersion",e.affectedVersion!==void 0),r("fixedVersion",e.fixedVersion!==void 0),r("component",e.component!==void 0),r("regression",e.regression!==void 0),r("customerImpact",e.customerImpact!==void 0),r("dep",e.dep!==void 0),r("depRemove",e.depRemove!==void 0),r("dep",e.replaceDeps===!0),r("comment",e.comment!==void 0),r("note",e.note!==void 0),r("learning",e.learning!==void 0),r("file",e.file!==void 0),r("test",e.test!==void 0),r("test",e.replaceTests===!0),r("file",e.replaceFiles===!0),r("doc",e.replaceDocs===!0),r("doc",e.doc!==void 0),r("reminder",e.reminder!==void 0),r("event",e.event!==void 0),r("typeOption",e.typeOption!==void 0),r("field",e.field!==void 0),r("force",e.force===!0),r("ownershipMetadataBypass",e.ownershipMetadataBypass===!0),r("ownershipDependencyBypass",e.ownershipDependencyBypass===!0),r("dep",e.clearDeps===!0),r("comment",e.clearComments===!0),r("note",e.clearNotes===!0),r("learning",e.clearLearnings===!0),r("file",e.clearFiles===!0),r("test",e.clearTests===!0),r("doc",e.clearDocs===!0),r("reminder",e.clearReminders===!0),r("event",e.clearEvents===!0),r("typeOption",e.clearTypeOptions===!0),e.unset&&e.unset.length>0){let s=nv(e.unset,t,n);for(let a of s.optionKeys)r(a,!0)}return i}function fO(e,t,n,i,r){let s=Hi(e,n);if(!s)throw new _(`Invalid type value "${e}"`,m.USAGE);let a=nn(s,"update",[]);if(a.errors.length>0)throw new _(a.errors.join("; "),m.CONFLICT);let o=pO(t,i,r);for(let c of a.disabled)if(o.has(Jy(c,e)))throw new _(`Option ${Te("update",c)} is disabled for type "${e}" by command_option_policies`,m.USAGE);for(let c of a.required)if(!o.has(Jy(c,e)))throw new _(`Missing required option ${Te("update",c)} for type "${e}"`,m.USAGE)}var gO=new Set(["order","rank"]),hO=$a.filter(e=>!gO.has(e)),ov=["tags","closeReason",...hO],yO=["title","description","body","status","closeReason","completedAt","priority","type",...$a,"dep","depRemove","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],vO=[{optionKey:"deadline",metadataKey:"deadline",transform:(e,t)=>ge(e,t.nowValue,"deadline")},{optionKey:"estimatedMinutes",metadataKey:"estimated_minutes",transform:e=>fr(e,"estimated-minutes")},{optionKey:"acceptanceCriteria",metadataKey:"acceptance_criteria",transform:e=>e},{optionKey:"definitionOfReady",metadataKey:"definition_of_ready"},{optionKey:"goal",metadataKey:"goal"},{optionKey:"objective",metadataKey:"objective"},{optionKey:"value",metadataKey:"value"},{optionKey:"impact",metadataKey:"impact"},{optionKey:"outcome",metadataKey:"outcome"},{optionKey:"whyNow",metadataKey:"why_now"}],wO=[{optionKey:"reviewer",metadataKey:"reviewer"},{optionKey:"risk",metadataKey:"risk",transform:e=>He(Us(e),Wi,"risk")},{optionKey:"confidence",metadataKey:"confidence",transform:e=>Gs(e)}],bO=[{optionKey:"blockedReason",metadataKey:"blocked_reason"},{optionKey:"unblockNote",metadataKey:"unblock_note"},{optionKey:"reporter",metadataKey:"reporter"},{optionKey:"severity",metadataKey:"severity",transform:e=>He(js(e),Bi,"severity")},{optionKey:"environment",metadataKey:"environment"},{optionKey:"reproSteps",metadataKey:"repro_steps"},{optionKey:"resolution",metadataKey:"resolution"},{optionKey:"expectedResult",metadataKey:"expected_result"},{optionKey:"actualResult",metadataKey:"actual_result"},{optionKey:"affectedVersion",metadataKey:"affected_version"},{optionKey:"fixedVersion",metadataKey:"fixed_version"},{optionKey:"component",metadataKey:"component"},{optionKey:"regression",metadataKey:"regression",transform:e=>qs(e)},{optionKey:"customerImpact",metadataKey:"customer_impact"}];function Jc(e,t,n){for(let i of e){let r=t[i.optionKey],s=n.clearItemMetadataKeys.has(i.metadataKey);if(!(r===void 0&&!s)){if(s){delete n.metadataRecord[i.metadataKey],n.changedFields.push(i.metadataKey);continue}if(typeof r!="string")throw new _(`${Te("update",String(i.optionKey))} must be a string value`,m.USAGE);n.metadataRecord[i.metadataKey]=i.transform?i.transform(r,n):r.trim(),n.changedFields.push(i.metadataKey)}}}async function kO(e){return tv(await pr(e,[["body","--body"],["description","--description"]],[["dep","--dep"],["depRemove","--dep-remove"],["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"],["field","--field"]]))}async function EO(e){return Ft(e)?await kO(e):tv(e)}function SO(e){return[{enabled:e.clearDeps||e.replaceDeps,optionKey:"dep",clearFlag:"--clear-deps",valueFlag:"--dep",values:e.dep,metadataKey:"dependencies"},{enabled:e.clearComments,optionKey:"comment",clearFlag:"--clear-comments",valueFlag:"--comment",values:e.comment,metadataKey:"comments"},{enabled:e.clearNotes,optionKey:"note",clearFlag:"--clear-notes",valueFlag:"--note",values:e.note,metadataKey:"notes"},{enabled:e.clearLearnings,optionKey:"learning",clearFlag:"--clear-learnings",valueFlag:"--learning",values:e.learning,metadataKey:"learnings"},{enabled:e.clearFiles||e.replaceFiles,optionKey:"file",clearFlag:"--clear-files",valueFlag:"--file",values:e.file,metadataKey:"files"},{enabled:e.clearTests||e.replaceTests,optionKey:"test",clearFlag:"--clear-tests",valueFlag:"--test",values:e.test,metadataKey:"tests"},{enabled:e.clearDocs||e.replaceDocs,optionKey:"doc",clearFlag:"--clear-docs",valueFlag:"--doc",values:e.doc,metadataKey:"docs"},{enabled:e.clearReminders,optionKey:"reminder",clearFlag:"--clear-reminders",valueFlag:"--reminder",values:e.reminder,metadataKey:"reminders"},{enabled:e.clearEvents,optionKey:"event",clearFlag:"--clear-events",valueFlag:"--event",values:e.event,metadataKey:"events"},{enabled:e.clearTypeOptions,optionKey:"typeOption",clearFlag:"--clear-type-options",valueFlag:"--type-option",values:e.typeOption,metadataKey:"type_options"}]}function Vc(e){if(e.enabled&&(!e.values||e.values.length===0))throw new _(`${e.replaceFlag} requires at least one ${e.valueFlag} entry`,m.USAGE);if(e.enabled&&e.clearEnabled)throw new _(`${e.replaceFlag} cannot be combined with ${e.clearFlag}`,m.USAGE)}function TO(e){let t=(e.addAc?.length??0)>0||(e.removeAc?.length??0)>0;if(e.acceptanceCriteria!==void 0&&t)throw new _("Cannot combine --acceptance-criteria replacement with --add-ac or --remove-ac. Use --remove-ac and --add-ac together for an atomic one-entry repair.",m.USAGE,{code:"acceptance_criteria_mutation_conflict",reason:"replacement_and_additive_mutation_combined",nextSteps:["Use --acceptance-criteria alone to replace the complete list.","Use --remove-ac <old> --add-ac <new> to repair one criterion without replacing unrelated entries."]});if(e.replaceDeps===!0&&(e.dep===void 0||e.dep.length===0))throw new _("--replace-deps requires at least one --dep entry",m.USAGE);if(e.replaceDeps===!0&&e.depRemove!==void 0&&e.depRemove.length>0)throw new _("--replace-deps cannot be combined with --dep-remove",m.USAGE);Vc({enabled:e.replaceTests===!0,values:e.test,replaceFlag:"--replace-tests",clearEnabled:e.clearTests===!0,clearFlag:"--clear-tests",valueFlag:"--test"}),Vc({enabled:e.replaceFiles===!0,values:e.file,replaceFlag:"--replace-files",clearEnabled:e.clearFiles===!0,clearFlag:"--clear-files",valueFlag:"--file"}),Vc({enabled:e.replaceDocs===!0,values:e.doc,replaceFlag:"--replace-docs",clearEnabled:e.clearDocs===!0,clearFlag:"--clear-docs",valueFlag:"--doc"})}function AO(e){for(let t of e.definitions){if(!t.enabled)continue;let n=t.optionKey==="dep"&&e.options.replaceDeps===!0||t.optionKey==="test"&&e.options.replaceTests===!0||t.optionKey==="file"&&e.options.replaceFiles===!0||t.optionKey==="doc"&&e.options.replaceDocs===!0;if(t.values&&t.values.length>0&&!n)throw new _(`Cannot combine ${t.clearFlag} with ${t.valueFlag}`,m.USAGE);e.clearOptionKeys.add(t.optionKey),e.clearItemMetadataKeys.add(t.metadataKey)}}function IO(e){let t={};for(let n of ov)t[String(n)]=e[n]!==void 0;return t.order=e.order!==void 0||e.rank!==void 0,t}function CO(e,t){let n=IO(e);for(let[i,r]of Object.entries(n)){if(!r||!t.optionKeys.has(i))continue;let s=ra.get(i)??i;throw new _(`Cannot combine --unset ${s} with ${Te("update",i)}`,m.USAGE)}if(t.metadataKeys.has("acceptance_criteria")){if(Array.isArray(e.addAc)&&e.addAc.length>0)throw new _("Cannot combine --unset acceptance-criteria with --add-ac",m.USAGE);if(Array.isArray(e.removeAc)&&e.removeAc.length>0)throw new _("Cannot combine --unset acceptance-criteria with --remove-ac",m.USAGE)}if(t.metadataKeys.has("tags")){if(Array.isArray(e.addTags)&&e.addTags.length>0)throw new _("Cannot combine --unset tags with --add-tags",m.USAGE);if(Array.isArray(e.removeTags)&&e.removeTags.length>0)throw new _("Cannot combine --unset tags with --remove-tags",m.USAGE)}}function xO(e){let t=(n,i)=>{let r=ra.get(i),s=r?`Use --unset ${r} to clear this field.`:void 0;Ws(n,Te("update",i),s)};for(let n of ov)t(e[n],String(n));t(e.order??e.rank,"order"),Re(e.reminder,"--reminder","Use --clear-reminders to clear reminders."),Re(e.event,"--event","Use --clear-events to clear linked events.")}function RO(e,t){let n={};for(let i of yO)n[String(i)]=e[i]!==void 0;return n.tags=e.tags!==void 0,n.addTags=Array.isArray(e.addTags)&&e.addTags.length>0,n.removeTags=Array.isArray(e.removeTags)&&e.removeTags.length>0,n.addAc=Array.isArray(e.addAc)&&e.addAc.length>0,n.removeAc=Array.isArray(e.removeAc)&&e.removeAc.length>0,n.order=e.order!==void 0,n.rank=e.rank!==void 0,n.replaceDeps=e.replaceDeps===!0,n.replaceTests=e.replaceTests===!0,n.replaceFiles=e.replaceFiles===!0,n.replaceDocs=e.replaceDocs===!0,n.unset=e.unset!==void 0&&e.unset.length>0,n.clearDeps=e.clearDeps===!0,n.clearComments=e.clearComments===!0,n.clearNotes=e.clearNotes===!0,n.clearLearnings=e.clearLearnings===!0,n.clearFiles=e.clearFiles===!0,n.clearTests=e.clearTests===!0,n.clearDocs=e.clearDocs===!0,n.clearReminders=e.clearReminders===!0,n.clearEvents=e.clearEvents===!0,n.clearTypeOptions=e.clearTypeOptions===!0,n.documentAnnotationSnapshot=e.documentAnnotationSnapshot!==void 0,n.runtimeFields=Object.keys(t).length>0,n}async function OO(e){let t=await Y(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await zn(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await he(t,{schema:e.settings.schema});return{item:n.metadata,changed_fields:[],warnings:["noop_no_update_fields"]}}async function LO(e){if(!(!e.fieldFlags.dep&&!e.fieldFlags.blockedBy&&!e.fieldFlags.parent&&!e.clearedMetadataKeys.has("parent")))return Se(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}function DO(e){e.before&&(Is(e.before,e.before.map(t=>t.id===e.document.metadata.id?e.document.metadata:t)),Rr(e.before,e.before.map(t=>t.id===e.document.metadata.id?e.document.metadata:t),e.document.metadata.id,t=>_e(t,e.statusRegistry),ae()))}function NO(e){if(e.order!==void 0&&e.rank!==void 0&&e.order!==e.rank)throw new _("--order and --rank must match when both are provided",m.USAGE)}async function MO(e){if(e.options.parent===void 0||e.unsetTargets.metadataKeys.has("parent"))return{resolvedParentValue:void 0,warnings:[]};let t=Cr(gr(e.options.parent),e.settings.id_prefix);if(Sr(t))return{resolvedParentValue:t,warnings:[]};if(yr(e.id,t,e.settings.id_prefix),await Y(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder))return{resolvedParentValue:t,warnings:[]};let n=kt(t,e.settings.id_prefix);return{resolvedParentValue:t,warnings:hr(n,e.parentReferencePolicy).warnings}}function PO(e){return e.unresolved===void 0?[]:[`blocked_by_unresolved:${e.unresolved}`]}async function FO(e){if(e.workflowEnforcement==="off"||e.typeWorkflows.length===0||!e.fieldFlags.status||e.options.status===void 0)return[];let t=await Y(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await zn(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await he(t,{schema:e.settings.schema}),i=e.options.type!==void 0?st(e.options.type,e.typeRegistry)??e.options.type:n.metadata?.type??"",r=ia({enforcement:e.workflowEnforcement,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry,typeName:i,fromStatus:n.metadata?.status??"",toStatus:e.options.status});return r?[r]:[]}async function $O(e){if(!e.fieldFlags.status||me(e.options.status,e.statusRegistry)!==e.statusRegistry.close_status)return;let t=Object.entries(e.fieldFlags).filter(([a,o])=>o&&a!=="status"&&a!=="closeReason"&&a!=="completedAt").map(([a])=>a),n=[],i=[];if(t.length>0){let a=Qe(e.options,{...e.options,status:void 0,closeReason:void 0,message:void 0}),o=await aa(e.id,a,e.global);i=o.changed_fields,n.push(...o.warnings)}let r=await Ss(e.id,e.options.closeReason,{author:e.options.author,message:e.options.message,force:e.options.force,completedAt:e.options.completedAt},e.global),s=[...e.workflowTransitionWarnings,...n,...r.warnings,"auto_routed_from_update_to_close"];return{item:r.item,changed_fields:[...i,...r.changed_fields],warnings:s}}function UO(e,t,n,i){return t.title!==void 0&&(e.metadata.title=Hc(t.title,"--title"),i.push("title")),t.description!==void 0&&(e.metadata.description=t.description,i.push("description")),t.body!==void 0&&(e.body=t.body,i.push("body")),me(e.metadata.status,n)??e.metadata.status}var jO=["closed_at","completed_at","close_reason","resolution","expected_result","actual_result","fixed_version"];function GO(e,t){for(let n of jO)e[n]!==void 0&&(delete e[n],t.push(n))}function qO(e,t,n,i,r){let s=tO(n,t.statusRegistry);if(e.metadata.status=s,r.push("status"),s===t.statusRegistry.close_status&&(e.metadata.closed_at===void 0||e.metadata.closed_at===null)){e.metadata.closed_at=t.nowIso,e.metadata.completed_at=t.nowIso,r.push("closed_at","completed_at");return}!_e(s,t.statusRegistry)&&_e(i,t.statusRegistry)&&GO(e.metadata,r)}function KO(e,t,n,i){if(t.options.status!==void 0&&qO(e,t,t.options.status,n,i),t.options.completedAt!==void 0){if(!_e(e.metadata.status,t.statusRegistry))throw new _("--completed-at can only be set on a terminal item",m.USAGE);e.metadata.completed_at=ge(t.options.completedAt,new Date(t.nowIso),"completed-at"),i.push("completed_at")}}function zO(e,t,n,i){if(t.options.closeReason!==void 0||t.clearItemMetadataKeys.has("close_reason")){if(t.clearItemMetadataKeys.has("close_reason"))delete e.metadata.close_reason;else{let r=t.options.closeReason?.trim()??"";if(r.length===0)throw new _("--close-reason must not be empty",m.USAGE);e.metadata.close_reason=r}i.push("close_reason");return}t.options.status!==void 0&&_e(n,t.statusRegistry)&&!_e(e.metadata.status,t.statusRegistry)&&e.metadata.close_reason!==void 0&&(delete e.metadata.close_reason,i.push("close_reason"))}function WO(e,t,n,i){KO(e,t,n,i),zO(e,t,n,i)}function BO(e,t,n){let i=st(e.metadata.type,t.typeRegistry)??e.metadata.type;if(t.options.priority!==void 0&&(e.metadata.priority=vr(t.options.priority),n.push("priority")),t.options.type!==void 0){let r=st(t.options.type,t.typeRegistry);if(!r)throw new _(br(t.options.type,t.typeRegistry.types,Qi(t.pmRoot,t.settings.schema)),m.USAGE);e.metadata.type=r,i=r,n.push("type")}return fO(i,t.options,t.typeRegistry,t.runtimeFieldRegistry,t.extensionFieldNames),HO(e,t,i,n),i}function HO(e,t,n,i){if(t.options.typeOption!==void 0||t.clearItemMetadataKeys.has("type_options")){if(t.clearItemMetadataKeys.has("type_options"))delete e.metadata.type_options;else{let s=Zs(t.options.typeOption??[]),a=$n(n,s,t.typeRegistry);if(a.errors.length>0)throw new _(a.errors.join("; "),m.USAGE);e.metadata.type_options=a.normalized}i.push("type_options");return}if(t.options.type===void 0||e.metadata.type_options===void 0)return;let r=$n(n,e.metadata.type_options,t.typeRegistry);if(r.errors.length>0)throw new _(`Current type options are incompatible with type "${n}". ${r.errors.join("; ")}. Use --clear-type-options to clear them.`,m.USAGE);e.metadata.type_options=r.normalized}function VO(e,t){let n=new Set(t.map(r=>sa(r))),i=new Set;return e.filter(r=>{if(!n.has(sa(r)))return!0;let s=oO(r);return i.has(s)?!1:(i.add(s),!0)})}function YO(e,t,n){let i=t.filter(r=>!e.some(s=>av(s,r)));if(i.length!==0)throw new _(`Dependency removal did not match ${i.length===1?"a stored edge":"stored edges"}.`,m.NOT_FOUND,{code:"dependency_remove_no_match",reason:"selector_not_found",unmatched_selectors:i,available_dependencies:e.map(r=>({id:r.id,kind:r.kind,source_kind:r.source_kind,author:r.author,created_at:r.created_at})),why:"Failing on a zero-match selector prevents a mistyped dependency removal from being reported as successful.",nextSteps:[`Inspect the current item with: pm get ${n} --full`,"Retry --dep-remove with the exact id plus any kind, source_kind, author, or created_at selectors needed to identify one stored row."]})}function JO(e,t,n){if(t.options.dep===void 0&&t.options.depRemove===void 0&&!t.clearItemMetadataKeys.has("dependencies"))return;let i=t.clearItemMetadataKeys.has("dependencies")?[]:[...e.metadata.dependencies??[]];if(t.dependencyUpdates.additions.length>0){i=VO(i,t.dependencyUpdates.additions);let r=new Set(i.map(s=>sa(s)));for(let s of t.dependencyUpdates.additions){let a=sa(s);r.has(a)||(i.push(s),r.add(a))}}t.dependencyRemovals.length>0&&(YO(i,t.dependencyRemovals,e.metadata.id),i=i.filter(r=>!t.dependencyRemovals.some(s=>av(r,s)))),i.length===0?delete e.metadata.dependencies:e.metadata.dependencies=i,n.push("dependencies")}function XO(e,t,n){Yc(e,"comments",t.options.comment,t.commentUpdates.values,t.clearItemMetadataKeys,n),Yc(e,"notes",t.options.note,t.noteUpdates.values,t.clearItemMetadataKeys,n),Yc(e,"learnings",t.options.learning,t.learningUpdates.values,t.clearItemMetadataKeys,n)}function Yc(e,t,n,i,r,s){n===void 0&&!r.has(t)||(r.has(t)||!i||i.length===0?delete e.metadata[t]:e.metadata[t]=[...e.metadata[t]??[],...i],s.push(t))}function QO(e,t,n){Xy(e,"files",t.options.file,t.fileUpdates.values,uO,t.options.replaceFiles===!0,t.clearItemMetadataKeys,n),ZO(e,t,n),Xy(e,"docs",t.options.doc,t.docUpdates.values,mO,t.options.replaceDocs===!0,t.clearItemMetadataKeys,n)}function Xy(e,t,n,i,r,s,a,o){if(!(n===void 0&&!a.has(t))){if(s)e.metadata[t]=i;else if(a.has(t)||!i||i.length===0)delete e.metadata[t];else{let c=[...e.metadata[t]??[]],d=new Set(c.map(l=>r(l)));for(let l of i){let u=r(l);d.has(u)||(c.push(l),d.add(u))}e.metadata[t]=c}o.push(t)}}function ZO(e,t,n){t.options.test===void 0&&!t.clearItemMetadataKeys.has("tests")||(t.clearItemMetadataKeys.has("tests")&&t.options.replaceTests===!0?e.metadata.tests=Qy(t.testUpdates.values)??[]:t.clearItemMetadataKeys.has("tests")||!t.testUpdates.values||t.testUpdates.values.length===0?delete e.metadata.tests:e.metadata.tests=Qy([...e.metadata.tests??[],...t.testUpdates.values]),e.metadata.tests!==void 0&&e.metadata.tests.length===0&&delete e.metadata.tests,n.push("tests"))}function Qy(e){if(!e||e.length===0)return;let t=[],n=new Set;for(let i of e){let r=_O(i);n.has(r)||(t.push(i),n.add(r))}return t}function eL(e,t,n){let i=t.options.addTags,r=t.options.removeTags,s=Array.isArray(i)&&i.length>0||Array.isArray(r)&&r.length>0;if(t.options.tags!==void 0||t.clearItemMetadataKeys.has("tags")||s){let a=t.clearItemMetadataKeys.has("tags")?[]:t.options.tags!==void 0?ur(t.options.tags):Array.isArray(e.metadata.tags)?[...e.metadata.tags]:[];e.metadata.tags=a_(_r(a,i),r),n.changedFields.push("tags")}Jc(vO,t.options,n),nL(e,t,n.changedFields)}function tL(e,t,n){let i=t.options.addAc,r=t.options.removeAc;if(!(Array.isArray(i)&&i.length>0)&&!(Array.isArray(r)&&r.length>0))return;let s=s_(mr(e.metadata.acceptance_criteria),i,r);if(s.unmatchedRemovals.length>0)throw new _(`Acceptance criteria removal did not match: ${s.unmatchedRemovals.join(", ")}`,m.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:s.unmatchedRemovals,why:"Lossless removal fails instead of silently applying the remaining mutations when an exact selector is wrong.",nextSteps:["Read the current acceptance_criteria value and retry with the exact criterion text.","Use --acceptance-criteria alone only when replacing the complete list is intentional."]});let a=s.criteria.join("; ");e.metadata.acceptance_criteria!==a&&(a===""&&e.metadata.acceptance_criteria===void 0||(e.metadata.acceptance_criteria=a,n.changedFields.includes("acceptance_criteria")||n.changedFields.push("acceptance_criteria")))}function nL(e,t,n){let i=t.options.order??t.options.rank;if(!(i===void 0&&!t.clearItemMetadataKeys.has("order"))){if(t.clearItemMetadataKeys.has("order"))delete e.metadata.order;else{let r=ye(i??"","order");if(!Number.isInteger(r))throw new _("Order must be an integer",m.USAGE);e.metadata.order=r}n.push("order")}}function iL(e,t,n,i){rL(e,t,n.changedFields),sL(e,t,n.changedFields),Jc(wO,t.options,n),Zy(e,t,"sprint",i,n.changedFields),Zy(e,t,"release",i,n.changedFields),aL(e,t,n.changedFields),Jc(bO,t.options,n)}function rL(e,t,n){if(!(t.options.assignee===void 0&&!t.clearItemMetadataKeys.has("assignee"))){if(t.clearItemMetadataKeys.has("assignee"))delete e.metadata.assignee;else{let i=t.options.assignee?.trim()??"";if(i==="")throw new _("--assignee must not be empty. Use --unset assignee to clear it.",m.USAGE);e.metadata.assignee=i}n.push("assignee")}}function sL(e,t,n){t.options.parent===void 0&&!t.clearItemMetadataKeys.has("parent")||(t.clearItemMetadataKeys.has("parent")?delete e.metadata.parent:e.metadata.parent=t.resolvedParentValue??"",n.push("parent"))}function Zy(e,t,n,i,r){if(!(t.options[n]===void 0&&!t.clearItemMetadataKeys.has(n))){if(t.clearItemMetadataKeys.has(n))delete e.metadata[n];else{let s=wr(n,t.options[n]??"",t.settings.validation.sprint_release_format);e.metadata[n]=s.value,i.push(...s.warnings)}r.push(n)}}function aL(e,t,n){t.options.blockedBy===void 0&&!t.clearItemMetadataKeys.has("blocked_by")||(t.clearItemMetadataKeys.has("blocked_by")?delete e.metadata.blocked_by:e.metadata.blocked_by=t.options.blockedBy?.trim()??"",n.push("blocked_by"),(t.clearItemMetadataKeys.has("blocked_by")||t.resolvedBlockedByDependencyId!==void 0)&&lO(e.metadata,t.resolvedBlockedByDependencyId,t.nowIso,t.author,n))}function oL(e,t,n){(t.options.reminder!==void 0||t.clearItemMetadataKeys.has("reminders"))&&(t.clearItemMetadataKeys.has("reminders")?delete e.metadata.reminders:e.metadata.reminders=Xs(t.options.reminder??[],t.nowValue,{valueMode:"trimmed"}),n.push("reminders")),(t.options.event!==void 0||t.clearItemMetadataKeys.has("events"))&&(t.clearItemMetadataKeys.has("events")?delete e.metadata.events:e.metadata.events=Qs(t.options.event??[],t.nowValue,{allDayEmptyGuard:"truthy",recurrenceEmptyNumericGuard:"truthy"}),n.push("events"))}function cL(e,t,n){ev(e,t.runtimeFieldRegistry.definitions.map(r=>r.metadata_key),t.clearItemMetadataKeys,n),ev(e,t.extensionFieldNames,t.clearItemMetadataKeys,n);for(let[r,s]of Object.entries(t.runtimeFieldUpdates)){if(t.clearItemMetadataKeys.has(r)){let a=r.replaceAll("_","-"),o=t.runtimeFieldRegistry.definitions.find(c=>c.metadata_key===r)?.cli_flag??a;throw new _(`Cannot combine --unset ${a} with --${o}`,m.USAGE)}Fe(e[r],s)||(e[r]=s,n.push(r))}let i=ir(t.options.field,t.extensionRegistrations,Ks);for(let r of Object.keys(i))if(t.clearItemMetadataKeys.has(r))throw new _(`Cannot combine --unset ${r.replaceAll("_","-")} with --field ${r}=...`,m.USAGE);for(let[r,s]of Object.entries(i))Fe(e[r],s)||(e[r]=s,n.push(r))}function ev(e,t,n,i){for(let r of t)!n.has(r)||e[r]===void 0||(delete e[r],i.push(r))}function dL(e,t){if(t===void 0)return;let n=e.metadata,i=["comments","notes","learnings"].find(r=>{let s=t[r];return s!==void 0&&(!Array.isArray(s)||!Fe(s,n[r]??[]))});if(i!==void 0)throw new _(`Full-item --stdin-json update changed persisted ${i}; no item fields were written.`,m.USAGE,{code:"stdin_json_persisted_annotation_changed",reason:`${i}_requires_annotation_command`,required:`Use pm ${i} ${e.metadata.id} --edit <index> --add <text> to correct an existing entry.`,why:"Full-item update appends new annotations but cannot replace or remove existing audit entries.",nextSteps:[`Inspect the current ${i} with pm ${i} ${e.metadata.id}.`,`Apply the correction with pm ${i} ${e.metadata.id} --edit <index> --add <text>.`]})}function lL(e,t){dL(e,t.options.documentAnnotationSnapshot);let n=structuredClone(e.metadata),i=e.body,r=[],s=[],a=UO(e,t.options,t.statusRegistry,r),o=e.metadata,c={metadataRecord:o,clearItemMetadataKeys:t.clearItemMetadataKeys,changedFields:r,nowValue:t.nowValue};WO(e,t,a,r),BO(e,t,r),JO(e,t,r),XO(e,t,r),QO(e,t,r),eL(e,t,c),tL(e,t,c),iL(e,t,c,s),(t.options.dep!==void 0||t.options.depRemove!==void 0||t.options.blockedBy!==void 0||t.clearItemMetadataKeys.has("dependencies")||t.clearItemMetadataKeys.has("blocked_by"))&&Ii(e.metadata.id,e.metadata.dependencies),me(e.metadata.status,t.statusRegistry)===t.statusRegistry.canceled_status&&e.metadata.assignee!==void 0&&(delete e.metadata.assignee,r.includes("assignee")||r.push("assignee")),oL(e,t,r),cL(o,t,r);try{rr(o,t.extensionRegistrations,{skipDefaultFields:t.clearItemMetadataKeys})}catch(u){throw new _(u instanceof Error?u.message:"Invalid extension item field values",m.USAGE)}let d=e.metadata,l=[...new Set(r)].filter(u=>u==="body"?e.body!==i:!Fe(n[u],d[u]));return t.options.acceptanceCriteria!==void 0&&l.includes("acceptance_criteria")&&s.push(`acceptance_criteria_replaced:${mr(n.acceptance_criteria).length}:${mr(d.acceptance_criteria).length}`),{changedFields:l,warnings:s}}async function cv(e,t,n,i={}){t=await EO(t);let r=x(process.cwd(),n.path);await $(r);let s=await I(r),a=K(s.schema),o=rn(s.schema),c=P(),d=Et(c),l=F(s,c),u=s.governance.workflow_enforcement??"off",p=u==="off"?[]:kr(s.schema),g=[{strict_error:"strict_error",warn:"warn",off:"off"},{strict_error:"warn",warn:"warn",off:"off"}][+(t.allowMissingParent===!0)][s.validation.parent_reference],f=nv(t.unset,o,d),h=new Set(f.optionKeys),y=new Set(f.metadataKeys);TO(t),AO({definitions:SO(t),options:t,clearOptionKeys:h,clearItemMetadataKeys:y}),eO(e,t,y),CO(t,f),xO(t);let v=U(t.author,s.author_default),w=new Date,k=w.toISOString(),S=sO(t.dep,s.id_prefix,k,v);Ii(e,S.additions);let A=await Js({pmRoot:r,dependencies:S.additions,idPrefix:s.id_prefix,itemFormat:s.item_format,typeToFolder:l.type_to_folder,allowUnresolved:t.allowUnresolvedDeps,holders:[{id:e}],schema:s.schema}),C=aO(t.depRemove,s.id_prefix),b=Xt("--comment",t.comment,k,v),E=t.ownershipMetadataBypass===!0&&b.values?{...b,values:b.values.map(D=>({...D,author:v}))}:b,N=Xt("--note",t.note,k,v),T=Xt("--learning",t.learning,k,v),R=zc(t.file),G=Wc(t.test);G.values=await Tn(G.values,v,k);let pe=Bc(t.doc),ce=[],de=await MO({id:e,options:t,unsetTargets:f,pmRoot:r,settings:s,typeRegistry:l,parentReferencePolicy:g}),ue=await dO(t.blockedBy,y.has("blocked_by"),r,s.id_prefix,s.item_format,l.type_to_folder),tn=ue.id,Pn=[...de.warnings,...PO(ue)],it=iu(t,o,t.runtimeFieldCommands),Ne=RO(t,it);if(!Object.values(Ne).some(Boolean))return OO({pmRoot:r,id:e,settings:s,typeRegistry:l});ce.push(...await FO({options:t,fieldFlags:Ne,workflowEnforcement:u,typeWorkflows:p,statusRegistry:a,typeRegistry:l,pmRoot:r,id:e,settings:s}));let ht=await $O({options:t,fieldFlags:Ne,statusRegistry:a,workflowTransitionWarnings:ce,global:n,id:e});if(ht)return ht;NO(t);let Ee=ae(),Me=Ne.parent&&!y.has("parent")||S.additions.some(D=>As(D.kind,Ee)),yt=await $s({pmRoot:r,author:v,ttlSeconds:s.locks.ttl_seconds,waitMs:s.locks.wait_ms,required:Me});try{let D=await LO({fieldFlags:Ne,clearedMetadataKeys:y,pmRoot:r,settings:s,typeToFolder:l.type_to_folder}),rt,vt,V=await cr({pmRoot:r,settings:s,typeToFolder:l.type_to_folder,id:e,op:uL(t,i),author:v,message:t.message,resolveHistoryContext:()=>vt,force:t.force,bypassAssigneeConflict:t.ownershipMetadataBypass===!0||t.ownershipDependencyBypass===!0,extensionFieldNames:d,skipNoop:!0,mutate(Ve){rt=mL({document:Ve,recurrenceReason:i.recurrenceReason,requestedStatus:t.status,statusRegistry:a}),vt=rt?{recurrence:rt}:void 0,D=D?.map(Ui=>Ui.id===Ve.metadata.id?structuredClone(Ve.metadata):Ui);let Aa=lL(Ve,{options:t,settings:s,typeRegistry:l,statusRegistry:a,runtimeFieldRegistry:o,extensionRegistrations:c,extensionFieldNames:d,clearItemMetadataKeys:y,dependencyUpdates:S,dependencyRemovals:C,commentUpdates:E,noteUpdates:N,learningUpdates:T,fileUpdates:R,testUpdates:G,docUpdates:pe,resolvedParentValue:de.resolvedParentValue,resolvedBlockedByDependencyId:tn,runtimeFieldUpdates:it,nowValue:w,nowIso:k,author:v,pmRoot:r});return DO({before:D,document:Ve,statusRegistry:a}),Aa}});await yt();let Ta=D?Ts(D,D.map(Ve=>Ve.id===V.item.id?V.item:Ve),V.item.id):[];return{item:V.item,changed_fields:V.changedFields,warnings:[...ce,...Pn,...A,...Ta,...V.warnings],...rt===void 0?{}:{lifecycle_transition:rt}}}finally{await yt()}}function uL(e,t){return e.ownershipMetadataBypass===!0||e.ownershipDependencyBypass===!0?"update_ownership_bypass":t.recurrenceReason===void 0?"update":"reopen"}function mL(e){if(e.recurrenceReason===void 0)return;let t=me(e.document.metadata.status,e.statusRegistry)??e.document.metadata.status;if(!_e(t,e.statusRegistry))throw new _(`Item ${e.document.metadata.id} is already active with status ${t}; recurrence transitions require a terminal item.`,m.CONFLICT,{code:"item_already_active",reason:"recurrence_requires_terminal_item",required:"Use item reopen only for a terminal item whose work has recurred.",why:"Appending a recurrence event to active work would corrupt lifecycle history.",recovery:{suggested_retry:`pm get ${e.document.metadata.id} --full`,suggested_retry_args:["get",e.document.metadata.id,"--full"]},nextSteps:[`Inspect the active item with: pm get ${e.document.metadata.id} --full`,`Continue the existing work with: pm update ${e.document.metadata.id} ...`]});let n=e.requestedStatus??e.statusRegistry.open_status,i=me(n,e.statusRegistry)??n,r=e.document.metadata,s=Object.fromEntries(["close_reason","resolution","expected_result","actual_result","fixed_version"].flatMap(a=>{let o=r[a];return typeof o=="string"?[[a,o]]:[]}));return{reason:e.recurrenceReason,from_status:t,to_status:i,previous_terminal:s}}async function aa(e,t,n){return cv(e,t,n)}async function b2(e,t,n,i){let r=await cv(e,t,n,{recurrenceReason:i});if(r.lifecycle_transition===void 0)throw new _(`Item ${e} did not produce the required recurrence receipt.`,m.GENERIC_FAILURE,{code:"reopen_receipt_missing",reason:"recurrence_transition_not_recorded",required:"A successful reopen must return the terminal-to-active lifecycle transition recorded in immutable history."});return{...r,lifecycle_transition:r.lifecycle_transition}}(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]="56177893-3ccb-5b3f-aa82-9365c26c5d34")}catch{}})();async function dv(e,t,n){return[...await Promise.resolve().then(()=>ct(at(e,t),t)).catch(()=>[])].reverse().find(i=>i.patch.some(r=>r.path==="/metadata/assignee"))?.op==="claim"?`claimed by ${n}`:`assigned to ${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]="e32c9f13-2e6a-5ac6-a1ce-9c839121441a")}catch{}})();function oa(e,t){if(e.handoff===void 0)return;if(e.pause===!0)throw new _("--handoff cannot be combined with --pause. Choose a handoff queue or pause the item.",m.USAGE);let n=typeof e.handoff=="string"?Ke(e.handoff,t):void 0;if(n===void 0||Nt(n,t)||n===t.in_progress_status)throw new _("--handoff must name a configured non-terminal status distinct from the in-progress status. Inspect pm schema statuses or add a project queue with pm schema add-status <queue> --role active.",m.USAGE);if(typeof e.message!="string"||e.message.trim().length===0)throw new _("--handoff requires --message with implementation evidence and the next verification step.",m.USAGE);return n}function lv(e,t,n,i,r){if(Nt(e.status,i)||!e.assignee?.trim())throw new _("Handoff requires a claimed, non-terminal item. Claim the active work before handing it off; use pm item reopen for completed work.",m.CONFLICT);let s=n.governance.workflow_enforcement??"off",a=ia({enforcement:s,typeWorkflows:s==="off"?[]:kr(n.schema),statusRegistry:i,typeName:e.type,fromStatus:e.status,toStatus:t}),o={from_status:e.status,to_status:t,message:r},c=e.status===t?[]:["status"];return e.status=t,{receipt:o,warnings:a?[a]:[],changedFields:c}}(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]="ca9fb199-0de6-5eea-bed8-7afac49123bc")}catch{}})();var uv="no_available_next_item";function _L(e){if(!(e instanceof Error)||e.name!=="PmCliError")return!1;let t=e.context;return typeof t=="object"&&t!==null&&"code"in t&&t.code==="already_claimed_by"}async function Qc(e,t,n,i={}){let r=x(process.cwd(),n.path);await $(r);let s=await I(r),a=K(s.schema),o=U(i.author,s.author_default),c=Wa(o),d=null,l=!1,u=[],p=await se({pmRoot:r,settings:s,id:e,op:"claim",author:o,message:i.message,force:t,skipNoop:!0,async mutate(g){let f=g.metadata.assignee??"",h=g.metadata.claim_principal?.trim()||f;if(d=f.trim().length>0?f:null,Nt(g.metadata.status,a)&&!t)throw new _(`Cannot claim terminal item ${g.metadata.id} without --force`,m.CONFLICT);if(d!==null&&h!==c){if(i.ifAvailable===!0)return l=!0,u.push(`claim_skipped_held_by:${d}`),{changedFields:[]};if(!t){let w=await dv(r,g.metadata.id,f);throw new _(`Item ${g.metadata.id} is already ${w}. Use --force to take over, or --if-available to skip without failing.`,m.CONFLICT,{code:"already_claimed_by",why:"Claim is an atomic test-and-set so parallel agents never proceed believing they own the same item.",nextSteps:["Run pm next to pick a different unclaimed item.","Re-run with --if-available to treat a held item as a no-op skip.","Re-run with --force only when taking over the item is coordinated."]})}u.push(`claim_takeover:${d}->${o}`)}let y={assignee:o,claim_principal:c},v=["assignee","claim_principal"].filter(w=>g.metadata[w]!==y[w]);return Object.assign(g.metadata,y),{changedFields:v,warnings:u}}});return l||await up({pmRoot:r,settings:s,principal:c,itemId:p.item.id}),{item:p.item,changed_fields:p.changedFields,claimed_by:l&&d!==null?d:o,previous_assignee:d,forced:t,...l?{skipped:!0}:{},...u.length>0?{warnings:u}:{}}}async function U2(e,t,n={},i={}){let r=pL(n.maxAttempts),s=await I(x(process.cwd(),t.path)),a={...n,author:U(n.author,s.author_default)},o=await _p({...i,callerAuthor:a.author,limit:String(r)},t),c=[o.recommended,...o.ready].filter(d=>d!==null).map(d=>({...d,reasons:"reasons"in d?d.reasons:["ranked ready candidate"]}));return fL(c.slice(0,r),e,t,a)}function pL(e){if(e===void 0)return 10;let t=Number(e);if(!Number.isSafeInteger(t)||t<1||t>100)throw new _("--max-attempts must be an integer from 1 to 100",m.USAGE);return t}async function fL(e,t,n,i={},r=Qc){let s=0;for(let o of e){s+=1;try{let c=await r(o.id,t,n,i),d={...c,recommendation:o,attempts:s,available:!0};if(!c.skipped)return d}catch(c){if(!_L(c))throw c}}if(i.ifAvailable===!0)return{available:!1,item:null,claimed_by:U(i.author,""),previous_assignee:null,forced:t,skipped:!0,recommendation:null,attempts:s,warnings:[uv]};let a=s===0;throw new _(a?"No actionable items matched the selection filters":"No actionable item remained available to claim",a?m.NOT_FOUND:m.CONFLICT,{code:uv,why:a?"No ready items matched the specified filters or selection criteria.":"Every ranked candidate was claimed by another agent before this atomic selection completed.",nextSteps:[a?"Verify the filters or run pm next to inspect all ready work.":"Run pm claim --next again to refresh the ranked candidate set."]})}async function Zc(e,t,n,i={}){let r=x(process.cwd(),n.path);await $(r);let s=await I(r),a=U(i.author,s.author_default),o=Wa(a),c=i.ownershipReleaseBypass===!0,d=null,l=K(s.schema),u=oa(i,l);if(u!==void 0&&c)throw new _("Ownership-release bypass only clears ownership; it cannot change a handoff status.",m.USAGE);let p,g;try{g=await se({pmRoot:r,settings:s,id:e,op:"release",author:a,message:i.message,force:t,bypassAssigneeConflict:c,mutate(h){d=h.metadata.assignee??null;let y=u===void 0?void 0:lv(h.metadata,u,s,l,i.message);return p=y?.receipt,!d&&!h.metadata.claim_principal?{changedFields:[]}:(delete h.metadata.assignee,delete h.metadata.claim_principal,{changedFields:["assignee","claim_principal",...y?.changedFields??[]],warnings:y?.warnings})}})}catch(h){ai(h,{required:"For approved non-owner handoffs, prefer the ownership-release bypass before considering --force.",examples:['pm release pm-a1b2 --author "reviewer" --force'],nextSteps:["Use the package-provided ownership-release bypass for handoffs that only clear assignee metadata.","Use --force only when an explicit override is approved for broader ownership conflicts."]})}await mp({pmRoot:r,principal:o,itemId:g.item.id});let f=za(g.item.status,l)===za(l.in_progress_status,l);return{item:g.item,released_by:a,changed_fields:g.changedFields,previous_assignee:d,forced:t,...p===void 0?{}:{handoff:p},...g.warnings.length>0||f?{warnings:[...g.warnings,...f?["released_unclaimed_in_progress"]:[]]}:{},...f?{suggestions:[`${g.item.id} remains ${g.item.status} and unclaimed. If work is paused, run pm release ${g.item.id} --pause to move it to ${l.open_status}.`]}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="23f3ce6b-d536-5df2-92b1-ec756d53aa02")}catch{}})();async function ed(e,t,n){try{return await n()}catch(i){let r=i instanceof _?i.context:{},s=new _(i instanceof Error?i.message:String(i),i instanceof _?i.exitCode:m.GENERIC_FAILURE,{...r,item_id:e,why:`${t} completed for ${e} before the following step failed. No rollback was performed.${r.why?` ${r.why}`:""}`,nextSteps:[`Inspect the persisted state with pm get ${e} and pm history ${e} before retrying the failed step.`,...r.nextSteps??[]]});throw s.cause=i,s}}async function Q2(e,t,n){if(t.next===!0||t.ifAvailable===!0)throw new _("--start cannot be combined with --next or --if-available for an explicit item",m.USAGE,{code:"invalid_argument_value",required:"Remove --next and --if-available when starting an explicit item.",nextSteps:["Remove --next and --if-available, keep the explicit item ID and other supplied arguments, then retry."]});let i=await I(x(process.cwd(),n.path)),r=Hy(K(i.schema)),s=await Qc(e,t.force===!0,n,t),a=s.item.id,o=await ed(a,"claim",()=>aa(a,Do(t,{status:r},["assignee","start","next","ifAvailable","maxAttempts"]),n));return{id:a,action:"start_task",claim:s,update:o}}async function Z2(e,t,n){let i=await I(x(process.cwd(),n.path)),r=K(i.schema);oa({...t,pause:!0},r);let s=r.open_status,a=await aa(e,Do(t,{status:s},["assignee","pause"]),n),o=a.item.id,c=await ed(o,"update",()=>Zc(o,t.force===!0,n,t));return{id:o,action:"pause_task",update:a,release:c}}async function eB(e,t,n,i){let r=await Ss(e,t,n,i),s=r.item.id,a=await ed(s,"close",()=>Zc(s,n.force===!0,i,n));return{id:s,action:"close_task",close:r,release: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]="62b04ebf-f842-5a88-8817-ed9b17350034")}catch{}})();import xi from"node:crypto";import{cp as mv,lstat as gL,mkdir as Qt,readFile as Rn,readdir as nd,rename as fv,rm as rd,writeFile as ca}from"node:fs/promises";import j 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]="3b4a5521-a665-5f60-8d01-16033b078916")}catch{}})();var gv="https://schema.unbrained.dev/pm/workspace-snapshot/v1",gB=["create","list","inspect","restore","delete"],hv=j.join("runtime","workspace-snapshots"),hL=new Set(["checkpoints","locks","runtime","search","transactions"]),yL=/^[a-z0-9][a-z0-9._-]*$/,Ci="sdk-workspace-transaction",td={capacity:{code:"workspace_snapshot_storage_exhausted"},permission:{code:"workspace_snapshot_permission_denied"},resource:{code:"workspace_snapshot_resource_exhausted"}},yv={renameEntry:fv,removeEntry:async e=>{await rd(e,{recursive:!0,force:!0})}},id=class{lockPath;owner;intervalMs;timer;refresh;failure;constructor(t,n,i){this.lockPath=t,this.owner=n,this.intervalMs=Math.max(10,Math.floor(i*1e3/3))}start(){this.scheduleRenewal(),this.timer=setInterval(()=>{this.scheduleRenewal()},this.intervalMs),this.timer.unref()}async refreshNow(){this.scheduleRenewal(),await this.refresh,this.assertHealthy()}assertHealthy(){if(this.failure!==void 0)throw new Error("Workspace snapshot restore lost its writer lock",{cause:this.failure})}async stop(){this.timer!==void 0&&clearInterval(this.timer),await this.refresh,this.assertHealthy()}scheduleRenewal(){this.refresh!==void 0||this.failure!==void 0||(this.refresh=this.renew().catch(t=>{this.failure=t}).finally(()=>{this.refresh=void 0}))}async renew(){let t=JSON.parse(await Rn(this.lockPath,"utf8"));if(typeof t!="object"||t===null||Array.isArray(t))throw new Error("Workspace writer lock has invalid structure");let n=t;if(n.id!==Ci||n.owner!==this.owner||n.pid!==process.pid)throw new Error("Workspace writer lock ownership changed");await Oe(this.lockPath,`${JSON.stringify({...n,created_at:new Date().toISOString()},null,2)}
|
|
12
|
-
`)}};async function
|
|
13
|
-
`).filter(t=>t.trim().length>0).length}async function
|
|
14
|
-
`,"utf8"),await
|
|
15
|
-
`,"utf8"),await
|
|
16
|
-
`)}var
|
|
17
|
-
`,result:r})}});return{changed:a.changed,observation:a.result,ledger_path:"improvement-ledger.json"}}async function Dv(e={}){let t=x(e.cwd??process.cwd(),e.pmRoot);await $(t);let n=e.metric===void 0?void 0:Rv(e.metric),i=e.since===void 0?void 0:Ov(e.since,"since"),r=ML(e.limit),s=od(await Q(xv.join(t,"improvement-ledger.json"))).observations.filter(o=>(n===void 0||o.metric===n)&&(e.itemId===void 0||o.item_id===e.itemId)&&(i===void 0||o.observed_at>=i)),a=new Map;for(let o of s){let c=a.get(o.metric)??[];c.push(o),a.set(o.metric,c)}return{observations:[...s].reverse().slice(0,r),total:s.length,truncated:s.length>r,trends:[...a].map(([,o])=>UL(o)).sort((o,c)=>o.metric.localeCompare(c.metric)),source:"audited_workspace_singleton"}}(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]="28dd16ac-2e3b-55ed-98a6-db5f6786cbd7")}catch{}})();function jL(e){return e.agent_episode!==void 0?{id:e.agent_episode.id,source:"declared"}:{id:e.agent_instance?`inferred:instance:${e.agent_instance}`:`inferred:author:${e.author}:${e.ts.slice(0,13)}`,source:"inferred"}}function GL(e,t,n){let i=t,r=new Set([e.id]);for(;i!==void 0&&!r.has(i.id);)r.add(i.id),i=i.parent_id?n.get(i.parent_id):void 0;return i===void 0}function qL(e){let t=[e];for(;t.length>0;){let n=t.pop();n.sort((i,r)=>i.entries[0].ts.localeCompare(r.entries[0].ts)||i.id.localeCompare(r.id)),t.push(...n.map(i=>i.children))}}function Nv(e=qn,t=Gn){return t.map(n=>{let i=e.filter(r=>((n==="model"?r.model_environment_keys:r.provenance_environment_keys?.[n])?.length??0)>0||r.provenance_resolvers?.[n]!==void 0).map(r=>r.harness).sort();return{dimension:n,harnesses:i,covered:i.length>0}})}function tH(e,t=1){let n=new Map;for(let i of e){if(!i.agent_harness)continue;let r=n.get(i.agent_harness)??{harness:i.agent_harness,entries:0,observed:0,unavailable:0,legacy_missing:0};r.entries+=1,i.agent_model||i.agent_provenance?.model&&i.agent_provenance.model.value.length>0?r.observed+=1:i.agent_provenance?.model===null?r.unavailable+=1:r.legacy_missing+=1,n.set(i.agent_harness,r)}return[...n.values()].map(i=>{let r=i.observed+i.unavailable;return{...i,coverage:r===0?null:i.observed/r,inert:r>=t&&i.observed===0}}).sort((i,r)=>i.harness.localeCompare(r.harness))}function Mv(e,t=Gn,n=1){let i=new Map;for(let r of e)if(r.agent_harness)for(let s of t){let a=`${r.agent_harness}\0${s}`,o=i.get(a)??{harness:r.agent_harness,dimension:s,entries:0,observed:0,unavailable:0,legacy_missing:0};o.entries+=1;let c=r.agent_provenance?.[s];c!=null&&c.value.length>0?o.observed+=1:c===null?o.unavailable+=1:o.legacy_missing+=1,i.set(a,o)}return[...i.values()].map(r=>{let s=r.observed+r.unavailable;return{...r,coverage:s===0?null:r.observed/s,inert:s>=n&&r.observed===0}}).sort((r,s)=>r.harness.localeCompare(s.harness)||r.dimension.localeCompare(s.dimension))}function nH(e,t={}){let n=t.minimumCoverage??.8,i=t.minimumEntries??5;if(![Number.isFinite(n),n>=0,n<=1].every(Boolean))throw new RangeError("Semantic attribution minimum coverage must be from 0 to 1.");if(![Number.isSafeInteger(i),i>=1].every(Boolean))throw new RangeError("Semantic attribution minimum entries must be a positive integer.");let r=new Map;for(let c of e)if(c.agent_harness)for(let d of["role","topic"]){let l=`${c.agent_harness}\0${d}`,u=r.get(l)??{harness:c.agent_harness,dimension:d,entries:0,observed:0,by_source:{},coverage:0};u.entries+=1;let p=c.agent_provenance?.[d];p?.value&&(u.observed+=1,u.by_source[p.source]=(u.by_source[p.source]??0)+1),r.set(l,u)}let s=[...r.values()].map(c=>({...c,coverage:c.observed/c.entries,by_source:Object.fromEntries(Object.entries(c.by_source).sort(([d],[l])=>d.localeCompare(l)))})).sort((c,d)=>c.harness.localeCompare(d.harness)||c.dimension.localeCompare(d.dimension)),a=s.filter(c=>c.entries>=i),o=a.filter(c=>c.coverage<n).map(c=>`${c.harness}:${c.dimension}`);return{passed:a.length>0&&o.length===0,minimum_coverage:n,minimum_entries:i,rows:s,failures:o}}function iH(e){let t=[...e].sort((s,a)=>s.ts.localeCompare(a.ts)||s.author.localeCompare(a.author)||s.op.localeCompare(a.op)||s.before_hash.localeCompare(a.before_hash)||s.after_hash.localeCompare(a.after_hash)),n=new Map,i=new Map;for(let s of t){let a=s.agent_episode,o=jL(s),c=`${o.source}:${o.id}`,d=n.get(c);if(d){d.entries.push(s);continue}let l={id:o.id,...a?.label===void 0?{}:{label:a.label},...a?.parent_id===void 0?{}:{parent_id:a.parent_id},source:o.source,entries:[s],children:[]};n.set(c,l),a!==void 0&&i.set(o.id,l)}let r=[];for(let s of n.values()){let a=s.parent_id?i.get(s.parent_id):void 0;a&&GL(s,a,i)?a.children.push(s):r.push(s)}return qL(r),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]="6b51fdd9-9923-53c5-a798-41c15fd847a0")}catch{}})();var KL=1e4,Pv=1e5,zL=1e3,WL=30,BL=["append","comment","docs","file","learning","note","test_run"];function HL(e){let t=e??KL;if(!Number.isSafeInteger(t)||t<1||t>Pv)throw new _(`History analytics event limit must be an integer from 1 to ${Pv}.`,m.USAGE,{code:"invalid_history_analytics_limit"});return t}function Fv(e){let t=e??5;if(!Number.isSafeInteger(t)||t<1||t>1e4)throw new _("History analytics minimum sample must be an integer from 1 to 10000.",m.USAGE,{code:"invalid_history_analytics_minimum_sample"});return t}function VL(e){let t=e?.trim();if(!t)return new Date(Date.now()-WL*864e5).toISOString();let n=/^-(\d+)([dh])$/u.exec(t);if(n){let r=Number(n[1]),s=n[2]==="d"?864e5:36e5;if(!Number.isSafeInteger(r)||r<1)throw new _("History analytics --since duration must be positive.",m.USAGE,{code:"invalid_history_analytics_since"});return new Date(Date.now()-r*s).toISOString()}let i=Date.parse(t);if(!Number.isFinite(i))throw new _("History analytics --since must be an ISO timestamp or negative duration such as -30d.",m.USAGE,{code:"invalid_history_analytics_since"});return new Date(i).toISOString()}async function da(e,t){let n=HL(t.eventLimit),i=VL(t.since),r=[],s=i,a=!1;for(;r.length<n;){let o=await pp({pmRoot:e,since:s,limit:Math.min(zL,n-r.length),full:!0}),c=o.events.map(d=>({item_id:d.item_id,entry:d.entry}));if(r.push(...c),a=o.has_more,s=o.next_cursor,!o.has_more)break}return{events:r,receipt:{since:i,events:r.length,truncated:a,...a?{next_cursor:s}:{},source:"history_event_index"}}}function YL(e,t){return t==="harness"?e.agent_harness:t==="author_source"?e.author_source:e.agent_model??e.agent_provenance?.model?.value}function JL(e){for(let t=e.patch.length-1;t>=0;t-=1){let n=e.patch[t];if(n.path==="/metadata/status"&&"value"in n&&typeof n.value=="string")return n.value}}function XL(e){return BL.some(t=>e.startsWith(t))}function $v(e,t){let n=e.get(t);if(n)return n;let i={events:0,stateEvents:0,annotationEvents:0,closes:0,reopens:0,defectEscapes:0};return e.set(t,i),i}function QL(e,t,n){let i=new Map,r=new Map,s=new Map;for(let a of t){let o=YL(a.entry,e),c=JL(a.entry),d=r.get(a.item_id)===!0,l=c===void 0?d:n.has(c);if(c!==void 0&&r.set(a.item_id,l),!o)continue;let u=$v(i,o);u.events+=1,XL(a.entry.op)?u.annotationEvents+=1:u.stateEvents+=1,c!==void 0&&!d&&l?(u.closes+=1,s.set(a.item_id,o)):c!==void 0&&d&&!l&&(u.reopens+=1)}return{buckets:i,lastCloseValue:s}}function ZL(e,t,n){for(let i of n){if(i.type!=="Issue")continue;let r=new Set((i.dependencies??[]).filter(s=>s.kind==="discovered_from").map(s=>s.id));for(let s of r){let a=t.get(s);a&&($v(e,a).defectEscapes+=1)}}}function eD(e,t,n,i){let r=t.closes>=n?"available":"insufficient";return{value:e,events:t.events,state_events:t.stateEvents,annotation_events:t.annotationEvents,closes:t.closes,reopens:t.reopens,defect_escapes:t.defectEscapes,throughput_per_day:r==="available"?t.closes/i:null,rework_rate:r==="available"?t.reopens/t.closes:null,defect_escape_rate:r==="available"?t.defectEscapes/t.closes:null,sample_status:r}}function tD(e,t,n,i,r,s){let{buckets:a,lastCloseValue:o}=QL(e,t,i);return ZL(a,o,n),{dimension:e,status:a.size===0?"unavailable":"available",rows:[...a].map(([c,d])=>eD(c,d,r,s)).sort((c,d)=>d.events-c.events||c.value.localeCompare(d.value))}}function nD(e,t){let n=e[0]?.entry.ts??t,i=e[e.length-1]?.entry.ts??n,r=Date.parse(n),s=Date.parse(i);return!Number.isFinite(r)||!Number.isFinite(s)?1:Math.max(1,(s-r)/864e5)}function iD(e,t,n){let i=Nv(t),r=Mv(e,Gn,n),s=r.filter(o=>o.inert).map(o=>({harness:o.harness,dimension:o.dimension,explicit_samples:o.observed+o.unavailable})),a=i.filter(o=>!o.covered).map(o=>o.dimension);return{descriptors:i,observations:r,inert:s,undeclared:a,warnings:[...s.map(o=>`provenance_dimension_inert:${o.harness}:${o.dimension}:${String(o.explicit_samples)}`),...a.map(o=>`provenance_dimension_undeclared:${o}`)]}}async function lH(e,t=qn,n={}){return cd(await da(e,n),t,n)}function cd(e,t=qn,n={}){let i=Fv(n.minimumSample);return{...iD(e.events.map(r=>r.entry),t,i),window:e.receipt}}async function uH(e,t,n,i={}){return dd(await da(e,i),t,n,i)}function dd(e,t,n,i={}){let r=Fv(i.minimumSample),s=nD(e.events,e.receipt.since);return{dimensions:["harness","model","author_source"].map(a=>tD(a,e.events,t,n,r,s)),minimum_sample:r,policy:"observational_only_not_for_authorization_or_routing",window:e.receipt}}(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]="3e70310d-fc4f-5ea9-b9fb-7c519035301b")}catch{}})();var rD=32;function sD(e){let t=[];for(let n of e??[]){let i=[];for(let r of n.split(",")){let s=r.slice(0,r.indexOf("=")).trim();i.length>0&&s!=="unit"&&s!=="threshold"&&(t.push(i.join(",")),i=[]),i.push(r)}t.push(i.join(","))}return t}function Oi(e,t){let n=sD(e).map(i=>{let[r,...s]=i.split(","),a=r.indexOf("="),o=r.slice(0,a).trim(),c=r.slice(a+1).trim(),d=Number(c);if(a<=0||o.length===0||c.length===0||!Number.isFinite(d))throw new _(`Invalid --measure "${i}"; expected name=value[,unit=...][,threshold=...]`,m.USAGE);let l,u;for(let p of s){let g=p.indexOf("="),f=p.slice(0,g).trim(),h=p.slice(g+1).trim();if(f==="unit"&&h.length>0)l=h;else if(f==="threshold"&&h.length>0&&Number.isFinite(Number(h)))u=Number(h);else throw new _(`Invalid --measure attribute "${p}"`,m.USAGE)}return{name:o,value:d,unit:l,threshold:u,recorded_at:t}});return[...new Map(n.map(i=>[i.name,i])).values()].sort((i,r)=>i.name.localeCompare(r.name)).slice(0,rD)}function Uv(e,t,n){return e.flatMap(i=>(i.measurements??[]).filter(r=>r.name===t&&r.value<n).map(r=>({...r,run_id:i.run_id})))}function jv(e,t){let n=e.flatMap(s=>s.measurements??[]).filter(s=>s.name===t).sort((s,a)=>a.recorded_at.localeCompare(s.recorded_at)),i=n[0],r=n[1];return{name:t,latest:i?.value??null,previous:r?.value??null,delta:i!==void 0&&r!==void 0?i.value-r.value:null,unit:i?.unit}}import oD from"node:fs/promises";import qv 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]="9cd23db4-2411-5c95-a6a0-fa30dd3a9a18")}catch{}})();function la(e,t,n,i,r,s="min"){let a=r==="min"?e-t:t-e,o=s==="min"?n.localeCompare(i??n):(i??n).localeCompare(n);return a<0||a===0&&i!==null&&o<0}function aD(e,t){let n=Buffer.byteLength(t,"utf8"),i=0,r=null,s=null,a=Number.POSITIVE_INFINITY,o=Number.NEGATIVE_INFINITY;for(let c of t.split(/\r?\n/)){let d=c.trim();if(d==="")continue;i+=1;let l;try{l=JSON.parse(d)}catch{continue}if(l===null||typeof l!="object"||!("ts"in l)||typeof l.ts!="string")continue;let u=l.ts,p=Date.parse(u);Number.isNaN(p)||(la(p,a,u,r,"min")&&(a=p,r=u),la(p,o,u,s,"max","max")&&(o=p,s=u))}return{id:e,bytes:n,lines:i,oldest_ts:r,newest_ts:s}}function Gv(e,t){let n=t?.topN??5,i=Math.max(0,Math.floor(n)),r=e.map(({id:g,raw:f})=>aD(g,f)),s=0,a=0,o=null,c=null,d=Number.POSITIVE_INFINITY,l=Number.NEGATIVE_INFINITY;for(let g of r){if(s+=g.lines,a+=g.bytes,g.oldest_ts!==null){let f=Date.parse(g.oldest_ts);la(f,d,g.id,o?.id??null,"min")&&(d=f,o={id:g.id,ts:g.oldest_ts})}if(g.newest_ts!==null){let f=Date.parse(g.newest_ts);la(f,l,g.id,c?.id??null,"max")&&(l=f,c={id:g.id,ts:g.newest_ts})}}let u=i===0?[]:[...r].sort((g,f)=>f.bytes-g.bytes||g.id.localeCompare(f.id)).slice(0,i),p=i===0?[]:[...r].sort((g,f)=>f.lines-g.lines||g.id.localeCompare(f.id)).slice(0,i);return{total_streams:e.length,total_lines:s,total_bytes:a,largest_by_bytes:u,deepest_by_lines:p,oldest_entry:o,newest_entry:c}}(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]="b9d089ef-bca9-547f-a860-4002ec181cd0")}catch{}})();function cD(e){return e.reduce((t,n)=>(t[n]=0,t),{})}function dD(e,t,n,i,r){let s=Hn(e,"type",i),a=new Set(s.rows.map(u=>u.key)),o=t.filter(u=>!a.has(u)),c=(r?[...s.rows,...o.map(u=>({label:u,key:u,total:0,buckets:{open:0,in_progress:0,blocked:0,draft:0,closed:0,canceled:0,other:0}}))]:s.rows).map(u=>({type:u.key??u.label,total:u.total,open:u.buckets.open,in_progress:u.buckets.in_progress,blocked:u.buckets.blocked,draft:u.buckets.draft,closed:u.buckets.closed,canceled:u.buckets.canceled,other:u.buckets.other})),d=cD([...n]);for(let u of e)d[u.status]+=1;let l=Object.fromEntries(Object.entries(d).filter(([,u])=>r||u>0));return{byType:c,byStatus:l,omitted:r?0:o.length+Object.values(d).filter(u=>u===0).length}}function lD(e){return e.trim().length===0?0:e.split(/\r?\n/u).filter(t=>t.trim().length>0).length}async function uD(e){let t=qv.join(e,"history");if(!await te(t))return[];await $e({path:t,scope:"project"});let n=(await oD.readdir(t)).filter(r=>r.endsWith(".jsonl")).sort((r,s)=>r.localeCompare(s)),i=[];for(let r of n){let s=qv.join(t,r),a=await Q(s);a!==null&&(await $e({path:s,scope:"project"}),i.push({id:r.slice(0,-6),raw:a}))}return i}async function mD(e,t){let n=[],i=O();for(let r of Oi(t.observe,i))n.push(await Lv({metric:r.name,value:r.value,direction:t.direction,unit:r.unit,threshold:r.threshold,source:t.measurementSource,itemId:t.measurementItem,revision:t.measurementRevision,observedAt:i,author:t.author,message:t.message},e));return n}function _D(e,t,n){let i={};return t.byAssignee&&(i.assignee=Hn(e,"assignee",n)),t.byTag&&(i.tag=Hn(e,"tag",n,{tagPrefix:t.tagPrefix})),t.byPriority&&(i.priority=Hn(e,"priority",n)),i}async function pD(e,t,n,i,r){let s={since:r.since,eventLimit:r.eventLimit,minimumSample:r.minimumSample},a=r.provenanceCoverage||r.fleetAttribution?await da(e,s):void 0;return{provenanceCoverage:r.provenanceCoverage&&a?cd(a,n.agent_identity?.harness_signals,s):void 0,fleetAttribution:r.fleetAttribution&&a?dd(a,t,i,s):void 0}}function fD(e,t,n,i,r){let s=Object.keys(r.breakdowns).length>0;return{totals:e,by_type:t,by_status:n,omitted_zero_buckets:i,...r.metadataCoverage?{metadata_coverage:r.metadataCoverage}:{},...s?{breakdowns:r.breakdowns}:{},...r.storage?{storage:r.storage}:{},...r.fieldUtilization?{field_utilization:r.fieldUtilization}:{},...r.improvementLedger?{improvement_ledger:r.improvementLedger}:{},...r.recordedObservations.length>0?{recorded_observations:r.recordedObservations}:{},...r.provenanceCoverage?{provenance_coverage:r.provenanceCoverage}:{},...r.fleetAttribution?{fleet_attribution:r.fleetAttribution}:{},generated_at:O()}}async function NH(e,t={}){let n=x(process.cwd(),e.path);await $(n);let i=await I(n),r=await mD(e,t),s=F(i,P()),a=K(i.schema),o=t.fieldUtilization?await dt(n,i.item_format,s.type_to_folder,void 0,i.schema):await Se(n,i.item_format,s.type_to_folder,void 0,i.schema);await sr({pmRoot:n,settings:i,itemIds:o.map(k=>k.id),commandLabel:"stats"});let c=j_(a),d=dD(o,s.types,a.definitions.map(k=>k.id),c,t.includeEmpty===!0),l=await uD(n),u=0;for(let k of l)u+=lD(k.raw);let p=t.storage?Gv(l):void 0,g=t.metadataCoverage?G_(o,c):void 0,f=_D(o,t,c),h=t.fieldUtilization?q_(o):void 0,y=t.measurements===!0||r.length>0?await Dv({pmRoot:n,metric:t.metric,itemId:t.measurementItem,limit:t.measurementLimit}):void 0,{provenanceCoverage:v,fleetAttribution:w}=await pD(n,o,i,a.terminal_statuses,t);return fD({items:o.length,history_streams:l.length,history_entries:u},d.byType,d.byStatus,d.omitted,{metadataCoverage:g,breakdowns:f,storage:p,fieldUtilization:h,improvementLedger:y,recordedObservations:r,provenanceCoverage:v,fleetAttribution:w})}import gD from"node:fs/promises";import gt 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]="a41eaff2-6a15-5e82-b3aa-03ca48fc3eb5")}catch{}})();var Hv=gt.join("runtime","telemetry","events.jsonl"),md=gt.join("runtime","telemetry","state.json"),hD=gt.join("runtime","telemetry"),yD=20,_d=Ot.filter(e=>e.lifecycle==="deprecated"),Kv=["status","flush","stats","clear"],zv=(e,t)=>{let n=Math.ceil(t*e.length),i=Math.min(e.length-1,Math.max(0,n-1));return e[i]},ld=(e,t)=>typeof e!="string"?t:e.trim().length>0?e:t,Wv=e=>{if(!(typeof e!="number"||!Number.isFinite(e)))return Math.trunc(e)},vD=e=>({command:ld(e.event.command,"<unknown>"),eventType:ld(e.event.event_type,"unknown"),eventSchemaVersion:Wv(e.event.schema_version),clientSchemaVersion:Wv(e.client_schema_version)}),wD=()=>({count:0,max_attempts:0,event_type_counts:{},event_schema_versions:new Set,client_schema_versions:new Set,finish_durations_ms:[],ok_count:0,error_count:0,resolution_counts:{}}),bD=e=>{let t=e?.duration_ms;return typeof t=="number"&&Number.isFinite(t)?t:void 0},kD=e=>{let t=e?.command_resolution;return ld(t,"")||void 0},Vv=(e,t)=>{e[t]=(e[t]??0)+1},ED=(e,t)=>{let n=bD(t);n!==void 0&&e.finish_durations_ms.push(n),t?.ok===!0?e.ok_count+=1:e.error_count+=1;let i=kD(t);i!==void 0&&Vv(e.resolution_counts,i)},SD=e=>Number.isFinite(e)?Math.max(0,Math.trunc(e)):0,Bv=(e,t)=>{t!==void 0&&e.add(t)},TD=(e,t)=>{let n=vD(t),i=e.get(n.command)??wD();i.count+=1,i.max_attempts=Math.max(i.max_attempts,SD(t.attempts)),Vv(i.event_type_counts,n.eventType),Bv(i.event_schema_versions,n.eventSchemaVersion),Bv(i.client_schema_versions,n.clientSchemaVersion),n.eventType==="command_finish"&&ED(i,t.event.payload),e.set(n.command,i)},AD=(e,t)=>{let n=t.ok_count+t.error_count,i=[...t.finish_durations_ms].sort((s,a)=>s-a),r=Object.entries(t.resolution_counts).sort((s,a)=>s[0].localeCompare(a[0]));return{command:e,count:t.count,event_type_counts:Object.fromEntries(Object.entries(t.event_type_counts).sort((s,a)=>s[0].localeCompare(a[0]))),max_attempts:t.max_attempts,event_schema_versions:[...t.event_schema_versions].sort((s,a)=>s-a),client_schema_versions:[...t.client_schema_versions].sort((s,a)=>s-a),...i.length>0?{duration_p50_ms:zv(i,.5),duration_p95_ms:zv(i,.95),duration_max_ms:i[i.length-1]}:{},...n>0?{ok_count:t.ok_count,error_count:t.error_count,error_rate:t.error_count/n}:{},...r.length>0?{command_resolution_counts:Object.fromEntries(r)}:{}}},ID=e=>{let t=(e??"status").trim().toLowerCase();if(Kv.includes(t))return t;throw dr({command_path:"telemetry",token:e?.trim()||"<empty>",allowed:Kv,examples:["pm telemetry status","pm telemetry flush","pm telemetry stats --limit 10","pm telemetry clear"]})},pd=()=>{throw new _("--limit must be a positive integer",m.USAGE)},Yv=e=>[!Number.isFinite(e),!Number.isInteger(e),e<=0].includes(!0)?pd():e,CD=e=>{let t=e.trim();return[t.length===0,!/^\d+$/.test(t)].includes(!0)?pd():Yv(Number.parseInt(t,10))},xD=e=>e===void 0?yD:typeof e=="number"?Yv(e):typeof e=="string"?CD(e):pd(),RD=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.attempts=="number"&&typeof t.event=="object"&&t.event!==null},OD=e=>{try{let t=JSON.parse(e);return RD(t)?t:void 0}catch{return}},LD=e=>e===null?[]:e.split(`
|
|
18
|
-
`).map(t=>t.trim()).filter(t=>t.length>0),
|
|
19
|
-
`)},e,250)}catch{}return s}async function
|
|
20
|
-
`),!0},n,250)}catch{return!1}}var ua=e=>e??null,_a=async e=>{let t=await I(e),n=gt.join(e,Hv),i=gt.join(e,md),r=await Q(n),s=Jv(r),a=await ma(i),o=$t();return{enabled:t.telemetry.enabled&&!o.telemetry_disabled,configured_enabled:t.telemetry.enabled,env_overrides:o,endpoint:t.telemetry.endpoint,queue_path:n,state_path:i,queue_rows_total:s.rows_total,queue_entries:s.valid_entries,queue_invalid_rows:s.invalid_rows,queue_size_bytes:Buffer.byteLength(r??"","utf8"),last_attempted_flush_at:ua(a.last_attempted_flush_at),last_successful_flush_at:ua(a.last_successful_flush_at),last_failed_flush_at:ua(a.last_failed_flush_at),last_failed_flush_error:ua(a.last_failed_flush_error)}},FD=e=>{let t=new Map;for(let n of e)TD(t,n);return[...t.entries()].map(([n,i])=>AD(n,i)).sort((n,i)=>i.count-n.count||n.command.localeCompare(i.command))},$D=async(e,t)=>({action:"telemetry",subcommand:"status",status:await _a(t.globalPmRoot),generated_at:O()}),UD=async(e,t)=>{let n=await _a(t.globalPmRoot);await S_(t.globalPmRoot);let i=await _a(t.globalPmRoot),r=Math.max(0,n.queue_entries-i.queue_entries),s=i.queue_entries===0;return{action:"telemetry",subcommand:"flush",queue_entries_before:n.queue_entries,queue_entries_after:i.queue_entries,queue_entries_drained:r,queue_progressed:r>0,queue_empty:s,queue_drained:s,status:i,generated_at:O()}},jD=async(e,t)=>{let n=xD(e.limit),i=await Q(t.queuePath),r=Jv(i),s=FD(r.entries),a=s.slice(0,n),o=await I(t.globalPmRoot),c=await PD(t.globalPmRoot,t.statePath,o.telemetry.retention_days),d=Object.entries(c).map(([l,u])=>{let p=Object.values(u.days);return{alias:l,canonical:u.canonical,count:p.reduce((g,f)=>Math.min(Number.MAX_SAFE_INTEGER,g+f.count),0),last_seen:p.map(g=>g.last_seen).sort().at(-1)}}).sort((l,u)=>u.count-l.count||l.alias.localeCompare(u.alias));return{action:"telemetry",subcommand:"stats",limit:n,total_commands:s.length,queue_entries:r.valid_entries,queue_invalid_rows:r.invalid_rows,queue_rows_total:r.rows_total,truncated:s.length>a.length,stats:a,alias_usage:d,zero_use_aliases:_d.map(l=>l.alias).filter(l=>c[l]===void 0),alias_usage_retention_days:o.telemetry.retention_days,generated_at:O()}},GD=async(e,t)=>Er(async()=>{let n=await I(t.globalPmRoot),i=[n.telemetry.enabled!==!1,n.telemetry.installation_id!=="",n.telemetry.first_run_prompt_completed!==!0].includes(!0);n.telemetry.enabled=!1,n.telemetry.first_run_prompt_completed=!0,n.telemetry.installation_id="",i&&await fu(t.globalPmRoot,n,"telemetry:clear");let r=gt.join(t.globalPmRoot,hD),s=await te(r);return await gD.rm(r,{recursive:!0,force:!0}),{action:"telemetry",subcommand:"clear",settings_changed:i,runtime_dir_removed:s&&!await te(r),queue_exists_after:await te(t.queuePath),state_exists_after:await te(t.statePath),status:await _a(t.globalPmRoot),generated_at:O()}},t.globalPmRoot),qD={status:$D,flush:UD,stats:jD,clear:GD};async function YH(e,t){let n=ID(e.subcommand),i=qe(process.cwd());return qD[n](e,{globalPmRoot:i,queuePath:gt.join(i,Hv),statePath:gt.join(i,md)})}(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]="2661c74e-3e73-50f5-80a2-f103ff0cf2d4")}catch{}})();var Qv=100;function On(e,t="--only-index"){let n=typeof e=="number"?e:Number(String(e).trim());if(!Number.isInteger(n)||n<1)throw new _(`${t} requires a 1-based integer index into the linked-test list (got "${e}"). Use pm test <id> --list to inspect positions.`,m.USAGE);return n}function KD(e){let t=(e.command??e.path??"<no command>").replaceAll(/\s+/g," ").trim()||"<no command>";return t.length<=Qv?t:`${t.slice(0,Qv-3)}...`}function Zv(e){return e.map((t,n)=>`${n+1}. ${KD(t)}`).join("; ")}function zD(e){let t=[];return e.match!==void 0&&t.push("match"),e.onlyIndex!==void 0&&t.push("only-index"),e.onlyLast===!0&&t.push("only-last"),t}function WD(e,t){let n=e.command?.toLowerCase()??"",i=e.path?.toLowerCase()??"";return n.includes(t)||i.includes(t)}function ew(e,t){let n=zD(t);if(n.length===0)return{selector:null,requested:null,selected:e,selected_indexes:e.map((r,s)=>s+1),selected_count:e.length,skipped_count:0};if(n.length>1)throw new _(`Combine at most one linked-test selector per run: ${n.map(r=>`--${r}`).join(" and ")} were provided. Pick one of --match, --only-index, --only-last.`,m.USAGE);let i=n[0];if(e.length===0)throw new _(`--${i} matched no linked tests because this item has none. Add one first with --add, --command, or --add-json.`,m.USAGE);if(i==="match"){let r=t.match.trim().toLowerCase();if(r.length===0)throw new _("--match requires a non-empty substring to match against linked-test command/path values",m.USAGE);let s=[],a=[];for(let o=0;o<e.length;o+=1)WD(e[o],r)&&(a.push(e[o]),s.push(o+1));if(a.length===0)throw new _(`--match "${t.match}" matched none of the ${e.length} linked test(s). Available entries: ${Zv(e)}`,m.USAGE);return{selector:"match",requested:t.match,selected:a,selected_indexes:s,selected_count:a.length,skipped_count:e.length-a.length}}if(i==="only-index"){let r=On(t.onlyIndex);if(r>e.length)throw new _(`--only-index ${r} is out of range: this item has ${e.length} linked test(s). Available entries: ${Zv(e)}`,m.USAGE);return{selector:"only-index",requested:String(r),selected:[e[r-1]],selected_indexes:[r],selected_count:1,skipped_count:e.length-1}}return{selector:"only-last",requested:"last",selected:[e[e.length-1]],selected_indexes:[e.length],selected_count:1,skipped_count:e.length-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]="cfcc5f4f-caf0-5a2e-8a9d-219c3afb5d2d")}catch{}})();function tw(e){if(e.update===void 0&&e.updateIndex===void 0&&e.setJson===void 0)return;if(e.update===void 0==(e.updateIndex===void 0)||e.setJson===void 0)throw new _("Use exactly one --update or --update-index with --set-json",m.USAGE);let t;try{t=JSON.parse(e.setJson)}catch{throw new _("--set-json must contain a JSON object with explicit linked-test metadata fields",m.USAGE)}if(e.updateIndex!==void 0)return{selector:{index:On(e.updateIndex,"--update-index")},patch:t};let n=e.update,i=/^(command|path)=/u.exec(n);return{selector:i?.[1]==="path"?{path:n.slice(i[0].length)}:{command:i?n.slice(i[0].length):n},patch:t}}function nw(e){if([e.list,e.run,e.progress,e.timeout!==void 0,e.acknowledgeLinkedTests,e.metricBelow!==void 0,e.metricDiff!==void 0,(e.add?.length??0)>0,(e.addJson?.length??0)>0,(e.remove?.length??0)>0,(e.removeIndex?.length??0)>0].some(Boolean))throw new _("Edit linked-test metadata separately from listing, additions, removals, execution options, metric filters and trust acknowledgement",m.USAGE)}function BD(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new _("Select one linked test by index, command, or path",m.USAGE);let n=Object.keys(t);if(n.length!==1||!["index","command","path"].includes(n[0]))throw new _("Select one linked test by index, command, or path",m.USAGE);if("index"in t){let i=On(t.index,"--update-index");if(i<=e.length)return i-1}else{let i="command"in t?"command":"path",r="command"in t?t.command:t.path;if(typeof r!="string"||r.trim().length===0)throw new _("Linked-test selector must be a non-empty command or path",m.USAGE);let s=e.flatMap((a,o)=>a[i]===r?[o]:[]);if(s.length===1)return s[0];if(s.length>1)throw new _(`Linked-test selector is ambiguous; matching indexes: ${s.map(a=>a+1).join(", ")}`,m.USAGE,{code:"linked_test_update_ambiguous",required:"List linked tests and select one current --update-index."})}throw new _("No linked test matched the update selector",m.NOT_FOUND,{code:"linked_test_update_no_match",required:"List linked tests and select a current command, path, or --update-index."})}function HD(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new _("Linked-test metadata patch must be a JSON object",m.USAGE);let n=Object.keys(t);if(n.length===0||n.some(o=>!Ge.includes(o)||["command","cmd","timeout"].includes(o)))throw new _("Patch explicit linked-test metadata fields; command, aliases and provenance cannot be edited",m.USAGE);if(t.scope===null)throw new _("scope is required and cannot be cleared",m.USAGE);let i=Object.fromEntries(Object.entries(e).filter(([o])=>Ge.includes(o))),r=ru(Fs(JSON.stringify({...i,command:e.command??"legacy-path-only",...Object.fromEntries(Object.entries(t).map(([o,c])=>[o,c===null?void 0:c]))}),"--set-json")[0]);ms(r);let s=n.filter(o=>!Fe(e[o],r[o])),a={...e};for(let o of s){let c=r[o];Object.assign(a,{[o]:c}),c===void 0&&delete a[o]}if(!a.command?.trim()&&!a.path?.trim())throw new _("Linked-test entry must retain a command or path",m.USAGE);return{test:a,fields:s}}async function iw(e,t,n={}){let i=x(process.cwd(),n.path);await $(i);let r=await I(i),s=U(t.author,r.author_default),a=F(r,P()),o=0,c=[],d=await cr({pmRoot:i,settings:r,id:e,author:s,op:"tests_update",message:t.message,force:t.force,skipNoop:!0,typeToFolder:a.type_to_folder,resolveHistoryContext:()=>({linked_test_update:{index:o,fields:c}}),mutate(u){let p=u.metadata.tests??[],g=BD(p,t.selector),f=HD(p[g],t.patch);return o=g+1,c=f.fields,f.fields.length===0?{changedFields:[]}:(u.metadata.tests=p.map((h,y)=>y===g?{...f.test,updated_by:s,updated_at:O()}:h),{changedFields:["tests"]})}}),l=d.item.tests;return{ok:!0,id:d.item.id,tests:l,count:l.length,changed:d.changedFields.length>0,updated_index:o,updated_fields:c}}(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]="8316bbdc-b0f7-59b2-8875-1e0ad77eb8c0")}catch{}})();var VD=[{code:"no_projects_matched_filters",regex:/\bNo projects matched the filters\b/i},{code:"no_test_files_found",regex:/\bNo test files found\b/i},{code:"no_tests_found",regex:/\bNo tests found\b/i},{code:"no_matching_tests",regex:/\bNo matching tests?\b/i},{code:"collected_zero_items",regex:/\bcollected 0 items?\b/i},{code:"reported_zero_tests",regex:/^\s*Ran 0 tests? across \d+ files?\./imu},{code:"reported_zero_passes",regex:/(?:^\s*(?:#|ℹ)?\s*tests\s+0\s*$[\s\S]*^\s*(?:#|ℹ)?\s*pass\s+0\s*$|^\s*(?:#|ℹ)?\s*pass\s+0\s*$[\s\S]*^\s*(?:#|ℹ)?\s*tests\s+0\s*$)/imu},{code:"reported_zero_tests",regex:/^\s*(?:#|ℹ)?\s*tests\s+0\s*$/imu}],YD=[{receiptCode:"reported_tests",regex:/^\s*(?:#|ℹ)?\s*tests\s+[1-9]\d*\s*$/imu},{receiptCode:"reported_passes",regex:/^\s*(?:#|ℹ)?\s*pass\s+[1-9]\d*\s*$/imu},{receiptCode:"tests_passed",regex:/\bTests?\s+[1-9]\d*\s+passed\b/iu},{receiptCode:"passed_count",regex:/\b[1-9]\d*\s+passed\b/iu},{receiptCode:"tests_summary",regex:/\bTests:\s+(?:.*\b)?[1-9]\d*\s+passed\b/iu},{receiptCode:"bun_pass_count",regex:/^\s*[1-9]\d* pass\s*$/imu},{receiptCode:"bun_executed_tests",regex:/^\s*Ran [1-9]\d* tests? across \d+ files?\./imu}];function pa(e,t){let n=`${e}
|
|
21
|
-
${t}`;for(let i of VD)if(i.regex.test(n))return{code:i.code};return null}function rw(e,t){for(let[n,i]of[["stdout",e],["stderr",t]]){let r=YD.find(s=>s.regex.test(i));if(r)return{code:r.receiptCode,stream: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]="5aa7e990-08d9-56e4-860c-3fc52cebe728")}catch{}})();function sw(e,t,n,i,r){if((t.measure?.length??0)===0||r.some(a=>typeof a.stdout=="string"&&a.failure_category!=="spawn_error"&&a.failure_category!=="empty_run"&&pa(a.stdout,a.stderr??"")===null))return;let s=["--pm-path",i,...n.noExtensions?["--no-extensions"]:[],...n.author?["--author",n.author]:[],"test",e,"--list","--json"];throw new _("--measure requires an executed linked test",m.USAGE,{code:"test_measure_requires_execution",required:"Execute at least one linked command before recording measurement evidence.",why:"Empty, skipped and pre-execution refused runs cannot support measured evidence.",nextSteps:["Inspect the linked commands, adjust empty selections or missing commands, and resolve any trust refusal before retrying the measurement."],recovery:{suggested_retry:fe(s),suggested_retry_args:s}})}function fd(e,t,n,i,r=!1){if((t.measure?.length??0)===0||t.run===!0)return;let s=["--pm-path",i,...n.noExtensions?["--no-extensions"]:[],...n.author?["--author",n.author]:[]],a=[...s,...np(e,t),...t.list?["--list"]:[],...r?["--background"]:[]],o=t.acknowledgeLinkedTests?[...s,"test",e,"--help"]:a,c=[...s,"test",e,"--acknowledge-linked-tests",...t.author?["--author",t.author]:[]];throw new _("--measure requires --run",m.USAGE,{code:"test_measure_requires_run",flag:"--measure",required:"Run the linked tests with --run to record measurement evidence.",why:"Measurements describe an executed linked-test run; recording them without execution would fabricate evidence.",...t.acknowledgeLinkedTests?{nextSteps:[`Review the linked commands and apply any requested link updates separately before acknowledging trust: ${fe([...s,"test",e,"--list"])}`,`After review, acknowledge trust as a separate non-executing operation: ${fe(c)}`,`Then run the measurement without --acknowledge-linked-tests: ${fe(a)}`]}:{},recovery:{missing:["--run"],suggested_retry:fe(o),suggested_retry_args:o}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="92f73d30-eac7-5c84-a7be-133323d1f549")}catch{}})();function aw(e){if(!/^(?:[^.[\]]+|\[\d+\])(?:\.[^.[\]]+|\[\d+\])*$/u.test(e))return[];let t=[],n=e.matchAll(/[^.[\]]+|\[\d+\]/g);for(let[i]of n){if(i.startsWith("[")&&i.endsWith("]")){let r=Number.parseInt(i.slice(1,-1),10);if(!Number.isSafeInteger(r))return[];t.push(r);continue}t.push(i)}return t}function gd(e,t){let n=t.trim();if(n.length===0)return{found:!1,value:void 0};let i=aw(n);if(i.length===0)return{found:!1,value:void 0};let r=e;for(let s of i){if(typeof r!="object"||r===null)return{found:!1,value:void 0};if(typeof s=="number"&&(!Array.isArray(r)||s>=r.length))return{found:!1,value:void 0};let a=Object.getOwnPropertyDescriptor(r,s);if(!a||!Object.hasOwn(a,"value"))return{found:!1,value:void 0};r=a.value}return{found:!0,value:r}}import{cp as JD,lstat as XD,mkdir as QD,readlink as ZD,realpath as yd,stat as eN,symlink as ow}from"node:fs/promises";import{execFile as tN}from"node:child_process";import B from"node:path";import{promisify as nN}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]="26cfff37-1b7e-556f-8656-2e5c7c9d616f")}catch{}})();var iN=new Set([".agents",".git",".nyc_output",".turbo","coverage"]),cw=nN(tN);async function rN(e,t){let n=await fa(B.join(e,".git"));if(!n||n.isDirectory()&&!await fa(B.join(e,".git/HEAD")))return;let i=Object.fromEntries(Object.entries(process.env).filter(([r])=>!r.toUpperCase().startsWith("GIT_")));await cw("git",["clone","--no-local","--no-checkout","--template=","--origin=origin","--",e,t],{env:i,timeout:12e4,maxBuffer:1024*1024,windowsHide:!0}),await cw("git",["-C",t,"remote","remove","origin"],{env:i,timeout:1e4,windowsHide:!0})}function hd(e){return e.split(B.sep).some(t=>iN.has(t.toLowerCase()))}function Li(e){return e===".."||e.startsWith(`..${B.sep}`)||B.isAbsolute(e)}async function fa(e){try{return await eN(e)}catch(t){if(!q(t))throw t;return}}async function ga(e){let t=[],n=e;for(;B.dirname(n)!==n;)try{return B.join(await yd(n),...t)}catch(i){if(!q(i))throw i;t.unshift(B.basename(n)),n=B.dirname(n)}return B.join(await yd(n),...t)}async function sN(e,t,n){let i=B.relative(t,await ga(e));if(!Li(i))return i;let r=[],s=e;for(;B.dirname(s)!==s;){let a=await ga(s),o=n.find(([,c])=>c===a);if(o)return B.join(o[0],...r);r.unshift(B.basename(s)),s=B.dirname(s)}return i}async function dw(e,t){let n=[],i=[],r=await yd(e),s=await ga(B.resolve(t));if(![B.relative(r,s),B.relative(s,r)].every(Li))throw new Error("Snapshot destination must be disjoint from the source workspace; choose a temporary root outside the checkout.");await QD(B.dirname(t),{recursive:!0}),await rN(r,t),await JD(r,t,{recursive:!0,force:!0,async filter(a){let o=B.relative(r,a);if(!o)return!0;if(hd(o))return!1;if(B.basename(a).toLowerCase()==="node_modules"){if((await fa(a))?.isDirectory()){let c=await ga(a),d=B.relative(r,c);if(!Li(B.relative(c,r))||!Li(d)&&(hd(d)||!d.split(B.sep).some(l=>l.toLowerCase()==="node_modules")))throw new Error(`Dependency symlink must target an included dependency directory or external installation: ${o}`);n.push([o,c])}return!1}return(await XD(a)).isSymbolicLink()?(i.push([o,B.resolve(B.dirname(a),await ZD(a)),(await fa(a))?.isDirectory()?"junction":"file"]),!1):!0}});for(let[a]of n)await ow(B.resolve(r,a),B.join(t,a),"junction");for(let[a,o,c]of i){let d=await sN(o,r,n);if(Li(d)||hd(d))throw new Error(`Source symlink must target included workspace source: ${a}`);await ow(B.resolve(t,d),B.join(t,a),c)}}import{spawn as Iw}from"node:child_process";import{cp as uw,mkdir as Sd,mkdtemp as Cw,open as bd,readdir as kd,rm as Ni,symlink as oN}from"node:fs/promises";import{tmpdir as xw}from"node:os";import oe 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]="b74444c7-c283-52b2-b65f-b0a086ff2b53")}catch{}})();var lw=20;function aN(){let e=process.env.PM_TRACKED_TEST_RUN_HISTORY_LIMIT;if(!e||e.trim().length===0)return lw;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?lw:t}function vd(e){let t=[...e].filter(i=>i.run_id.trim().length>0&&i.started_at.trim().length>0&&i.finished_at.trim().length>0&&i.recorded_at.trim().length>0).sort((i,r)=>{let s=Xi(i.recorded_at,r.recorded_at);if(s!==0)return s;let a=i.run_id.localeCompare(r.run_id);return a!==0?a:i.kind.localeCompare(r.kind)}),n=aN();return t.length>n?t.slice(t.length-n):t}async function ha(e){await se({pmRoot:e.pmRoot,settings:e.settings,id:e.itemId,op:"test_run_track",author:e.author,message:e.message,force:!1,mutate(t){let n=t.metadata.test_runs??[];return t.metadata.test_runs=vd([...n,e.entry]),{changedFields:["test_runs"]}}})}(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]="54338522-5725-5511-be94-b047d2c82fdc")}catch{}})();var wa=20*1024*1024,cN=3e3,dN=1e4,lN=5e3,mw=120,uN=new Set(["locks","extensions","runtime"]),mN=new Set(["history","index","search","extensions","locks","runtime"]),_N=[/eaddrinuse/i,/address already in use/i,/port\s+\d+\s+is already in use/i,/web server[^.\n]*already running/i,/failed to listen on/i],pN=/\b(?:could not|failed to|unable to)\s+acquire\b[^\n.]*\block\b/i,fN=/\b(?:already running|timed?\s*out|timeout|held by another|lock\s+is\s+held)\b/i,gN=new Set(["activity","calendar","context","ctx","deps","get","health","history","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","search","stats","test-all","validate"]);function Td(e,t){let n=process.env[e];if(typeof n!="string"||n.trim().length===0)return t;let i=Number.parseInt(n,10);return!Number.isFinite(i)||i<=0?t:i}function hN(){return Td("PM_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS",cN)}function yN(){return Td("PM_LINKED_TEST_HEARTBEAT_INTERVAL_MS",dN)}function vN(){return Td("PM_LINKED_TEST_PIPE_CLOSE_GRACE_MS",lN)}function wN(e){let t=process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();return t&&t.length>0?t:`${e}-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function bN(e){let t=0,n=0,i=0;for(let r of e){if(r.status==="passed"){t+=1;continue}if(r.status==="failed"||r.status==="refused"){n+=1;continue}i+=1}return{passed:t,failed:n,skipped:i}}function Ad(e){let t=0,n=0,i=0,r=0;for(let s of e){let a=s.execution_context;!a||a.is_pm_command!==!0||(t+=1,a.is_pm_tracker_read_command===!0&&(n+=1),a.mismatch_detected===!0&&(i+=1),a.auto_pm_context_applied===!0&&(r+=1))}return{checked_pm_commands:t,tracker_read_commands:n,mismatches:i,auto_remediated:r}}function kN(e){let t=e??"project";if(!Pe.includes(t))throw new _(`Invalid scope "${e}"`,m.USAGE);return t}function ka(e){if(!e)return"schema";let t=e.trim().toLowerCase();if(Bt.includes(t))return t;throw new _(`Invalid --pm-context value "${e}". Expected one of: ${Bt.join(", ")}`,m.USAGE)}function EN(e){return Vt(e??"source","--workspace-context")}function Rw(e,t,n){return n?t:Vt(e.workspace_context_mode,"linked test")??t}function Ow(e,t,n){return n||typeof e.pm_context_mode!="string"||e.pm_context_mode.trim().length===0?t:ka(e.pm_context_mode)}function Lw(e,t){return e==="auto"?t?"tracker":"schema":e}function SN(e){return Object.entries(e).filter(([t])=>t.startsWith("assert_")).some(([,t])=>t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:typeof t=="string"?t.trim().length>0:!0)}function TN(e){let{executionContext:t,runLevelPmContextMode:n,linkedOverridePmContextMode:i}=e;return!t.is_pm_tracker_read_command||!t.mismatch_detected?"":n==="tracker"&&i==="schema"?" Linked test metadata pm_context_mode=schema overrides run-level --pm-context tracker. Set pm_context_mode=tracker (or auto) on the linked test, or remove the override, to run against seeded tracker data.":t.pm_context_mode==="schema"?" Use --auto-pm-context to route PM tracker-read linked commands through seeded tracker data automatically. Alternatively, use --pm-context tracker for the whole run.":""}function AN(e,t){let n={};if(!e)return n;for(let i of e){let r=Ei(i,t);if(r)for(let[s,a]of Object.entries(r))n[s]=a}return n}function IN(e,t){if(!e)return[];let n=[];for(let i of e){let r=Si(i,t);r&&n.push(...r)}return[...new Set(n)]}function CN(e){let t=Pi(e);return qt(t).some(n=>os(n)!==null)}function Dw(e){let t=Pi(e);return qt(t).some(n=>{let i=os(n);if(!i)return!1;let r=uc(i);return r?gN.has(r.subcommand):!1})}function ya(e){if(e)return Jg.has(e.subcommand)?It(e.args,Xg)?.subcommand:e.subcommand}function _w(e,t){if(e==="npx"||e==="bunx")return Kt(t)?.command;if(e==="pnpm")return ya(It(t,oc));if(e==="npm")return ya(It(t,cc));if(e==="yarn")return ya(It(t,Vg));if(e==="bun")return ya(It(t,Yg))}function va(e){return e?e==="vitest"||e==="test"||e.startsWith("test:"):!1}function wd(e){return!e||!pi(e.command)&&!lc(e.command)?!1:ds(e.args)==="test-all"}var Nw=new Map([...["sh","bash","dash","zsh"].map(e=>[e,/^(?:-c|-[a-z]*c[a-z]*)$/u]),...["cmd","cmd.exe"].map(e=>[e,/^\/[ck]$/u]),...["powershell","powershell.exe","pwsh","pwsh.exe"].map(e=>[e,/^-(?:c|command)$/u])]),xN=new Set(["npx","bunx"]);function Mw(e){let t=e.split(" ").filter(a=>a.length>0),n=cs(t);if(n.length===0)return!1;let[i,...r]=n,s=Nw.get(i);if(s){let a=r.findIndex(o=>s.test(o));return a>=0?Mw(r.slice(a+1).join(" ")):!1}return pi(i)||fi(i)?ds(r)==="test-all":i==="node"&&r.length>0&&fi(r[0])?ds(r.slice(1))==="test-all":xN.has(i)?wd(Kt(r)):i==="pnpm"?wd(ls(r)):i==="npm"?wd(us(r)):!1}function Pw(e){let t=Pi(e);return qt(t).some(n=>Mw(n))}function Fw(e){if(Pw(e))throw new _('Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.',m.USAGE)}function Pi(e){return e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase()}function pw(e){return e.includes("node scripts/run-tests.mjs ")||e.endsWith("node scripts/run-tests.mjs")||e.includes("node ./scripts/run-tests.mjs ")||e.endsWith("node ./scripts/run-tests.mjs")}function Id(e){let t=e.split(" ").filter(a=>a.length>0),n=cs(t);if(n.length===0)return!1;let[i,...r]=n,s=Nw.get(i);if(s){let a=r.findIndex(o=>s.test(o));return a>=0&&Id(r.slice(a+1).join(" "))}return i==="vitest"||i.endsWith("/vitest")||i.endsWith("/vitest.mjs")?!0:i==="node"?RN(r):ON(i,r)}function RN(e){return e.includes("--test")||e.some(t=>t==="vitest"||t==="vitest.mjs"||t.endsWith("/vitest")||t.endsWith("/vitest.mjs"))}function ON(e,t){return e==="npx"||e==="bunx"?va(Kt(t)?.command):e==="pnpm"||e==="npm"?va((e==="pnpm"?ls(t):us(t))?.command)||va(_w(e,t)):(e==="yarn"||e==="bun")&&va(_w(e,t))}function p5(e){let t=Pi(e),n=qt(t),i=n.some(s=>!pw(s)&&Id(s)),r=n.some(pw);return{accepted:!0,command_kind:i?"direct_runner":r?"sandbox_runner":"other",tracker_isolation:"runtime_injected",trust_boundary:"provenance",advisory:i?"Accepted with runtime-injected tracker isolation. Prefer the repository sandbox runner when available for reproducible build and coverage setup.":"Accepted with runtime-injected tracker isolation and provenance checks before execution."}}function LN(e){if(Pw(e))return'Linked test command skipped: Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.'}function DN(e){return e?e.map(NN):[]}function NN(e){let t=e.trim(),n=Qg(t)?_s(Z(e,"--add"),"--add"):{command:t},i=ve(n.command);if(!i)throw new _("--add requires command=<value> or a bare command (path=<value> is optional metadata)",m.USAGE);return Fw(i),{command:i,path:ve(n.path),scope:kN(n.scope),timeout_seconds:MN(ve(n.timeout_seconds),ve(n.timeout)),pm_context_mode:Ls(ve(n.pm_context_mode),"--add"),workspace_context_mode:Vt(ve(n.workspace_context_mode),"--add"),env_set:Ei(ve(n.env_set),"--add"),env_clear:Si(ve(n.env_clear),"--add"),shared_host_safe:Os(ve(n.shared_host_safe),"--add","shared_host_safe"),assert_stdout_contains:Yt(ve(n.assert_stdout_contains)),assert_stdout_regex:Cn(ve(n.assert_stdout_regex),"--add","assert_stdout_regex"),assert_stderr_contains:Yt(ve(n.assert_stderr_contains)),assert_stderr_regex:Cn(ve(n.assert_stderr_regex),"--add","assert_stderr_regex"),assert_stdout_min_lines:Ds(ve(n.assert_stdout_min_lines),"--add"),assert_json_field_equals:Ns(ve(n.assert_json_field_equals),"--add"),assert_json_field_gte:Ms(ve(n.assert_json_field_gte),"--add"),note:ve(n.note)}}function ve(e){let t=e?.trim();return t&&t.length>0?t:void 0}function MN(e,t){if(e&&t&&e!==t)throw new _("--add timeout and timeout_seconds must match when both are provided",m.USAGE);let n=e??t;if(n===void 0)return;let i=Math.floor(ye(n,"timeout_seconds"));if(i<=0)throw new _("--add timeout_seconds must be a positive integer",m.USAGE);return i}function PN(e){return e?e.flatMap(t=>{let n=Fs(t,"--add-json");for(let i of n){let r=i.command;if(!r)throw new _("--add-json requires a non-empty command string",m.USAGE);Fw(r)}return n}):[]}function FN(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new _("--remove requires command or path value",m.USAGE);let i=/^(command|path)\s*=/i.exec(n);if(i){let r=n.slice(i[0].length).trim();if(!r)throw new _("--remove requires a non-empty command=<value> or path=<value>",m.USAGE);return{kind:i[1].toLowerCase(),value:r}}if(/^[A-Za-z_][\w-]*=\S+$/u.test(n))throw new _("--remove structured selectors require command=<value> or path=<value>",m.USAGE);if(/^(?:[-*+]\s+)?(?:path|command)\s*:/i.test(n)||n.startsWith("```")){let r=Z(n,"--remove"),s=r.path!==void 0?"path":"command",a=r.path??r.command;if(!a?.trim())throw new _("--remove requires command=<value> and/or path=<value>",m.USAGE);return{kind:s,value:a.trim()}}return{kind:"either",value:n}}):[]}function $N(e){return e?[...new Set(e.map(t=>{let n=typeof t=="number"?t:Number.parseInt(t,10);if(!Number.isInteger(n)||n<1||String(n)!==String(t).trim())throw new _("--remove-index must be a positive integer",m.USAGE);return n}))]:[]}function UN(e){try{e.stdin?.end()}catch{}}function $w(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length<=mw?t:`${t.slice(0,mw-3)}...`}function Uw(e){return e==="off"?!1:e==="always"?!0:process.stderr.isTTY===!0}function Ed(e){try{process.stderr.write(`${e}
|
|
22
|
-
`)}catch{}}function
|
|
23
|
-
[pm linked-test output truncated at ${
|
|
24
|
-
`:"",E={stdout:`${S.text}${b}`,stderr:
|
|
25
|
-
`);return _N.some(n=>n.test(t))||t.split(/\r?\n/u).some(n=>pN.test(n)&&fN.test(n))}function YN(e){return VN(e)?"infra_collision":e.timedOut?"timeout":e.maxBufferExceeded?"max_buffer":e.spawnError?"spawn_error":e.signal?"signal":"assertion_failure"}function JN(){return{infra_collision:0,trust_refusal:0,config_refusal:0,assertion_failure:0,empty_run:0,timeout:0,max_buffer:0,spawn_error:0,signal:0}}function Mi(e){let t=JN();for(let n of e)n.status!=="failed"&&n.status!=="refused"||!n.failure_category||(t[n.failure_category]+=1);return t}function hw(e,t){for(let[n,i]of Object.entries(t.env_set))Ht.has(n.toUpperCase())||(e[n]=i);for(let n of t.env_clear)Ht.has(n.toUpperCase())||delete e[n]}function XN(e){e.PORT===void 0&&(e.PORT="0"),e.HOST===void 0&&(e.HOST="127.0.0.1"),e.PM_SHARED_HOST_SAFE===void 0&&(e.PM_SHARED_HOST_SAFE="1"),e.PLAYWRIGHT_HTML_OPEN===void 0&&(e.PLAYWRIGHT_HTML_OPEN="never"),e.PW_TEST_HTML_REPORT_OPEN===void 0&&(e.PW_TEST_HTML_REPORT_OPEN="never")}function QN(e,t){let n={...e.env_set,...t.env_set},i=[...new Set([...e.env_clear,...t.env_clear??[]])],r=t.shared_host_safe??e.shared_host_safe;return{env_set:n,env_clear:i,shared_host_safe:r}}function ZN(e,t,n){return{env_set:AN(e,"--env-set"),env_clear:IN(t,"--env-clear"),shared_host_safe:n===!0}}async function Di(e,t,n=!1,i=Sd){if(await te(e))try{await Un("seed_linked_test",async()=>{if(await i(oe.dirname(t),{recursive:!0}),n){await uw(e,t,{recursive:!0,force:!0});return}await uw(e,t,{force:!0})},{why:"Linked tests need an isolated PM context without mutating the source tracker.",nextSteps:["Reclaim capacity on the filesystem that hosts the linked-test temporary directory."]})}catch(r){if(typeof r=="object"&&r!==null&&"code"in r&&q(r))return;throw r}}async function yw(e,t,n,i=!1){for(let[r,s]of[[n.projectPmRoot,e],[n.globalPmRoot,t]])if(i){let a=await Q(Ae(r));if(a!==null){let o=await I(s);await Ba({pmRoot:s,filePath:Ae(s),raw:a,op:"settings:write",author:U(void 0,o.author_default),lockTtlSeconds:o.locks.ttl_seconds,lockWaitMs:o.locks.wait_ms,recordCreation:!0,message:"Seed linked-test schema settings history"})}}else await Di(Ae(r),Ae(s));await Di(oe.join(n.projectPmRoot,"extensions"),oe.join(e,"extensions"),!0),await Di(oe.join(n.globalPmRoot,"extensions"),oe.join(t,"extensions"),!0)}async function vw(e,t){if(!await te(e))return;let n=await kd(e,{withFileTypes:!0});for(let i of n){if(uN.has(i.name))continue;let r=oe.join(e,i.name),s=oe.join(t,i.name);if(i.isDirectory()){await Di(r,s,!0);continue}i.isFile()&&await Di(r,s)}}async function ww(e,t){let n=await Q(Ae(e));if(n===null||await te(Kn(e)))return;let i=await I(t);await Ni(Kn(t),{force:!0}),await Ni(Ae(t),{force:!0}),await Ba({pmRoot:t,filePath:Ae(t),raw:n,op:"settings:write",author:U(void 0,i.author_default),lockTtlSeconds:i.locks.ttl_seconds,lockWaitMs:i.locks.wait_ms,recordCreation:!0,message:"Seed linked-test tracker settings history"})}async function Ln(e){if(!await te(e))return 0;let t=0,n=await kd(e,{withFileTypes:!0});for(let i of n){if(!i.isDirectory()||mN.has(i.name))continue;let r=oe.join(e,i.name),s;try{s=await kd(r,{withFileTypes:!0})}catch{continue}for(let a of s)a.isFile()&&Dt.some(o=>a.name.toLowerCase().endsWith(o))&&(t+=1)}return t}function eM(e){let t=typeof e.exitCode=="number"?e.exitCode:1;return(e.timedOut||e.maxBufferExceeded)&&t===0?1:t}function tM(e){let t=e.trim();if(t==="true")return!0;if(t==="false")return!1;if(t==="null")return null;let n=Number(t);if(t.length>0&&Number.isFinite(n))return n;if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch{}return t}function nM(e,t){return typeof e=="object"&&e!==null&&typeof t=="object"&&t!==null?Fe(e,t):Object.is(e,t)}function iM(e,t,n){let i=[];i.push(...bw("stdout",t,e.assert_stdout_contains)),i.push(...kw("stdout",t,e.assert_stdout_regex)),i.push(...bw("stderr",n,e.assert_stderr_contains)),i.push(...kw("stderr",n,e.assert_stderr_regex)),i.push(...rM(t,e.assert_stdout_min_lines));let r=e.assert_json_field_equals??{},s=e.assert_json_field_gte??{};if(!(Object.keys(r).length>0||Object.keys(s).length>0))return i;let a;try{a=JSON.parse(t)}catch(o){return i.push(`stdout is not valid JSON for assert_json_field_* checks: ${o instanceof Error?o.message:String(o)}`),i}for(let[o,c]of Object.entries(r)){let d=gd(a,o);if(!d.found){i.push(`assert_json_field_equals missing path "${o}"`);continue}let l=tM(c);nM(d.value,l)||i.push(`assert_json_field_equals mismatch at "${o}" (expected=${JSON.stringify(l)} actual=${JSON.stringify(d.value)})`)}for(let[o,c]of Object.entries(s)){let d=gd(a,o);if(!d.found){i.push(`assert_json_field_gte missing path "${o}"`);continue}if(typeof d.value!="number"||!Number.isFinite(d.value)){i.push(`assert_json_field_gte path "${o}" resolved to non-numeric value`);continue}d.value<c&&i.push(`assert_json_field_gte failed at "${o}" (expected >= ${c}, actual ${d.value})`)}return i}function bw(e,t,n){let i=[];for(let r of n??[])t.includes(r)||i.push(`${e} missing required text: "${r}"`);return i}function kw(e,t,n){let i=[];for(let r of n??[])try{new RegExp(r,"m").test(t)||i.push(`${e} failed regex assertion: /${r}/m`)}catch(s){i.push(`${e} regex assertion is invalid: /${r}/ (${s instanceof Error?s.message:String(s)})`)}return i}function rM(e,t){if(typeof t!="number")return[];let n=e.split(/\r?\n/).map(i=>i.trim()).filter(i=>i.length>0).length;return n<t?[`stdout line count ${n} is below required minimum ${t}`]:[]}function Ew(e){let t=Pi(e);return/(?:^|\s)(?:--test-name-pattern|--testnamepattern)(?:=|\s)/u.test(t)?!0:qt(t).some(n=>/(?:^|\s)-t(?:=|\s)/u.test(n)&&Id(n))}function sM(e){return{root:e,schemaProjectPmPath:oe.join(e,"schema","project",".agents","pm"),schemaGlobalPmPath:oe.join(e,"schema","global"),trackerProjectPmPath:oe.join(e,"tracker","project",".agents","pm"),trackerGlobalPmPath:oe.join(e,"tracker","global"),workspaceSnapshotRoot:oe.join(e,"workspace","project"),workspaceIsolatedRoot:oe.join(e,"workspace","isolated")}}function aM(e,t,n){return e.some(i=>Rw(i,t,n)==="snapshot")}async function oM(e,t){let n=oe.join(e,".agents"),i=oe.join(n,"pm");await Sd(n,{recursive:!0}),await Ni(i,{recursive:!0,force:!0}),await oN(t,i,process.platform==="win32"?"junction":"dir")}async function cM(e,t=go,n=!0){let i={defaults:!0,agentGuidance:"skip"};await t(void 0,{path:e.schemaProjectPmPath},i),await t(void 0,{path:e.schemaGlobalPmPath},i),n&&(await t(void 0,{path:e.trackerProjectPmPath},i),await t(void 0,{path:e.trackerGlobalPmPath},i))}async function dM(e,t,n){t&&(await yw(e.schemaProjectPmPath,e.schemaGlobalPmPath,t,!0),n&&(await yw(e.trackerProjectPmPath,e.trackerGlobalPmPath,t),await vw(t.projectPmRoot,e.trackerProjectPmPath),await vw(t.globalPmRoot,e.trackerGlobalPmPath),await ww(t.projectPmRoot,e.trackerProjectPmPath),await ww(t.globalPmRoot,e.trackerGlobalPmPath)))}function lM(e,t,n){return e.some(i=>{let r=i.command??"",s=r.length>0&&Dw(r),a=n?.autoPmContext===!0&&s?"auto":Ow(i,t,n?.overrideLinkedPmContext===!0);return Lw(a,s)==="tracker"})}async function uM(e,t){return{sourceProjectItemCount:t?await Ln(t.projectPmRoot):0,sourceGlobalItemCount:t?await Ln(t.globalPmRoot):0,schemaProjectItemCount:await Ln(e.schemaProjectPmPath),schemaGlobalItemCount:await Ln(e.schemaGlobalPmPath),trackerProjectItemCount:await Ln(e.trackerProjectPmPath),trackerGlobalItemCount:await Ln(e.trackerGlobalPmPath)}}function mM(e){let t=e.effectivePmContextMode==="tracker",n=t?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath,i=t?e.layout.trackerGlobalPmPath:e.layout.schemaGlobalPmPath,r=t?e.counts.trackerProjectItemCount:e.counts.schemaProjectItemCount,s=t?e.counts.trackerGlobalItemCount:e.counts.schemaGlobalItemCount,a=e.workspaceContextMode==="snapshot"?e.layout.workspaceSnapshotRoot:e.workspaceContextMode==="isolated"?e.layout.workspaceIsolatedRoot:e.sourceWorkspaceRoot,o=e.workspaceContextMode==="isolated"?"":a;return{requested_pm_context_mode:e.requestedPmContextMode,pm_context_mode:e.effectivePmContextMode,auto_pm_context_applied:e.autoPmContextApplied,is_pm_command:e.isPmCommand,is_pm_tracker_read_command:e.isPmTrackerReadCommand,source_project_pm_path:e.sourceRoots?.projectPmRoot??"",sandbox_project_pm_path:n,source_global_pm_path:e.sourceRoots?.globalPmRoot??"",sandbox_global_pm_path:i,source_project_item_count:e.counts.sourceProjectItemCount,sandbox_project_item_count:r,source_global_item_count:e.counts.sourceGlobalItemCount,sandbox_global_item_count:s,mismatch_detected:e.isPmCommand&&(e.counts.sourceProjectItemCount!==r||e.counts.sourceGlobalItemCount!==s),project_extensions_seeded:!!e.sourceRoots,global_extensions_seeded:!!e.sourceRoots,requested_workspace_context_mode:e.requestedWorkspaceContextMode,workspace_context_mode:e.workspaceContextMode,working_directory:a,source_workspace_root:o,trust:e.trust}}async function _M(e){let t=typeof e.linkedTest.pm_context_mode=="string"&&e.linkedTest.pm_context_mode.trim().length>0?ka(e.linkedTest.pm_context_mode):void 0,n=typeof e.linkedTest.command=="string"&&e.linkedTest.command.length>0?e.linkedTest.command:void 0,i=n?CN(n):!1,r=i&&n?Dw(n):!1,s=e.options?.autoPmContext===!0&&r,a=s?"auto":Ow(e.linkedTest,e.runLevelPmContextMode,e.options?.overrideLinkedPmContext===!0),o=Lw(a,r),c=o==="tracker"?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath;e.workspaceContextMode==="snapshot"&&await oM(e.layout.workspaceSnapshotRoot,c);let d=e.options?.pmRoot?await fc(e.options.pmRoot,e.linkedTest,e.currentSourceRef):await fc(e.layout.root,e.linkedTest,e.currentSourceRef);return{linkedOverridePmContextMode:t,executionContext:mM({layout:e.layout,counts:e.counts,sourceRoots:e.sourceRoots,isPmCommand:i,isPmTrackerReadCommand:r,requestedPmContextMode:a,effectivePmContextMode:o,autoPmContextApplied:s,requestedWorkspaceContextMode:e.requestedWorkspaceContextMode,workspaceContextMode:e.workspaceContextMode,sourceWorkspaceRoot:e.sourceWorkspaceRoot,trust:d})}}function Sw(e,t,n){return{command:e.command,path:e.path,status:"skipped",execution_context:t,error:n}}function pM(e,t,n,i){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"assertion_failure",execution_context:t,...i?{stdout:i.stdout,stderr:i.stderr}:{},error:n}}function fM(e,t,n){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"trust_refusal",execution_context:t,error:n}}function gM(e){if(e.executionContext.trust.trusted)return null;let t=e.options?.allowUntrustedLinkedTests===!0,n=e.options?.untrustedLinkedTestsPolicyEnabled===!0;if(t&&n)return null;let i=n?"Retry with --allow-untrusted-linked-tests for this invocation, or acknowledge the current commands with --acknowledge-linked-tests.":"Set testing.allow_untrusted_linked_tests=true, then retry with --allow-untrusted-linked-tests; alternatively acknowledge the current commands with --acknowledge-linked-tests.";return fM(e.linkedTest,e.executionContext,`Linked test command is not trusted by this clone (source_ref=${e.executionContext.trust.source_ref??"unknown"}, current_ref=${e.executionContext.trust.current_source_ref??"unknown"}). ${i}`)}function hM(e){if(!e.linkedTest.command)return Sw(e.linkedTest,e.executionContext,"No command configured for this linked test.");let t=LN(e.linkedTest.command);return t?Sw(e.linkedTest,e.executionContext,t):null}function yM(e){return e.executionContext.pm_context_mode!=="none"?null:e.executionContext.workspace_context_mode==="source"?ba(e.linkedTest,e.executionContext,"pm_context_mode=none requires workspace_context_mode=isolated or snapshot so implicit tracker discovery cannot reach the source workspace."):e.executionContext.is_pm_command?ba(e.linkedTest,e.executionContext,"pm_context_mode=none is for self-isolating SDK tests; direct PM commands require schema, tracker, or auto context."):null}function ba(e,t,n){return{command:e.command,path:e.path,status:"refused",exit_code:null,failure_category:"config_refusal",execution_context:t,error:n}}function vM(e){let t=e.executionContext.pm_context_mode==="schema"&&e.executionContext.is_pm_tracker_read_command&&e.executionContext.mismatch_detected,n=e.options?.failOnContextMismatch===!0&&e.executionContext.is_pm_command&&e.executionContext.mismatch_detected;if(!t&&!n)return null;let i=TN({executionContext:e.executionContext,runLevelPmContextMode:e.runLevelPmContextMode,linkedOverridePmContextMode:e.linkedOverridePmContextMode}),r=e.options?.checkContext===!0?"Linked test preflight PM context mismatch detected":"Linked test PM context mismatch detected";return ba(e.linkedTest,e.executionContext,`${r} (source_project_items=${e.executionContext.source_project_item_count}, sandbox_project_items=${e.executionContext.sandbox_project_item_count}).${i}`)}function wM(e){return hM(e)||gM(e)||yM(e)||vM(e)||(e.options?.requireAssertionsForPm===!0&&e.executionContext.is_pm_command&&!SN(e.linkedTest)?ba(e.linkedTest,e.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled."):null)}function bM(e){let t=QN(e.runtimeDirectives,e.linkedTest),n={...process.env,SENTRY_ENVIRONMENT:"test"};return hw(n,e.runtimeDirectives),hw(n,{env_set:e.linkedTest.env_set??{},env_clear:e.linkedTest.env_clear??[]}),t.shared_host_safe&&XN(n),n.FORCE_COLOR="0",e.executionContext.pm_context_mode==="none"?delete n.PM_PATH:n.PM_PATH=e.executionContext.sandbox_project_pm_path,n.PM_GLOBAL_PATH=e.executionContext.sandbox_global_pm_path,e.executionContext.workspace_context_mode!=="source"&&(delete n.PM_BUILD_CONSUMER_LEASE,delete n.PM_BUILD_CONSUMER_LEASE_ROOT),e.executionContext.workspace_context_mode==="isolated"?(delete n.PM_SOURCE_WORKSPACE_ROOT,delete n.PM_SOURCE_PM_PATH,delete n[Jn]):(n.PM_SOURCE_WORKSPACE_ROOT=e.executionContext.source_workspace_root,n.PM_SOURCE_PM_PATH=e.executionContext.workspace_context_mode==="snapshot"?e.executionContext.sandbox_project_pm_path:e.executionContext.source_project_pm_path,n[Jn]="read_only"),n}function kM(e,t,n,i){return{command:e.command,path:e.path,status:"passed",exit_code:0,execution_context:t,stdout:n.stdout,stderr:n.stderr,...i?{execution_receipt:i}:{}}}function Tw(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:1,failure_category:"empty_run",execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:`Linked test reported an empty test run (${e.emptyRunSignal.code}). Update the test selection so at least one test executes; unfiltered commands may opt out by omitting --fail-on-empty-test-run.`}}function EM(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:eM(e.execution),failure_category:YN(e.execution),execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:HN(e.execution,e.timeoutMs)}}function SM(e){let t=rw(e.execution.stdout,e.execution.stderr);if(e.options?.failOnEmptyTestRun===!0||Ew(e.linkedTest.command??"")){let i=pa(e.execution.stdout,e.execution.stderr);if(i)return Tw({...e,emptyRunSignal:i});if(Ew(e.linkedTest.command??"")&&!t)return Tw({...e,emptyRunSignal:{code:"missing_positive_execution_receipt"}})}let n=iM(e.linkedTest,e.execution.stdout,e.execution.stderr);return n.length>0?pM(e.linkedTest,e.executionContext,`Linked test assertion(s) failed: ${n.join("; ")}`,e.execution):kM(e.linkedTest,e.executionContext,e.execution,t)}async function TM(e){let t=e.linkedTest.command??"",n=(e.linkedTest.timeout_seconds??e.defaultTimeoutSeconds??120)*1e3,i=await BN(t,n,bM(e),{index:e.index+1,total:e.total,timeoutMs:n,command:t},e.progressMode,e.executionContext.working_directory);return i.exitCode===0&&!i.timedOut&&!i.maxBufferExceeded?SM({...e,execution:i}):EM({...e,execution:i,timeoutMs:n})}async function Cd(e,t,n){let i=[],r=await Cw(oe.join(xw(),"pm-linked-test-")),s=sM(r),a=ka(n?.pmContext),o=EN(n?.workspaceContext),c=n?.progress===!0?"always":"auto",d=ZN(n?.envSet,n?.envClear,n?.sharedHostSafe),l=n?.sourceRoots,u=yi(),p=lM(e,a,n),g=aM(e,o,n?.overrideLinkedWorkspaceContext===!0),f=await hi(u);try{await cM(s,go,p),await Sd(s.workspaceIsolatedRoot,{recursive:!0}),await dM(s,l,p),g&&await dw(u,s.workspaceSnapshotRoot);let h=await uM(s,l);for(let y=0;y<e.length;y+=1){let v=e[y],w=Rw(v,o,n?.overrideLinkedWorkspaceContext===!0),k=await _M({linkedTest:v,layout:s,counts:h,sourceRoots:l,runLevelPmContextMode:a,options:n,requestedWorkspaceContextMode:o,workspaceContextMode:w,currentSourceRef:f,sourceWorkspaceRoot:u}),S=wM({linkedTest:v,executionContext:k.executionContext,runLevelPmContextMode:a,linkedOverridePmContextMode:k.linkedOverridePmContextMode,options:n});if(S){i.push(S);continue}i.push(await TM({linkedTest:v,index:y,total:e.length,defaultTimeoutSeconds:t,runtimeDirectives:d,progressMode:c,executionContext:k.executionContext,options:n}))}}finally{await Ni(s.root,{recursive:!0,force:!0,maxRetries:3,retryDelay:100})}return i}async function AM(e){let{id:t,pmRoot:n,settings:i,typeToFolder:r}=e,s=await Y(n,t,i.id_prefix,i.item_format,r);if(!s)throw new _(`Item ${t} not found`,m.NOT_FOUND);let a=await he(s,{schema:i.schema});return{itemId:s.id,tests:a.document.metadata.tests??[],testRuns:a.document.metadata.test_runs??[],changed:!1,removed:0}}function IM(e,t){return e.command===t.command&&e.path===t.path&&e.scope===t.scope&&e.pm_context_mode===t.pm_context_mode&&e.workspace_context_mode===t.workspace_context_mode}function CM(e,t){let n=[...e];for(let i of t)n.some(r=>IM(r,i))||n.push(i);return n}function xM(e,t,n){if(t.length===0&&n.length===0)return{tests:e,removed:0};let i=new Set(n),r=e.filter((s,a)=>i.has(a+1)?!1:!t.some(o=>o.kind==="command"?s.command===o.value:o.kind==="path"?s.path===o.value:s.command===o.value||s.path===o.value));return{tests:r,removed:e.length-r.length}}function RM(e,t,n,i){return xM(CM(e,t),n,i)}function OM(e){return[(e.envSet?.length??0)>0,(e.envClear?.length??0)>0,e.sharedHostSafe===!0,e.pmContext!==void 0,e.overrideLinkedPmContext===!0,e.failOnContextMismatch===!0,e.failOnSkipped===!0,e.failOnEmptyTestRun===!0,e.requireAssertionsForPm===!0,e.checkContext===!0,e.autoPmContext===!0,e.workspaceContext!==void 0,e.overrideLinkedWorkspaceContext===!0,e.allowUntrustedLinkedTests===!0].some(Boolean)}function jw(e){if(OM(e)&&e.run!==!0)throw new _("--env-set, --env-clear, --shared-host-safe, --pm-context, --override-linked-pm-context, --workspace-context, --override-linked-workspace-context, --allow-untrusted-linked-tests, --fail-on-context-mismatch, --fail-on-skipped, --fail-on-empty-test-run, --require-assertions-for-pm, --check-context, and --auto-pm-context require --run",m.USAGE);if(e.acknowledgeLinkedTests===!0&&e.run===!0)throw new _("--acknowledge-linked-tests records trust without executing commands; run it separately before --run",m.USAGE);if((e.match!==void 0||e.onlyIndex!==void 0||e.onlyLast===!0)&&e.run!==!0)throw new _("--match, --only-index, and --only-last require --run",m.USAGE)}async function LM(e){let{id:t,options:n,pmRoot:i,settings:r,typeToFolder:s,adds:a,removes:o,removeIndexes:c}=e;if(a.length===0&&o.length===0&&c.length===0)return AM({id:t,pmRoot:i,settings:r,typeToFolder:s});let d=0,l=await se({pmRoot:i,settings:r,id:t,op:a.length>0?"tests_add":"tests_remove",author:U(n.author,r.author_default),message:n.message,force:n.force,skipNoop:!0,mutate(u){let p=u.metadata.tests??[],g=RM(p,a,o,c);if(d=g.removed,(o.length>0||c.length>0)&&d===0)throw new _("No linked tests matched the requested removal selector",m.NOT_FOUND,{code:"linked_test_remove_no_match",unmatched:[...o.map(f=>`${f.kind}=${f.value}`),...c.map(f=>`index=${f}`)],required:"List linked tests and retry with an exact command/path or a current 1-based --remove-index.",examples:[`pm test ${t} --list`,`pm test ${t} --remove-index 1`]});return u.metadata.tests=g.tests,{changedFields:Fe(p,g.tests)?[]:["tests"]}}});return{itemId:l.item.id,tests:l.item.tests??[],testRuns:l.item.test_runs??[],changed:l.changedFields.length>0,removed:d}}function DM(e,t){jw(e);let n={match:e.match,onlyIndex:e.onlyIndex===void 0?void 0:On(e.onlyIndex),onlyLast:e.onlyLast},i=e.run===!0?ew(t,n):void 0,r=e.timeout===void 0?void 0:ye(e.timeout,"timeout");if(r!==void 0&&r<=0)throw new _("Test timeout must be a positive number",m.USAGE);return{defaultTimeoutSeconds:r,pmContextMode:ka(e.pmContext),runSelection:i,testsToRun:i?.selected??t}}async function NM(e){let{options:t,runOptions:n,pmRoot:i}=e;return t.run!==!0?[]:await Cd(n.testsToRun,n.defaultTimeoutSeconds,{progress:t.progress,envSet:t.envSet,envClear:t.envClear,sharedHostSafe:t.sharedHostSafe,pmContext:n.pmContextMode,overrideLinkedPmContext:t.overrideLinkedPmContext,failOnContextMismatch:t.failOnContextMismatch,failOnEmptyTestRun:t.failOnEmptyTestRun===!0||(t.measure?.length??0)>0,requireAssertionsForPm:t.requireAssertionsForPm,checkContext:t.checkContext,autoPmContext:t.autoPmContext,workspaceContext:t.workspaceContext,overrideLinkedWorkspaceContext:t.overrideLinkedWorkspaceContext,pmRoot:i,allowUntrustedLinkedTests:t.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:e.untrustedLinkedTestsPolicyEnabled,sourceRoots:{projectPmRoot:i,globalPmRoot:qe(process.cwd())}})}function MM(e,t,n){let i=[];if(t&&t.selector!==null&&i.push(`linked_test_selection:${t.selector}=${t.requested};selected=${t.selected_count};skipped=${t.skipped_count};indexes=${t.selected_indexes.join(",")}`),e.run===!0&&e.checkContext===!0){let r=Ad(n);i.push(`context_preflight:checked_pm_commands=${r.checked_pm_commands};tracker_read_commands=${r.tracker_read_commands};mismatches=${r.mismatches};auto_remediated=${r.auto_remediated}`)}return i}function PM(e){let t=bN(e.runResults),n=Number.parseInt(process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim()??"",10),i=process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM?.trim(),r=O(),s=Oi(e.options.measure,r);return{run_id:wN("test"),kind:"test",status:t.failed>0||e.failOnSkippedTriggered?"failed":"passed",started_at:e.runStartedAt,finished_at:r,recorded_at:r,attempt:Number.isFinite(n)&&n>=1?n:void 0,resumed_from:i&&i.length>0?i:void 0,passed:t.passed,failed:t.failed,skipped:t.skipped,fail_on_skipped_triggered:e.failOnSkippedTriggered?!0:void 0,measurements:s.length>0?s:void 0,executions:e.runResults.filter(a=>a.command?.trim()).slice(0,32).map(a=>({command:a.command.trim(),requested_pm_context_mode:a.execution_context?.requested_pm_context_mode,pm_context_mode:a.execution_context?.pm_context_mode,workspace_context_mode:a.execution_context?.workspace_context_mode,trust_reason:a.execution_context?.trust.reason}))}}async function FM(e){let{options:t,pmRoot:n,settings:i,itemId:r,runStartedAt:s,runResults:a,failOnSkippedTriggered:o,warnings:c}=e;if(t.run!==!0||!s)return;let d=PM({options:t,runStartedAt:s,runResults:a,failOnSkippedTriggered:o});if(i.testing.record_results_to_items!==!0)return{entry:d,receipt:{recorded:!1,reason:"tracking_disabled",run_id:d.run_id,recovery_command:"pm config project set test-result-tracking --policy enabled"}};try{return await ha({pmRoot:n,settings:i,itemId:r,author:U(t.author,i.author_default),message:`Track test run summary (${d.run_id})`,entry:d}),{entry:d,receipt:{recorded:!0,reason:"recorded",run_id:d.run_id}}}catch(l){return c.push(`test_result_tracking_failed:${r}:${l instanceof Error?l.message:String(l)}`),{entry:d,receipt:{recorded:!1,reason:"write_failed",run_id:d.run_id}}}}function Aw(e,t,n){let i;if(e.metricBelow!==void 0){let r=e.metricBelow.indexOf("="),s=e.metricBelow.slice(0,r).trim(),a=e.metricBelow.slice(r+1).trim(),o=Number(a);if(r<=0||s.length===0||a.length===0||!Number.isFinite(o))throw new _("--metric-below must use name=value",m.USAGE);i=Uv(t,s,o)}return{measurements:n?.measurements,metric_below:i,metric_diff:e.metricDiff===void 0?void 0:jv(t,e.metricDiff)}}async function $M(e,t,n){if(e.acknowledgeLinkedTests===!0)return rh(t,n,O())}function UM(e){let{item:t,runResults:n,failureCategories:i,runSelection:r,failOnSkippedTriggered:s,warnings:a,recording:o,measurementProjection:c}=e;return{ok:n.every(d=>d.status!=="failed"&&d.status!=="refused")&&s!==!0,id:t.itemId,tests:t.tests,run_results:n,failure_categories:i,selection:r?{selector:r.selector,requested:r.requested,selected_indexes:r.selected_indexes,selected_count:r.selected_count,skipped_count:r.skipped_count}:void 0,fail_on_skipped_triggered:s?!0:void 0,warnings:a.length>0?a:void 0,changed:t.changed||o?.receipt.recorded===!0,...o?{evidence_recording:o.receipt}:{},count:t.tests.length,...t.removed>0?{removed:t.removed}:{},...c}}async function Gw(e,t,n){let i=tw(t);if(i)return nw(t),jw(t),fd(e,t,n,x(process.cwd(),n.path)),{...await iw(e,{...i,author:t.author,message:t.message,force:t.force},n),run_results:[],failure_categories:Mi([])};let r=dn(),s=x(process.cwd(),n.path);await $(s);let a=await I(s);fd(e,t,n,s),Oi(t.measure,"validation"),Aw(t,[],void 0);let o=F(a,P()),c=await r.resolveList(t.add,"--add"),d=await r.resolveList(t.addJson,"--add-json"),l=await r.resolveList(t.remove,"--remove"),u=[...DN(c),...PN(d)],p=await Tn(u,U(t.author,a.author_default),O())??[],g=FN(l),f=$N(t.removeIndex),h=await LM({id:e,options:t,pmRoot:s,settings:a,typeToFolder:o.type_to_folder,adds:p,removes:g,removeIndexes:f}),y=DM(t,h.tests),v=await $M(t,s,h.tests),w=t.run===!0?O():void 0,k=await NM({options:t,runOptions:y,pmRoot:s,untrustedLinkedTestsPolicyEnabled:a.testing.allow_untrusted_linked_tests});sw(e,t,n,s,k);let S=Mi(k),A=t.run===!0&&t.failOnSkipped===!0&&k.some(T=>T.status==="skipped"),C=MM(t,y.runSelection,k);v&&C.push(`linked_test_trust_acknowledged:${v.acknowledged}`);let b=await FM({options:t,pmRoot:s,settings:a,itemId:h.itemId,runStartedAt:w,runResults:k,failOnSkippedTriggered:A,warnings:C}),E=b?.receipt.recorded?vd([...h.testRuns,b.entry]):h.testRuns,N=Aw(t,E,b?.entry);return UM({item:h,runResults:k,failureCategories:S,runSelection:y.runSelection,failOnSkippedTriggered:A,warnings:C,recording:b,measurementProjection: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]="61f797d4-1c7c-52f2-83a9-818c2faca5ff")}catch{}})();var jM=(e,t)=>{if(e===void 0)return;let n=me(e,t);if(!n){let i=t.definitions.map(r=>r.id);throw new _(`Invalid --status value "${e}". Allowed: ${i.join(", ")}`,m.USAGE)}return n},GM=e=>{if(e===void 0)return;let t=ye(e,"timeout");if(t<=0)throw new _("timeout must be a positive number",m.USAGE);return t},qw=(e,t)=>{if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw new _(`${t} must be a non-negative integer`,m.USAGE);return n},qM=e=>e instanceof Error?e.message:String(e),KM=()=>{let e=process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();return e&&e.length>0?e:`test-all-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`},zM=e=>e.trim().replaceAll(/\s+/g," "),WM=e=>!e||Object.keys(e).length===0?"{}":JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))),BM=e=>!e||e.length===0?"[]":JSON.stringify([...e].sort((t,n)=>t.localeCompare(n))),HM=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"none"},VM=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"source"},Ea=e=>[...new Set(e??[])].sort((t,n)=>t.localeCompare(n)),Kw=e=>Object.fromEntries(Object.entries(e??{}).sort(([t],[n])=>t.localeCompare(n))),YM=e=>typeof e=="number"?e:void 0,JM=e=>{let t={assert_stdout_contains:Ea(e.assert_stdout_contains),assert_stdout_regex:Ea(e.assert_stdout_regex),assert_stderr_contains:Ea(e.assert_stderr_contains),assert_stderr_regex:Ea(e.assert_stderr_regex),assert_stdout_min_lines:YM(e.assert_stdout_min_lines),assert_json_field_equals:Kw(e.assert_json_field_equals),assert_json_field_gte:Kw(e.assert_json_field_gte)};return JSON.stringify(t)},XM=e=>{let t=xd(e.command);return t!==void 0?`command:${e.scope}:${zM(t)}`:`path:${e.scope}:${xd(e.path)??""}`},zw=e=>{let t=WM(e.env_set),n=BM(e.env_clear),i=HM(e.pm_context_mode),r=VM(e.workspace_context_mode),s=e.shared_host_safe===!0?"true":"false",a=JM(e);return`${XM(e)}:${t}:${n}:${i}:${r}:${s}:${a}`},QM=(e,t)=>t===void 0?e:e===void 0||t>e?t:e,ZM=e=>{let t=0,n=0,i=0;for(let r of e){if(r.status==="passed"){t+=1;continue}if(r.status==="failed"||r.status==="refused"){n+=1;continue}i+=1}return{passed:t,failed:n,skipped:i}},eP=(e,t)=>{for(let[n,i]of Object.entries(t))e[n]+=i},Sa=(e,t)=>{if(e.progress===!0)try{process.stderr.write(`[pm test-all] ${t}
|
|
26
|
-
`)}catch{}},
|
|
27
|
-
`)}async function
|
|
28
|
-
`);return}await Oe(e.result_path,`${JSON.stringify({parse_error:"Background run output was not valid JSON.",stdout_excerpt:
|
|
29
|
-
`)}async function
|
|
30
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{$ as J_,$a as lp,$c as gp,B as z_,C as Wn,F as W_,Fb as _p,Ia as cp,Ja as dp,Jb as pp,Kb as fp,L as Bn,M as Hn,N as Ir,O as ae,Q as Cr,T as xr,U as B_,W as lo,X as H_,Z as V_,_ as Y_,aa as X_,ab as up,bb as Yn,c as Au,cb as fo,cd as hp,fb as mp,l as q_,na as Q_,sb as Jn,vb as mn,y as K_,yb as _n}from"./chunk-OEJ3G7XT.js";import{Ca as rp,Ga as po,f as Iu,ha as uo,ra as np,sa as mo,ta as _o,u as tp,xa as ip}from"./chunk-H3XYP24A.js";import{$ as Ba,$a as ym,A as ku,Aa as Vu,Ab as qm,Ac as Ft,Ba as Yu,Bb as Xa,Ca as Ju,Cb as Km,Cc as _r,Cd as y_,Ce as C_,D as Eu,Da as Xu,Db as zm,Dc as cn,De as Er,E as sr,Eb as Qa,Ec as ye,Ee as x_,F as Su,Fa as Qu,Fb as Wm,Fc as pr,Fe as Sr,Ga as Ya,Gb as Bm,Ge as R_,H as Y,Ha as Zu,Hb as Hm,Hc as Za,Hd as v_,He as oo,I as he,Ia as em,Ib as Vm,Ja as tm,Jb as Ym,Jd as w_,Je as O_,K as ar,Ka as nm,Kb as St,Ke as L_,L as Se,La as im,Lb as Jm,M as dt,Ma as rm,Mb as Xm,Md as to,Me as D_,N as Tu,Na as sm,Nb as Qm,Nc as fr,Ne as N_,Nf as ap,O as qn,Oa as am,Ob as Zm,Oc as m_,Od as b_,Oe as Tr,Pa as om,Pc as gr,Pe as M_,Pf as op,Q as or,Qa as cm,Qb as e_,Qc as hr,Qd as k_,R as se,Ra as dm,Rc as yr,Rd as $t,Sa as lm,Sb as t_,Ta as um,Tc as vr,Ua as mm,Ub as n_,Va as _m,Vb as i_,W as Wa,Wa as Ja,Wb as r_,Wc as __,X as Cu,Xa as pm,Xb as s_,Ya as fm,Za as gm,Zb as a_,Zc as zn,_ as xu,_a as hm,aa as Pt,ab as vm,bb as wm,ca as Ru,cb as bm,d as yu,db as km,eb as Em,fb as Sm,ha as Ha,hc as cr,hd as wr,he as no,i as kt,ia as Va,ic as o_,ie as io,j as vu,ja as Ou,jb as Tm,je as ro,ka as Lu,kb as Am,kd as br,ke as so,la as Du,lb as Im,ld as p_,lf as co,ma as Nu,mb as Cm,mc as dr,md as f_,me as E_,na as Mu,nb as xm,nc as lr,nd as g_,oa as Pu,ob as Rm,oc as ur,p as wu,pa as Fu,pb as Om,pc as c_,pf as P_,qa as $u,qb as Lm,qc as mr,qe as ao,ra as Uu,rb as Dm,rc as d_,rd as eo,rf as F_,sa as ju,sb as Nm,sc as Z,sd as h_,sf as $_,t as Et,ta as Gu,tb as Mm,tc as on,te as S_,tf as U_,u as nr,ua as qu,ub as Pm,uc as Kn,uf as j_,v as ir,va as Ku,vb as Fm,vc as we,ve as T_,vf as Ar,wa as zu,wb as $m,wc as l_,we as A_,wf as G_,x as rr,xa as Wu,xb as Um,xe as kr,ya as Bu,yb as jm,yc as Ze,ye as I_,yf as sp,z as bu,za as Hu,zb as Gm,zc as u_}from"./chunk-4CXQSRSP.js";import{a as Vn,b as ep,i as Tt,k as dn,l as ln,m as un}from"./chunk-O2ZRRLAP.js";import{$ as pl,$b as Ul,$c as zl,$f as Nt,$g as ct,$h as fu,Aa as Ae,Af as $,Ah as mu,Ba as hl,Bd as fe,Bh as _u,Ca as yl,D as ne,Da as at,Ea as Hi,Eh as pu,Fa as vl,Ff as iu,G as cl,Ga as wl,Gc as jl,Gg as lu,Ha as Fa,Ia as $a,Ja as bl,Jg as Un,Ka as kl,Kg as jn,La as El,M as dl,Ma as Sl,Na as Tl,Oa as Al,Oc as P,Pa as ie,Pe as O,Q as Da,Qa as Fe,Qd as Vl,Qe as Zl,Ra as Il,Re as Ga,Rh as Mt,Sa as Cl,Se as eu,Sh as Gn,T as Na,Te as Ji,U as Pe,Ub as Fn,Uc as Gl,Ud as Yl,Uf as Xi,Ug as uu,V as zi,Vc as ql,Ve as ge,Vh as sn,W as Wi,We as bt,Wh as an,X as ll,Xb as $l,Xf as K,Xh as za,Y as ul,Yc as ot,Yf as Ke,Yg as Ka,Z as ml,Zc as Kl,Zd as ja,Zf as nn,Zg as U,_ as _l,_c as $e,aa as fl,ad as Wl,ba as gl,bb as xl,bd as Bl,ca as Ma,cb as Rl,cg as ru,db as Ol,dg as su,e as Je,eb as Ll,eg as Qi,fb as Dl,fg as $n,g as H,gb as Nl,h as Gi,hb as Qe,hf as tu,hg as Zi,hi as gu,i as Ot,ib as Ml,ii as I,ji as hu,ka as Pa,kg as er,la as Mn,lg as me,m as Xd,ma as Te,md as Hl,me as Jl,mg as qa,ne as Xl,ng as _e,o as Qd,ob as Pl,og as rn,pa as F,pb as Fl,pe as Ql,pg as au,q as Oa,qa as st,qb as Ua,qg as ou,ra as Bi,s as Zd,sa as tn,sg as tr,ta as Pn,tg as cu,ua as Dt,ug as du,v as La,vc as Vi,xa as x,xc as Yi,xf as nu,ya as Xe,z as ol,za as qe}from"./chunk-QG4LMU7A.js";import{c as Z_}from"./chunk-LBEMB3BW.js";import{B as m,D as _,E as wt,F as te,G as Ki,H as q,I as Q,L as Oe,N as al,b as el,n as tl,q as nl,t as il,v as rl,x as sl,y as qi,z as Lt}from"./chunk-QKAAZWGC.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c2e89d3c-9abc-5ca7-a290-69a54dd694ab")}catch{}})();var Yb=Object.freeze({"--body":"Set the item body.","--body-file":"Read the item body from a file, or from stdin when set to -.","--description":"Set the item description.","--stdin":"Read the value from stdin.","--stdin-json":"Read a complete JSON document from stdin."}),Jb=new Set(["--add","--body","--comment","--dep","--dep-remove","--description","--doc","--event","--field","--file","--learning","--note","--remove","--reminder","--test","--type-option"]),Xb=new Set(["append","comments","create","docs","files","learnings","notes","test","update","update-many"]),Qb=new Set(["close-many:--ids","comments:--file","create:--body-file","history-compact:--ids","learnings:--file","notes:--file","update:--body-file","update-many:--ids"]),Zb=new Set(["close-many:--ids","history-compact:--ids","update-many:--ids"]),ek=["--allow-","--check-","--dry-run","--explain","--fail-","--fix-","--full","--has-","--include-","--json","--no-","--prune-","--quiet","--refresh-","--require-","--runtime-only","--schema-only","--skip-","--stream","--strict-","--summary","--today","--verbose"],tk=new Set(["--activate","--active-only","--adopt","--adopt-all","--all","--all-actionable","--all-affected-ids","--all-day","--all-streams","--acknowledge-linked-tests","--append-stable","--auto-fix","--auto-pm-context","--availability-only","--background","--brief","--by-assignee","--by-priority","--by-tag","--catalog","--claim","--clear","--clear-comments","--clear-criteria","--clear-deps","--clear-docs","--clear-events","--clear-files","--clear-learnings","--clear-notes","--clear-reminders","--clear-tests","--clear-type-options","--cli-only","--closed","--compact","--completion","--count","--counts","--deactivate","--declarative","--defaults","--describe","--diff","--doctor","--empty-body","--explore","--field-utilization","--filter-empty-body","--flags-only","--follow","--force","--global","--highlight","--hybrid","--id-only","--if-available","--ignore-global","--include_unparented","--infer","--init","--install","--isolated","--lean","--list","--local","--manage","--markdown","--metadata-coverage","--next","--normalize-provenance","--only","--only-last","--output-row-contract","--override-linked-pm-context","--override-linked-workspace-context","--packages-only","--past","--phrase-exact","--profile","--progress","--project","--promote-to-item-dep","--provenance","--provenance-summary","--raw","--ready-only","--ready_only","--rebuild","--recent","--reload","--repair","--replace-deps","--replace-docs","--replace-files","--replace-tests","--required","--required-on-create","--run","--runtime-probe","--save-baseline","--scaffold","--semantic","--shared-host-safe","--storage","--title-exact","--token-accounting","--trace","--tree","--unbounded","--uninstall","--validate-paths","--verify","--watch","--with-packages"]),nk=new Set(["--only-index"]),ik=new Set(["activity:--stream","eval:--fail-under","validate:--fix-scope"]),rk=new Set(["activity:--stream","close:--validate-close","close-many:--validate-close","comments:--author","learnings:--author","notes:--author"]),sk=new Set(["--regression"]);function ak(e,t){return t==="--stdin"||t==="--stdin-json"?["stdin"]:Qb.has(`${e}:${t}`)?["argv","file","stdin"]:t.endsWith("-file")?["argv","file"]:Jb.has(t)&&Xb.has(e)?["argv","stdin"]:["argv"]}function ok(e,t){let n=ik.has(`${e}:${t.flag}`)||t.value_name!==void 0||t.value_type==="string"||t.value_type==="number"||t.list===!0||t.repeatable===!0,i=t.value_type==="boolean"||t.flag==="--stdin"||t.flag==="--stdin-json"||t.flag.startsWith("--filter-")&&(t.flag.endsWith("-missing")||t.flag.startsWith("--filter-has-")||t.flag.startsWith("--filter-no-"))||ek.some(r=>t.flag.startsWith(r));return n||nk.has(t.flag)||!tk.has(t.flag)&&!i}function ck(e,t){return t.value_arity!==void 0?t.value_arity:ok(e,t)?sk.has(t.flag)||rk.has(`${e}:${t.flag}`)?"optional":"required":"none"}function dk(e,t){let n=Gi(e),i=ck(n,t),r=i!=="none",s=ak(n,t.flag),a=t.description??Yb[t.flag]??`${r?"Set":"Enable"} ${t.flag.slice(2).replaceAll("-"," ")}.`;return{...t,description:a,takes_value:r,value_required:i==="required",...r?{value_name:t.value_name??"value"}:{},value_type:r?t.value_type??"string":"boolean",required:t.required===!0,repeatable:t.repeatable===!0||t.list===!0,input_sources:s,...s.includes("stdin")&&t.flag!=="--stdin"&&t.flag!=="--stdin-json"?{stdin_token:"-"}:{},...Zb.has(`${n}:${t.flag}`)?{file_token_prefix:"@"}:{}}}function yp(e,t){return t.map(n=>dk(e,n))}function rF(e,t,n){let i=e.trim().toLowerCase(),r=[],s=new Map,a=0;for(let c of n)if(c.command.trim().toLowerCase()===i){if(a+=1,s.has(c.flag)){r.push({code:"duplicate_observation",command:i,flag:c.flag,detail:`${i} ${c.flag} was observed more than once.`});continue}s.set(c.flag,c)}let o=new Set(t.map(({flag:c})=>c));for(let c of t){let d=s.get(c.flag);if(!d){r.push({code:"missing_observation",command:i,flag:c.flag,detail:`${i} ${c.flag} has no executable option observation.`});continue}for(let[l,u]of[["takes_value","takes_value_mismatch"],["value_required","value_required_mismatch"],["repeatable","repeatable_mismatch"]])c[l]!==d[l]&&r.push({code:u,command:i,flag:c.flag,detail:`${i} ${c.flag} declares ${l}=${String(c[l])} but the executable option reports ${String(d[l])}.`})}for(let c of s.values())o.has(c.flag)||r.push({code:"undeclared_observation",command:i,flag:c.flag,detail:`${i} ${c.flag} is executable but absent from invocation contracts.`});return r.sort((c,d)=>c.flag.localeCompare(d.flag)||c.code.localeCompare(d.code)),{ok:r.length===0,declared_count:t.length,observed_count:a,findings: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]="0c0bb7ab-6157-5861-ad7e-a63ae62220f4")}catch{}})();var lk=new Set(["claim","close","context","create","get","help","init","list","next","plan","release","search","update","validate","workspace"]),uk=new Set(["append","comments","config","contracts","deps","docs","events","files","focus","graph","health","history","learnings","list-all","list-blocked","list-closed","list-in-progress","list-open","notes","profile","schema","test"]),mk=Object.freeze({workspace:new Set(["config","gc","health","init","merge","profile","schema","telemetry","workspace"]),intake:new Set(["copy","create","focus","item","restore"]),context:new Set(["activity","aggregate","context","ctx","duplicates","eval","get","help","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","next","search","stats"]),lifecycle:new Set(["claim","close","close-many","close-task","delete","pause-task","item-reopen","release","start-task","update","update-many"]),evidence:new Set(["append","comments","docs","events","files","history","history-attest","history-author-acknowledge","history-compact","history-redact","history-repair","learnings","notes"]),graph:new Set(["deps","graph","plan"]),quality:new Set(["assurance","contracts","test","test-all","validate"]),automation:new Set(["event","meet","remind"])}),_k=new Set(["extension","install","package","packages","upgrade"]);function pk(e){let t=H(e.trim().toLowerCase());if(t==="ops")return"quality";for(let[n,i]of Object.entries(mk))if(i.has(t))return n;return _k.has(t)?"extensions":"internal"}var pn=Object.freeze([...Qe.flatMap(e=>e==="item"?["item","item-reopen"]:[e,...Je.filter(t=>t.alias===e).map(t=>t.canonical)]).map(e=>({command:e,tier:lk.has(H(e))?"core":uk.has(H(e))?"standard":"full",family:pk(e)})),{command:"ops",tier:"core",family:"quality"},{command:"completion-statuses",tier:"internal",family:"internal"},{command:"completion-tags",tier:"internal",family:"internal"},{command:"completion-types",tier:"internal",family:"internal"},{command:"test-runs-worker",tier:"internal",family:"internal"},{command:"item test worker",tier:"internal",family:"internal"}]),fk=pn,vp=Object.freeze({max_lines:50,max_utf8_bytes:6e3}),cF=Object.freeze(["-V, --version","--all","--json","--output-include <fields>","--output-limit <count>","--output-budget <tokens|unbounded>","--output-cursor <cursor>","--pm-path <dir>","--no-extensions","--no-pager","--explain","-h, --help"]);function dF(e){let t=e===""?0:e.split(/\r?\n/).length,n=Buffer.byteLength(e,"utf8");return{lines:t,utf8_bytes:n,within_budget:t<=vp.max_lines&&n<=vp.max_utf8_bytes}}var wp={core:0,standard:1,full:2,internal:3},bp=new Map(fk.map(({command:e,tier:t})=>[e,t]));function go(e,t="standard"){return bp.get(e.trim().toLowerCase())??bp.get(H(e.trim().toLowerCase()))??t}function lF(e){return kp(e,pn)}function kp(e,t){let n=wp[e];return t.filter(i=>i.tier!=="internal"&&wp[i.tier]<=n).map(i=>i.command)}function uF(e){return Ep(e,pn)}function Ep(e,t){return t.filter(n=>n.family===e).map(n=>n.command)}var gk=["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"],hk=new Set([...Ot.filter(e=>e.hidden).map(e=>e.alias),"ctx","extension","install","item-reopen","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","packages","upgrade"]);function mF(e=pn){return gk.map(t=>({family:t,commands:Ep(t,e).filter(n=>e.find(i=>i.command===n)?.tier!=="internal"&&!hk.has(n))})).filter(({commands:t})=>t.length>0)}var yk=Object.freeze({pm_append:"append",pm_claim:"claim",pm_close:"close",pm_comments:"comments",pm_config:"config",pm_context:"context",pm_contracts:"contracts",pm_copy:"copy",pm_create:"create",pm_deps:"deps",pm_discover:"help",pm_docs:"docs",pm_events:"history",pm_files:"files",pm_focus:"focus",pm_get:"get",pm_graph:"graph",pm_health:"health",pm_learnings:"learnings",pm_list:"list",pm_mutate:"update",pm_next:"next",pm_notes:"notes",pm_plan:"plan",pm_profile:"profile",pm_release:"release",pm_run:"package",pm_schema:"schema",pm_search:"search",pm_test:"test",pm_update:"update",pm_validate:"validate"});function _F(e,t){return vk(e,t,pn)}function vk(e,t,n){if(t==="full")return[...e];let i=new Set(kp(t,n));return e.filter(r=>{let s=yk[r];return s!==void 0&&i.has(s)})}var pF=Object.freeze([{uri:"pm://workspace/context",name:"Workspace context",description:"Bounded project context for orientation, including active hierarchy and progress.",mimeType:"application/json"},{uri:"pm://workspace/focus",name:"Active focus",description:"The session focus that supplies the default create parent.",mimeType:"application/json"},{uri:"pm://workspace/claims",name:"Active claims",description:"Bounded in-progress work and active ownership context.",mimeType:"application/json"},{uri:"pm://workspace/agent-guide",name:"Agent guidance",description:"Repository-local AGENTS.md instructions, bounded for safe host attachment.",mimeType:"text/markdown"}]),fF=Object.freeze([{name:"orient",description:"Build bounded live context, search all statuses, and select canonical work without creating duplicates.",arguments:[{name:"request",description:"The user's requested outcome or topic.",required:!0},{name:"scope",description:"Optional bounded workspace or subsystem scope.",required:!1}],template:"Orient to the live pm workspace for: {{request}}. Scope hint: {{scope}}. Read context, search all statuses, inspect full metadata for relevant items, and select canonical lineage before any mutation."},{name:"claim-and-start",description:"Claim one canonical item and begin implementation with linked context.",arguments:[{name:"id",description:"Canonical pm item id.",required:!0}],template:"Read {{id}} in full, claim it, set it in_progress, then implement only its acceptance scope while linking files, docs, tests, and evidence."},{name:"record-evidence-and-close",description:"Record exact verification evidence, close the item, and release ownership.",arguments:[{name:"id",description:"Canonical pm item id.",required:!0},{name:"evidence",description:"Exact verification and outcome evidence.",required:!0}],template:"For {{id}}, record this evidence: {{evidence}}. Verify linked tests, close only if acceptance is met, then release the claim."}]);function gF(){return wk(pn)}function wk(e){return["# Generated agent command surface","","This file is generated from `PM_COMMAND_CAPABILITY_CONTRACTS`. Do not edit it manually.","","| Command | Minimum visibility tier | Capability family |","| --- | --- | --- |",...e.map(({command:t,tier:n,family:i})=>`| \`${t}\` | ${n} | ${i} |`),""].join(`
|
|
2
|
+
`)}(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]="7df4fe91-e8a4-540f-8737-c67f2efa460e")}catch{}})();var bk=[{exit_code:1,class:"generic_failure"},{exit_code:2,class:"usage"},{exit_code:3,class:"not_found"},{exit_code:4,class:"conflict"},{exit_code:5,class:"dependency_failed"}],kk=new Map(bk.map(e=>[e.exit_code,e.class]));function Rr(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))].sort()}function Ek(e){if(!e)return[];let t=new Set,n=new Set;return e.map(i=>{let r=i.state.trim(),s=i.probe_id.trim(),a=Rr(i.entrypoints);if(!/^[a-z][a-z0-9_]*$/.test(r)||!/^[a-z][a-z0-9-]*$/.test(s)||a.length===0||t.has(r)||n.has(s))throw new TypeError("Invalid pm refusal state contract");return t.add(r),n.add(s),{state:r,probe_id:s,entrypoints:a,expected_exit_class:i.expected_exit_class}}).sort((i,r)=>i.state.localeCompare(r.state))}function Sk(e,t,n,i,r){return![[1,2,3,4,5].includes(e.exit_code),e.meaning.trim().length>0,e.recovery.trim().length>0,t.length>0,n.length>0,/^[a-z][a-z0-9_]*$/.test(i),r.every(s=>/^[a-z][a-z0-9_]*$/.test(s)),kk.get(e.exit_code)===e.class].includes(!1)}function Tk(e,t){let n=e,i=new Set;for(;n.canonical_code!==n.code;){if(i.has(n.code))throw new TypeError(`Alias cycle in pm error code catalog: ${e.code}`);i.add(n.code);let r=t.get(n.canonical_code);if(!r)throw new TypeError(`Invalid pm error code contract: ${e.code}`);n=r}return n}function Ak(e){let t=new Map(e.map(n=>[n.code,n]));for(let n of e){let i=Tk(n,t);if(i.exit_code!==n.exit_code||i.class!==n.class)throw new TypeError(`Alias transport mismatch for pm error code: ${n.code}`);let r=e.filter(s=>s.code!==i.code&&s.canonical_code===i.code).map(s=>s.code).sort();if(n.code===i.code?JSON.stringify(n.aliases)!==JSON.stringify(r):n.aliases.length>0)throw new TypeError(`Invalid pm error code contract: ${n.code}`)}}function Tp(e){let t=new Set,n=e.map(i=>{let r=i.code.trim();if(!/^[a-z][a-z0-9_]*$/.test(r))throw new TypeError(`Invalid pm error code: ${JSON.stringify(i.code)}`);if(t.has(r))throw new TypeError(`Duplicate pm error code: ${r}`);t.add(r);let s=Rr(i.sources),a=Rr(i.emitting_commands),o=(i.canonical_code??r).trim(),c=Rr(i.aliases??[]),d=Ek(i.owned_states);if(!Sk(i,s,a,o,c))throw new TypeError(`Invalid pm error code contract: ${r}`);if(d.some(l=>l.expected_exit_class!==i.class))throw new TypeError(`Invalid pm refusal state exit class: ${r}`);return Object.freeze({...i,code:r,meaning:i.meaning.trim(),recovery:i.recovery.trim(),sources:s,emitting_commands:a,canonical_code:o,aliases:c,owned_states:d})});return Ak(n),Object.freeze(n.sort((i,r)=>i.code.localeCompare(r.code)))}function yF(e,t){let n=Sp(e,t);return Sp(n.canonical_code??n.code,t)}function Sp(e,t){let n=e.trim(),i=t.find(r=>r.code===n);if(!i)throw new TypeError(`Unknown pm error code "${n}"`);return i}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="aab6be67-e864-5a59-8639-a7b0cd873f51")}catch{}})();var Ap=[{code:"acceptance_criteria_mutation_conflict",meaning:"Acceptance criteria mutation conflict condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/update.ts"],emitting_commands:["update","update-many"],canonical_code:"acceptance_criteria_mutation_conflict",aliases:[]},{code:"acceptance_criteria_remove_unmatched",meaning:"Acceptance criteria remove unmatched condition.",stability:"provisional",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/update-many.ts","sdk/lifecycle/update.ts"],emitting_commands:["update","update-many"],canonical_code:"acceptance_criteria_remove_unmatched",aliases:[]},{code:"acceptance_criteria_semicolon_forbidden",meaning:"Acceptance criteria semicolon forbidden condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/item/parse.ts"],emitting_commands:["*"],canonical_code:"acceptance_criteria_semicolon_forbidden",aliases:[]},{code:"accepted_rejected_value",meaning:"Accepted rejected value condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts"],emitting_commands:["*"],canonical_code:"accepted_rejected_value",aliases:[]},{code:"alias_collision",meaning:"Alias collision condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"],emitting_commands:["*"],canonical_code:"alias_collision",aliases:[]},{code:"alias_target_missing",meaning:"Alias target missing condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"alias_target_missing",aliases:[]},{code:"already_claimed_by",meaning:"Already claimed by condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/claim.ts"],emitting_commands:["claim"],canonical_code:"already_claimed_by",aliases:[]},{code:"ambiguous_option_combination",meaning:"Ambiguous option combination condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"],canonical_code:"ambiguous_option_combination",aliases:[]},{code:"annotation_alias_conflict",meaning:"Annotation alias conflict condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-annotations.ts"],emitting_commands:["*"],canonical_code:"annotation_alias_conflict",aliases:[]},{code:"annotation_flag_like_value",meaning:"Annotation flag like value condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/annotations.ts"],emitting_commands:["*"],canonical_code:"annotation_flag_like_value",aliases:[]},{code:"annotation_if_absent_without_append",meaning:"Annotation if absent without append condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/annotations.ts"],emitting_commands:["*"],canonical_code:"annotation_if_absent_without_append",aliases:[]},{code:"annotation_message_without_text",meaning:"Annotation message without text condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/annotations.ts"],emitting_commands:["*"],canonical_code:"annotation_message_without_text",aliases:[]},{code:"annotation_transposed_subcommand",meaning:"Annotation transposed subcommand condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-annotations.ts"],emitting_commands:["*"],canonical_code:"annotation_transposed_subcommand",aliases:[]},{code:"append_empty_body",meaning:"Append empty body condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/append.ts"],emitting_commands:["append"],canonical_code:"append_empty_body",aliases:[]},{code:"assurance_registry_invalid",meaning:"Assurance registry invalid condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/governance/assurance.ts"],emitting_commands:["*"],canonical_code:"assurance_registry_invalid",aliases:[]},{code:"bare_comma_entry_ambiguous",meaning:"Bare comma entry ambiguous condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/item/parse.ts"],emitting_commands:["*"],canonical_code:"bare_comma_entry_ambiguous",aliases:[]},{code:"blocker_identity_read_failed",meaning:"Blocker identity read failed condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/query/get.ts"],emitting_commands:["get"],canonical_code:"blocker_identity_read_failed",aliases:[]},{code:"body_file_conflicts_with_body",meaning:"Body file conflicts with body condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/io/body-file.ts"],emitting_commands:["*"],canonical_code:"body_file_conflicts_with_body",aliases:[]},{code:"body_file_missing_path",meaning:"Body file missing path condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/io/body-file.ts"],emitting_commands:["*"],canonical_code:"body_file_missing_path",aliases:[]},{code:"body_file_unreadable",meaning:"Body file unreadable condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/io/body-file.ts"],emitting_commands:["*"],canonical_code:"body_file_unreadable",aliases:[]},{code:"budget_exceeded",meaning:"Budget exceeded condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"],emitting_commands:["*"],canonical_code:"budget_exceeded",aliases:[]},{code:"bulk_create_route",meaning:"Bulk create route condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-mutation.ts"],emitting_commands:["*"],canonical_code:"bulk_create_route",aliases:[]},{code:"bulk_ids_input_empty",meaning:"Bulk ids input empty condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/io/bulk-ids-input.ts","sdk/history-compact.ts","sdk/history-mcp.ts"],emitting_commands:["*"],canonical_code:"bulk_ids_input_empty",aliases:[],owned_states:[{state:"bulk_ids_stdin_contains_no_nonempty_ids",probe_id:"bulk-ids-stdin-empty",entrypoints:["update-many"],expected_exit_class:"usage"}]},{code:"bulk_ids_input_missing_path",meaning:"Bulk ids input missing path condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/io/bulk-ids-input.ts"],emitting_commands:["*"],canonical_code:"bulk_ids_input_missing_path",aliases:[],owned_states:[{state:"bulk_ids_file_token_omits_its_path",probe_id:"bulk-ids-file-path-missing",entrypoints:["update-many"],expected_exit_class:"usage"}]},{code:"bulk_ids_input_unreadable",meaning:"Bulk ids input unreadable condition.",stability:"provisional",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/io/bulk-ids-input.ts"],emitting_commands:["*"],canonical_code:"bulk_ids_input_unreadable",aliases:[],owned_states:[{state:"bulk_ids_file_path_cannot_be_read",probe_id:"bulk-ids-file-unreadable",entrypoints:["update-many"],expected_exit_class:"not_found"}]},{code:"bundle_integrity_torn_install",meaning:"Bundle integrity torn install condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/bundle-integrity.ts"],emitting_commands:["*"],canonical_code:"bundle_integrity_torn_install",aliases:[]},{code:"capability_undeclared",meaning:"Capability undeclared condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"],canonical_code:"capability_undeclared",aliases:[]},{code:"capability_unused",meaning:"Capability unused condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"],canonical_code:"capability_unused",aliases:[]},{code:"child_projection_item_bound_exceeded",meaning:"Child projection item bound exceeded condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/item-children.ts"],emitting_commands:["*"],canonical_code:"child_projection_item_bound_exceeded",aliases:[]},{code:"close_reason_required",meaning:"Close reason required condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle-policy.ts","sdk/lifecycle/close-many.ts"],emitting_commands:["*","close-many"],canonical_code:"close_reason_required",aliases:[]},{code:"close_through_update",meaning:"Close through update condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/telemetry/observability.ts"],emitting_commands:["*"],canonical_code:"close_through_update",aliases:[]},{code:"close_validation_missing_fields",meaning:"Close validation missing fields condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"],canonical_code:"close_validation_missing_fields",aliases:[]},{code:"collected_zero_items",meaning:"Collected zero items condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution-receipts.ts"],emitting_commands:["*"],canonical_code:"collected_zero_items",aliases:[]},{code:"collection_transposed_subcommand",meaning:"Collection transposed subcommand condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"],canonical_code:"collection_transposed_subcommand",aliases:[]},{code:"command_failed",meaning:"Command failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"],canonical_code:"command_failed",aliases:[]},{code:"command_namespace",meaning:"Command namespace condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/runtime-contracts.ts"],emitting_commands:["*"],canonical_code:"command_namespace",aliases:[]},{code:"command_override_conflict",meaning:"Command override conflict condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"],canonical_code:"command_override_conflict",aliases:[]},{code:"config_duplicate",meaning:"Config duplicate condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"config_duplicate",aliases:[]},{code:"config_key_unknown",meaning:"Config key unknown condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"config_key_unknown",aliases:[]},{code:"config_value_invalid",meaning:"Config value invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"config_value_invalid",aliases:[]},{code:"conflicting_lifecycle_owner",meaning:"Conflicting lifecycle owner condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-operations.ts"],emitting_commands:["*"],canonical_code:"conflicting_lifecycle_owner",aliases:[]},{code:"context_evaluation_read_incomplete",meaning:"Context evaluation read incomplete condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/context-relevance.ts"],emitting_commands:["*"],canonical_code:"context_evaluation_read_incomplete",aliases:[]},{code:"context_signal_store_invalid",meaning:"Context signal store invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/context-signal-store.ts"],emitting_commands:["*"],canonical_code:"context_signal_store_invalid",aliases:[]},{code:"context_signal_store_stale",meaning:"Context signal store stale condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/context-signal-store.ts"],emitting_commands:["*"],canonical_code:"context_signal_store_stale",aliases:[]},{code:"context_signal_store_write_failed",meaning:"Context signal store write failed condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/context-signal-store.ts"],emitting_commands:["*"],canonical_code:"context_signal_store_write_failed",aliases:[]},{code:"context_takes_no_item_argument",meaning:"Context takes no item argument condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"],canonical_code:"context_takes_no_item_argument",aliases:[]},{code:"core_item_field_requires_dedicated_flag",meaning:"Core item field requires dedicated flag condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/item-fields.ts"],emitting_commands:["*"],canonical_code:"core_item_field_requires_dedicated_flag",aliases:[]},{code:"create_positional_type_without_title",meaning:"Create positional type without title condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-mutation.ts"],emitting_commands:["*"],canonical_code:"create_positional_type_without_title",aliases:[]},{code:"dependency_cardinality_created",meaning:"Dependency cardinality created condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/graph/cardinality-integrity.ts"],emitting_commands:["*"],canonical_code:"dependency_cardinality_created",aliases:[]},{code:"dependency_edge_not_allowed",meaning:"Dependency edge not allowed condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/dependency-flag-validation.ts"],emitting_commands:["*"],canonical_code:"dependency_edge_not_allowed",aliases:[]},{code:"dependency_flag_value_invalid",meaning:"Dependency flag value invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/dependency-flag-validation.ts"],emitting_commands:["*"],canonical_code:"dependency_flag_value_invalid",aliases:[]},{code:"dependency_remove_no_match",meaning:"Dependency remove no match condition.",stability:"provisional",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"],canonical_code:"dependency_remove_no_match",aliases:[]},{code:"dependency_target_not_found",meaning:"Dependency target not found condition.",stability:"provisional",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/dependency-flag-validation.ts"],emitting_commands:["*"],canonical_code:"dependency_target_not_found",aliases:[]},{code:"dependency_temporal_order_invalid",meaning:"Dependency temporal order invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/dependency-flag-validation.ts"],emitting_commands:["*"],canonical_code:"dependency_temporal_order_invalid",aliases:[]},{code:"duplicate_canonical_flag",meaning:"Duplicate canonical flag condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"],emitting_commands:["*"],canonical_code:"duplicate_canonical_flag",aliases:[]},{code:"duplicate_command",meaning:"Duplicate command condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"],canonical_code:"duplicate_command",aliases:[]},{code:"duplicate_destination",meaning:"Duplicate destination condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"duplicate_destination",aliases:[]},{code:"duplicate_edge",meaning:"Duplicate edge condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/graph/remediation.ts"],emitting_commands:["*"],canonical_code:"duplicate_edge",aliases:[]},{code:"duplicate_observation",meaning:"Duplicate observation condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/flag-invocation-contracts.ts"],emitting_commands:["*"],canonical_code:"duplicate_observation",aliases:[]},{code:"duplicate_probe",meaning:"Duplicate probe condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts"],emitting_commands:["*"],canonical_code:"duplicate_probe",aliases:[]},{code:"duplicate_sweep_cost_limit",meaning:"Duplicate sweep cost limit condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/query/duplicate-candidates.ts"],emitting_commands:["duplicate-candidates"],canonical_code:"duplicate_sweep_cost_limit",aliases:[]},{code:"duplicate_target_circular",meaning:"Duplicate target circular condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"],canonical_code:"duplicate_target_circular",aliases:[]},{code:"duplicate_target_is_duplicate",meaning:"Duplicate target is duplicate condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"],canonical_code:"duplicate_target_is_duplicate",aliases:[]},{code:"duplicate_target_missing",meaning:"Duplicate target missing condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"],canonical_code:"duplicate_target_missing",aliases:[]},{code:"duplicate_target_self",meaning:"Duplicate target self condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/close.ts"],emitting_commands:["close"],canonical_code:"duplicate_target_self",aliases:[]},{code:"empty_corpus",meaning:"Empty corpus condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts"],emitting_commands:["*"],canonical_code:"empty_corpus",aliases:[]},{code:"empty_surface",meaning:"Empty surface condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"],canonical_code:"empty_surface",aliases:[]},{code:"error_code_mismatch",meaning:"Error code mismatch condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts","sdk/agent/tracker-preflight-contracts.ts"],emitting_commands:["*"],canonical_code:"error_code_mismatch",aliases:[]},{code:"event_cursor_query_mismatch",meaning:"Event cursor query mismatch condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-events.ts"],emitting_commands:["*"],canonical_code:"event_cursor_query_mismatch",aliases:[]},{code:"event_index_unavailable",meaning:"Event index unavailable condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-events.ts"],emitting_commands:["*"],canonical_code:"event_index_unavailable",aliases:[]},{code:"exit_code_mismatch",meaning:"Exit code mismatch condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/tracker-preflight-contracts.ts"],emitting_commands:["*"],canonical_code:"exit_code_mismatch",aliases:[]},{code:"extension_command_activation_failed",meaning:"Extension command activation failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/commander-usage.ts"],emitting_commands:["*"],canonical_code:"extension_command_activation_failed",aliases:[]},{code:"extension_dependency_name_unsafe",meaning:"Extension dependency name unsafe condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"],canonical_code:"extension_dependency_name_unsafe",aliases:[]},{code:"extension_dependency_spec_invalid",meaning:"Extension dependency spec invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"],canonical_code:"extension_dependency_spec_invalid",aliases:[]},{code:"extension_dependency_version_unsafe",meaning:"Extension dependency version unsafe condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"],canonical_code:"extension_dependency_version_unsafe",aliases:[]},{code:"extension_flag_value_invalid",meaning:"Extension flag value invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/extension-command-options.ts"],emitting_commands:["*"],canonical_code:"extension_flag_value_invalid",aliases:[]},{code:"extension_install_incomplete_source_scan",meaning:"Extension install incomplete source scan condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-plan.ts"],emitting_commands:["*"],canonical_code:"extension_install_incomplete_source_scan",aliases:[]},{code:"extension_install_soft_failed",meaning:"Extension install soft failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-setup.ts"],emitting_commands:["*"],canonical_code:"extension_install_soft_failed",aliases:[]},{code:"extension_install_source_contains_destination",meaning:"Extension install source contains destination condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-runtime.ts"],emitting_commands:["*"],canonical_code:"extension_install_source_contains_destination",aliases:[]},{code:"extension_item_field_reserved",meaning:"Extension item field reserved condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/item-fields.ts"],emitting_commands:["*"],canonical_code:"extension_item_field_reserved",aliases:[]},{code:"extension_item_field_type_conflict",meaning:"Extension item field type conflict condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/item-fields.ts"],emitting_commands:["*"],canonical_code:"extension_item_field_type_conflict",aliases:[]},{code:"extension_item_field_unknown",meaning:"Extension item field unknown condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/item-fields.ts"],emitting_commands:["*"],canonical_code:"extension_item_field_unknown",aliases:[]},{code:"extension_mutation_guard_failed",meaning:"Extension mutation guard failed condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/extension-hook-runtime.ts"],emitting_commands:["*"],canonical_code:"extension_mutation_guard_failed",aliases:[]},{code:"extension_mutation_guard_invalid_decision",meaning:"Extension mutation guard invalid decision condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/extension-hook-runtime.ts"],emitting_commands:["*"],canonical_code:"extension_mutation_guard_invalid_decision",aliases:[]},{code:"extension_mutation_guard_invalid_denial",meaning:"Extension mutation guard invalid denial condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/extension-hook-runtime.ts"],emitting_commands:["*"],canonical_code:"extension_mutation_guard_invalid_denial",aliases:[]},{code:"extension_mutation_guard_timed_out",meaning:"Extension mutation guard timed out condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/extension-hook-runtime.ts"],emitting_commands:["*"],canonical_code:"extension_mutation_guard_timed_out",aliases:[]},{code:"extension_read_output_invalid",meaning:"Extension read output invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/read-output/extension.ts"],emitting_commands:["*"],canonical_code:"extension_read_output_invalid",aliases:[]},{code:"extension_update_health_partial_coverage",meaning:"Extension update health partial coverage condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"extension_update_health_partial_coverage",aliases:[]},{code:"extensions_unreadable",meaning:"Extensions unreadable condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/static-inventory.ts"],emitting_commands:["*"],canonical_code:"extensions_unreadable",aliases:[]},{code:"field_duplicate",meaning:"Field duplicate condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"field_duplicate",aliases:[]},{code:"field_invalid",meaning:"Field invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"field_invalid",aliases:[]},{code:"field_mcp_input_collision",meaning:"Field mcp input collision condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"field_mcp_input_collision",aliases:[]},{code:"github_source_entry_unbuilt",meaning:"Github source entry unbuilt condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/shared.ts"],emitting_commands:["*"],canonical_code:"github_source_entry_unbuilt",aliases:[]},{code:"hierarchy_cardinality_created",meaning:"Hierarchy cardinality created condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/graph/hierarchy-integrity.ts"],emitting_commands:["*"],canonical_code:"hierarchy_cardinality_created",aliases:[]},{code:"hierarchy_cycle_created",meaning:"Hierarchy cycle created condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/graph/hierarchy-integrity.ts"],emitting_commands:["*"],canonical_code:"hierarchy_cycle_created",aliases:[]},{code:"hierarchy_parent_divergence_created",meaning:"Hierarchy parent divergence created condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/graph/hierarchy-integrity.ts"],emitting_commands:["*"],canonical_code:"hierarchy_parent_divergence_created",aliases:[]},{code:"history_author_acknowledge_plan_conflict",meaning:"History author acknowledge plan conflict condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/author-attribution.ts"],emitting_commands:["*"],canonical_code:"history_author_acknowledge_plan_conflict",aliases:[]},{code:"history_author_acknowledge_plan_fingerprint_required",meaning:"History author acknowledge plan fingerprint required condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/author-attribution.ts"],emitting_commands:["*"],canonical_code:"history_author_acknowledge_plan_fingerprint_required",aliases:[]},{code:"history_author_acknowledge_preview_limit_invalid",meaning:"History author acknowledge preview limit invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/author-attribution.ts"],emitting_commands:["*"],canonical_code:"history_author_acknowledge_preview_limit_invalid",aliases:[]},{code:"history_author_acknowledge_required_values_missing",meaning:"History author acknowledge required values missing condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/author-attribution.ts"],emitting_commands:["*"],canonical_code:"history_author_acknowledge_required_values_missing",aliases:[]},{code:"history_author_acknowledge_selector_conflict",meaning:"History author acknowledge selector conflict condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/author-attribution.ts"],emitting_commands:["*"],canonical_code:"history_author_acknowledge_selector_conflict",aliases:[]},{code:"history_author_acknowledge_selector_required",meaning:"History author acknowledge selector required condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/author-attribution.ts"],emitting_commands:["*"],canonical_code:"history_author_acknowledge_selector_required",aliases:[]},{code:"history_author_acknowledge_target_not_actionable",meaning:"History author acknowledge target not actionable condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/author-attribution.ts"],emitting_commands:["*"],canonical_code:"history_author_acknowledge_target_not_actionable",aliases:[]},{code:"history_author_acknowledge_target_unreadable",meaning:"History author acknowledge target unreadable condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/author-attribution.ts"],emitting_commands:["*"],canonical_code:"history_author_acknowledge_target_unreadable",aliases:[]},{code:"history_baseline_unavailable",meaning:"History baseline unavailable condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/projection.ts"],emitting_commands:["*"],canonical_code:"history_baseline_unavailable",aliases:[]},{code:"history_drift_chain_mismatch",meaning:"History drift chain mismatch condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_chain_mismatch",aliases:["validate_history_drift_chain_mismatches"]},{code:"history_drift_hash_mismatch",meaning:"History drift hash mismatch condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_hash_mismatch",aliases:["validate_history_drift_hash_mismatches"]},{code:"history_drift_merge_receipt",meaning:"History drift merge receipt condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_merge_receipt",aliases:[]},{code:"history_drift_missing_stream",meaning:"History drift missing stream condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_missing_stream",aliases:["validate_history_drift_missing_streams"]},{code:"history_drift_unreadable_stream",meaning:"History drift unreadable stream condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_unreadable_stream",aliases:["validate_history_drift_unreadable_streams"]},{code:"history_drift_version_skew",meaning:"History drift version skew condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_version_skew",aliases:["validate_history_drift_version_skews"]},{code:"history_json_invalid",meaning:"History json invalid condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/read.ts"],emitting_commands:["*"],canonical_code:"history_json_invalid",aliases:[]},{code:"history_merge_conflict_markers_detected",meaning:"History merge conflict markers detected condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/read.ts"],emitting_commands:["*"],canonical_code:"merge_conflict_markers_detected",aliases:[]},{code:"history_replay_invalid",meaning:"History replay invalid condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/projection.ts","core/history/tombstone.ts"],emitting_commands:["*"],canonical_code:"history_replay_invalid",aliases:[]},{code:"history_salvage_refused",meaning:"History salvage refused condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/history/salvage.ts"],emitting_commands:["*"],canonical_code:"history_salvage_refused",aliases:[]},{code:"history_stream_over_compact_threshold",meaning:"History stream over compact threshold condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_stream_over_compact_threshold",aliases:[]},{code:"history_target_out_of_range",meaning:"History target out of range condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/projection.ts"],emitting_commands:["*"],canonical_code:"history_target_out_of_range",aliases:[]},{code:"history_timestamp_invalid",meaning:"History timestamp invalid condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/event-index.ts","core/history/history.ts"],emitting_commands:["*"],canonical_code:"history_timestamp_invalid",aliases:[]},{code:"history_unknown_author_events",meaning:"History unknown author events condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_unknown_author_events",aliases:["validate_history_unknown_author_events"]},{code:"history_version_mapping_unavailable",meaning:"History version mapping unavailable condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/version-address.ts"],emitting_commands:["*"],canonical_code:"history_version_mapping_unavailable",aliases:[]},{code:"history_version_pruned",meaning:"History version pruned condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/projection.ts"],emitting_commands:["*"],canonical_code:"history_version_pruned",aliases:[]},{code:"host_environment_capacity_fault",meaning:"Host environment capacity fault condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/fs/host-environment-errors.ts"],emitting_commands:["*"],canonical_code:"host_environment_capacity_fault",aliases:[]},{code:"host_environment_operation_invalid",meaning:"Host environment operation invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/fs/host-environment-errors.ts"],emitting_commands:["*"],canonical_code:"host_environment_operation_invalid",aliases:[]},{code:"host_environment_permission_fault",meaning:"Host environment permission fault condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/fs/host-environment-errors.ts"],emitting_commands:["*"],canonical_code:"host_environment_permission_fault",aliases:[]},{code:"host_environment_resource_fault",meaning:"Host environment resource fault condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/fs/host-environment-errors.ts"],emitting_commands:["*"],canonical_code:"host_environment_resource_fault",aliases:[]},{code:"improvement_metric_contract_conflict",meaning:"Improvement metric contract conflict condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/improvement-ledger.ts"],emitting_commands:["*"],canonical_code:"improvement_metric_contract_conflict",aliases:[]},{code:"improvement_observation_conflict",meaning:"Improvement observation conflict condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/improvement-ledger.ts"],emitting_commands:["*"],canonical_code:"improvement_observation_conflict",aliases:[]},{code:"incomplete_allowed_values",meaning:"Incomplete allowed values condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts"],emitting_commands:["*"],canonical_code:"incomplete_allowed_values",aliases:[]},{code:"inconsistent_concept_kind",meaning:"Inconsistent concept kind condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"],emitting_commands:["*"],canonical_code:"inconsistent_concept_kind",aliases:[]},{code:"init_existing_settings_requires_force",meaning:"Init existing settings requires force condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/init.ts"],emitting_commands:["*"],canonical_code:"init_existing_settings_requires_force",aliases:[]},{code:"init_gitignore_unwritable",meaning:"Init gitignore unwritable condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace.ts"],emitting_commands:["*"],canonical_code:"init_gitignore_unwritable",aliases:[]},{code:"init_id_prefix_conflict",meaning:"Init id prefix conflict condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/init.ts"],emitting_commands:["*"],canonical_code:"init_id_prefix_conflict",aliases:[]},{code:"init_id_prefix_path_like",meaning:"Init id prefix path like condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/init.ts"],emitting_commands:["*"],canonical_code:"init_id_prefix_path_like",aliases:[]},{code:"integrity_history_conflict_marker",meaning:"Integrity history conflict marker condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_history_conflict_marker",aliases:["validate_storage_history_conflict_markers"]},{code:"integrity_history_invalid_json",meaning:"Integrity history invalid json condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_history_invalid_json",aliases:[]},{code:"integrity_history_unreadable",meaning:"Integrity history unreadable condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_history_unreadable",aliases:[]},{code:"integrity_item_ahead_format_version",meaning:"Integrity item ahead format version condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_item_ahead_format_version",aliases:["validate_format_version_ahead_items"]},{code:"integrity_item_conflict_marker",meaning:"Integrity item conflict marker condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_item_conflict_marker",aliases:[]},{code:"integrity_item_outdated_format_version",meaning:"Integrity item outdated format version condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_item_outdated_format_version",aliases:["validate_format_version_outdated_items"]},{code:"integrity_item_parse_failed",meaning:"Integrity item parse failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_item_parse_failed",aliases:[]},{code:"integrity_item_unreadable",meaning:"Integrity item unreadable condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_item_unreadable",aliases:[]},{code:"invalid_argument_value",meaning:"Invalid argument value condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/context-intent-contracts.ts","sdk/governance/assurance-mutation-error.ts","sdk/lifecycle/create.ts","sdk/lifecycle/task-composition.ts","sdk/runtime/schema-preview.ts"],emitting_commands:["*","create","task-composition"],canonical_code:"invalid_argument_value",aliases:[]},{code:"invalid_command_usage",meaning:"Invalid command usage condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts"],emitting_commands:["*"],canonical_code:"invalid_command_usage",aliases:[]},{code:"invalid_event_cursor",meaning:"Invalid event cursor condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-events.ts"],emitting_commands:["*"],canonical_code:"invalid_event_cursor",aliases:[]},{code:"invalid_event_cursor_mode",meaning:"Invalid event cursor mode condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-list-query.ts","sdk/mutation-events.ts","sdk/runtime-extended-actions.ts"],emitting_commands:["*"],canonical_code:"invalid_event_cursor_mode",aliases:[]},{code:"invalid_event_follow_interval",meaning:"Invalid event follow interval condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-events.ts"],emitting_commands:["*"],canonical_code:"invalid_event_follow_interval",aliases:[]},{code:"invalid_event_limit",meaning:"Invalid event limit condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-events.ts"],emitting_commands:["*"],canonical_code:"invalid_event_limit",aliases:[]},{code:"invalid_event_since",meaning:"Invalid event since condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-events.ts"],emitting_commands:["*"],canonical_code:"invalid_event_since",aliases:[]},{code:"invalid_history_analytics_limit",meaning:"Invalid history analytics limit condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/history-analytics.ts"],emitting_commands:["*"],canonical_code:"invalid_history_analytics_limit",aliases:[]},{code:"invalid_history_analytics_minimum_sample",meaning:"Invalid history analytics minimum sample condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/history-analytics.ts"],emitting_commands:["*"],canonical_code:"invalid_history_analytics_minimum_sample",aliases:[]},{code:"invalid_history_analytics_since",meaning:"Invalid history analytics since condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/history-analytics.ts"],emitting_commands:["*"],canonical_code:"invalid_history_analytics_since",aliases:[]},{code:"invalid_improvement_ledger",meaning:"Invalid improvement ledger condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/improvement-ledger-validation.ts"],emitting_commands:["*"],canonical_code:"invalid_improvement_ledger",aliases:[]},{code:"invalid_improvement_metric",meaning:"Invalid improvement metric condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/improvement-ledger.ts"],emitting_commands:["*"],canonical_code:"invalid_improvement_metric",aliases:[]},{code:"invalid_improvement_observation",meaning:"Invalid improvement observation condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/improvement-ledger.ts"],emitting_commands:["*"],canonical_code:"invalid_improvement_observation",aliases:[]},{code:"invalid_improvement_observation_limit",meaning:"Invalid improvement observation limit condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/improvement-ledger.ts"],emitting_commands:["*"],canonical_code:"invalid_improvement_observation_limit",aliases:[]},{code:"invalid_improvement_observation_timestamp",meaning:"Invalid improvement observation timestamp condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/improvement-ledger.ts"],emitting_commands:["*"],canonical_code:"invalid_improvement_observation_timestamp",aliases:[]},{code:"invalid_provenance_predicate",meaning:"Invalid provenance predicate condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/history-provenance.ts"],emitting_commands:["*"],canonical_code:"invalid_provenance_predicate",aliases:[]},{code:"invalid_query_cursor",meaning:"Invalid query cursor condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/pagination.ts"],emitting_commands:["*"],canonical_code:"invalid_query_cursor",aliases:[]},{code:"invalid_read_output_session",meaning:"Invalid read output session condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/read-output-session.ts"],emitting_commands:["*"],canonical_code:"invalid_read_output_session",aliases:[]},{code:"invalid_reproducible_process_environment",meaning:"Invalid reproducible process environment condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/reproducibility/process.ts"],emitting_commands:["*"],canonical_code:"invalid_reproducible_process_environment",aliases:[]},{code:"invalid_workspace_snapshot_target",meaning:"Invalid workspace snapshot target condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"],canonical_code:"invalid_workspace_snapshot_target",aliases:[]},{code:"item_already_active",meaning:"Item already active condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"],canonical_code:"item_already_active",aliases:[]},{code:"item_already_exists",meaning:"Item already exists condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/create.ts"],emitting_commands:["create"],canonical_code:"item_already_exists",aliases:[]},{code:"item_deleted",meaning:"Item deleted condition.",stability:"provisional",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/tombstone.ts"],emitting_commands:["*"],canonical_code:"item_deleted",aliases:[]},{code:"item_document_encoding_invalid",meaning:"Item document encoding invalid condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/store/item-store.ts"],emitting_commands:["*"],canonical_code:"item_document_encoding_invalid",aliases:[]},{code:"item_document_invalid",meaning:"Item document invalid condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/item/item-format.ts"],emitting_commands:["*"],canonical_code:"item_document_invalid",aliases:[]},{code:"item_document_roundtrip_failed",meaning:"Item document roundtrip failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/item/item-format.ts"],emitting_commands:["*"],canonical_code:"item_document_roundtrip_failed",aliases:[]},{code:"item_format_version_unsupported",meaning:"Item format version unsupported condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/item/item-format.ts"],emitting_commands:["*"],canonical_code:"item_format_version_unsupported",aliases:[]},{code:"item_id_collision",meaning:"Item id collision condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/copy.ts"],emitting_commands:["copy"],canonical_code:"item_id_collision",aliases:[]},{code:"item_identity_ambiguous",meaning:"Item identity ambiguous condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/store/item-store.ts"],emitting_commands:["*"],canonical_code:"item_identity_ambiguous",aliases:[]},{code:"item_identity_conflict",meaning:"Item identity conflict condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/governance/validate-history-drift.ts","sdk/merge/three-way.ts","sdk/query/get.ts"],emitting_commands:["*","get"],canonical_code:"item_identity_conflict",aliases:[]},{code:"item_identity_reserved",meaning:"Item identity reserved condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/history.ts"],emitting_commands:["*"],canonical_code:"item_identity_reserved",aliases:[]},{code:"item_not_found",meaning:"Item not found condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/governance/validate-history-drift.ts"],emitting_commands:["*"],canonical_code:"item_not_found",aliases:[]},{code:"likely_duplicate",meaning:"Likely duplicate condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/similarity.ts"],emitting_commands:["*"],canonical_code:"likely_duplicate",aliases:[]},{code:"linked_artifact_mutation_conflict",meaning:"Linked artifact mutation conflict condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/linked-artifacts.ts"],emitting_commands:["*"],canonical_code:"linked_artifact_mutation_conflict",aliases:[]},{code:"linked_test_context_invalid",meaning:"Linked test context invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/entry.ts"],emitting_commands:["*"],canonical_code:"linked_test_context_invalid",aliases:[]},{code:"linked_test_remove_no_match",meaning:"Linked test remove no match condition.",stability:"provisional",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution.ts"],emitting_commands:["*"],canonical_code:"linked_test_remove_no_match",aliases:[]},{code:"linked_test_update_ambiguous",meaning:"Linked test update ambiguous condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/update.ts"],emitting_commands:["*"],canonical_code:"linked_test_update_ambiguous",aliases:[]},{code:"linked_test_update_no_match",meaning:"Linked test update no match condition.",stability:"provisional",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/update.ts"],emitting_commands:["*"],canonical_code:"linked_test_update_no_match",aliases:[]},{code:"linked_test_value_not_quoted",meaning:"Linked test value not quoted condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"],canonical_code:"linked_test_value_not_quoted",aliases:[]},{code:"list_source_incomplete",meaning:"List source incomplete condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/query/list.ts"],emitting_commands:["list"],canonical_code:"list_source_incomplete",aliases:[]},{code:"local_package_archive_unsafe",meaning:"Local package archive unsafe condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"],canonical_code:"local_package_archive_unsafe",aliases:[]},{code:"local_source_not_found_bare_name",meaning:"Local source not found bare name condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"],canonical_code:"local_source_not_found_bare_name",aliases:[]},{code:"lock_conflict",meaning:"Lock conflict condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/lock/lock.ts","core/telemetry/observability.ts"],emitting_commands:["*"],canonical_code:"lock_conflict",aliases:[]},{code:"locks_stale_count",meaning:"Locks stale count condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"locks_stale_count",aliases:[]},{code:"locks_unreadable",meaning:"Locks unreadable condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"locks_unreadable",aliases:[]},{code:"malformed_plan_step_evidence",meaning:"Malformed plan step evidence condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"],canonical_code:"malformed_plan_step_evidence",aliases:[]},{code:"managed_state_invalid",meaning:"Managed state invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/static-inventory.ts"],emitting_commands:["*"],canonical_code:"managed_state_invalid",aliases:[]},{code:"managed_state_unreadable",meaning:"Managed state unreadable condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/static-inventory.ts"],emitting_commands:["*"],canonical_code:"managed_state_unreadable",aliases:[]},{code:"manifest_capabilities_absent",meaning:"Manifest capabilities absent condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"],canonical_code:"manifest_capabilities_absent",aliases:[]},{code:"manifest_invalid",meaning:"Manifest invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/static-inventory.ts"],emitting_commands:["*"],canonical_code:"manifest_invalid",aliases:[]},{code:"manifest_unknown_key",meaning:"Manifest unknown key condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/manifest-schema.ts"],emitting_commands:["*"],canonical_code:"manifest_unknown_key",aliases:[],owned_states:[{state:"author_workspace_manifest_declares_an_unknown_top_level_key",probe_id:"author-manifest-unknown-key",entrypoints:["health"],expected_exit_class:"generic_failure"}]},{code:"manifest_unreadable",meaning:"Manifest unreadable condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/static-inventory.ts"],emitting_commands:["*"],canonical_code:"manifest_unreadable",aliases:[]},{code:"mcp_annotation_file_unavailable",meaning:"Mcp annotation file unavailable condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/runtime-input.ts"],emitting_commands:["*"],canonical_code:"mcp_annotation_file_unavailable",aliases:[]},{code:"mcp_stdin_unavailable",meaning:"Mcp stdin unavailable condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/annotations.ts"],emitting_commands:["*"],canonical_code:"mcp_stdin_unavailable",aliases:[]},{code:"mcp_task_not_found_or_not_authorized",meaning:"Mcp task not found or not authorized condition.",stability:"provisional",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mcp/tasks.ts"],emitting_commands:["*"],canonical_code:"mcp_task_not_found_or_not_authorized",aliases:[]},{code:"merge_bun_launcher_unavailable",meaning:"Merge bun launcher unavailable condition.",stability:"provisional",exit_code:5,class:"dependency_failed",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/merge/install.ts"],emitting_commands:["*"],canonical_code:"merge_bun_launcher_unavailable",aliases:[]},{code:"merge_conflict_markers_detected",meaning:"Merge conflict markers detected condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/item/item-format.ts"],emitting_commands:["*"],canonical_code:"merge_conflict_markers_detected",aliases:["history_merge_conflict_markers_detected"]},{code:"merge_decisions_unreviewed",meaning:"Merge decisions unreviewed condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"merge_decisions_unreviewed",aliases:[]},{code:"merge_driver_configuration_drift",meaning:"Merge driver configuration drift condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"merge_driver_configuration_drift",aliases:[]},{code:"merge_driver_configuration_missing",meaning:"Merge driver configuration missing condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"merge_driver_configuration_missing",aliases:[]},{code:"merge_fence_drift",meaning:"Merge fence drift condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"merge_fence_drift",aliases:[]},{code:"merge_fence_missing",meaning:"Merge fence missing condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"merge_fence_missing",aliases:[]},{code:"merge_git_config_unwritable",meaning:"Merge git config unwritable condition.",stability:"stable",exit_code:5,class:"dependency_failed",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/merge/install.ts"],emitting_commands:["*"],canonical_code:"merge_git_config_unwritable",aliases:[]},{code:"merge_receipt_evidence_invalid",meaning:"Merge receipt evidence invalid condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts","sdk/merge/reconcile.ts"],emitting_commands:["*"],canonical_code:"merge_receipt_evidence_invalid",aliases:[]},{code:"merge_receipt_history_reference_missing",meaning:"Merge receipt history reference missing condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"merge_receipt_history_reference_missing",aliases:[]},{code:"merge_receipt_not_portable",meaning:"Merge receipt not portable condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/merge/receipts.ts"],emitting_commands:["*"],canonical_code:"merge_receipt_not_portable",aliases:[]},{code:"merge_receipts_pending",meaning:"Merge receipts pending condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"merge_receipts_pending",aliases:[]},{code:"merge_reconcile_receipt_evidence_untrusted",meaning:"Merge reconcile receipt evidence untrusted condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/history-repair.ts"],emitting_commands:["*"],canonical_code:"merge_reconcile_receipt_evidence_untrusted",aliases:[]},{code:"merge_root_not_found",meaning:"Merge root not found condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/merge/install.ts"],emitting_commands:["*"],canonical_code:"merge_root_not_found",aliases:[]},{code:"merge_settlement_hook_conflict",meaning:"Merge settlement hook conflict condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/merge/settlement-hook.ts"],emitting_commands:["*"],canonical_code:"merge_settlement_hook_conflict",aliases:[]}];(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]="371256f7-07df-56ad-bb36-09c7642c2d1d")}catch{}})();var Ip=[{code:"merge_settlement_review_required",meaning:"Merge settlement review required condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/merge/reconcile.ts","sdk/merge/stage.ts"],emitting_commands:["*"],canonical_code:"merge_settlement_review_required",aliases:[]},{code:"missing_allowed_values",meaning:"Missing allowed values condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts"],emitting_commands:["*"],canonical_code:"missing_allowed_values",aliases:[]},{code:"missing_budget",meaning:"Missing budget condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"],emitting_commands:["*"],canonical_code:"missing_budget",aliases:[]},{code:"missing_cli_flag",meaning:"Missing cli flag condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/tool-option-contracts.ts"],emitting_commands:["*"],canonical_code:"missing_cli_flag",aliases:[]},{code:"missing_destination",meaning:"Missing destination condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"missing_destination",aliases:[]},{code:"missing_directory",meaning:"Missing directory condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"missing_directory",aliases:[]},{code:"missing_init_recovery",meaning:"Missing init recovery condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/tracker-preflight-contracts.ts"],emitting_commands:["*"],canonical_code:"missing_init_recovery",aliases:[]},{code:"missing_lifecycle_target",meaning:"Missing lifecycle target condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension.ts"],emitting_commands:["*"],canonical_code:"missing_lifecycle_target",aliases:[]},{code:"missing_observation",meaning:"Missing observation condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/flag-invocation-contracts.ts"],emitting_commands:["*"],canonical_code:"missing_observation",aliases:[]},{code:"missing_observed_signature",meaning:"Missing observed signature condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"missing_observed_signature",aliases:[]},{code:"missing_parameter_alias",meaning:"Missing parameter alias condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/tool-option-contracts.ts"],emitting_commands:["*"],canonical_code:"missing_parameter_alias",aliases:[]},{code:"missing_positive_execution_receipt",meaning:"Missing positive execution receipt condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution.ts"],emitting_commands:["*"],canonical_code:"missing_positive_execution_receipt",aliases:[]},{code:"missing_probe",meaning:"Missing probe condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/tracker-preflight-contracts.ts"],emitting_commands:["*"],canonical_code:"missing_probe",aliases:[]},{code:"missing_required_argument",meaning:"Missing required argument condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","cli/main.ts","cli/register-mutation.ts","cli/schema/registration.ts","core/telemetry/observability.ts","sdk/governance/assurance-action.ts","sdk/history-redact.ts","sdk/invocation-author.ts"],emitting_commands:["*"],canonical_code:"missing_required_argument",aliases:[]},{code:"missing_required_option",meaning:"Missing required option condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/context-intent-contracts.ts","sdk/lifecycle/create.ts","sdk/lifecycle/plan.ts"],emitting_commands:["*","create","plan"],canonical_code:"missing_required_option",aliases:[]},{code:"missing_suggested_retry",meaning:"Missing suggested retry condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts"],emitting_commands:["*"],canonical_code:"missing_suggested_retry",aliases:[]},{code:"missing_suggested_retry_args",meaning:"Missing suggested retry args condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts"],emitting_commands:["*"],canonical_code:"missing_suggested_retry_args",aliases:[]},{code:"module_import_failed",meaning:"Module import failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"],canonical_code:"module_import_failed",aliases:[]},{code:"multi_target_github_install_ambiguous",meaning:"Multi target github install ambiguous condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-setup.ts"],emitting_commands:["*"],canonical_code:"multi_target_github_install_ambiguous",aliases:[]},{code:"mutation_author_required",meaning:"Mutation author required condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-guard.ts"],emitting_commands:["*"],canonical_code:"mutation_author_required",aliases:[]},{code:"mutation_document_unreadable",meaning:"Mutation document unreadable condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/register-structured-mutation.ts"],emitting_commands:["*"],canonical_code:"mutation_document_unreadable",aliases:[]},{code:"mutation_option_value_invalid",meaning:"Mutation option value invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/mutation-option-validation.ts"],emitting_commands:["item mutate"],canonical_code:"mutation_option_value_invalid",aliases:[]},{code:"mutation_secret_guard_blocked",meaning:"Mutation secret guard blocked condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/mutation-guard.ts"],emitting_commands:["*"],canonical_code:"mutation_secret_guard_blocked",aliases:[]},{code:"no_matching_tests",meaning:"No matching tests condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution-receipts.ts"],emitting_commands:["*"],canonical_code:"no_matching_tests",aliases:[]},{code:"no_projects_matched_filters",meaning:"No projects matched filters condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution-receipts.ts"],emitting_commands:["*"],canonical_code:"no_projects_matched_filters",aliases:[]},{code:"no_test_files_found",meaning:"No test files found condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution-receipts.ts"],emitting_commands:["*"],canonical_code:"no_test_files_found",aliases:[]},{code:"no_tests_found",meaning:"No tests found condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution-receipts.ts"],emitting_commands:["*"],canonical_code:"no_tests_found",aliases:[]},{code:"no_update_fields",meaning:"No update fields condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts"],emitting_commands:["*"],canonical_code:"no_update_fields",aliases:[]},{code:"no_version_bounds_declared",meaning:"No version bounds declared condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/extensions/manifest-schema.ts"],emitting_commands:["*"],canonical_code:"no_version_bounds_declared",aliases:[],owned_states:[{state:"author_workspace_manifest_omits_canonical_pm_version_bounds",probe_id:"author-manifest-version-bounds-missing",entrypoints:["health"],expected_exit_class:"generic_failure"}]},{code:"non_refusal_exit",meaning:"Non refusal exit condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts"],emitting_commands:["*"],canonical_code:"non_refusal_exit",aliases:[]},{code:"npm_pack_json_shape_unsupported",meaning:"Npm pack json shape unsupported condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"],canonical_code:"npm_pack_json_shape_unsupported",aliases:[]},{code:"npm_package_archive_missing",meaning:"Npm package archive missing condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"],canonical_code:"npm_package_archive_missing",aliases:[]},{code:"npm_package_archive_unsafe",meaning:"Npm package archive unsafe condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"],canonical_code:"npm_package_archive_unsafe",aliases:[]},{code:"npm_package_not_found",meaning:"Npm package not found condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/install-sources.ts"],emitting_commands:["*"],canonical_code:"npm_package_not_found",aliases:[]},{code:"ownership_conflict",meaning:"Ownership conflict condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/annotations.ts"],emitting_commands:["*"],canonical_code:"ownership_conflict",aliases:[]},{code:"ownership_dependency_bypass_restricted_options",meaning:"Ownership dependency bypass restricted options condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"],canonical_code:"ownership_dependency_bypass_restricted_options",aliases:[]},{code:"ownership_metadata_bypass_restricted_options",meaning:"Ownership metadata bypass restricted options condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"],canonical_code:"ownership_metadata_bypass_restricted_options",aliases:[]},{code:"package_spec_empty",meaning:"Package spec empty condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"package_spec_empty",aliases:[]},{code:"package_upgrade_modes_mutually_exclusive",meaning:"Package upgrade modes mutually exclusive condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/governance/upgrade.ts"],emitting_commands:["*"],canonical_code:"package_upgrade_modes_mutually_exclusive",aliases:[]},{code:"positional_shape_budget_exceeded",meaning:"Positional shape budget exceeded condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"positional_shape_budget_exceeded",aliases:[]},{code:"positional_signature_mismatch",meaning:"Positional signature mismatch condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"positional_signature_mismatch",aliases:[]},{code:"profile_name_empty",meaning:"Profile name empty condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"profile_name_empty",aliases:[]},{code:"profile_name_not_normalized",meaning:"Profile name not normalized condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"profile_name_not_normalized",aliases:[]},{code:"profile_summary_empty",meaning:"Profile summary empty condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"profile_summary_empty",aliases:[]},{code:"profile_title_empty",meaning:"Profile title empty condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"profile_title_empty",aliases:[]},{code:"project_runtime_history_epoch_incompatible",meaning:"Project runtime history epoch incompatible condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/environment/project-runtime-compatibility.ts"],emitting_commands:["*"],canonical_code:"project_runtime_history_epoch_incompatible",aliases:[]},{code:"project_runtime_item_format_incompatible",meaning:"Project runtime item format incompatible condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/environment/project-runtime-compatibility.ts"],emitting_commands:["*"],canonical_code:"project_runtime_item_format_incompatible",aliases:[]},{code:"project_runtime_stale_mutation",meaning:"Project runtime stale mutation condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/environment/project-runtime-compatibility.ts"],emitting_commands:["*"],canonical_code:"project_runtime_stale_mutation",aliases:[]},{code:"project_runtime_stale_read",meaning:"Project runtime stale read condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/environment/project-runtime-compatibility.ts"],emitting_commands:["*"],canonical_code:"project_runtime_stale_read",aliases:[]},{code:"projection_options_mutually_exclusive",meaning:"Projection options mutually exclusive condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/query/get.ts","sdk/query/list.ts","sdk/query/search-contracts.ts"],emitting_commands:["get","list","search"],canonical_code:"projection_options_mutually_exclusive",aliases:[]},{code:"provenance_value_domain_invalid",meaning:"Provenance value domain invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"provenance_value_domain_invalid",aliases:[]},{code:"read_output_cursor_command_mismatch",meaning:"Read output cursor command mismatch condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/read-output/continuation.ts"],emitting_commands:["*"],canonical_code:"read_output_cursor_command_mismatch",aliases:[]},{code:"read_output_cursor_invalid",meaning:"Read output cursor invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/read-output/continuation.ts"],emitting_commands:["*"],canonical_code:"read_output_cursor_invalid",aliases:[]},{code:"read_output_cursor_stale",meaning:"Read output cursor stale condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/read-output/continuation.ts"],emitting_commands:["*"],canonical_code:"read_output_cursor_stale",aliases:[]},{code:"recovery_kind_mismatch",meaning:"Recovery kind mismatch condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/tracker-preflight-contracts.ts"],emitting_commands:["*"],canonical_code:"recovery_kind_mismatch",aliases:[]},{code:"redundant_edge",meaning:"Redundant edge condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/graph/remediation.ts"],emitting_commands:["*"],canonical_code:"redundant_edge",aliases:[]},{code:"refusal_allowed_values_mismatch",meaning:"Refusal allowed values mismatch condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-corpus-contracts.ts"],emitting_commands:["*"],canonical_code:"refusal_allowed_values_mismatch",aliases:[]},{code:"refusal_error_code_mismatch",meaning:"Refusal error code mismatch condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-corpus-contracts.ts"],emitting_commands:["*"],canonical_code:"refusal_error_code_mismatch",aliases:[]},{code:"refusal_exit_code_mismatch",meaning:"Refusal exit code mismatch condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-corpus-contracts.ts"],emitting_commands:["*"],canonical_code:"refusal_exit_code_mismatch",aliases:[]},{code:"refusal_mutated_state",meaning:"Refusal mutated state condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-corpus-contracts.ts"],emitting_commands:["*"],canonical_code:"refusal_mutated_state",aliases:[]},{code:"refusal_probe_missing",meaning:"Refusal probe missing condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-corpus-contracts.ts"],emitting_commands:["*"],canonical_code:"refusal_probe_missing",aliases:[]},{code:"refusal_recovery_failed",meaning:"Refusal recovery failed condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-corpus-contracts.ts"],emitting_commands:["*"],canonical_code:"refusal_recovery_failed",aliases:[]},{code:"reindex_already_running",meaning:"Reindex already running condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/governance/reindex.ts"],emitting_commands:["*"],canonical_code:"reindex_already_running",aliases:[]},{code:"removed_canonical_spelling",meaning:"Removed canonical spelling condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"],emitting_commands:["*"],canonical_code:"removed_canonical_spelling",aliases:[]},{code:"removed_compatibility_spelling",meaning:"Removed compatibility spelling condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"],emitting_commands:["*"],canonical_code:"removed_compatibility_spelling",aliases:[]},{code:"reopen_reason_required",meaning:"Reopen reason required condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/reopen.ts"],emitting_commands:["item reopen"],canonical_code:"reopen_reason_required",aliases:[]},{code:"reopen_receipt_missing",meaning:"Reopen receipt missing condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"],canonical_code:"reopen_receipt_missing",aliases:[]},{code:"reopen_target_status_invalid",meaning:"Reopen target status invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/reopen.ts"],emitting_commands:["item reopen"],canonical_code:"reopen_target_status_invalid",aliases:[]},{code:"reported_zero_passes",meaning:"Reported zero passes condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution-receipts.ts"],emitting_commands:["*"],canonical_code:"reported_zero_passes",aliases:[]},{code:"reported_zero_tests",meaning:"Reported zero tests condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/execution-receipts.ts"],emitting_commands:["*"],canonical_code:"reported_zero_tests",aliases:[]},{code:"reserved_item_field",meaning:"Reserved item field condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/compose.ts"],emitting_commands:["*"],canonical_code:"reserved_item_field",aliases:[]},{code:"retry_failed",meaning:"Retry failed condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts","sdk/agent/tracker-preflight-contracts.ts"],emitting_commands:["*"],canonical_code:"retry_failed",aliases:[]},{code:"schema_migration_input_required",meaning:"Schema migration input required condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/migration-gates.ts"],emitting_commands:["*"],canonical_code:"schema_migration_input_required",aliases:[]},{code:"semantic_spelling_collision",meaning:"Semantic spelling collision condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"],emitting_commands:["*"],canonical_code:"semantic_spelling_collision",aliases:[]},{code:"settings_invalid",meaning:"Settings invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/static-inventory.ts"],emitting_commands:["*"],canonical_code:"settings_invalid",aliases:[]},{code:"settings_read_fs_error",meaning:"Settings read fs error condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"settings_read_fs_error",aliases:[]},{code:"settings_read_invalid_json",meaning:"Settings read invalid json condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"settings_read_invalid_json",aliases:[]},{code:"settings_read_invalid_schema",meaning:"Settings read invalid schema condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"settings_read_invalid_schema",aliases:[]},{code:"settings_read_merge_failed",meaning:"Settings read merge failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"settings_read_merge_failed",aliases:[]},{code:"settings_unreadable",meaning:"Settings unreadable condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/extension/static-inventory.ts"],emitting_commands:["*"],canonical_code:"settings_unreadable",aliases:[]},{code:"settings_write_invalid_existing_json",meaning:"Settings write invalid existing json condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/store/settings.ts"],emitting_commands:["*"],canonical_code:"settings_write_invalid_existing_json",aliases:[]},{code:"stale_budget",meaning:"Stale budget condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/flag-lexicon-contracts.ts"],emitting_commands:["*"],canonical_code:"stale_budget",aliases:[]},{code:"stale_destination",meaning:"Stale destination condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"stale_destination",aliases:[]},{code:"stale_observed_signature",meaning:"Stale observed signature condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"stale_observed_signature",aliases:[]},{code:"status_duplicate",meaning:"Status duplicate condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"status_duplicate",aliases:[]},{code:"status_invalid",meaning:"Status invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"status_invalid",aliases:[]},{code:"status_lifecycle_role_required",meaning:"Status lifecycle role required condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/schema.ts"],emitting_commands:["*"],canonical_code:"status_lifecycle_role_required",aliases:[]},{code:"stdin_json_invalid",meaning:"Stdin json invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/structured-mutations.ts"],emitting_commands:["*"],canonical_code:"stdin_json_invalid",aliases:[]},{code:"stdin_json_persisted_annotation_changed",meaning:"Stdin json persisted annotation changed condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/update.ts"],emitting_commands:["update"],canonical_code:"stdin_json_persisted_annotation_changed",aliases:[]},{code:"stdin_json_unknown_key",meaning:"Stdin json unknown key condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/structured-mutations.ts"],emitting_commands:["*"],canonical_code:"stdin_json_unknown_key",aliases:[]},{code:"structured_event_immutable",meaning:"Structured event immutable condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/annotations.ts"],emitting_commands:["*"],canonical_code:"structured_event_immutable",aliases:[]},{code:"structured_event_input_conflict",meaning:"Structured event input conflict condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/notes.ts"],emitting_commands:["*"],canonical_code:"structured_event_input_conflict",aliases:[]},{code:"structured_event_json_empty",meaning:"Structured event json empty condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/notes.ts"],emitting_commands:["*"],canonical_code:"structured_event_json_empty",aliases:[]},{code:"structured_event_json_invalid",meaning:"Structured event json invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/notes.ts"],emitting_commands:["*"],canonical_code:"structured_event_json_invalid",aliases:[]},{code:"structured_event_since_invalid",meaning:"Structured event since invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/notes.ts"],emitting_commands:["*"],canonical_code:"structured_event_since_invalid",aliases:[]},{code:"suggested_retry_args_mismatch",meaning:"Suggested retry args mismatch condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-closure.ts"],emitting_commands:["*"],canonical_code:"suggested_retry_args_mismatch",aliases:[]},{code:"telemetry_endpoint_probe_failed",meaning:"Telemetry endpoint probe failed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"telemetry_endpoint_probe_failed",aliases:[]},{code:"telemetry_endpoint_probe_http_status",meaning:"Telemetry endpoint probe http status condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"telemetry_endpoint_probe_http_status",aliases:[]},{code:"telemetry_otel_export_failing",meaning:"Telemetry otel export failing condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"telemetry_otel_export_failing",aliases:[]},{code:"telemetry_queue_high_retries",meaning:"Telemetry queue high retries condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"telemetry_queue_high_retries",aliases:[]},{code:"telemetry_queue_invalid_rows",meaning:"Telemetry queue invalid rows condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"telemetry_queue_invalid_rows",aliases:[]},{code:"telemetry_queue_pending",meaning:"Telemetry queue pending condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"telemetry_queue_pending",aliases:[]},{code:"telemetry_schema_version_behind",meaning:"Telemetry schema version behind condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"telemetry_schema_version_behind",aliases:[]},{code:"telemetry_state_invalid_json",meaning:"Telemetry state invalid json condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"telemetry_state_invalid_json",aliases:[]},{code:"template_type_unknown",meaning:"Template type unknown condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"template_type_unknown",aliases:[]},{code:"terminal_plan_mutation",meaning:"Terminal plan mutation condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"],canonical_code:"terminal_plan_mutation",aliases:[]},{code:"terminal_state_conflict",meaning:"Terminal state conflict condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/telemetry/observability.ts"],emitting_commands:["*"],canonical_code:"terminal_state_conflict",aliases:[]},{code:"test_measure_requires_execution",meaning:"Test measure requires execution condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/prerequisites.ts"],emitting_commands:["*"],canonical_code:"test_measure_requires_execution",aliases:[]},{code:"test_measure_requires_run",meaning:"Test measure requires run condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/test/prerequisites.ts"],emitting_commands:["*"],canonical_code:"test_measure_requires_run",aliases:[]},{code:"text_unpaired_surrogate",meaning:"Text unpaired surrogate condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/item/item-format.ts"],emitting_commands:["*"],canonical_code:"text_unpaired_surrogate",aliases:[]},{code:"tracked_runtime_cache_files",meaning:"Tracked runtime cache files condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"tracked_runtime_cache_files",aliases:["validate_storage_tracked_runtime_cache_files"]},{code:"tracker_not_initialized",meaning:"Tracker not initialized condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/store/tracker-preflight.ts","core/telemetry/observability.ts"],emitting_commands:["*"],canonical_code:"tracker_not_initialized",aliases:[],owned_states:[{state:"selected_tracker_root_exists_without_settings",probe_id:"tracker-root-settings-missing",entrypoints:["list"],expected_exit_class:"not_found"}]},{code:"tracker_root_missing",meaning:"Tracker root missing condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/store/tracker-preflight.ts"],emitting_commands:["*"],canonical_code:"tracker_root_missing",aliases:[],owned_states:[{state:"selected_tracker_root_does_not_exist",probe_id:"tracker-root-missing",entrypoints:["list"],expected_exit_class:"not_found"}]},{code:"tracker_root_not_directory",meaning:"Tracker root not directory condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/store/tracker-preflight.ts"],emitting_commands:["*"],canonical_code:"tracker_root_not_directory",aliases:[],owned_states:[{state:"selected_tracker_root_is_a_regular_file",probe_id:"tracker-root-not-directory",entrypoints:["list"],expected_exit_class:"usage"}]},{code:"tracker_root_unreadable",meaning:"Tracker root unreadable condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/store/tracker-preflight.ts"],emitting_commands:["*"],canonical_code:"tracker_root_unreadable",aliases:[],owned_states:[{state:"selected_tracker_root_is_not_readable",probe_id:"tracker-root-unreadable",entrypoints:["list"],expected_exit_class:"generic_failure"}]},{code:"transaction_create_compensated",meaning:"Transaction create compensated condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/item-transaction.ts"],emitting_commands:["*"],canonical_code:"transaction_create_compensated",aliases:[]},{code:"transaction_journal_invalid",meaning:"Transaction journal invalid condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-transaction.ts"],emitting_commands:["*"],canonical_code:"transaction_journal_invalid",aliases:[]},{code:"transaction_plan_mismatch",meaning:"Transaction plan mismatch condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-transaction.ts"],emitting_commands:["*"],canonical_code:"transaction_plan_mismatch",aliases:[]},{code:"transaction_preview_external_schema",meaning:"Transaction preview external schema condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/item-transaction.ts"],emitting_commands:["*"],canonical_code:"transaction_preview_external_schema",aliases:[]},{code:"transaction_preview_non_regular_file",meaning:"Transaction preview non regular file condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/fs/fs-utils.ts"],emitting_commands:["*"],canonical_code:"transaction_preview_non_regular_file",aliases:[]},{code:"transaction_preview_snapshot_changed",meaning:"Transaction preview snapshot changed condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/item-transaction.ts"],emitting_commands:["*"],canonical_code:"transaction_preview_snapshot_changed",aliases:[]},{code:"type_duplicate",meaning:"Type duplicate condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"type_duplicate",aliases:[]},{code:"type_invalid",meaning:"Type invalid condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"type_invalid",aliases:[]},{code:"undeclared_observation",meaning:"Undeclared observation condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/flag-invocation-contracts.ts"],emitting_commands:["*"],canonical_code:"undeclared_observation",aliases:[]},{code:"unexpected_refusal_probe",meaning:"Unexpected refusal probe condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/refusal-corpus-contracts.ts"],emitting_commands:["*"],canonical_code:"unexpected_refusal_probe",aliases:[]},{code:"unknown_command",meaning:"Unknown command condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","core/telemetry/observability.ts","sdk/cli-contracts/runtime-contracts.ts"],emitting_commands:["*"],canonical_code:"unknown_command",aliases:[]},{code:"unknown_context_intent",meaning:"Unknown context intent condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/context-intent-contracts.ts"],emitting_commands:["*"],canonical_code:"unknown_context_intent",aliases:[]},{code:"unknown_error",meaning:"Unknown error condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"],canonical_code:"unknown_error",aliases:[]},{code:"unknown_field",meaning:"Unknown field condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/schema.ts"],emitting_commands:["*"],canonical_code:"unknown_field",aliases:[]},{code:"unknown_field_projection",meaning:"Unknown field projection condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/query/get.ts","sdk/query/list.ts","sdk/query/search-contracts.ts"],emitting_commands:["get","list","search"],canonical_code:"unknown_field_projection",aliases:[]},{code:"unknown_item_type",meaning:"Unknown item type condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/schema.ts"],emitting_commands:["*"],canonical_code:"unknown_item_type",aliases:[]},{code:"unknown_lifecycle_action",meaning:"Unknown lifecycle action condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/subcommand-recovery.ts"],emitting_commands:["*"],canonical_code:"unknown_subcommand",aliases:[]},{code:"unknown_noun",meaning:"Unknown noun condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"unknown_noun",aliases:[]},{code:"unknown_option",meaning:"Unknown option condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","cli/runtime/invocation-options.ts","core/telemetry/observability.ts"],emitting_commands:["*"],canonical_code:"unknown_option",aliases:[],owned_states:[{state:"declared_option_is_rejected_on_the_selected_command_path",probe_id:"cross-command-unknown-option",entrypoints:["deps"],expected_exit_class:"usage"}]},{code:"unknown_plan_template",meaning:"Unknown plan template condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"],canonical_code:"unknown_plan_template",aliases:[]},{code:"unknown_provenance_dimension",meaning:"Unknown provenance dimension condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/history-provenance.ts"],emitting_commands:["*"],canonical_code:"unknown_provenance_dimension",aliases:[]},{code:"unknown_status",meaning:"Unknown status condition.",stability:"stable",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/schema.ts"],emitting_commands:["*"],canonical_code:"unknown_status",aliases:[]},{code:"unknown_subcommand",meaning:"Unknown subcommand condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts","sdk/agent/subcommand-recovery.ts"],emitting_commands:["*"],canonical_code:"unknown_subcommand",aliases:["unknown_lifecycle_action"],owned_states:[{state:"config_action_token_is_not_declared",probe_id:"config-unknown-action",entrypoints:["config"],expected_exit_class:"usage"},{state:"graph_command_token_is_not_declared",probe_id:"graph-unknown-subcommand",entrypoints:["graph"],expected_exit_class:"usage"},{state:"nested_command_token_is_not_declared_by_its_family",probe_id:"schema-unknown-subcommand",entrypoints:["schema"],expected_exit_class:"usage"},{state:"package_lifecycle_token_is_not_declared",probe_id:"package-unknown-action",entrypoints:["package"],expected_exit_class:"usage"}]},{code:"unsafe_init_recovery",meaning:"Unsafe init recovery condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/agent/tracker-preflight-contracts.ts"],emitting_commands:["*"],canonical_code:"unsafe_init_recovery",aliases:[]},{code:"unsupported_update_option",meaning:"Unsupported update option condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["cli/error-guidance.ts"],emitting_commands:["*"],canonical_code:"unsupported_update_option",aliases:[]},{code:"upsert_key_ambiguous",meaning:"Upsert key ambiguous condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/structured-mutations.ts"],emitting_commands:["*"],canonical_code:"upsert_key_ambiguous",aliases:[]},{code:"upsert_key_conflict",meaning:"Upsert key conflict condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/item-transaction.ts"],emitting_commands:["*"],canonical_code:"upsert_key_conflict",aliases:[]},{code:"upsert_key_duplicate",meaning:"Upsert key duplicate condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/item-transaction.ts","sdk/structured-mutations.ts"],emitting_commands:["*"],canonical_code:"upsert_key_duplicate",aliases:[]},{code:"upsert_key_missing",meaning:"Upsert key missing condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/structured-mutations.ts"],emitting_commands:["*"],canonical_code:"upsert_key_missing",aliases:[]},{code:"upsert_match_changed",meaning:"Upsert match changed condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/item-transaction.ts"],emitting_commands:["*"],canonical_code:"upsert_match_changed",aliases:[]},{code:"validate_command_references_stale_pm_ids",meaning:"Validate command references stale pm ids condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_command_references_stale_pm_ids",aliases:[]},{code:"validate_files_missing_linked_paths",meaning:"Validate files missing linked paths condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_files_missing_linked_paths",aliases:[]},{code:"validate_files_orphaned_paths",meaning:"Validate files orphaned paths condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_files_orphaned_paths",aliases:[]},{code:"validate_files_tracked_all_strict_forces_pm_internals",meaning:"Validate files tracked all strict forces pm internals condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_files_tracked_all_strict_forces_pm_internals",aliases:[]},{code:"validate_format_version_ahead_items",meaning:"Validate format version ahead items condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_item_ahead_format_version",aliases:[]},{code:"validate_format_version_outdated_items",meaning:"Validate format version outdated items condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_item_outdated_format_version",aliases:[]},{code:"validate_hierarchy_parent_cycle",meaning:"Validate hierarchy parent cycle condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_hierarchy_parent_cycle",aliases:[]},{code:"validate_hierarchy_parent_cycle_error",meaning:"Validate hierarchy parent cycle error condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_hierarchy_parent_cycle_error",aliases:[]},{code:"validate_history_drift_chain_mismatches",meaning:"Validate history drift chain mismatches condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_chain_mismatch",aliases:[]},{code:"validate_history_drift_hash_mismatches",meaning:"Validate history drift hash mismatches condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_hash_mismatch",aliases:[]},{code:"validate_history_drift_missing_streams",meaning:"Validate history drift missing streams condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_missing_stream",aliases:[]},{code:"validate_history_drift_unreadable_streams",meaning:"Validate history drift unreadable streams condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_unreadable_stream",aliases:[]},{code:"validate_history_drift_version_skews",meaning:"Validate history drift version skews condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_drift_version_skew",aliases:[]},{code:"validate_history_unknown_author_events",meaning:"Validate history unknown author events condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"history_unknown_author_events",aliases:[]},{code:"validate_lifecycle_active_closure_like_metadata",meaning:"Validate lifecycle active closure like metadata condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_lifecycle_active_closure_like_metadata",aliases:[]},{code:"validate_lifecycle_active_terminal_parent",meaning:"Validate lifecycle active terminal parent condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_lifecycle_active_terminal_parent",aliases:[]},{code:"validate_lifecycle_dependency_cycles",meaning:"Validate lifecycle dependency cycles condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_lifecycle_dependency_cycles",aliases:[]},{code:"validate_lifecycle_dependency_cycles_error",meaning:"Validate lifecycle dependency cycles error condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_lifecycle_dependency_cycles_error",aliases:[]},{code:"validate_lifecycle_stale_blockers",meaning:"Validate lifecycle stale blockers condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_lifecycle_stale_blockers",aliases:[]},{code:"validate_merge_decisions_unreviewed",meaning:"Validate merge decisions unreviewed condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_merge_decisions_unreviewed",aliases:[]},{code:"validate_merge_driver_configuration",meaning:"Validate merge driver configuration condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_merge_driver_configuration",aliases:[]},{code:"validate_merge_fence_drift",meaning:"Validate merge fence drift condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_merge_fence_drift",aliases:[]},{code:"validate_metadata_custom_profile_missing_required_fields",meaning:"Validate metadata custom profile missing required fields condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_custom_profile_missing_required_fields",aliases:[]},{code:"validate_metadata_duplicate_issue_codes",meaning:"Validate metadata duplicate issue codes condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_duplicate_issue_codes",aliases:[]},{code:"validate_metadata_missing_acceptance_criteria",meaning:"Validate metadata missing acceptance criteria condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_missing_acceptance_criteria",aliases:[]},{code:"validate_metadata_missing_close_reason",meaning:"Validate metadata missing close reason condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_missing_close_reason",aliases:[]},{code:"validate_metadata_missing_closed_at",meaning:"Validate metadata missing closed at condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_missing_closed_at",aliases:[]},{code:"validate_metadata_missing_confidence",meaning:"Validate metadata missing confidence condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_missing_confidence",aliases:[]},{code:"validate_metadata_missing_estimate",meaning:"Validate metadata missing estimate condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_missing_estimate",aliases:[]},{code:"validate_metadata_missing_release",meaning:"Validate metadata missing release condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_missing_release",aliases:[]},{code:"validate_metadata_missing_reviewer",meaning:"Validate metadata missing reviewer condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_missing_reviewer",aliases:[]},{code:"validate_metadata_missing_risk",meaning:"Validate metadata missing risk condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_missing_risk",aliases:[]},{code:"validate_metadata_missing_sprint",meaning:"Validate metadata missing sprint condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_metadata_missing_sprint",aliases:[]},{code:"validate_resolution_missing_fields",meaning:"Validate resolution missing fields condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_resolution_missing_fields",aliases:[]},{code:"validate_storage_duplicate_item_ids",meaning:"Validate storage duplicate item ids condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_storage_duplicate_item_ids",aliases:[]},{code:"validate_storage_history_conflict_markers",meaning:"Validate storage history conflict markers condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"integrity_history_conflict_marker",aliases:[]},{code:"validate_storage_resurrected_items",meaning:"Validate storage resurrected items condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_storage_resurrected_items",aliases:[]},{code:"validate_storage_tracked_runtime_cache_files",meaning:"Validate storage tracked runtime cache files condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"tracked_runtime_cache_files",aliases:[]},{code:"validate_storage_unparseable_config",meaning:"Validate storage unparseable config condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_storage_unparseable_config",aliases:[]},{code:"validate_storage_unparseable_history",meaning:"Validate storage unparseable history condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_storage_unparseable_history",aliases:[]},{code:"validate_storage_unreadable_items",meaning:"Validate storage unreadable items condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"validate_storage_unreadable_items",aliases:[]},{code:"vectorization_embedding_identity_changed",meaning:"Vectorization embedding identity changed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"vectorization_embedding_identity_changed",aliases:[]},{code:"vectorization_stale_items_remaining",meaning:"Vectorization stale items remaining condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/diagnostics/remediation.ts"],emitting_commands:["*"],canonical_code:"vectorization_stale_items_remaining",aliases:[]},{code:"visible_surface_ceiling_exceeded",meaning:"Visible surface ceiling exceeded condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/cli-contracts/grammar-contracts.ts"],emitting_commands:["*"],canonical_code:"visible_surface_ceiling_exceeded",aliases:[]},{code:"workflow_duplicate_type",meaning:"Workflow duplicate type condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"workflow_duplicate_type",aliases:[]},{code:"workflow_policy_approval_history_invalid",meaning:"Workflow policy approval history invalid condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/policy/workflow-policy-store.ts"],emitting_commands:["*"],canonical_code:"workflow_policy_approval_history_invalid",aliases:[]},{code:"workflow_policy_audit_failed",meaning:"Workflow policy audit failed condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/policy/workflow-policy-store.ts"],emitting_commands:["*"],canonical_code:"workflow_policy_audit_failed",aliases:[]},{code:"workflow_policy_input_unreadable",meaning:"Workflow policy input unreadable condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/policy/workflow-policy-store.ts"],emitting_commands:["*"],canonical_code:"workflow_policy_input_unreadable",aliases:[]},{code:"workflow_policy_invalid",meaning:"Workflow policy invalid condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/policy/workflow-policy.ts"],emitting_commands:["*"],canonical_code:"workflow_policy_invalid",aliases:[]},{code:"workflow_policy_refused",meaning:"Workflow policy refused condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/policy/workflow-policy-store.ts"],emitting_commands:["*"],canonical_code:"workflow_policy_refused",aliases:[]},{code:"workflow_policy_registry_invalid",meaning:"Workflow policy registry invalid condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/policy/workflow-policy-store.ts"],emitting_commands:["*"],canonical_code:"workflow_policy_registry_invalid",aliases:[]},{code:"workflow_status_unknown",meaning:"Workflow status unknown condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"workflow_status_unknown",aliases:[]},{code:"workflow_transition_malformed",meaning:"Workflow transition malformed condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"workflow_transition_malformed",aliases:[]},{code:"workflow_type_empty",meaning:"Workflow type empty condition.",stability:"stable",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"workflow_type_empty",aliases:[]},{code:"workflow_type_unknown",meaning:"Workflow type unknown condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/profile/profile-lint.ts"],emitting_commands:["*"],canonical_code:"workflow_type_unknown",aliases:[]},{code:"workspace_history_chain_invalid",meaning:"Workspace history chain invalid condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/workspace-history.ts"],emitting_commands:["*"],canonical_code:"workspace_history_chain_invalid",aliases:[]},{code:"workspace_history_state_conflict",meaning:"Workspace history state conflict condition.",stability:"stable",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["core/history/workspace-history.ts"],emitting_commands:["*"],canonical_code:"workspace_history_state_conflict",aliases:[]},{code:"workspace_root_pm_path",meaning:"Workspace root pm path condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/init.ts"],emitting_commands:["*"],canonical_code:"workspace_root_pm_path",aliases:[]},{code:"workspace_snapshot_force_required",meaning:"Workspace snapshot force required condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"],canonical_code:"workspace_snapshot_force_required",aliases:[]},{code:"workspace_snapshot_manifest_mismatch",meaning:"Workspace snapshot manifest mismatch condition.",stability:"provisional",exit_code:4,class:"conflict",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"],canonical_code:"workspace_snapshot_manifest_mismatch",aliases:[]},{code:"workspace_snapshot_name_reserved_fingerprint",meaning:"Workspace snapshot name reserved fingerprint condition.",stability:"provisional",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"],canonical_code:"workspace_snapshot_name_reserved_fingerprint",aliases:[]},{code:"workspace_snapshot_not_found",meaning:"Workspace snapshot not found condition.",stability:"provisional",exit_code:3,class:"not_found",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"],canonical_code:"workspace_snapshot_not_found",aliases:[]},{code:"workspace_snapshot_permission_denied",meaning:"Workspace snapshot permission denied condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"],canonical_code:"workspace_snapshot_permission_denied",aliases:[]},{code:"workspace_snapshot_resource_exhausted",meaning:"Workspace snapshot resource exhausted condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"],canonical_code:"workspace_snapshot_resource_exhausted",aliases:[]},{code:"workspace_snapshot_storage_exhausted",meaning:"Workspace snapshot storage exhausted condition.",stability:"provisional",exit_code:1,class:"generic_failure",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/workspace-snapshot.ts"],emitting_commands:["*"],canonical_code:"workspace_snapshot_storage_exhausted",aliases:[]},{code:"wrong_item_type",meaning:"Wrong item type condition.",stability:"stable",exit_code:2,class:"usage",recovery:"Inspect the structured error guidance and retry the suggested command.",sources:["sdk/lifecycle/plan.ts"],emitting_commands:["plan"],canonical_code:"wrong_item_type",aliases:[]}];(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]="70a7dc18-ab34-5e17-83eb-f5fac0b7fdd9")}catch{}})();var Cp=Tp([...Ap,...Ip]);(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]="76c420db-b520-5fde-bd43-16a7324feb0a")}catch{}})();var Ik=["mutation_receipt","entity","collection","diagnostic","stream"],Ck=new Set(["append","claim","close","close-task","copy","create","delete","focus","pause-task","release","restore","start-task","update"]),xk=new Set(["close-many","update-many"]),Rk=new Set(["activity","comments","contracts","events","history","learnings","list","notes","search"]),Ok=new Set(["aggregate","deps","graph","health","history-redact","history-repair","history-compact","stats","validate"]);function Xn(e){if(e.command.trim().length===0)throw new TypeError("command must be a non-empty command path");if(!Ik.includes(e.kind))throw new TypeError(`Unsupported output envelope kind: ${e.kind}`);return e}function xp(e){let t=e.trim().replace(/\s+/gu," "),[n=t]=t.split(" ");return xk.has(n)?Xn({command:t,kind:"collection",wrapper_key:"rows",cardinality:"many",format_flag:"--json"}):Ck.has(n)?Xn({command:t,kind:"mutation_receipt",wrapper_key:null,cardinality:"one",format_flag:"--json"}):Rk.has(n)?Xn({command:t,kind:"collection",wrapper_key:n==="contracts"?null:"items",cardinality:"many",format_flag:"--json"}):Ok.has(n)?Xn({command:t,kind:"diagnostic",wrapper_key:null,cardinality:"none",format_flag:"--json"}):Xn({command:t,kind:n==="get"?"entity":"diagnostic",wrapper_key:n==="get"?"item":null,cardinality:n==="get"?"one":"none",format_flag:"--json"})}var Lk=Qe.map(e=>xp(e)),Dk=new Map(Lk.map(e=>[e.command,e]));function Rp(e){let t=e.trim().replace(/\s+/gu," ");if(t.length===0)throw new TypeError("command must be a non-empty command path");let[n=t]=Gi(t).split(" "),i=Dk.get(n);return i?{...i,command:t}:xp(t)}function Nk(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Mk(e){return Nk(e)&&typeof e.id=="string"&&e.id.length>0&&typeof e.status=="string"&&e.status.length>0&&Number.isSafeInteger(e.changed_field_count)&&Number(e.changed_field_count)>=0&&(e.close_reason===void 0||typeof e.close_reason=="string")&&(e.deleted===void 0||typeof e.deleted=="boolean")&&(e.previous_status===void 0||typeof e.previous_status=="string")&&(e.warnings===void 0||Array.isArray(e.warnings))}function CF(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch(n){throw new TypeError(`Mutation receipt must be valid JSON: ${String(n)}`,{cause:n})}if(!Mk(t))throw new TypeError("Mutation receipt must be a flat object with top-level id, status, and changed_field_count fields");return{id:t.id,status:t.status,changedFieldCount:t.changed_field_count,...typeof t.close_reason=="string"?{closeReason:t.close_reason}:{},...typeof t.deleted=="boolean"?{deleted:t.deleted}:{},...typeof t.previous_status=="string"?{previousStatus:t.previous_status}:{},...Array.isArray(t.warnings)?{warnings:t.warnings}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7c95b311-b408-50f7-87e8-2c2fa2323092")}catch{}})();var ho=[{exit_code:m.SUCCESS,outcome:"effect",success:!0,meaning:"The requested operation completed with its intended effect."},{exit_code:m.GENERIC_FAILURE,outcome:"internal_failure",success:!1,meaning:"An unexpected runtime or internal failure prevented completion."},{exit_code:m.USAGE,outcome:"refused_input",success:!1,meaning:"The invocation was refused because its input or composition was invalid."},{exit_code:m.NOT_FOUND,outcome:"refused_tracker_state",success:!1,meaning:"The requested tracker, item, or resource was not present."},{exit_code:m.CONFLICT,outcome:"conflict",success:!1,meaning:"Current state or concurrency prevented the requested effect."},{exit_code:m.DEPENDENCY_FAILED,outcome:"dependency_failed",success:!1,meaning:"A required dependency operation failed."},{exit_code:m.NO_EFFECT,outcome:"no_effect",success:!0,meaning:"The request was valid and completed, but matched nothing to change."},{exit_code:m.PARTIAL_EFFECT,outcome:"partial_effect",success:!0,meaning:"The request completed and changed some, but not all, selected targets."}],Op=[m.SUCCESS,m.GENERIC_FAILURE,m.USAGE,m.NOT_FOUND,m.CONFLICT,m.DEPENDENCY_FAILED],Pk=new Set(["close-many","update-many"]),Dp=Qe.map(e=>({command:e,exit_codes:Pk.has(e)?[...Op,m.NO_EFFECT,m.PARTIAL_EFFECT]:[...Op]})),Lp=new Map(Dp.map(e=>[e.command,e])),Fk=[m.SUCCESS,m.NO_EFFECT,m.PARTIAL_EFFECT];function LF(e){return Fk.includes(e)}function DF(e){return ho.some(t=>t.exit_code===e)}function Np(e){let t=e.trim().toLowerCase().split(/\s+/u).filter(Boolean).join(" ");return Lp.get(t)??Lp.get(t.split(" ")[0])}function NF(e,t=Qe,n=Dp){let i=new Map(n.map(c=>[c.command,c])),r=t.filter(c=>!i.has(c)),s=e.filter(c=>{let d=i.get(c.command)??i.get(c.command.split(" ")[0]);return d===void 0||!d.exit_codes.includes(c.exit_code)}),a=new Set(e.map(c=>c.exit_code)),o=[...new Set(n.flatMap(c=>c.exit_codes))].filter(c=>!a.has(c)).sort((c,d)=>c-d);return{ok:r.length===0&&s.length===0&&o.length===0,missing_commands:r,undeclared_observations:s,unreachable_exit_codes:o}}function MF(e){return e.applied===0&&e.failed>0?{outcome:"dependency_failed",exit_code:m.DEPENDENCY_FAILED}:e.applied===0?{outcome:"no_effect",exit_code:m.NO_EFFECT}:e.skipped>0||e.failed>0||e.unmatched>0?{outcome:"partial_effect",exit_code:m.PARTIAL_EFFECT}:{outcome:"effect",exit_code:m.SUCCESS}}(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]="081bf1eb-4b9a-5fa9-a272-34ae781d250c")}catch{}})();var M=class extends TypeError{constructor(t){super(t),this.name="AssuranceMutationRefusalError"}},Le=class extends TypeError{context;constructor(t,n={}){super(t),this.name="AssuranceEvaluationRefusalError",this.context=n}},et=class extends TypeError{measurement_id;source_kind;field;check;constructor(t,n){super(t),this.name="AssuranceSourceResolutionError",this.measurement_id=n.measurement_id,this.source_kind=n.source_kind,this.field=n.field,this.check=n.check}};async function fn(e){try{return await e()}catch(t){throw t instanceof M?new _(t.message,m.USAGE,{code:"invalid_argument_value",reason:"assurance_mutation_refused"}):t}}async function Mp(e){try{return await e()}catch(t){throw t instanceof Le?new _(t.message,m.USAGE,{code:"invalid_argument_value",reason:"assurance_evaluation_refused",...t.context}):t}}import{createHash as $k}from"node:crypto";import Uk 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]="b00dcab2-22c6-55b7-b93d-f6f5413d4b04")}catch{}})();var gn=1e3;(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]="416aaf09-e4f6-5d10-aee0-eba374f1cd83")}catch{}})();var Fp=1,lt=["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"],Qn=["items","dependency_kind","prose_edge_gap","graph","validate","health","history","links","provider","derived"],jk=["ceiling","floor","equals","zero","monotone_nondecreasing","monotone_nonincreasing","subset_of"],Gk=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,Or=30,Lr=5e3,$p=4,qk=50;function ut(e,t){if(!Gk.test(e))throw new M(`${t} must be a stable lowercase id`)}function Kk(e,t){if(!Number.isFinite(e)||e<0)throw new M(`${t} must be a finite non-negative number`)}function Zn(e){let t=jk.filter(r=>e[r]!==void 0);if(t.length!==1)throw new M(`assertion ${e.id} must declare exactly one polarity`);let n=t[0],i=e[n];return{polarity:n,value:n==="zero"?0:i}}function vo(e,t){return ie(e)===ie(t)}function Up(e,t){if(t.polarity==="equals")return vo(e,t.value);if(t.polarity==="subset_of"){if(!Array.isArray(e)||!Array.isArray(t.value))return!1;let i=t.value;return e.every(r=>i.includes(r))}if(typeof e!="number")return!1;let n=t.value;return t.polarity==="ceiling"||t.polarity==="monotone_nonincreasing"?e<=n:t.polarity==="floor"||t.polarity==="monotone_nondecreasing"?e>=n:e===0}function jp(e){let t=Zn(e),n=e.negative_control.cases;return n.some(i=>i.expected==="pass")&&n.some(i=>i.expected==="fail")&&n.every(i=>Up(i.observed,t)===(i.expected==="pass"))}function zk(e,t){if(e.polarity!==t.polarity)return!0;if(typeof e.value=="number"&&typeof t.value=="number")return e.polarity==="ceiling"||e.polarity==="monotone_nonincreasing"?t.value>e.value:e.polarity==="floor"||e.polarity==="monotone_nondecreasing"?t.value<e.value:t.value!==e.value;if(e.polarity==="subset_of"){let n=e.value,i=t.value;return!Array.isArray(n)||!Array.isArray(i)||i.some(r=>!n.includes(r))}return!vo(e.value,t.value)}function Wk(e,t){if(e.measurement_id!==t.measurement_id||e.owner_item_id!==t.owner_item_id||ie(e.scope)!==ie(t.scope))return!0;let n={observe:0,warn:1,block:2},i=(e.lifetime??"hold")==="hold"&&(t.lifetime??"hold")==="retire";return zk(Zn(e),Zn(t))||n[t.enforcement]<n[e.enforcement]||i}function Bk(e){if(e.state!==void 0&&!(e.state==="present"||e.state==="missing"))throw new M("items source state must be present or missing");let t=Object.hasOwn(e,"equals"),n=e.state!==void 0,i=Number(t)+Number(n);if(e.field!==void 0&&i!==1)throw new M("items source with field requires exactly one of equals or state");if(e.field===void 0&&i!==0)throw new M("items source equals/state requires field")}function Hk(e){if(typeof e.dependency_kind!="string"||e.dependency_kind.trim().length===0)throw new M("dependency_kind source requires dependency_kind");if([e.source_kind,e.source_kind_prefix,e.source_kind_state].filter(t=>t!==void 0).length>1)throw new M("dependency_kind source accepts at most one source_kind predicate");if(e.source_kind!==void 0&&e.source_kind.trim().length===0||e.source_kind_prefix!==void 0&&e.source_kind_prefix.trim().length===0)throw new M("dependency_kind source provenance values must not be empty");if(e.source_kind_state!==void 0&&e.source_kind_state!=="present"&&e.source_kind_state!=="missing")throw new M("dependency_kind source source_kind_state must be present or missing")}function Vk(e){if(e.sample_limit!==void 0&&(!Number.isInteger(e.sample_limit)||e.sample_limit<1))throw new M("prose_edge_gap sample_limit must be a positive integer");for(let t of e.exemptions??[]){if(typeof t.holder_id!="string"||t.holder_id.trim().length===0||typeof t.reason!="string"||t.reason.trim().length===0)throw new M("prose_edge_gap exemptions require holder_id and reason");if(t.target_id!==void 0&&t.target_id.trim().length===0||t.text_contains!==void 0&&t.text_contains.trim().length===0)throw new M("prose_edge_gap exemption selectors must not be empty")}}function wo(e){ut(e.id,"measurement.id"),e.max_cost!==void 0&&Kk(e.max_cost,"measurement.max_cost");let t=e.source;if(Object.prototype.toString.call(t)!=="[object Object]")throw new M(`measurement.source.kind must be one of ${Qn.join(", ")}`);let n=Reflect.get(t,"kind");if(!Qn.includes(n))throw new M(`measurement.source.kind must be one of ${Qn.join(", ")}`);let i=t;if(i.kind==="items"&&Bk(i),i.kind==="dependency_kind"&&Hk(i),i.kind==="prose_edge_gap"&&Vk(i),(i.kind==="graph"||i.kind==="validate"||i.kind==="health")&&(typeof i.field!="string"||i.field.trim().length===0))throw new M(`${i.kind} source requires field`);return i.kind==="provider"&&(ut(i.provider,"provider source provider"),ut(i.key,"provider source key")),e}function bo(e){if(ut(e.id,"assertion.id"),ut(e.measurement_id,"assertion.measurement_id"),typeof e.owner_item_id!="string"||e.owner_item_id.trim().length===0)throw new M("assertion.owner_item_id is required");let t=Zn(e);if(typeof t.value=="number"&&!Number.isFinite(t.value))throw new M(`assertion.${t.polarity} must be a finite number`);if(e.lifetime==="retire"&&(typeof e.retire_reason!="string"||e.retire_reason.trim().length===0))throw new M("retired assertion requires retire_reason");e.scope.kind==="filter"&&ut(e.scope.measurement_id,"assertion.scope.measurement_id");let n=e.negative_control?.cases;if(!Array.isArray(n)||!n.some(i=>i.expected==="pass")||!n.some(i=>i.expected==="fail"))throw new M("assertion negative control requires pass and fail cases");if(!jp(e))throw new M(`assertion ${e.id} negative control does not prove its bound`);return e}function Yk(e){if(!Array.isArray(e.allowed_providers))throw new M("gate provider_policy.allowed_providers must be an array");for(let t of e.allowed_providers)ut(t,"gate.provider_policy.allowed_provider");if(typeof e.triggers!="object"||e.triggers===null||Array.isArray(e.triggers))throw new M("gate provider_policy.triggers must be an object");for(let[t,n]of Object.entries(e.triggers)){if(!lt.includes(t))throw new M(`gate provider policy has unknown trigger ${t}`);if(typeof n!="object"||n===null||!["low","medium","high"].includes(n.max_cost_class)||typeof n.allow_network!="boolean")throw new M(`gate provider policy trigger ${t} is invalid`)}}function Gp(e){if(ut(e.id,"gate.id"),!Array.isArray(e.assertion_ids))throw new M("gate.assertion_ids is required and must be an array");if(e.assertion_ids.length===0)throw new M("gate requires at least one assertion");for(let t of e.assertion_ids)ut(t,"gate.assertion_id");if(!Array.isArray(e.triggers))throw new M(`gate.triggers is required and must be an array of ${lt.join(", ")}`);if(e.triggers.length===0)throw new M("gate requires at least one trigger");for(let t of e.triggers)if(!lt.includes(t))throw new M(`gate trigger must be one of ${lt.join(", ")}`);return e.provider_policy&&Yk(e.provider_policy),e}function hn(e){if(e.version!==Fp)throw new M(`unsupported assurance document version ${String(e.version)}`);let t=new Set;for(let i of e.measurements){if(wo(i),t.has(`measurement:${i.id}`))throw new M(`duplicate measurement ${i.id}`);t.add(`measurement:${i.id}`)}for(let i of e.assertions){if(bo(i),t.has(`assertion:${i.id}`))throw new M(`duplicate assertion ${i.id}`);t.add(`assertion:${i.id}`)}for(let i of e.gates){Gp(i);let r=i.assertion_ids.filter(s=>!e.assertions.some(a=>a.id===s));if(r.length>0)throw new M(`gate ${i.id} references missing assertions: ${r.join(", ")}`);if(t.has(`gate:${i.id}`))throw new M(`duplicate gate ${i.id}`);t.add(`gate:${i.id}`)}let n=new Set(e.measurements.map(i=>i.id));for(let[i,r]of qp(e))if(!n.has(i))throw new M(`${r.join(", ")} references missing measurement ${i}`);return e}function ko(e,t){if("measurement"in e){t.push(e.measurement);return}if("operator"in e)for(let n of e.operands)ko(n,t)}function qp(e){let t=new Map,n=(i,r)=>{let s=t.get(i)??[];s.push(r),t.set(i,s)};for(let i of e.assertions)n(i.measurement_id,`assertion ${i.id}`),i.scope.kind==="filter"&&n(i.scope.measurement_id,`assertion ${i.id} scope`);for(let i of e.measurements){if(i.source.kind!=="derived")continue;let r=[];ko(i.source.expression,r);for(let s of r)n(s,`derived measurement ${i.id}`)}return t}function Jk(e,t){let n=e.assertion_ids.flatMap(s=>{let a=t.assertions.find(o=>o.id===s);return[a.measurement_id,...a.scope.kind==="filter"?[a.scope.measurement_id]:[]]}),i=new Set,r=new Set;for(;n.length>0;){let s=n.pop();if(i.has(s))continue;i.add(s);let a=t.measurements.find(o=>o.id===s);a.source.kind==="provider"?r.add(a.source.provider):a.source.kind==="derived"&&ko(a.source.expression,n)}return r}function ei(){return{version:Fp,measurements:[],assertions:[],gates:[]}}function Xk(e,t){let n=t.items.filter(i=>(e.statuses===void 0||e.statuses.includes(i.status))&&(e.types===void 0||e.types.includes(i.type))&&(e.tags===void 0||e.tags.every(r=>i.tags?.includes(r)))&&(e.field===void 0||(()=>{let r=i[e.field];if(e.state!==void 0){let s=r==null||r===""||Array.isArray(r)&&r.length===0;return e.state==="missing"?s:!s}return vo(r,e.equals)})()));return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(i=>i.id)}}function Qk(e,t){return e.source_kind!==void 0?t?.toLowerCase()===e.source_kind.trim().toLowerCase():e.source_kind_prefix!==void 0?t?.toLowerCase().startsWith(e.source_kind_prefix.trim().toLowerCase())===!0:e.source_kind_state==="present"?t!==void 0&&t.length>0:e.source_kind_state==="missing"?t===void 0||t.length===0:!0}function Zk(e,t){let n=[],i=Oa(e.dependency_kind)??e.dependency_kind.trim().toLowerCase();for(let r of t.items)for(let s of r.dependencies??[]){let a=Oa(s.kind)??s.kind.trim().toLowerCase(),o=s.source_kind?.trim();a===i&&Qk(e,o)&&n.push(`${r.id}->${s.id}${o?`@${o}`:""}`)}return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n}}function e0(e){let t=[e.description,e.body].filter(n=>typeof n=="string").map(n=>n.trim()).filter(Boolean);for(let n of["comments","notes","learnings"]){let i=e[n];if(Array.isArray(i)){for(let r of i)if(typeof r=="string")t.push(r);else if(typeof r=="object"&&r!==null){let s=Reflect.get(r,"text");typeof s=="string"&&t.push(s)}}}return t}function t0(e,t,n,i){return e.some(r=>r.holder_id.trim().toLowerCase()===t.toLowerCase()&&(r.target_id===void 0||r.target_id.trim().toLowerCase()===n.toLowerCase())&&(r.text_contains===void 0||i.toLowerCase().includes(r.text_contains.trim().toLowerCase())))}function yo(e,t){return[e.toLowerCase(),t.toLowerCase()].sort().join("\0")}function n0(e){let t=new Map,n=new Set,i=[],r=/(?<![\w-])[a-z0-9]+(?:-+[a-z0-9]+)+(?![\w-])/giu,s=0;for(let a of e){t.set(a.id.toLowerCase(),a.id);for(let o of a.dependencies??[])n.add(yo(a.id,o.id));for(let o of[a.parent,a.blocked_by])typeof o=="string"&&n.add(yo(a.id,o));for(let o of e0(a)){let c=[...o.matchAll(r)].map(d=>d[0]);s+=c.length,i.push({holder_id:a.id,segment:o,mentioned_ids:c})}}return{canonical_ids:t,linked_pairs:n,prose_mentions:i,mention_count:s}}function i0(e,t){let n=n0(t.items),i=new Map;for(let a of n.prose_mentions){let o=a.mentioned_ids.map(d=>n.canonical_ids.get(d.toLowerCase())).filter(d=>d!==void 0&&d!==a.holder_id),c=[...new Set(o)];for(let d of c){let l=yo(a.holder_id,d);if(n.linked_pairs.has(l)||t0(e.exemptions??[],a.holder_id,d,a.segment))continue;let u=c.some(p=>p!==d);i.get(l)?.explicit===!0&&!u||i.set(l,{contributor:`${a.holder_id}->${d}|subject=${u?"explicit":"implicit"}`,explicit:u})}}let r=[...i.values()],s=r.map(a=>a.contributor).sort();return{value:s.length,population_size:n.canonical_ids.size,cost:t.items.length+n.linked_pairs.size+n.mention_count,contributors:s.slice(0,e.sample_limit??25),partitions:{explicit_subject:r.filter(a=>a.explicit).length,implicit_subject:r.filter(a=>!a.explicit).length}}}function r0(e,t){return{value:t.history.filter(n=>(e.op===void 0||n.op===e.op)&&(e.author===void 0||n.author===e.author)&&(e.harness===void 0||n.agent_harness===e.harness)&&(e.model===void 0||n.agent_model===e.model)).length,population_size:t.history.length,cost:t.history.length}}function s0(e,t){let n=t.items.filter(i=>{let r=i[e.link],s=Array.isArray(r)&&r.length>0;return e.state==="present"?s:!s});return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(i=>i.id)}}function a0(e,t){let n=e.source;return n.kind==="items"?Xk(n,t):n.kind==="dependency_kind"?Zk(n,t):n.kind==="prose_edge_gap"?i0(n,t):n.kind==="history"?r0(n,t):n.kind==="links"?s0(n,t):null}function Kp(e,t){return e.reduce((n,i)=>({units:n.units+i.units,items_scanned:n.items_scanned+i.items_scanned,history_entries:n.history_entries+i.history_entries,provider_calls:n.provider_calls+i.provider_calls,duration_ms:t}),{units:0,items_scanned:0,history_entries:0,provider_calls:0,duration_ms:t})}function o0(e,t){if(t.length===0)throw new TypeError(`derived ${e} requires operands`);if(e==="add")return t.reduce((n,i)=>n+i,0);if(e==="subtract")return t.slice(1).reduce((n,i)=>n-i,t[0]);if(e==="multiply")return t.reduce((n,i)=>n*i,1);if(e==="divide"){if(t.slice(1).includes(0))throw new TypeError("derived divide cannot divide by zero");return t.slice(1).reduce((n,i)=>n/i,t[0])}return e==="min"?Math.min(...t):Math.max(...t)}async function zp(e,t,n){let i=new Array(e.length),r=0,s=Array.from({length:Math.min(t,e.length)},async()=>{for(;r<e.length;){let a=r;r+=1,i[a]=await n(e[a],a)}});return await Promise.all(s),i}async function Wp(e,t,n,i,r){if("literal"in e)return{value:e.literal,costs:[],population_size:0,contributors:[]};if("measurement"in e){let a=n.find(d=>d.id===e.measurement);if(!a)throw new TypeError(`derived measurement references missing ${e.measurement}`);let o=await Bp(a,t,n,i,r);if(typeof o.value!="number")throw new TypeError(`derived measurement ${a.id} is not numeric`);let c=r.charged.has(a.id)?[]:[o.cost];return r.charged.add(a.id),{value:o.value,costs:c,population_size:o.population_size,contributors:o.contributors}}let s=await zp(e.operands,$p,a=>Wp(a,t,n,i,r));return{value:o0(e.operator,s.map(a=>a.value)),costs:s.flatMap(a=>a.costs),population_size:Math.max(0,...s.map(a=>a.population_size)),contributors:[...new Set(s.flatMap(a=>a.contributors))]}}async function c0(e,t,n,i,r){wo(e);let s=Date.now(),a,o=[],c=0;if(e.source.kind==="derived"){let u=await Wp(e.source.expression,t,n,[...i,e.id],r);a={value:u.value,population_size:u.population_size,cost:0,contributors:u.contributors},o=u.costs}else{let u=a0(e,t);u!==null?a=u:(a=await t.external(e.source),c=1)}let d={units:a.cost,items_scanned:e.source.kind==="items"||e.source.kind==="dependency_kind"||e.source.kind==="prose_edge_gap"||e.source.kind==="links"?t.items.length:0,history_entries:e.source.kind==="history"?t.history.length:0,provider_calls:c,duration_ms:Date.now()-s},l=Kp([...o,d],Date.now()-s);if(e.max_cost!==void 0&&l.units>e.max_cost)throw new Le(`measurement ${e.id} exceeded cost ceiling ${e.max_cost} with ${l.units}`);return{id:e.id,definition_fingerprint:`sha256:${$k("sha256").update(ie(e)).digest("hex")}`,value:a.value,population_size:a.population_size,cost:l,contributors:a.contributors??[],...a.partitions?{partitions:a.partitions}:{}}}function Bp(e,t,n,i,r){if(i.includes(e.id))throw new TypeError(`derived measurement cycle: ${[...i,e.id].join(" -> ")}`);let s=r.cache.get(e.id);if(s)return s;let a=c0(e,t,n,i,r).catch(o=>{if(o instanceof et&&o.measurement_id===void 0){let c={measurement_id:e.id,source_kind:o.source_kind,field:o.field,...o.check?{check:o.check}:{}},d=new et(o.message,c);throw d.cause=o,d}throw o});return r.cache.set(e.id,a),a}async function Eo(e,t,n=[e]){return Bp(e,t,n,[],{cache:new Map,charged:new Set})}function d0(e,t){return typeof e!="number"||typeof t.value!="number"?null:t.polarity==="ceiling"||t.polarity==="monotone_nonincreasing"?t.value-e:(t.polarity==="floor"||t.polarity,e-t.value)}function l0(e,t,n={}){bo(e);let i=Zn(e),r=e.lifetime==="retire"&&n.owner_terminal===!0;return{assertion_id:e.id,measurement_id:e.measurement_id,measurement_definition_fingerprint:t.definition_fingerprint,scope:e.scope,population_size:t.population_size,observed:t.value,bound:i,distance:d0(t.value,i),verdict:r?"retired":Up(t.value,i)?"pass":"fail",enforcement:e.enforcement,negative_control_proven:jp(e),cost:t.cost,contributors:t.contributors,...t.partitions?{partitions:t.partitions}:{}}}function u0(e,t,n,i){let r=Jk(e,t);if(r.size===0)return;let s=e.provider_policy,a=s?.triggers[i];if(!s||!a)throw new Le(`assurance gate ${e.id} refuses provider execution at trigger ${i} without an explicit provider policy`);let o=new Set(s.allowed_providers),c={low:0,medium:1,high:2};for(let d of r){if(!o.has(d))throw new Le(`assurance gate ${e.id} refuses provider ${d}`);let l=n.provider_capabilities?.[d];if(!l)throw new Le(`assurance provider ${d} has no declared capabilities`);if(c[l.cost_class]>c[a.max_cost_class])throw new Le(`assurance gate ${e.id} refuses ${l.cost_class}-cost provider ${d} at trigger ${i}`);if(l.network&&!a.allow_network)throw new Le(`assurance gate ${e.id} refuses network provider ${d} at trigger ${i}`)}}async function Pp(e,t,n,i,r){try{return await Eo(n,i,r)}catch(s){if(s instanceof et){let a=s.check?` check ${s.check}`:"",o=s.measurement_id??n.id,c=new Le(`assurance gate ${e} assertion ${t} measurement ${o} source ${s.source_kind}${a} field ${s.field} could not resolve: ${s.message}`,{gate_id:e,assertion_id:t,measurement_id:o,source_kind:s.source_kind,field:s.field,...s.check?{check:s.check}:{}});throw c.cause=s,c}throw s}}async function Hp(e,t,n,i){hn(t);let r=t.gates.find(c=>c.id===e);if(!r)throw new Le(`assurance gate ${e} not found`);if(!r.triggers.includes(i.trigger))throw new Le(`assurance gate ${e} does not declare trigger ${i.trigger}`);u0(r,t,n,i.trigger);let s=await zp(r.assertion_ids,$p,async c=>{let d=t.assertions.find(f=>f.id===c),l=t.measurements.find(f=>f.id===d.measurement_id),u=n;if(d.scope.kind==="active"){let f=new Set(n.terminal_statuses??["closed","canceled"]);u={...n,items:n.items.filter(h=>!f.has(h.status))}}else if(d.scope.kind==="filter"){let f=d.scope.measurement_id,h=t.measurements.find(w=>w.id===f),y=await Pp(r.id,d.id,h,n,t.measurements),v=new Set(y.contributors);u={...n,items:n.items.filter(w=>v.has(w.id))}}let p=n.items.find(f=>f.id===d.owner_item_id),g=p!==void 0&&new Set(n.terminal_statuses??["closed","canceled"]).has(p.status);return l0(d,await Pp(r.id,d.id,l,u,t.measurements),{owner_terminal:g})}),a=s.some(c=>c.verdict==="fail"&&c.enforcement==="block"),o=s.some(c=>c.verdict==="fail"&&c.enforcement==="warn");return{gate_id:r.id,tree_id:n.tree_id,trigger:i.trigger,dry_run:i.dry_run===!0,evaluated_at:new Date().toISOString(),verdict:a?"block":o?"warn":"pass",exit_code:a?1:0,assertions:s,assertions_total:s.length,row_contract:{row_keys:["assertions"],jq_selector:".assertions[]"},cost:Kp(s.map(c=>c.cost),Math.max(0,...s.map(c=>c.cost.duration_ms)))}}function Dr(e){return Uk.join(e,"assurance.json")}async function Vp(e){let t=await Q(Dr(e));return t===null?ei():Nr(t)}function Nr(e){try{return hn(JSON.parse(e))}catch(t){throw new _("The assurance registry is invalid. Repair or restore .agents/pm/assurance.json and retry.",m.GENERIC_FAILURE,{code:"assurance_registry_invalid",reason:String(t),nextSteps:["Restore a valid assurance.json from version control or repair its declaration references.","Run pm assurance list measurement after the repair."]})}}function Mr(e,t){return t==="measurement"?e.measurements:t==="assertion"?e.assertions:e.gates}function m0(e,t){e==="measurement"?wo(t):e==="assertion"?bo(t):Gp(t)}async function ti(e,t){let n=structuredClone(Mr(await Vp(e),t));return{items:n,count:n.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function So(e,t,n){let i=Mr(await Vp(e),t).find(r=>r.id===n);if(!i)throw new TypeError(`assurance ${t} ${n} not found`);return structuredClone(i)}async function Pr(e,t,n,i={}){m0(t,n);let r=await I(e),s=U(i.author,r.author_default),a=await an({pmRoot:e,filePath:Dr(e),op:`assurance:${t}:put`,author:s,message:i.message,lockTtlSeconds:Or,lockWaitMs:Lr,mutate:o=>{let c=o===null?ei():Nr(o),d=Mr(c,t),l=d.findIndex(p=>p.id===n.id),u=l<0?"created":"updated";if(t==="assertion"&&l>=0&&Wk(d[l],n)){let p=n.authorization_decision;if(!p||!i.authorized_decision_ids?.includes(p))throw new M(`loosening assertion ${n.id} requires a verified authorization_decision`)}return l<0?d.push(structuredClone(n)):d[l]=structuredClone(n),hn(c),{raw:`${JSON.stringify(c,null,2)}
|
|
3
|
+
`,result:{changed:!0,action:u,kind:t,id:n.id}}}});return{...a.result,changed:a.changed}}async function To(e,t,n={}){let i=ei();i.measurements=structuredClone(t.measurements),i.assertions=structuredClone(t.assertions),i.gates=structuredClone(t.gates),hn(i);let r=await I(e),s=U(n.author,r.author_default),a=await an({pmRoot:e,filePath:Dr(e),op:"assurance:bundle:apply",author:s,message:n.message,lockTtlSeconds:Or,lockWaitMs:Lr,mutate:o=>{let c=o===null?ei():Nr(o),d=[],l=[],u=(p,g,f)=>{for(let h of g){let y=p.find(v=>v.id===h.id);if(!y){p.push(structuredClone(h)),d.push(`${f}:${h.id}`);continue}if(ie(y)!==ie(h))throw new M(`assurance bundle refuses to replace divergent ${f} ${h.id}`);l.push(`${f}:${h.id}`)}};return u(c.measurements,i.measurements,"measurement"),u(c.assertions,i.assertions,"assertion"),u(c.gates,i.gates,"gate"),hn(c),{raw:`${JSON.stringify(c,null,2)}
|
|
4
|
+
`,result:{changed:d.length>0,created_ids:d,unchanged_ids:l}}}});return{...a.result,changed:a.changed}}async function Yp(e,t,n,i={}){let r=await I(e),s=U(i.author,r.author_default),a=await an({pmRoot:e,filePath:Dr(e),op:`assurance:${t}:remove`,author:s,message:i.message,lockTtlSeconds:Or,lockWaitMs:Lr,mutate:o=>{let c=o===null?ei():Nr(o);if(t==="measurement"){let u=qp(c).get(n);if(u&&u.length>0)throw new M(`assurance measurement ${n} is referenced by ${u.join(", ")}`)}if(t==="assertion"&&c.gates.some(u=>u.assertion_ids.includes(n)))throw new M(`assurance assertion ${n} is referenced by gate`);let d=Mr(c,t),l=d.findIndex(u=>u.id===n);if(l<0)throw new M(`assurance ${t} ${n} not found`);return d.splice(l,1),hn(c),{raw:`${JSON.stringify(c,null,2)}
|
|
5
|
+
`,result:{changed:!0,action:"removed",kind:t,id:n}}}});return{...a.result,changed:a.changed}}async function Jp(e,t,n={}){if(t.dry_run)throw new TypeError("dry-run assurance verdicts are not persisted");let i=await I(e);await sn({pmRoot:e,op:"assurance:gate:verdict",author:U(n.author,i.author_default),context:{assurance_verdict:t},message:n.message??`Assurance gate ${t.gate_id} returned ${t.verdict}`,lockTtlSeconds:Or,lockWaitMs:Lr})}async function Xp(e,t={}){let n=t.limit??qk;if(!Number.isInteger(n)||n<1||n>gn)throw new TypeError(`assurance verdict limit must be an integer from 1 through ${gn}`);return(await ct(Gn(e),Mt)).reverse().filter(i=>i.op==="assurance:gate:verdict").map(i=>i.context?.assurance_verdict).filter(i=>typeof i=="object"&&i!==null&&"gate_id"in i).filter(i=>t.gate_id===void 0||i.gate_id===t.gate_id).slice(0,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]="16979f9d-779a-595a-abe8-94430fb470d5")}catch{}})();var _0=co("list").properties.outputSession,p0={outputInclude:{type:"string",minLength:1,description:"Comma-separated fields or sections retained by any built-in read action."},outputLimit:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}],description:"Universal read row ceiling, or unbounded to disable the shared ceiling."},outputBudget:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}],description:"Universal estimated-token ceiling, or unbounded to return the complete read result."},outputFormat:{type:"string",enum:["json","toon"],description:"Universal read-result encoding selector."},outputSession:{..._0},outputCursor:{type:"string",minLength:1,description:"Opaque continuation cursor returned after budget compaction of a declared row collection."}},Qp={definition:{anyOf:[{type:"object"},{type:"string"}],description:"Policy declaration for policy-put, or proposed metadata for policy-check; structured JSON or JSON text."},policy:{type:"string",description:"Approval policy id for policy-approve."},message:{type:"string",description:"History explanation for policy mutations and approvals."},dryRun:{type:"boolean",description:"Preview registry changes without writing; policy-approve rejects previews."}},Zp={type:"object",properties:{cwd:{type:"string",description:"Workspace directory to run the native pm operation in. Defaults to the MCP server process cwd."},path:{type:"string",description:"Optional pm data root, equivalent to PM_PATH/global --path. Leave unset for real repository tracking."},author:{type:"string",description:"Optional mutation author override. Otherwise pm uses PM_AUTHOR, project settings, or detected harness identity."},tokenAccounting:{type:"boolean",description:"Attach the same bounded per-section token-cost receipt emitted by CLI --token-accounting."}},additionalProperties:!0},le={type:"string",description:"pm item id, for example pm-abc1."},f0=`Operation name (one of): ${Ua.join(", ")}. Package-owned actions are available dynamically when their provider package is installed.`,g0={status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."},offset:{type:["string","number"],description:"Alias for options.offset."}},h0={mode:{type:"string",description:"Alias for options.mode."},status:{type:"string",description:"Alias for options.status."},type:{type:"string",description:"Alias for options.type."},tag:{type:"string",description:"Alias for options.tag."},priority:{type:"string",description:"Alias for options.priority."},limit:{type:["string","number"],description:"Alias for options.limit."}};function z(e,t=[]){return{...Zp,properties:{...Zp.properties,...e},required:t}}var y0=[{name:"pm_run",description:"Run any supported pm operation natively through the pm library. Use this for commands not covered by narrower pm_* tools.",inputSchema:z({action:{type:"string",enum:[...Ua],description:f0},id:le,query:{type:"string",description:"Search query for action=search."},reason:{type:"string",description:"Close reason for action=close."},force:{type:"boolean",description:"Force ownership/terminal-state override when supported."},subcommand:{type:"string",description:"Subcommand selector for actions that take one (for example telemetry, or schema \u2014 prefer the dedicated pm_schema tool for schema operations)."},options:{type:"object",description:"Underlying pm command options using camelCase keys."},fullChangedFields:{type:"boolean",description:"For mutation actions, return the full changed_fields array instead of the default changed_field_count."},idOnly:{type:"boolean",description:"For single-item mutation actions, return only id and status."},...p0},["action"])},{name:"pm_discover",description:"Discover the smallest relevant authorized pm tool catalog under an explicit token budget. Ranking is deterministic and returns public lexical, semantic, graph, permission, freshness, and usage signal explanations. Continue with next_cursor; set includeSchema=true only when complete input schemas are needed.",inputSchema:z({query:{type:"string",maxLength:4096,description:"Free-text capability intent. Empty text lists by stable policy order."},family:{type:"string",enum:["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"],description:"Optional stable capability-family filter."},tier:{type:"string",enum:["core","standard","full"],description:"Maximum command visibility tier included in results."},limit:{type:"integer",minimum:1,maximum:100,description:"Maximum result rows; defaults to 10."},cursor:{type:"string",minLength:1,maxLength:4096,description:"Opaque next_cursor from an equivalent discovery request."},includeSchema:{type:"boolean",description:"Include complete tool input schemas; false by default."},outputBudget:{anyOf:[{type:"integer",minimum:128},{const:"unbounded"}],description:"Estimated-token ceiling; defaults to 1200."}})},{name:"pm_context",description:"Return the agent-oriented project context snapshot. Pass options.depth=brief|standard|deep|full (full = every section with no per-section row cap), options.parent='<id>' to scope the snapshot to one item's subtree (the item plus all descendants), options.fields='id,title,priority' to project focus rows to a field subset for low-token reads, or options.section=['hierarchy','progress',...] to pick sections.",inputSchema:z({options:{type:"object"}})},{name:"pm_next",description:"Recommend the next actionable work item: the single highest-priority READY item (active status, no open blockers, no open children; completed containers surface only when no concrete leaf work is ready) plus the ranked ready and blocked queues. The recommended item carries a rationale and each blocked item lists the open blockers gating it. Pass options.parent='<id>' to scope to one subtree, options.limit=N to cap ready rows, options.readyOnly=true to omit the blocked list, or filters (options.type/tag/priority/assignee/sprint/release). The most token-efficient 'what should I do now?' read for agents.",inputSchema:z({options:{type:"object"}})},{name:"pm_search",description:"Search pm items with keyword, semantic, or hybrid search. Defaults to a compact projection for token efficiency. Pass options.mode=keyword|semantic|hybrid (default follows search.default_mode: auto runs hybrid when semantic search is configured and runnable, else keyword; the result reports mode_source), options.limit=N to cap hits, options.status='all' for no lifecycle restriction, options.fields='id,title,score' for a custom projection, or options.full=true for full item bodies (can be large). The result echoes the applied filters and projection mode in query_summary.",inputSchema:z({query:{type:"string"},options:{type:"object"},...h0},["query"])},{name:"pm_list",description:"List pm items with status/type/tag/priority filters. Defaults to compact projection for token efficiency. options.status accepts CSV (all,open,in_progress). Pass options.compact=false or options.includeBody=true for full bodies/comments. Pass options.brief=true for ultra-terse (id/status/type/title only). Pass options.fields='id,title,priority' for custom projection. Pass options.limit=N to cap row count. The result echoes the applied filters and projection mode in query_summary.",inputSchema:z({options:{type:"object"},...g0})},{name:"pm_get",description:"Read one pm item with shared SDK projections. Pass options.depth='brief' or options.fields='id,title,status' for low-token inspection, options.fields='id,schedule.start_at' for schedule context, or options.at='7' / an ISO timestamp for a verified mutation-free historical read. Parent results include bounded child counts, samples, and continuation metadata.",inputSchema:z({id:le,options:{type:"object",description:"Get options such as depth=brief|standard|deep|full, fields=id,title,status, or at=<version|ISO timestamp>."}},["id"])},{name:"pm_events",description:"Read a bounded, cursor-resumable page of committed mutation events across item history streams. Batch cursors are the token-efficient default; pass cursorMode=row for per-event checkpoints.",inputSchema:z({since:{type:"string",description:"Durable event cursor or ISO timestamp lower bound."},type:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},author:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},item:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},limit:{type:"integer",minimum:0,maximum:1e3},full:{type:"boolean"},cursorMode:{type:"string",enum:["batch","row"],description:"Cursor framing: batch returns one terminal next_cursor (default); row also adds a cursor to every event."}})},{name:"pm_create",description:"Create a pm item natively and write pm history. Output is compact by default (changed_fields replaced with changed_field_count for token efficiency); pass fullChangedFields=true for the full changed_fields array.",inputSchema:z({fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},allowMissingParent:{type:"boolean",description:"Allow unresolved parent references and emit a validation warning."},allowDuplicate:{type:"boolean",description:"Explicitly create when strict similarity governance finds likely duplicates."},options:{type:"object",description:"Create options. title and description are required."}},["options"])},{name:"pm_mutate",description:"Apply an ordered create/update/close/release batch atomically through the public pm SDK. Create rows may declare ref and omit id; @ref forward references resolve deterministically from the stable transactionId, which is derived from the batch when omitted. Bulk creation: rows shaped as {item:{title,type,...}} are create documents using pm create field names; upsertKey updates the existing item whose field matches instead of creating a duplicate. Set dryRun=true to validate and preview without writes.",inputSchema:z({transactionId:{type:"string",description:"Stable idempotency key for this atomic mutation batch; derived from the batch content when omitted."},mutations:{type:"array",minItems:1,description:"Ordered rows shaped as {op:create|update|close|release,id?,ref?,options?,reason?} or create documents {ref?,item:{...}}.",items:{type:"object",properties:{op:{type:"string",enum:["create","update","close","release"],description:"Operation; omitted rows carrying item are creates."},id:le,ref:{type:"string",description:"Batch-local create alias; its deterministic id can be referenced as @alias by any row."},reason:{type:"string"},options:{type:"object"},item:{type:"object",description:"Create document using pm create field names (title, type, description, body, tags, parent, custom fields)."},unique:{type:"object",description:"Create-only guard {key,value} re-checked under the writer lock; keyed upsert sets it on rows that matched nothing at planning time."},match:{type:"object",description:"Update-only guard {key,value} re-read under the writer lock; keyed upsert sets it on rows it converted into updates of a matched item."}},additionalProperties:!1}},upsertKey:{type:"string",description:"Item field whose value identifies an existing item to update instead of creating a duplicate."},dryRun:{type:"boolean",description:"Validate and preview without writing."},createCompensation:{type:"string",enum:["close","delete"],description:"How a failed batch compensates created items; defaults to close."},lockTtlSeconds:{type:"number"},lockWaitMs:{type:"number"}},["mutations"])},{name:"pm_copy",description:"Copy an existing pm item into a new id while resetting lifecycle fields. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:z({id:le,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object",description:"Copy options such as title override, author, and message."}},["id"])},{name:"pm_focus",description:"Set, clear, or show the session focused item. When focused, pm_create defaults its parent to the focused item (an explicit parent still overrides). Pass id to focus an item, options.clear=true to clear, or neither to show current focus.",inputSchema:z({id:le,clear:{type:"boolean",description:"Clear the focused item (cannot be combined with id)."},options:{type:"object",description:"Focus options such as clear (boolean)."}},[])},{name:"pm_update",description:"Update pm item metadata/body/dependencies/log seeds natively. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields delta.",inputSchema:z({id:le,fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object"}},["id","options"])},{name:"pm_append",description:"Append markdown text to a pm item body and write pm history. Useful for seeding evidence/log entries before close. Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:z({id:le,body:{type:"string",description:"Markdown text to append to the item body. Required here or as options.body."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},options:{type:"object",description:"Append options such as body, author, and message."}},["id"])},{name:"pm_claim",description:"Claim a pm item.",inputSchema:z({id:le,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_release",description:"Release a pm item claim.",inputSchema:z({id:le,force:{type:"boolean"},options:{type:"object"}},["id"])},{name:"pm_close",description:"Close a pm item with optional close reason and optional close validation (reason requirement follows governance settings). Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.",inputSchema:z({id:le,reason:{type:"string",description:"Close reason text when provided or required by governance settings."},duplicateOf:{type:"string",description:"Canonical item id when closing this item as a duplicate."},fullChangedFields:{type:"boolean",description:"Return full changed_fields instead of changed_field_count."},idOnly:{type:"boolean",description:"Return only id and status."},options:{type:"object"}},["id"])},{name:"pm_comments",description:"List, add, edit, or delete comments on a pm item. Use options.add to append, options.edit=<1-based index> with replacement text to fix a comment, or options.delete=<1-based index> to remove one. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. List calls default to the most recent 20 comments with total_count/has_more metadata for token efficiency. Pass options.limit=N to choose a page size, options.limit=0 for summary-only metadata, or options.full=true for full history.",inputSchema:z({id:le,options:{type:"object"}},["id"])},{name:"pm_files",description:"List, add, remove, or validate linked files for a pm item.",inputSchema:z({id:le,options:{type:"object"}},["id"])},{name:"pm_docs",description:"List, add, or remove linked docs for a pm item.",inputSchema:z({id:le,options:{type:"object"}},["id"])},{name:"pm_notes",description:"List, add, edit, or delete structured notes on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing notes.",inputSchema:z({id:le,options:{type:"object"}},["id"])},{name:"pm_learnings",description:"List, add, edit, or delete learnings on a pm item. options.ifAbsent applies only to options.add for retry-safe author-and-text deduplication and cannot combine with options.edit or options.delete. Omit mutation options to list existing learnings.",inputSchema:z({id:le,options:{type:"object"}},["id"])},{name:"pm_deps",description:"Read dependency trees/graphs or one bounded explainable relationship context packet. Use options.format=context with direction, kind, depth, node, edge, token, and cursor bounds; context returns a counts-first summary, per-node roles/reasons, root evidence pointers, and enumerated missing references.",inputSchema:z({id:le,options:{type:"object"}},["id"])},{name:"pm_graph",description:"Run bounded workspace relationship-graph queries: ancestors/descendants (hierarchy), predecessors/successors (ordering), paths, impact (blast radius), analyze (execution + knowledge analytics), audit (governance findings with change-since-baseline deltas), communities (label-propagation clusters), redundancy (transitively implied edges), dominators (structural bottlenecks), slack (critical-path method float per task), centrality (betweenness/closeness/degree with directed fan-in/out), articulation (cut points and bridges \u2014 single points of failure), plan (dry-run remediation proposals derived from the audit), and index (durable cross-process graph index status/rebuild/clear). Traversals, paths, impact, and dominators require id; paths also requires target. Options support kind, maxDepth, limit, after, direction, maxPaths, sample, exemptIsolate, exemptIsolateType, saveBaseline (audit), rebuild/clear (index), and counts-first summary.",inputSchema:z({subcommand:{type:"string",enum:[...Ml]},id:le,target:le,options:{type:"object"}},["subcommand"])},{name:"pm_test",description:"List, add, remove, or run linked tests for a pm item.",inputSchema:z({id:le,options:{type:"object"}},["id"])},{name:"pm_validate",description:"Run pm validation checks.",inputSchema:z({options:{type:"object"}})},{name:"pm_health",description:"Run pm health diagnostics. Pass options.brief=true for compact low-token details, options.skipIntegrity=true, options.skipDrift=true, options.skipVectors=true for a fast status-only check, or options.full=true for the complete deep check.",inputSchema:z({options:{type:"object"}})},{name:"pm_contracts",description:"Inspect pm command, flag, schema, and availability contracts.",inputSchema:z({options:{type:"object"}})},{name:"pm_schema",description:"Inspect or modify the workspace item-type/status/field schema (pm schema). subcommand selects the operation; name carries the item type name (show/add-type/remove-type), status id (show-status/add-status/remove-status), or field key (show-field/add-field/remove-field). apply-preset adopts a domain type preset; add-type with infer=true derives types from title-prefix conventions. Policy verbs author declarations, preview changes, set enforcement, and record content-bound approvals. Registry mutations write workspace history; approvals write item history.",inputSchema:z({...Qp,subcommand:{type:"string",enum:["list","show","show-status","add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset",...Cl],description:"Schema subcommand to run."},name:{type:"string",description:"Item type name, status id, field key, policy id, or item id for the selected schema verb; policy-mode requires advise|refuse."},description:{type:"string",description:"Custom item type, status, or field description for add-type/add-status/add-field."},defaultStatus:{type:"string",description:"Default status for add-type."},folder:{type:"string",description:"Storage folder for add-type."},alias:{type:"array",items:{type:"string"},description:"Aliases for add-type/add-status, or extra CLI flag aliases for add-field."},role:{type:"array",items:{type:"string",enum:[...Da]},description:`Lifecycle roles for add-status: ${Da.join(", ")}.`},order:{type:"number",description:"Display/sort order for add-status."},fieldType:{type:"string",enum:["string","number","boolean","string_array"],description:"Value type for a custom field (add-field)."},commands:{type:"array",items:{type:"string"},description:"Commands a custom field is wired onto (add-field): create, update, update_many, list, search, calendar, context."},cliFlag:{type:"string",description:"Override the auto-derived CLI flag for a custom field (add-field)."},required:{type:"boolean",description:"Mark a custom field as always required (add-field)."},requiredOnCreate:{type:"boolean",description:"Mark a custom field as required at create time (add-field)."},allowUnset:{type:"boolean",description:"Whether a custom field may be cleared via --unset (add-field); defaults to true."},requiredTypes:{type:"array",items:{type:"string"},description:"Restrict a custom field's requirement to specific item types (add-field)."},typePreset:{type:"string",enum:["agile","ops","research"],description:"Domain type preset to adopt (apply-preset)."},infer:{type:"boolean",description:"Infer item types from title-prefix conventions (add-type); previews unless apply is true."},minCount:{type:"number",description:"Minimum items sharing a prefix for add-type inference (default 10)."},apply:{type:"boolean",description:"Register inferred types (add-type infer); without it the call previews only."},force:{type:"boolean",description:"Override removal guardrails for destructive schema changes when supported."},options:{type:"object",description:"Additional schema options using camelCase keys.",properties:Qp}},["subcommand"])},{name:"pm_profile",description:"List, show, apply, or lint project profiles (pm profile) \u2014 archetype bundles that stage item types, statuses, fields, per-type workflows, config knobs, create templates, and recommended packages. subcommand selects the operation; name carries the profile name (agile, ops, research) for show/apply/lint. apply stages every dimension idempotently; dryRun previews the diff without writing; lint reports author-time consistency findings (graded error/warning) without touching the tracker. Profile staging writes workspace config/schema files, not item history.",inputSchema:z({subcommand:{type:"string",enum:["list","show","apply","lint"],description:"Profile subcommand to run."},name:{type:"string",description:"Profile name for show/apply/lint. Required for those subcommands. Built-ins are agile, ops, and research; an active extension can contribute additional archetype names that resolve here too."},dryRun:{type:"boolean",description:"Preview the apply diff without writing any files (apply)."},author:{type:"string",description:"Mutation author for apply."},force:{type:"boolean",description:"Force ownership/lock override for apply."},options:{type:"object",description:"Additional profile options using camelCase keys."}},["subcommand"])},{name:"pm_config",description:"Read or write pm workspace configuration (pm config). configAction selects get/set/list/export; key/value address a single setting for get/set. scope chooses the project (default) or global settings file.",inputSchema:z({configAction:{type:"string",enum:["get","set","list","export"],description:"Config operation to perform. get/set require key; list/export dump the resolved settings surface."},key:{type:"string",description:"Settings key for get/set, for example governance-require-close-reason, telemetry-tracking, or a nested leaf such as search_provider (dash and underscore variants accepted; configAction=get without a key lists supported keys in the error)."},value:{type:"string",description:"New value for configAction=set."},scope:{type:"string",enum:["project","global"],description:"Settings scope to read or write. Defaults to project."},options:{type:"object",description:"Additional config options such as criterion, clearCriteria, format, or policy."}},["configAction"])},{name:"pm_plan",description:"Run agent-optimized Plan workflows. options.subcommand selects: create|show|add-step|update-step|complete-step|block-step|reorder-step|remove-step|link|unlink|decision|discovery|validation|resume|approve|materialize. Provide id for all non-create subcommands; provide stepRef for step lifecycle subcommands. Plans store agent-readable steps with dependencies, decisions, discoveries, validation, and resume context.",inputSchema:z({id:{type:"string",description:"Plan id (required for all subcommands except create)."},stepRef:{type:"string",description:"Step id or order for step lifecycle subcommands."},options:{type:"object",description:"Plan options including subcommand, stepRef, stepStatus, link, depth, etc."}})}],v0={pm_append:"append",pm_claim:"claim",pm_close:"close",pm_comments:"comments",pm_config:"config",pm_context:"context",pm_contracts:"contracts",pm_copy:"copy",pm_create:"create",pm_deps:"deps",pm_docs:"docs",pm_events:"events",pm_files:"files",pm_focus:"focus",pm_get:"get",pm_graph:"graph",pm_health:"health",pm_learnings:"learnings",pm_list:"list",pm_next:"next",pm_notes:"notes",pm_plan:"plan",pm_profile:"profile",pm_release:"release",pm_schema:"schema",pm_search:"search",pm_test:"test",pm_update:"update",pm_validate:"validate"},w0=y0.map(e=>{let t=v0[e.name];if(!t)return e;let n=e.inputSchema.properties,i=e.inputSchema.required.map(String);return{...e,inputSchema:co(t,{properties:n,required:i})}});function ef(){return w0.map(e=>{let t=e.inputSchema.required,n=Array.isArray(t)?t.map(i=>String(i)).sort((i,r)=>i.localeCompare(r)):[];return{name:e.name,description:e.description,required:n,input_schema:e.inputSchema}}).sort((e,t)=>e.name.localeCompare(t.name))}(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]="58e5d12e-060d-509d-9111-01d82054f4c3")}catch{}})();var tf=new Map([["claim",["--if-available","--next","--type","--priority","--token-budget","--explain-ranking"]],["close",["--reason","--validate-close","--resolution","--expected-result","--actual-result","--message"]],["context",["--limit","--after","--depth","--section","--token-budget","--explain-ranking"]],["contracts",["--command","--flags-only","--summary","--runtime-only","--availability-only","--full"]],["create",["--title","--type","--status","--priority","--dep","--comment"]],["get",["--full","--depth","--fields","--tree","--tree-depth","--format"]],["health",["--check-only","--summary","--brief","--check-telemetry","--strict-exit","--full"]],["list",["--status","--type","--limit","--after","--brief","--fields"]],["next",["--limit","--blocked-limit","--ready-only","--token-budget","--explain-ranking","--format"]],["search",["--mode","--status","--type","--limit","--after","--fields"]],["update",["--status","--message","--dep","--comment","--file","--test"]],["validate",["--check-resolution","--check-history-drift","--check-storage-integrity","--counts","--strict-exit","--fix-hints"]]]),b0=["--limit","--after","--offset","--token-budget","--brief","--summary","--compact","--fields","--full","--format","--since","--until"],mf=new Set(["list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"]),$r=new Set(["calendar","guide","reindex","completion","test-runs-list","test-runs-status","test-runs-logs","test-runs-stop","test-runs-resume","templates-list","templates-save","templates-show"]),Ut=new Set(["meet","event","remind","search-advanced","dedupe-audit","dedupe-merge","comments-audit","cal","calendar","completion","completion-statuses","completion-tags","completion-types","guide","reindex","normalize","templates","templates list","templates save","templates show","test-runs","test-runs list","test-runs status","test-runs logs","test-runs stop","test-runs resume"]),_f=new Map([["meet","calendar"],["event","calendar"],["remind","calendar"],["search-advanced","search-advanced"],["dedupe-audit","governance-audit"],["dedupe-merge","governance-audit"],["comments-audit","governance-audit"],["cal","calendar"],["calendar","calendar"],["completion","guide-shell"],["completion-statuses","guide-shell"],["completion-tags","guide-shell"],["completion-types","guide-shell"],["guide","guide-shell"],["reindex","search-advanced"],["normalize","governance-audit"],["templates","templates"],["templates list","templates"],["templates save","templates"],["templates show","templates"],["test-runs","linked-test-adapters"],["test-runs list","linked-test-adapters"],["test-runs status","linked-test-adapters"],["test-runs logs","linked-test-adapters"],["test-runs stop","linked-test-adapters"],["test-runs resume","linked-test-adapters"]]),pf=new Map([["calendar","calendar|cal"],["guide","guide"],["reindex","reindex"],["completion","completion"],["test-runs-list","test-runs|test-runs list"],["test-runs-status","test-runs status"],["test-runs-logs","test-runs logs"],["test-runs-stop","test-runs stop"],["test-runs-resume","test-runs resume"],["templates-list","templates|templates list"],["templates-save","templates save"],["templates-show","templates show"]]),ff=new Map([...pf.entries()].flatMap(([e,t])=>mt(t).map(n=>[n,e]))),gf=[{canonical:"context",aliases:["ctx"]},{canonical:"package",aliases:["extension","packages"]}],Co=new Map(gf.flatMap(e=>e.aliases.map(t=>[t,e.canonical]))),k0=10,E0=20,nf=new Map([["activity","Read activity."],["aggregate","Group counts."],["append","Append body."],["assurance","Evaluate assurance."],["assurance derive","Derive checks."],["assurance risk","Select checks for changes."],["assurance lineages","Measure recurrence coverage."],["beads","Manage Beads interoperability."],["cal","Manage calendar integration."],["calendar","Manage calendar integration."],["changelog","Generate changelog output."],["claim","Claim work."],["close","Close work."],["close-many","Close matching work."],["close-task","Close task work."],["command-kit","Inspect command authoring primitives."],["comments","Manage comments."],["comments-audit","Audit comment governance."],["completion","Generate shell completions."],["config","Manage settings."],["context","Build context."],["contracts","Inspect contracts."],["copy","Copy work."],["create","Create work."],["dedupe-audit","Audit duplicate work."],["dedupe-merge","Merge duplicate work."],["delete","Delete work."],["deps","Manage deps."],["duplicates","Find duplicate clusters."],["docs","Link docs."],["eval","Run evaluations."],["event","Manage events."],["events","Read events."],["files","Link files."],["focus","Manage focus."],["gc","Clean caches."],["get","Read item."],["graph","Query graph."],["guide","Show user guides."],["health","Check health."],["help","Show help."],["history","Inspect history."],["init","Initialize workspace."],["install","Install packages."],["item","Mutate items."],["learnings","Manage learnings."],["list","List work."],["list-all","List work across every status."],["list-blocked","List blocked work."],["list-canceled","List canceled work."],["list-closed","List closed work."],["list-draft","List draft work."],["list-in-progress","List in-progress work."],["list-open","List open work."],["meet","Record meeting context."],["merge","Manage tracker merges."],["next","Pick next work."],["notes","Manage notes."],["normalize","Normalize tracker data."],["ops","Run operations."],["package","Manage packages."],["packages","Manage packages."],["pause-task","Pause task work."],["plan","Manage plans."],["profile","Manage profiles."],["reindex","Refresh search index."],["release","Release claim."],["remind","Manage reminders."],["restore","Restore history."],["schema","Customize schema."],["search","Search work."],["search-advanced","Run advanced search."],["start-task","Start task work."],["stats","Show stats."],["telemetry","Manage telemetry."],["templates","Manage work templates."],["test","Run linked tests."],["test-all","Run all linked tests."],["test-runs","Inspect background test runs."],["todos","Manage source-code todos."],["twin","Manage repository twins."],["update","Update work."],["update-many","Update matching work."],["upgrade","Upgrade packages."],["validate","Validate data."],["vcs","Inspect version-control context."],["workspace","Manage workspaces."],["history-author-acknowledge","Acknowledge reviewed history authors."],["history-compact","Compact history."],["history-attest","Export or verify detached history proof."],["history-redact","Redact sensitive history values."],["history-repair","Repair history integrity."]]),hf=[["init",Qu],["install",em],["uninstall",tm],["explore",nm],["manage",cm],["describe",im],["reload",dm],["doctor",lm],["catalog",um],["adopt",mm],["adopt-all",rm],["activate",sm],["deactivate",am],["migrate",om]],S0=[...hf.map(([e,t])=>e==="init"?[e,Zu]:[e,t]),["upgrade",Ja]],T0=[...hf.map(([e,t])=>[`extension ${e}`,t]),...S0.flatMap(([e,t])=>[[`package ${e}`,t],[`packages ${e}`,t]]),["init",Yu],["config",Ju],["extension",Xu],["package",Ya],["packages",Ya],["install",_m],["create",Mm],["item mutate",Pm],["item complete",Fm],["item reopen",$m],["copy",Um],["focus",jm],["update",Gm],["update-many",qm],["upgrade",Ja],["calendar",Xa],["cal",Xa],["context",Qa],["ctx",Qa],["get",Wm],["search",Xm],["eval",Ym],["events",zm],["workspace",St],["workspace position",[]],["workspace snapshot",St],["workspace snapshot create",St],["workspace snapshot list",St],["workspace snapshot inspect",St],["workspace snapshot restore",St],["workspace snapshot delete",St],["next",Jm],["aggregate",Du],["deps",Hm],["graph",Vm],["guide",Bm],["reindex",pm],["history",Uu],["history-compact",zu],["history-attest",Wu],["history-redact",Gu],["history-repair",qu],["history-author-acknowledge",Ku],["merge",ju],["schema",Bu],["profile",Hu],["plan",Vu],["restore",vm],["delete",wm],["close",fm],["close-many",gm],["append",hm],["claim",ym],["release",bm],["start-task",km],["pause-task",Em],["close-task",Sm],["comments",Nu],["notes",Mu],["learnings",Pu],["files",Fu],["docs",$u],["test",Tm],["test-runs-worker",[]],["test-all",Am],["telemetry",Im],["test-runs",Cm],["gc",xm],["stats",Rm],["ops",[]],["duplicates",Om],["validate",Dm],["health",Lm],["assurance",Nm],...e_,["contracts",Qm],["completion",Zm],["activity",Km],...[...mf].map(e=>[e,Lu])],ni=new Map(T0);for(let{alias:e,canonical:t}of Je){let n=ni.get(e);n!==void 0&&ni.set(t,n)}function A0(e){return ff.get(e)||(e.startsWith("test-runs ")?`test-runs-${e.slice(10)}`:e.startsWith("templates ")?`templates-${e.slice(10)}`:e)}function rf(e){let t=Je.find(n=>n.alias===e);return t?`${t.canonical}|${t.alias}`:Qe.includes(e)?be(e):e.startsWith("extension-")?be(`extension ${e.slice(10)}`):e.startsWith("package-")?be(`package ${e.slice(8)}`):e.startsWith("item-")?be(`item ${e.slice(5)}`):e.startsWith("test-runs-")?be(`test-runs ${e.slice(10)}`):e.startsWith("templates-")?be(`templates ${e.slice(10)}`):$r.has(e)?pf.get(e)??be(e):null}function I0(e,t){let n=H(t);return n!==t||Je.some(i=>i.alias===t)?e.action===n:e.command_path===null?!1:mt(e.command_path).some(i=>i===t?!0:i.startsWith(`${t} `)||t.startsWith(`${i} `))}function mt(e){return e.split("|").map(t=>be(t)).filter(t=>t.length>0)}function C0(e,t){let n=new Set(t),i=new Set;for(let r of e)if(r.command_path)for(let s of mt(r.command_path)){let a=s.split(" ").filter(o=>o.length>0);if(a.length!==0)for(let o=a.length;o>0;o-=1){let c=a.slice(0,o).join(" ");if(n.has(c)){i.add(c);break}}}return[...i].sort((r,s)=>r.localeCompare(s))}function Fr(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function ii(e){let t=e.oneOf;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null):[]}function x0(e,t){if(!t)return{...e};let n=ii(e).filter(i=>{let r=i.properties;if(typeof r!="object"||r===null)return!1;let s=r.action;return typeof s!="object"||s===null?!1:s.const===t});return{...e,oneOf:n}}function Ao(e,t){let n=ii(e).filter(i=>{let r=i.properties;if(typeof r!="object"||r===null)return!1;let s=r.action;if(typeof s!="object"||s===null)return!1;let a=s.const;return typeof a=="string"&&t.has(a)});return{...e,oneOf:n}}function be(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function yf(e){return e.replace(/\s+/g,"-")}function At(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function sf(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let i of e){let r=At(i);!r||n.has(r)||(n.add(r),t.push(r))}return t}function Io(e,t,n){n&&(e[t]=!0)}function af(e,t){if(e==null)return null;if(typeof e!="string")throw new TypeError("Expected string for extension flag name.");let n=e.trim();return n.length===0?null:t==="long"?n.startsWith("--")&&n.length>2?$l(n):null:n.startsWith("-")&&!n.startsWith("--")&&n.length>1?n:null}function R0(e){let t=af(e.long,"long"),n=af(e.short,"short"),i=t??n;if(!i)return null;let r={flag:i};n&&t&&(r.short=n),Io(r,"required",e.required===!0),Io(r,"repeatable",e.repeatable===!0),Io(r,"list",e.list===!0);let s=At(e.description);s&&(r.description=s);let a=Ul(e);r.value_arity=a.value_arity;let o=At(e.value_name)??a.value_name;o&&(r.value_name=o);let c=a.value_type??(a.value_name?"string":null);return c&&(r.value_type=c),r}function vf(e){let t=new Map;for(let i of e){let r=be(i.target_command);if(r.length===0)continue;let s=t.get(r)??{flags:[],sources:[],dedupe:new Set,sourceDedupe:new Set},a=`${i.layer}:${i.name}`;s.sourceDedupe.has(a)||(s.sourceDedupe.add(a),s.sources.push({layer:i.layer,name:i.name}));for(let o of i.flags){let c=R0(o);if(!c)continue;let d=`${c.flag}|${c.short??""}`;s.dedupe.has(d)||(s.dedupe.add(d),s.flags.push(c))}t.set(r,s)}let n=new Map;for(let[i,r]of t.entries())n.set(i,{flags:r.flags,sources:r.sources.sort((s,a)=>{let o=s.layer.localeCompare(a.layer);return o!==0?o:(s.name??"").localeCompare(a.name??"")})});return n}function O0(e,t){return e.read_output===void 0?{flags:t}:{read_output:e.read_output,flags:[...t,...Va.filter(({flag:n})=>n.startsWith("--output-"))]}}function L0(e){let t=vf(e.flagRegistrations),n=new Map;for(let s of e.commandDefinitions){let a=be(s.command);if(a.length===0)continue;let o=At(s.action)??yf(a),c=Array.isArray(s.arguments)?s.arguments.map(d=>{let l=At(d.name);return l?{name:l,required:d.required===!0,variadic:d.variadic===!0,description:At(d.description)}:null}).filter(d=>d!==null):[];n.set(a,{...s.tier===void 0?{}:{tier:s.tier},...O0(s,t.get(a)?.flags??[]),command:a,action:o,source:{layer:s.layer,name:s.name},description:At(s.description),intent:At(s.intent),arguments:c,examples:sf(s.examples),failure_hints:sf(s.failure_hints)})}let i=new Set;for(let s of e.handlers)i.add(be(s));for(let s of n.keys())i.add(s);for(let s of t.keys())i.add(s);let r=[];for(let s of[...i].sort((a,o)=>a.localeCompare(o))){let a=n.get(s);r.push(D0(s,a,t.get(s)?.flags??[]))}return r}function D0(e,t,n){return t?{...t,flags:t.flags.length>0?t.flags:n}:{command:e,action:yf(e),source:null,description:null,intent:null,arguments:[],flags:n,examples:[],failure_hints:[]}}function N0(e){let t=e.flag.replace(/^-+/,"").trim();if(t.length===0)return null;let n=t.replace(/-([a-z0-9])/g,(i,r)=>r.toUpperCase()).replace(/[^a-zA-Z0-9]/g,"");return n.length>0?n:null}function M0(e,t){return e.variadic?{type:"array",items:{type:"string"},description:e.description??`Variadic argument '${e.name}' for extension action '${t}'.`}:{type:"string",description:e.description??`Argument '${e.name}' for extension action '${t}'.`}}function P0(e,t){let n=e.value_type??"boolean",i=n==="boolean"?"boolean":n==="number"?["number","string"]:"string",r=e.repeatable===!0||e.list===!0;return{type:r?"array":i,...r?{items:{type:i}}:{},description:e.description??`Extension option '${e.flag}' for action '${t}'.`}}function F0(e){let t=e.command.split("|").map(r=>r.trim()).filter(r=>r.length>0),n={action:{type:"string",const:e.action,description:e.intent??e.description??`Invoke extension command '${e.command}'.`}},i=["action"];for(let r of e.arguments)n[r.name]=M0(r,e.action),r.required&&i.push(r.name);for(let r of e.flags){let s=N0(r);!s||n[s]!==void 0||(n[s]=Va.some(a=>a.flag===r.flag&&a.flag.startsWith("--output-"))?M_[s]:P0(r,e.action),r.required===!0&&i.push(s))}return{type:"object",properties:n,required:i,additionalProperties:!0,"x-extension-source":e.source,"x-extension-command":t[0]??e.command,"x-extension-commands":t}}function $0(e,t){e.description??=t.description,e.value_name??=t.value_name,e.value_type??=t.value_type,t.required===!0&&(e.required=!0),t.repeatable===!0&&(e.repeatable=!0)}function U0(e){let t=new Map;for(let n of e){let i=t.get(n.action);if(!i){t.set(n.action,{...n,flags:[...n.flags],examples:[...n.examples],failure_hints:[...n.failure_hints]});continue}i.command=[...new Set([i.command,n.command])].sort((s,a)=>s.localeCompare(a)).join("|"),i.arguments=i.arguments.length>=n.arguments.length?i.arguments:n.arguments;let r=new Set(i.flags.map(s=>`${s.flag}|${s.short??""}`));for(let s of n.flags){let a=`${s.flag}|${s.short??""}`;if(!r.has(a))r.add(a),i.flags.push(s);else{let o=i.flags.find(c=>`${c.flag}|${c.short??""}`===a);o&&$0(o,s)}}i.examples=[...new Set([...i.examples,...n.examples])],i.failure_hints=[...new Set([...i.failure_hints,...n.failure_hints])]}return[...t.values()].sort((n,i)=>n.action.localeCompare(i.action))}async function j0(e,t=I){let n={mode:Lt.extensions.policy.mode,trust_mode:Lt.extensions.policy.trust_mode,default_sandbox_profile:Lt.extensions.policy.default_sandbox_profile};if(e.noExtensions)return{handlers:new Set,disabledReason:"extensions_disabled",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};let i=x(process.cwd(),e.path);if(!await te(Ae(i)))return{handlers:new Set,disabledReason:null,commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n};try{let r=await t(i),s=await Vi({pmRoot:i,settings:r,cwd:process.cwd(),noExtensions:!1}),a=await Yi({...s,loaded:s.loaded});return{handlers:new Set(a.commands.handlers.map(o=>be(o.command))),disabledReason:null,commandDefinitions:a.registrations.commands,flagRegistrations:a.registrations.flags,registrations:a.registrations,policyState:{mode:s.policy.mode,trust_mode:s.policy.trust_mode,default_sandbox_profile:s.policy.default_sandbox_profile}}}catch{return{handlers:new Set,disabledReason:"extension_runtime_probe_failed",commandDefinitions:[],flagRegistrations:[],registrations:null,policyState:n}}}function G0(e,t={}){let n=new Map;for(let i of Pl){let r=$r.has(i);if(r&&!t.includePackageOwnedActions)continue;let s=rf(i);n.set(i,{action:i,provider:r?"extension":"core",requires_extension:r,command_path:s})}if(t.includePackageOwnedActions)for(let i of $r)n.has(i)||n.set(i,{action:i,provider:"extension",requires_extension:!0,command_path:rf(i)});for(let i of e)n.has(i.action)||n.set(i.action,{action:i.action,provider:"extension",requires_extension:!0,command_path:Je.find(r=>r.alias===i.command)?.canonical??be(i.command)});return[...n.values()].sort((i,r)=>(i.action??"").localeCompare(r.action??""))}function q0(e,t){if(e.provider==="core"&&!e.requires_extension)return{action:e.action,invocable:!0,available:!0,requires_extension:!1,provider:"core",disabled_reason:null,command_path:e.command_path,cli_exposed:e.command_path!==null&&(!Ut.has(e.action)||t.handlers.has(e.action))};let n=e.command_path?mt(e.command_path):[],i=n.some(a=>t.handlers.has(a)||t.handlers.has(H(a))),r=n.map(a=>_f.get(H(a))).find(a=>typeof a=="string"),s=t.disabledReason===null&&i;return{action:e.action,invocable:s,available:s,requires_extension:!0,provider:"extension",disabled_reason:s?null:t.disabledReason??(r?`optional_package_not_installed:${r}`:"extension_command_not_registered"),command_path:e.command_path,cli_exposed:i,policy_state:{mode:t.policyState.mode,trust_mode:t.policyState.trust_mode,default_sandbox_profile:t.policyState.default_sandbox_profile}}}function wf(e){let t=ni.get(e)??Ou,n=t_(e).find(i=>i.flag==="--output-format"&&i.aliases?.includes("--format"));return n?[...t,n]:t}function K0(e){return Ut.has(H(e))?!1:ni.has(e)}function z0(e){return mf.has(e)?"list":e==="cal"?"calendar":e==="ctx"?"context":e==="update-many"?"update_many":e}function of(e){let t=e.trim();return t?t.startsWith("--")?t:t.startsWith("-")?null:`--${t}`:null}function W0(e){let t=e.trim();return!t||t.startsWith("--")?null:t.startsWith("-")?t:null}function B0(e){let t=new Map;for(let i of e.definitions){let r=of(i.cli_flag);if(!r)continue;let s=i.cli_aliases.map(o=>W0(o)).find(o=>o!==null),a=i.cli_aliases.map(o=>of(o)).filter(o=>o!==null&&o!==r);for(let o of i.commands){let c=t.get(o)??{flags:[],seen:new Set},d=s?{flag:r,short:s}:{flag:r},l=`${d.flag}|${d.short??""}`;c.seen.has(l)||(c.seen.add(l),c.flags.push(d));for(let u of a){let p=`${u}|`;c.seen.has(p)||(c.seen.add(p),c.flags.push({flag:u}))}t.set(o,c)}}let n=new Map;for(let[i,r]of t.entries())n.set(i,Ha(r.flags));return n}function cf(e,t){let n=[],i=new Set;for(let r of[...e,...t]){let s=`${r.flag}|${r.short??""}`;i.has(s)||(i.add(s),n.push(r))}return Ha(n)}function H0(e,t,n,i,r){let s=new Map(t);for(let{alias:a,canonical:o}of Je){let c=t.get(o)??t.get(a);c&&(s.set(a,c),s.set(o,c))}return e.map(a=>{let o=K0(a),c=o?wf(a):[],d=n.get(z0(a))??[],l=s.get(a),u=cf(c,d),p=cf(u,l?.flags??[]),g=c.length>0&&(l?.flags.length??0)>0?"mixed":o?"core":"extension";return{command:a,flags:p,...i?{canonical_command:kf(a),visibility:bf(a,r),positionals:Cu(a)?.slots??[],flag_invocations:yp(a,p)}:{},provider:g,extension_sources:l?.sources}}).sort((a,o)=>a.command.localeCompare(o.command))}function V0(e,t=Ot){let n=new Set(e),i=new Map;for(let r of gf){let s=r.aliases.filter(a=>n.has(a));i.set(r.canonical,{canonical:r.canonical,aliases:s,contracts:[]})}for(let r of t){if(!n.has(r.canonical)||r.registration==="commander"&&!n.has(r.alias))continue;let s=i.get(r.canonical)??{canonical:r.canonical,aliases:[],contracts:[]};s.aliases.includes(r.alias)||s.aliases.push(r.alias),s.contracts.push(r),i.set(r.canonical,s)}return[...i.values()].map(({contracts:r,...s})=>r.length===0?s:{...s,contracts:r}).sort((r,s)=>r.canonical.localeCompare(s.canonical))}function Y0(){return{create_string_options:$_,create_repeatable_options:U_,update_string_options:Ar,update_repeatable_options:G_,list_string_options:n_,search_string_options:i_,calendar_string_options:r_,context_string_options:s_,activity_string_options:a_}}function df(e,t){let n=new Set(["title","type"]);if(t==="strict"){for(let o of e.required_create_fields)n.add(o);for(let o of e.required_create_repeatables)n.add(o)}let i=tn(e,"create",n),r=[...new Set(i.required)].sort((o,c)=>o.localeCompare(c)),s=[...new Set(r.map(o=>Te("create",o)))].sort((o,c)=>o.localeCompare(c)),a=[...new Set(e.options.filter(o=>o.required===!0).map(o=>o.key))].sort((o,c)=>o.localeCompare(c));return{required_option_keys:r,required_flags:s,required_type_options:a,policy_errors:[...new Set(i.errors)].sort((o,c)=>o.localeCompare(c))}}function J0(e){let t={},n={};for(let i of[...e.types].sort((r,s)=>r.localeCompare(s))){let r=e.by_type[i];t[i]=df(r,"strict"),n[i]=df(r,"progressive")}return{default_create_mode:"strict",by_create_mode:{strict:{by_type:t},progressive:{by_type:n}}}}function X0(e,t){let n=ii(e);if(n.length===0)return e;let i=!1,r=n.map(s=>{let a=s.properties;if(typeof a!="object"||a===null)return s;let o=a.action;return typeof o!="object"||o===null||o.const!=="create"?s:(i=!0,{...s,"x-create-required-options":t})});return i?{...e,oneOf:r}:e}function Q0(e){let t=Fr(e.action)!==void 0||Fr(e.command)!==void 0,n=e.schemaOnly===!0||e.flagsOnly===!0||e.availabilityOnly===!0,i=e.summary===!0||e.full!==!0&&e.runtimeOnly!==!0&&!t&&!n,r=e.schemaOnly===!0,s=e.flagsOnly===!0,a=e.availabilityOnly===!0,o=e.runtimeOnly===!0,c=e.full===!0,d=Fr(e.action),l=Fr(e.command),u=!i&&!c&&!r&&!s&&!a&&!d&&!l;return{selectedAction:d,selectedCommand:l,summary:i,schemaOnly:r,flagsOnly:s,availabilityOnly:a,runtimeOnly:o,fullOutput:c,omitUnfilteredSchema:u,omitUnfilteredCommandFlags:u,omitUnfilteredCommanderAliases:u||l!==void 0&&!c}}function Z0(e){if([e.summary,e.schemaOnly,e.flagsOnly,e.availabilityOnly].filter(t=>t).length>1)throw new _("Choose only one projection flag: --summary, --schema-only, --flags-only, or --availability-only.",m.USAGE)}async function eE(e,t=I){try{return await t(e)}catch{return structuredClone(Lt)}}async function tE(e,t,n){let i=await eE(t),r=await j0(e),s=F(i,r.registrations??P()),a=nn(i.schema),o=L0(r);return{settings:i,runtimeProbe:r,typeRegistry:s,statusRegistry:K(i.schema),runtimeFieldRegistry:a,runtimeFieldFlagMap:B0(a),createRequiredOptionContracts:J0(s),extensionContracts:o,mergedExtensionContracts:U0(o.filter(c=>Ur(n,c.command,o))),extensionFlagMap:vf(r.flagRegistrations)}}function lf(e){return e.availabilityOnly&&(e.selectedAction!==void 0&&$r.has(e.selectedAction)||e.selectedCommand!==void 0&&Ut.has(H(e.selectedCommand)))}function nE(e,t){let n=G0(t,{includePackageOwnedActions:lf(e)});if(e.selectedAction===void 0&&e.selectedCommand===void 0){let i=new Set(Fl);return n.filter(r=>!i.has(r.action)&&(e.fullOutput||(t.find(s=>s.action===r.action)?.tier??go(r.action))!=="internal"))}return lf(e)&&e.selectedCommand!==void 0&&Ut.has(H(e.selectedCommand))&&!n.some(i=>i.command_path===e.selectedCommand)&&n.push({action:A0(H(e.selectedCommand)),provider:"extension",requires_extension:!0,command_path:e.selectedCommand}),n}function iE(e,t){let n=new Set(t.map(i=>i.action));if(e.selectedAction&&!n.has(e.selectedAction))throw new _(`Unknown action: "${e.selectedAction}".`,m.USAGE)}function rE(e,t){return[...new Set([...Qe.filter(n=>!Ut.has(H(n))),...[...ni.keys()].filter(n=>!Ut.has(H(n))),...e.flatMap(n=>n.command_path?mt(n.command_path).filter(i=>n.provider==="extension"||!Ut.has(H(i))||t.some(r=>r.action===n.action)):[]),...t.flatMap(n=>n.command.split("|").flatMap(i=>{let r=Je.find(s=>s.alias===i||s.canonical===i);return r===void 0?[i]:[r.alias,r.canonical]}))])].map(n=>be(n)).filter(n=>n.length>0).sort((n,i)=>n.localeCompare(i))}function sE(e,t){let n=t.slice(0,k0),i=t.length-n.length,r=i>0?`${n.join(", ")}, and ${i} more`:n.join(", "),s=t.slice(0,E0),a=t.slice(0,5).map(c=>`pm contracts --command "${c}" --flags-only --json`),o=t[0];return new _(`Command "${e}" is a command namespace. Choose a concrete child command: ${r}.`,m.USAGE,{code:"command_namespace",required:"Use a concrete child command path listed under this namespace.",why:"Command groups expose help at the namespace root, but command flag contracts belong to executable child commands.",examples:a,nextSteps:[`Retry with a child command, for example: ${a[0]}`],recovery:{suggested_retry:`pm contracts --command "${o}" --flags-only --json`,fallback_candidates:s.map(c=>({source:"command_namespace",command:`pm contracts --command "${c}" --flags-only --json`,reason:`Child command under ${e}`}))}})}function aE(e,t){return new _(`Unknown command: "${e}". Command "${e}" is provided by the optional "${t}" package. Run "pm package install ${t} --project" and retry.`,m.USAGE,{code:"unknown_command",required:`Install the optional "${t}" package, or choose a command from pm contracts --flags-only --json.`,why:"Command contracts include core commands plus commands registered by active packages and extensions.",examples:[`pm package install ${t} --project`,`pm contracts --command ${e} --flags-only --json`],nextSteps:[`Install the optional package first: pm package install ${t} --project`],recovery:{suggested_retry:`pm package install ${t} --project`}})}function oE(e){return new _(`Unknown command: "${e}".`,m.USAGE,{code:"unknown_command",required:"Use a command path listed by pm contracts --flags-only --json.",why:"Command contracts are generated from the active core, package, and extension command registry.",examples:["pm contracts --flags-only --json","pm --help"],nextSteps:["Verify spelling and active packages/extensions, then rerun with a known command path."],recovery:{suggested_retry:"pm contracts --flags-only --json"}})}function cE(e,t){if(!e.selectedCommand||new Set(t).has(e.selectedCommand))return;let n=t.filter(r=>r.startsWith(`${e.selectedCommand} `));if(n.length>0)throw sE(e.selectedCommand,n);let i=_f.get(H(e.selectedCommand));throw i?aE(e.selectedCommand,i):oE(e.selectedCommand)}function dE(e,t){let n=nE(e,t.mergedExtensionContracts);iE(e,n);let i=rE(n,t.mergedExtensionContracts);cE(e,i);let r=e.selectedCommand?ff.get(H(e.selectedCommand)):void 0,s=e.selectedCommand?n.filter(d=>r?d.action===r:I0(d,e.selectedCommand)):n;if(e.selectedCommand&&e.selectedAction&&!s.some(d=>d.action===e.selectedAction))throw new _(`Action "${e.selectedAction}" is not mapped to command "${e.selectedCommand}" in contracts output.`,m.USAGE);let a=e.selectedAction?s.filter(d=>d.action===e.selectedAction):s,o=[...new Map(a.map(d=>q0(d,t.runtimeProbe)).map(d=>[r?d.action:`${d.action}|${d.command_path??""}`,d])).values()],c=e.runtimeOnly&&!e.selectedAction&&!e.availabilityOnly?o.filter(d=>d.invocable):o;return{actionDescriptors:n,commandCatalog:i,commandScopedDescriptors:s,scopedActionDescriptors:a,selectedPackageOwnedAction:r,actionAvailability:c,actions:[...new Set(c.map(d=>d.action))]}}function lE(e){return new Set(ii(e).map(t=>{let n=t.properties;if(typeof n!="object"||n===null)return null;let i=n.action;if(typeof i!="object"||i===null)return null;let r=i.const;return typeof r=="string"?r:null}).filter(t=>t!==null))}function uE(e){let t=P_,n=ii(t),i=lE(t),r=e.filter(s=>!i.has(s.action)).map(s=>F0(s));return r.length>0?{...t,oneOf:[...n,...r]}:t}function uf(e,t,n){let i=new Set(t.actionDescriptors.map(s=>s.action)),r=e.selectedAction?x0(n,e.selectedAction):e.selectedCommand?Ao(n,new Set(t.scopedActionDescriptors.map(s=>s.action))):Ao(n,i);return e.runtimeOnly&&!e.selectedAction?Ao(r,new Set(t.actions)):r}function mE(e,t,n){let i=uE(t.mergedExtensionContracts),r=!e.flagsOnly&&!e.availabilityOnly?X0(uf(e,n,i),t.createRequiredOptionContracts):uf(e,n,i);return{mergedSchema:i,filteredSchema:r}}function _E(e,t){return e.selectedCommand!==void 0?[e.selectedCommand]:e.selectedAction?C0(t.scopedActionDescriptors,t.commandCatalog):t.commandCatalog}function bf(e,t){return t.find(n=>H(n.command)===H(e))?.tier??go(e)}function Ur(e,t,n){return e.fullOutput||e.selectedCommand!==void 0||e.selectedAction!==void 0||bf(t,n)!=="internal"}function pE(e,t,n){if(e.selectedCommand!==void 0||e.selectedAction!==void 0)return t;let i=new Set(Ot.filter(r=>r.hidden&&(r.lifecycle==="deprecated"||!e.fullOutput&&!e.availabilityOnly)).map(r=>r.alias));if(e.summary&&!e.fullOutput)for(let r of Co.keys())i.add(r);return t.filter(r=>!i.has(r)&&Ur(e,r,n))}function kf(e){let t=Je.find(i=>i.alias===e||i.canonical===e);if(t)return t.canonical;let n=e.split(" ")[0];return n.startsWith("list-")?"list":Co.get(n)??n}var fE=new Map([["activate","Activate"],["adopt","Adopt"],["adopt-all","Adopt all"],["catalog","Catalog"],["complete","Complete"],["create","Create"],["deactivate","Deactivate"],["delete","Delete"],["describe","Describe"],["doctor","Diagnose"],["explore","Explore"],["init","Initialize"],["inspect","Inspect"],["install","Install"],["list","List"],["manage","Manage"],["migrate","Migrate"],["mutate","Mutate"],["reload","Reload"],["restore","Restore"],["run","Run"],["snapshot","Manage snapshots for"],["uninstall","Uninstall"],["upgrade","Upgrade"]]),gE=new Map([["extension adopt-all","extensions"],["package adopt-all","packages"],["workspace snapshot list","workspace snapshots"]]);function hE(e,t){let n=nf.get(H(e))??(e.includes(" ")?void 0:nf.get(kf(e)));if(n!==void 0)return{intent:n,intent_source:"command"};let i=t.find(d=>mt(d.command).some(l=>H(l)===H(e)));if(i?.intent!==null&&i?.intent!==void 0)return{intent:i.intent,intent_source:"command"};if(i?.description!==null&&i?.description!==void 0)return{intent:i.description,intent_source:"description"};let r=e.split(" "),s=r.at(-1),a=r.slice(0,-1).join(" "),o=fE.get(s),c=gE.get(e)??a;return{intent:o===void 0||a.length===0?`Run ${e}.`:`${o} ${c}.`,intent_source:"generated"}}function yE(e,t=[],n={}){let i=n.includeFormatBudgets??!0,r=n.includeIntentProvenance??!0;return[...new Set(e.map(be))].filter(s=>s.length>0).sort((s,a)=>s.localeCompare(a)).map(s=>{let a=ja(s,{generateFallback:!0}),o=s.split(" ")[0],c=Co.get(o)??(o.startsWith("list-")?"list":o.startsWith("history-")?"history":o),d=new Set([...wf(s).map(p=>p.flag),...t.filter(p=>mt(p.command).some(g=>H(g)===H(s))).flatMap(p=>p.flags.map(g=>g.flag))]),l=(tf.get(H(s))??tf.get(c)??b0).filter(p=>d.has(p)),u=hE(s,t);return{command:s,intent:u.intent,...r||u.intent_source!=="command"?{intent_source:u.intent_source}:{},...l.length>0?{flags:l}:{},default_max_estimated_tokens:a.default_max_estimated_tokens,...i?{default_max_estimated_tokens_by_format:{...a.default_max_estimated_tokens_by_format}}:{}}})}function vE(e){return e.map(t=>({budget:ja(t,{generateFallback:!0}),envelope:Rp(t)}))}function wE(e){let t=new Map;for(let n of e){let i=Np(n),r=i===void 0?[m.SUCCESS,m.GENERIC_FAILURE,m.USAGE,m.NOT_FOUND,m.CONFLICT,m.DEPENDENCY_FAILED]:i.exit_codes,s=r.join(","),a=t.get(s)??{commands:[],exit_codes:r};a.commands.push(n),t.set(s,a)}return[...t.values()]}function bE(e,t,n){if(e.selectedCommand)return t.extensionContracts.filter(i=>mt(i.command).some(r=>H(r)===H(e.selectedCommand)));if(e.selectedAction){let i=new Set(n);return t.extensionContracts.filter(r=>mt(r.command).some(s=>i.has(s)))}return t.extensionContracts.filter(i=>Ur(e,i.command,t.extensionContracts))}function kE(e,t,n,i){return{schema_version:typeof t.mergedSchema["x-schema-version"]=="string"?t.mergedSchema["x-schema-version"]:null,schema_id:typeof t.mergedSchema.$id=="string"?t.mergedSchema.$id:null,selected:{action:e.selectedAction??null,command:e.selectedCommand??null,summary:e.summary,schema_only:e.schemaOnly,flags_only:e.flagsOnly,availability_only:e.availabilityOnly,runtime_only:e.runtimeOnly,command_scoped:e.selectedCommand!==void 0},commands:e.summary?[]:i,...!e.summary&&!e.flagsOnly?{actions:n.actions,action_availability:n.actionAvailability}:{}}}function EE(e,t,n){(n.selectedCommand==="history"||n.fullOutput)&&!n.flagsOnly&&!n.schemaOnly&&!n.availabilityOnly&&(e.history_operations=iu);let i=n.selectedCommand;e.runtime_schema={statuses:t.statusRegistry.definitions.map(r=>r.id),open_status:t.statusRegistry.open_status,close_status:t.statusRegistry.close_status,canceled_status:t.statusRegistry.canceled_status,types:[...t.typeRegistry.types],fields_by_command:Object.fromEntries([...t.runtimeFieldRegistry.command_to_fields.entries()].filter(([r])=>i===void 0||r===i).map(([r,s])=>[r,[...new Set(s.map(a=>`--${a.cli_flag}`))].sort((a,o)=>a.localeCompare(o))]))},!(i!==void 0&&!n.fullOutput)&&(e.extension_contracts={capabilities:[...xl],services:[...Rl],policy_modes:[...Ol],policy_mode_scope:"extensions.policy.mode",policy_surfaces:[...Nl],trust_modes:[...Ll],trust_mode_scope:"extensions.policy.trust_mode",sandbox_profiles:[...Dl],manifest_versions:[1,2],compatibility:{current:"v2",previous:["v1"],breaking_strategy:"versioned_breaking"}},e.governance_contracts={ownership_enforcement_modes:[...ul],create_modes:[...ml],close_validation_modes:[..._l],workflow_enforcement_modes:[...pl]},e.relationship_kind_contracts=[...Xd,...(t.runtimeProbe.registrations?.relationship_kinds??[]).flatMap(r=>r.definitions)].sort((r,s)=>r.kind.localeCompare(s.kind)).map(r=>({canonical:r.kind,aliases:[...r.aliases??[]],...r.inverse===void 0?{}:{inverse:r.inverse},ordering:r.ordering,hierarchy:r.hierarchy})))}function SE(e,t,n,i){if(!(t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredSchema){e.schema=n.filteredSchema,e.extension_commands=i;return}e.schema_omitted_reason="unfiltered_default_brief",e.extension_commands=i}}function TE(e,t,n,i,r){if(!(t.schemaOnly||t.availabilityOnly)){if(t.omitUnfilteredCommandFlags)e.command_flags_omitted_reason="unfiltered_default_brief";else{e.command_flags=H0(i,n.extensionFlagMap,n.runtimeFieldFlagMap,t.selectedCommand!==void 0,n.extensionContracts);let s=new Set(i);e.list_projections=Object.entries(X_).filter(([a])=>s.has(a)).map(([a,o])=>({command:a,default:o,brief_fields:[...J_],compact_fields:[...Y_]}))}e.command_aliases=t.fullOutput?r:r.map(({canonical:s,aliases:a})=>({canonical:s,aliases:a})),t.fullOutput||(e.command_alias_contracts_omitted_reason="compact_projection; restore with --full")}}function AE(e,t){if(!(t.schemaOnly||t.flagsOnly||t.availabilityOnly)){if(!t.omitUnfilteredCommanderAliases){e.commander_aliases=Y0();return}e.commander_aliases_omitted_reason=t.selectedCommand?"command_scoped":"unfiltered_default_brief"}}function IE(e,t,n,i){e.command_summaries=yE(t,n,{includeFormatBudgets:i.includeFormatBudgets,includeIntentProvenance:i.includeIntentProvenance}),e.output_policy={token_estimate:"ceil(utf8_bytes / 4)",degradation_ladder:[...Vl],allows_unbounded_opt_out:!0},e.output_projection_contracts={global_ladder_field:"output_policy.degradation_ladder",global_ladder_scope:"union_not_per_command",discovery:"pm contracts --command <command> --summary",...i.includeProjectionModeMatrix?{commands:[...new Set(t.map(be))].filter(r=>Xl(r)!==void 0).sort((r,s)=>r.localeCompare(s)).map(r=>({command:r,modes:[...Ql(r).keys()]}))}:{}},e.grammar_contracts={nouns:Pt.nouns,shared_verbs:Pt.shared_verbs,scope_before_verb:Pt.scope_before_verb,visible_top_level_ceiling:Pt.visible_top_level_ceiling,ceiling_raise_requires_pm_item:Pt.ceiling_raise_requires_pm_item,positional_shape_budget:Pt.positional_shape_budget,positional_shape_count:new Set(Ba.map(({slots:r})=>Ru(r))).size,positional_action_count:Wa.length,positional_action_parents:[...new Set(Wa.map(({parent:r})=>r))].sort((r,s)=>r.localeCompare(s)),...i.includePositionalSignatures?{positional_signatures:Ba}:{}}}async function v$(e,t){let n=Q0(e);Z0(n);let i=x(process.cwd(),t.path),r=await tE(t,i,n),s=dE(n,r),a=mE(n,r,s),o=_E(n,s),c=pE(n,o,r.extensionContracts),d=kE(n,a,s,c),l=bE(n,r,c),u=n.fullOutput||n.selectedCommand!==void 0;if((n.summary||n.fullOutput)&&IE(d,c,l,{includeFormatBudgets:u,includeIntentProvenance:u,includePositionalSignatures:u,includeProjectionModeMatrix:u}),n.summary)return d;let p=V0(s.commandCatalog.filter(g=>Ur(n,g,r.extensionContracts)));return n.flagsOnly&&!n.fullOutput||EE(d,r,n),SE(d,n,a,l),TE(d,n,r,c,p),AE(d,n),(n.selectedCommand==="assurance"||n.fullOutput)&&(d.assurance_contracts={measurement_source_kinds:[...Qn],gate_triggers:[...lt]}),n.fullOutput&&d.grammar_contracts&&(d.grammar_contracts.destinations=xu.map(g=>({...g,reason:g.reason??""}))),n.fullOutput&&!n.schemaOnly&&!n.flagsOnly&&!n.availabilityOnly&&(d.mcp_tools=ef(),d.context_intents=tu(),d.read_output_dimensions=Jl,d.error_codes=Cp,d.command_output_contracts=vE(c),d.diagnostic_output_contracts=Yl,d.command_exit_contracts={vocabulary:ho,command_sets:wE(c)}),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]="0f604cc2-c8cd-5c15-8fec-2243f64ef7d2")}catch{}})();var CE=Symbol("pm.mcp-mutation-transport"),xE=new Set(["activity","aggregate","context","contracts","deps","files-discover","files-lookup","get","graph","health","history","history-attest","list","next","search","stats","telemetry","validate"]);function Gr(e){return CE in e}function qr(e,t){return Gr(e)?l_(t):Ze(e,t)}function Oo(e,t,n=[]){let i=Ze(e,{...e,...t});for(let r of n)Reflect.deleteProperty(i,r);return i}function L(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n:void 0}function re(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 C$(e,t){let n=e[t];return typeof n=="string"?n:typeof n=="number"&&Number.isFinite(n)?String(n):void 0}function yn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Lo(e,t){if(typeof e=="number"){if(!Number.isInteger(e))throw new _(`${t} must be a finite integer.`,m.USAGE);return e}if(typeof e=="string"&&e.trim().length>0){let n=Number(e);if(!Number.isInteger(n))throw new _(`${t} must be a finite integer.`,m.USAGE);return n}}function x$(e,t){return typeof e.limit=="number"&&Number.isFinite(e.limit)?e.limit:typeof t.limit=="number"&&Number.isFinite(t.limit)?t.limit:L(e,"limit")??L(t,"limit")}function R$(e){let t=L(e,"outputFormat");return{json:!0,quiet:!0,author:L(e,"author"),path:L(e,"path"),noExtensions:e.noExtensions===!0||e.no_extensions===!0,noPager:!0,outputInclude:L(e,"outputInclude"),outputLimit:re(e,"outputLimit"),outputBudget:re(e,"outputBudget"),outputSession:L(e,"outputSession"),outputCursor:L(e,"outputCursor"),outputFormat:t==="json"||t==="toon"?t:void 0}}var RE=new Set(["tags","blockedBy","blocked_by","skills","fields"]),Sf=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"]),OE=new Set([...Sf].filter(e=>e!=="file")),LE=new Set(["files","files-discover","docs","test","test-all"]),Tf=new Set(["comments","notes","learnings"]);function DE(e,t){if(!(!Tf.has(e)||!Object.prototype.hasOwnProperty.call(t,"file")))throw new _(`MCP ${e} does not accept options.file. Pass annotation text in options.add instead.`,m.USAGE,{code:"mcp_annotation_file_unavailable",required:"Pass annotation text as JSON data; MCP annotation actions cannot read server-local files."})}var NE=new Set(["claim","release","start-task","pause-task","close-task"]),ME={"history-attest":["verify","output","hashAlgorithm"],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","releaseAssignment"],claim:["start","next","ifAvailable"],release:["pause","handoff"],comments:["ifAbsent"],notes:["ifAbsent"],learnings:["ifAbsent"],extension:["dryRun","offline"],package:["dryRun","offline"],install:["dryRun"],upgrade:["scope","dryRun","cliOnly","packagesOnly","repair","tag","packageName"],append:["body"]},PE=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor"];function Af(e,t=""){let n={},i=LE.has(t),r=t==="files"||t==="files-discover"||t==="docs",s=Tf.has(t)?OE:Sf;for(let[a,o]of Object.entries(e)){if(Array.isArray(o)&&RE.has(a)){n[a]=o.join(",");continue}if(a==="note"&&r){n[a]=o;continue}if(typeof o=="string"&&s.has(a)){n[a]=[o];continue}if(typeof o=="string"&&i&&(a==="add"||a==="remove")){n[a]=[o];continue}n[a]=o}return Object.assign(n,Object.fromEntries(Object.getOwnPropertySymbols(e).map(a=>[a,Reflect.get(e,a)]))),n}function FE(e,t,n){let i=L(e,"author");return i!==void 0?i:n!==void 0&&NE.has(n)?L(e,"assignee")??L(t,"assignee"):void 0}function $E(e,t){return t!==void 0&&e.author===void 0?{...e,author:t}:e}function O$(e,t){let n=yn(e.options)?e.options:void 0,i=dl(e.options),r={},s=c=>{i[c]!==void 0||e[c]===void 0||(r[c]=e[c])};for(let c of ME[t??""]??[])s(c);for(let c of PE)s(c);t!==void 0&&Gr(e)&&DE(t,i);let a=Af({...r,...i},t);if(t==="history-attest"&&Gr(e)&&(a.output!==void 0||typeof a.verify=="string"))throw new _("MCP history attest does not accept server-local proof paths. Export the returned JSON bundle and pass that JSON object as verify.",m.USAGE);let o=Gr(e)?e:n??e;return qr(o,$E(a,FE(e,a,t)))}function L$(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 D$(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 UE(e){let t=[],n=!0;for(let i of e.trim().toLowerCase()){if(i>="a"&&i<="z"||i>="0"&&i<="9"){t.push(i),n=!1;continue}n||(t.push("-"),n=!0)}return t.at(-1)==="-"&&t.pop(),t.join("")}function N$(e){return!xE.has(UE(e))}function M$(e){return e.trim().toLowerCase().split(/\s+/).filter(Boolean).join(" ")}function Do(e){return Array.isArray(e)?e.map(t=>String(t)).filter(t=>t.length>0):[]}function P$(e,t){let n=new Set(["action","args","author","cwd","fullChangedFields","id","options","path","query","reason","target"]),i={};for(let[s,a]of Object.entries(e))n.has(s)||(i[s]=a);let r={...i,...t};return delete r.args,r}function F$(e,t){let n=qr(t??{},{...t});return{changedFields:e.fullChangedFields===!0?"full":"compact",idOnly:e.idOnly===!0,runnerOptions:n}}function Ro(e){return{type:re(e,"filterType"),tag:re(e,"filterTag"),priority:re(e,"filterPriority"),deadlineBefore:re(e,"filterDeadlineBefore"),deadlineAfter:re(e,"filterDeadlineAfter"),updatedAfter:re(e,"filterUpdatedAfter"),updatedBefore:re(e,"filterUpdatedBefore"),createdAfter:re(e,"filterCreatedAfter"),createdBefore:re(e,"filterCreatedBefore"),ids:Za(e.ids),assignee:re(e,"filterAssignee"),assigneeFilter:re(e,"filterAssigneeFilter")??re(e,"filterAssignee_filter"),parent:re(e,"filterParent"),sprint:re(e,"filterSprint"),release:re(e,"filterRelease"),limit:re(e,"limit"),offset:re(e,"offset")}}function xo(e){if(typeof e=="string"&&e.trim().length>0)return e;if(Array.isArray(e))return Do(e)}function jr(e){if(typeof e=="number"&&Number.isFinite(e)||typeof e=="string"&&e.trim().length>0)return e}function $$(e){let t=xo(e.kind),n=xo(e.exemptIsolate),i=xo(e.exemptIsolateType);return{...t===void 0?{}:{kind:t},maxDepth:jr(e.maxDepth),limit:jr(e.limit),after:L(e,"after"),direction:L(e,"direction"),maxPaths:jr(e.maxPaths),sample:jr(e.sample),...n===void 0?{}:{exemptIsolate:n},...i===void 0?{}:{exemptIsolateType:i},saveBaseline:e.saveBaseline===!0,rebuild:e.rebuild===!0,clear:e.clear===!0,summary:e.summary===!0,...e.full===!0?{full:!0}:{}}}function If(e){let t=op(e);return e.ids!==void 0&&(t.ids=Za(e.ids)),t}function U$(e){return{status:L(e,"filterStatus"),list:yn(e.list)?If(e.list):Ro(e),reason:L(e,"reason"),resolution:L(e,"resolution"),expectedResult:L(e,"expectedResult")??L(e,"expected_result")??L(e,"expected"),actualResult:L(e,"actualResult")??L(e,"actual_result")??L(e,"actual"),validateClose:L(e,"validateClose")??L(e,"validate_close"),author:L(e,"author"),message:L(e,"message"),force:e.force===!0?!0:void 0,dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:L(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}var jE=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 Ef(e){let t={};for(let[n,i]of Object.entries(e))jE.has(n)||(t[n]=i);return Cf(t)}function Cf(e){let t=Af(e,"update-many");for(let n of Ar)for(let i of n.keys){let r=t[i];typeof r=="number"&&Number.isFinite(r)&&(t[i]=String(r))}return ap(t)}function j$(e){if(yn(e.list)||yn(e.update)){let t=yn(e.update)?e.update:Ef(e),n=qr(e,Cf(t));return{status:re(e,"filterStatus"),list:yn(e.list)?If(e.list):Ro(e),update:u_(t,n),dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:L(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}return{status:re(e,"filterStatus"),list:Ro(e),update:qr(e,Ef(e)),dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:L(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}import{readFile as GE}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="35773218-9c35-51d9-a19b-e9094bd23b66")}catch{}})();function n1(e){let t={...e,...e.full===!0?{fullHistory:!0}:{}};return delete t.full,Ze(e,t)}function xf(e,t){if(typeof e=="object"&&e!==null&&"format"in e&&e.format==="json")throw new _(`Structured context events are append-only and cannot be ${t}.`,m.USAGE,{code:"structured_event_immutable"})}function qE(e,t){return t===void 0?e:t===0?[]:e.slice(Math.max(0,e.length-t))}function jt(e,t){let n=e[t];return Array.isArray(n)?n:[]}function i1(e,t={}){let n=e.trim();if(!n)return"";let i=/^(?:[-*+]\s*)?text\s*[:=]/i.exec(n);if(t.stripPlainTextPrefix===!0&&i&&!n.startsWith("```"))return n.slice(i[0].length).trim()||n;if(!(/^(?:[-*+]\s*)?text\s*[:=]/im.test(n)||n.startsWith("```")))return n;try{let r=Z(n,"--add");return Object.keys(r).map(s=>s.trim().toLowerCase()).some(s=>s!=="text")?n:r.text?.trim()||n}catch{return n}}function KE(e){return typeof e=="object"&&e!==null&&"code"in e}function Rf(e,t){if(!Ft(e))throw new _(`${t} cannot read process stdin through the MCP JSON-RPC transport. Pass annotation text in options.add instead.`,m.USAGE,{code:"mcp_stdin_unavailable",required:"Pass annotation text as JSON data; the MCP protocol already owns process stdin."})}async function zE(e,t){if(+(e.add!==void 0)+ +(e.stdin===!0)+ +(typeof e.file=="string")>1)throw new _(`Specify ${t} text using only one input source: --add, --stdin, or --file`,m.USAGE);let n=cn(),i=Ft(e);if(e.add!==void 0)return{value:await n.resolveValue(e.add,"--add",i)??"",rawValue:e.add,emptyFlag:"--add"};if(e.stdin===!0)return Rf(e,"--stdin"),{value:await n.resolveValue("-","--stdin")??"",emptyFlag:"--stdin"};if(typeof e.file!="string")return;let r=e.file.trim();if(!r)throw new _("--file path cannot be empty",m.USAGE);if(r==="-")return Rf(e,"--file -"),{value:await n.resolveValue("-","--file")??"",emptyFlag:"--file"};try{return{value:await GE(r,"utf8"),emptyFlag:"--file"}}catch(s){if(KE(s)&&Ki(s))throw new _(`--file path not found: ${r}. Use --file - to read stdin.`,m.USAGE);let a=s instanceof Error?s.message:String(s);throw new _(`Failed to read --file path "${r}": ${a}. Use --file - to read stdin.`,m.USAGE)}}async function r1(e,t){if(e.edit!==void 0&&e.delete!==void 0)throw new _("Specify only one of --edit or --delete",m.USAGE);if(e.delete!==void 0){if(e.add!==void 0||e.stdin===!0||typeof e.file=="string")throw new _("--delete cannot be combined with replacement text",m.USAGE);if(!Number.isInteger(e.delete)||e.delete<1)throw new _("--delete must be a positive integer",m.USAGE);return{mode:"delete",index:e.delete}}if(e.edit!==void 0&&(!Number.isInteger(e.edit)||e.edit<1))throw new _("--edit must be a positive integer",m.USAGE);let n=await zE(e,t);if(e.edit!==void 0){if(!n)throw new _("--edit requires replacement text from --add, --stdin, or --file",m.USAGE);return{mode:"edit",index:e.edit,...n}}return n?{mode:"add",...n}:{mode:"list"}}function ri(e,t){throw e instanceof _&&e.exitCode===m.CONFLICT&&e.message.includes("is assigned to")&&e.message.includes("Use --force to override")?new _(e.message,e.exitCode,{code:"ownership_conflict",required:t.required,examples:t.examples,nextSteps:t.nextSteps}):e}function Lf(e){return e==="comments"?"--stdin":"--add -"}function WE(e,t){if((t.input.emptyFlag??"--add")!=="--add")return;let n=e.trim();if(!/^-{1,2}[A-Za-z][\w-]*(?:=.*)?$/.test(n))return;let i=Lf(t.collectionKey),r=t.input.mode==="edit"?`pm ${t.collectionKey} <id> --edit <index>`:`pm ${t.collectionKey} <id>`;throw new _(`--add value "${n}" looks like an option, not annotation text. Use ${i} to read stdin, or use text=${n} for literal dash-leading text.`,m.USAGE,{code:"annotation_flag_like_value",required:`Use ${i} for stdin input, pass plain text, or use text=${n} when the text really starts with "-".`,examples:[`${r} ${i}`,`${r} --add text=${n}`]})}function BE(e,t){if(t.ifAbsent===!0&&!["add","stdin","file"].includes(e.input.mode))throw new _(`--if-absent requires a ${e.collectionKey.replace(/s$/,"")} append`,m.USAGE,{code:"annotation_if_absent_without_append",required:"Combine --if-absent with one append text source; omit it for list, edit, and delete operations."});if(e.input.mode!=="list"||t.message===void 0)return;let n=e.collectionKey.replace(/s$/,"");throw new _(`--message labels a ${n} mutation but does not provide ${n} text. Pass text positionally or with --add, --stdin, or --file.`,m.USAGE,{code:"annotation_message_without_text",required:`Provide ${n} text through a content source; --message only annotates the history entry of a mutation.`,examples:[`pm ${e.collectionKey} <id> --add "text" --message "why"`,`pm ${e.collectionKey} <id> ${Lf(e.collectionKey)}`]})}function HE(e,t,n,i,r,s){let a=jt(e.metadata,t),o=r?a.findIndex(c=>c.author===n&&c.text===i):-1;return o>=0?{changedFields:[],entryIndex:o+1}:(a.push(s({created_at:O(),author:n,text:i})),e.metadata[t]=a,{changedFields:[t],entryIndex:a.length})}async function s1(e,t,n,i){BE(i,t);let r=x(process.cwd(),n.path);await $(r);let s=await I(r),a=F(s,P()),o=zn(t.limit);if(i.input.mode==="list"){let f=await Y(r,e,s.id_prefix,s.item_format,a.type_to_folder);if(!f)throw new _(`Item ${e} not found`,m.NOT_FOUND);let h=await he(f,{schema:s.schema}),y=jt(h.document.metadata,i.collectionKey);return Kr(f.id,i.collectionKey,y,o,t.includeMeta===!0)}let c=U(t.author,s.author_default);if(i.input.mode==="delete"){let f=i.deleteOp??i.op,h;try{h=await se({pmRoot:r,settings:s,id:e,op:f,author:c,message:t.message,force:t.force,bypassAssigneeConflict:i.bypassOwnershipConflict,mutate(v){let w=jt(v.metadata,i.collectionKey),k=Of(i.input.index,w.length,i.collectionKey);return xf(w[k],"deleted"),w.splice(k,1),v.metadata[i.collectionKey]=w,{changedFields:[i.collectionKey]}}})}catch(v){ri(v,i.conflictGuidance)}let y=jt(h.item,i.collectionKey);return Kr(h.item.id,i.collectionKey,y,o,t.includeMeta===!0,{action:"delete",entryIndex:i.input.index},t.fullHistory===!0)}let d=i.input.rawValue??i.input.value??"";WE(d,i);let l=i.parseText(i.input.value??"");if(!l.trim())throw new _(`${i.input.emptyFlag??"--add"} text cannot be empty`,m.USAGE);if(i.input.mode==="edit"){let f=i.editOp??i.op,h;try{h=await se({pmRoot:r,settings:s,id:e,op:f,author:c,message:t.message,force:t.force,bypassAssigneeConflict:i.bypassOwnershipConflict,mutate(v){let w=jt(v.metadata,i.collectionKey),k=Of(i.input.index,w.length,i.collectionKey),S=w[k];return xf(S,"edited"),w[k]={...S,text:l,edited_at:O()},v.metadata[i.collectionKey]=w,{changedFields:[i.collectionKey]}}})}catch(v){ri(v,i.conflictGuidance)}let y=jt(h.item,i.collectionKey);return Kr(h.item.id,i.collectionKey,y,o,t.includeMeta===!0,{action:"edit",entryIndex:i.input.index,entry:y[i.input.index-1]},t.fullHistory===!0)}let u,p=0;try{u=await se({pmRoot:r,settings:s,id:e,op:i.op,author:c,message:t.message,force:t.force,bypassAssigneeConflict:i.bypassOwnershipConflict,skipNoop:t.ifAbsent===!0,mutate(f){let h=HE(f,i.collectionKey,c,l,t.ifAbsent===!0,i.createEntry);return p=h.entryIndex,{changedFields:h.changedFields}}})}catch(f){ri(f,i.conflictGuidance)}let g=jt(u.item,i.collectionKey);return Kr(u.item.id,i.collectionKey,g,o,t.includeMeta===!0,{action:"add",entryIndex:p,entry:g[p-1],changedCount:t.ifAbsent===!0?Math.min(u.changedFields.length,1):void 0},t.fullHistory===!0)}function Of(e,t,n){if(e===void 0||!Number.isInteger(e)||e<1||e>t){let i=n.replace(/s$/,""),r=`${i.charAt(0).toUpperCase()}${i.slice(1)}`,s=t===1?`1 ${i}`:`${t} ${n}`;throw new _(`${r} index ${e??"(missing)"} out of range (item has ${s})`,m.USAGE)}return e-1}function VE(e,t,n){return t===void 0?{}:{mutation_receipt:{action:t.action,entry_index:t.entryIndex,changed_count:t.changedCount??1,full_history_included:!n},omission_receipt:{has_omissions:n,omitted_field_group_count:n?1:0,omitted_field_groups:n?[{name:`${e}_history`,restore_with:{selector:"full_history",cli_flag:"--full-history",sdk_option:"fullHistory",mcp_option:"full"}}]:[]}}}function Kr(e,t,n,i,r,s,a=!1){let o=s===void 0||a?qE(n,s!==void 0&&a?void 0:i):s.entry===void 0?[]:[s.entry],c=s!==void 0&&o.length<n.length;return{id:e,[t]:o,count:o.length,...s?.changedCount===void 0?{}:{changed:s.changedCount===1},...[r,s!==void 0].includes(!0)?{total_count:n.length,returned_count:o.length,has_more:c||o.length<n.length,...i!==void 0?{limit:i}:{}}:{},...VE(t,s,c)}}import{createHash as Nf}from"node:crypto";import si from"node:fs/promises";import ai 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]="69bf315a-01aa-56d9-bd56-196d6792dea2")}catch{}})();function Ue(e,t){throw new _(e,m.USAGE,t)}var YE="2026-07-15T06:22:12.276Z",JE=Date.parse(YE),XE=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],Df=e=>typeof e=="string"?e:"",Mf=e=>{let t=e??{},n=Df(t.author).trim().toLowerCase(),i=Number(["","unknown"].includes(n)),r=+(Date.parse(Df(t.ts))>=JE);return XE[i][r]};function Pf(e,t,n=20,i=new Set,r=!1){let s=[],a=[],o={legacy_unknown:0,actionable_unknown:0},c=Math.max(0,n),d=0,l=0,u=0;for(let[p,g]of t.split(/\r?\n/).entries()){let f;try{f=JSON.parse(g)}catch{continue}d+=1;let h=Mf(f);if(h!=="attributed"){if(l+=1,h==="actionable_unknown"&&i.has(`${e}:${p+1}`)){u+=1;continue}o[h]+=1,r&&h==="actionable_unknown"&&a.push({item_id:e,line:p+1}),s.length<c&&s.push({item_id:e,line:p+1})}}return{checked_events:d,unknown_event_count:l,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 f1=(e,t,n=20,i=new Set)=>Pf(e,t,n,i);function Ff(e){let t=new Set;for(let n of e.split(/\r?\n/)){let i;try{i=JSON.parse(n)}catch{continue}let r=(typeof i=="object"&&i!==null&&typeof i.context=="object"&&i.context!==null?i.context:{}).author_acknowledgment;if(!(typeof r!="object"||r===null||!Array.isArray(r.events)))for(let s of r.events)typeof s=="object"&&s!==null&&typeof s.item_id=="string"&&Number.isSafeInteger(s.line)&&t.add(`${s.item_id}:${String(s.line)}`)}return t}var oi=async(e,t=20,n=!1)=>{let i=ai.join(e,"history"),r;try{r=(await si.readdir(i)).filter(v=>v.endsWith(".jsonl")).sort((v,w)=>v.localeCompare(w))}catch{r=[]}let s=new Set,a=[],o=[],c=0,d=0,l=0,u=0,p=0,g=0,f="_workspace.jsonl",h=new Set;if(r.includes(f))try{h=Ff(await si.readFile(ai.join(i,f),"utf8"))}catch{h=new Set}for(let v of r){let w;try{w=await si.readFile(ai.join(i,v),"utf8")}catch{continue}let k=v.slice(0,-6),S=Pf(k,w,t-a.length,h,n);c+=1,d+=S.checked_events,l+=S.unknown_event_count,u+=S.legacy_unknown_event_count,p+=S.actionable_unknown_event_count,g+=S.acknowledged_actionable_event_count,S.unknown_event_count>0&&s.add(k),a.push(...S.samples),n&&o.push(...S.actionable_events)}let y=u+p;return{checked_streams:c,checked_events:d,unknown_event_count:l,legacy_unknown_event_count:u,actionable_unknown_event_count:p,acknowledged_actionable_event_count:g,affected_item_ids:[...s].sort((v,w)=>v.localeCompare(w)),samples:a,samples_truncated:y>a.length,...n?{actionable_events:o}:{}}};function QE(e){return[...new Map(e.map(t=>[`${t.item_id}:${t.line}`,{item_id:t.item_id,line:t.line}])).values()].sort((t,n)=>t.item_id.localeCompare(n.item_id)||t.line-n.line)}async function ZE(e){try{return Ff(await si.readFile(ai.join(e,"history","_workspace.jsonl"),"utf8"))}catch{return new Set}}function eS(e){return(e.item_id===Mt||/^[a-z0-9][a-z0-9-]*$/iu.test(e.item_id))&&Number.isSafeInteger(e.line)&&e.line>=1}function tS(e,t,n){let i=n[e.line-1]??"",r;try{r=JSON.parse(i)}catch{Ue(`Unknown-author acknowledgment target ${e.item_id}:${e.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}return Mf(r)!=="actionable_unknown"&&Ue(`Author acknowledgment target ${e.item_id}:${e.line} is not an actionable unknown-author event.`,{code:"history_author_acknowledge_target_not_actionable"}),{...e,source_event_hash:Nf("sha256").update(i).digest("hex"),disposition:t.has(`${e.item_id}:${e.line}`)?"already_acknowledged":"actionable"}}async function $f(e,t,n){let i=t.events??[],r=+(t.all_actionable===!0)+ +(i.length>0);r===0&&Ue("Specify exactly one selector: events or all_actionable.",{code:"history_author_acknowledge_selector_required"}),r>1&&Ue("Author acknowledgment accepts either explicit events or all_actionable, not both.",{code:"history_author_acknowledge_selector_conflict"}),(!Number.isSafeInteger(n)||n<0)&&Ue("Author acknowledgment coordinate_limit must be a non-negative integer.",{code:"history_author_acknowledge_preview_limit_invalid"});let s=QE(t.all_actionable===!0?(await oi(e,0,!0)).actionable_events:i),a=await ZE(e),o=new Map;for(let p of s)if(eS(p)||Ue(`Unknown-author acknowledgment target ${p.item_id}:${p.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"}),!o.has(p.item_id))try{o.set(p.item_id,(await si.readFile(ai.join(e,"history",`${p.item_id}.jsonl`),"utf8")).split(/\r?\n/u))}catch{Ue(`Unknown-author acknowledgment target ${p.item_id}:${p.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}let c=s.map(p=>tS(p,a,o.get(p.item_id))),d=t.all_actionable===!0?"all_actionable":"events",l=Nf("sha256").update(JSON.stringify({version:1,selection:d,coordinates:c})).digest("hex"),u=c.filter(({disposition:p})=>p==="actionable").length;return{plan:{selection:{kind:d},selected_count:c.length,actionable_count:u,already_acknowledged_count:c.length-u,omitted_count:Math.max(0,c.length-n),coordinates:c.slice(0,n),plan_fingerprint:l},completeCoordinates:c}}async function g1(e,t,n=50){return(await $f(e,t,n)).plan}function nS(e,t){let n=e.length>0;return n&&t&&Ue("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&&Ue("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:iS(e),all_actionable:t}}function iS(e){return e.map(t=>{let n=t.lastIndexOf(":"),i=t.slice(0,n).trim(),r=Number(t.slice(n+1)),s=i===Mt||/^[a-z0-9][a-z0-9-]*$/iu.test(i);return(n<1||!s||!Number.isSafeInteger(r)||r<1)&&Ue(`history-author-acknowledge --event expects <item-id>:<one-based-line>, received "${t}".`,{code:"history_author_acknowledge_target_unreadable"}),{item_id:i,line:r}})}function h1(e,t){let n=nS(Do(t.historyEvent),t.allActionable===!0||t.all_actionable===!0);return rS(e,{events:n.events,all_actionable:n.all_actionable,dry_run:t.dryRun===!0||t.dry_run===!0,plan_fingerprint:L(t,"planFingerprint")??L(t,"plan_fingerprint"),coordinate_limit:typeof t.limit=="number"?t.limit:typeof t.limit=="string"?Number(t.limit):void 0,attributed_author:L(t,"attributedAuthor")??L(t,"attributed_author")??void 0,reviewer:L(t,"reviewer"),reason:L(t,"reason")})}async function rS(e,t){let n=t.reviewer?.trim()??"",i=t.attributed_author?.trim()??"",r=t.reason?.trim()??"",s=await $f(e,t,t.coordinate_limit??50);if(t.dry_run===!0)return{dry_run:!0,mutated:!1,acknowledged:0,outcome:"preview",exit_code:m.SUCCESS,plan:s.plan};if([n.length>0,n.toLowerCase()!=="unknown",i.length>0,i.toLowerCase()!=="unknown",r.length>0].includes(!1)&&Ue("Author acknowledgment requires events, reviewer, attributed_author, and reason.",{code:"history_author_acknowledge_required_values_missing"}),t.plan_fingerprint?.trim()||Ue("Author acknowledgment apply requires plan_fingerprint from a fresh dry-run preview.",{code:"history_author_acknowledge_plan_fingerprint_required",recovery:{suggested_retry:"Rerun history-author-acknowledge with --dry-run, then pass --plan-fingerprint <value>."}}),t.plan_fingerprint.trim()!==s.plan.plan_fingerprint)throw new _("Author acknowledgment selection changed after preview; no history was mutated.",m.CONFLICT,{code:"history_author_acknowledge_plan_conflict",recovery:{suggested_retry:"Rerun history-author-acknowledge with --dry-run and apply the fresh plan_fingerprint."}});let a=s.completeCoordinates.filter(({disposition:l})=>s.plan.selection.kind==="events"||l==="actionable").map(({item_id:l,line:u})=>({item_id:l,line:u}));if(a.length===0)return{dry_run:!1,mutated:!1,acknowledged:0,outcome:"no_effect",exit_code:m.NO_EFFECT,plan:s.plan};let o=await I(e),c=await sn({pmRoot:e,op:"history:author-acknowledge",author:n,context:{author_acknowledgment:{events:a,attributed_author:i}},message:r,lockTtlSeconds:o.locks.ttl_seconds,lockWaitMs:o.locks.wait_ms}),d=s.plan.actionable_count>0&&s.plan.already_acknowledged_count>0?{outcome:"partial_effect",exit_code:m.PARTIAL_EFFECT}:{outcome:"effect",exit_code:m.SUCCESS};return{dry_run:!1,mutated:!0,acknowledged:a.length,...d,plan:s.plan,history_path:c.historyPath}}import aS from"node:fs/promises";import Ie from"node:path";import{glob as oS}from"tinyglobby";(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]="6f94fb3c-3d6c-5543-a2f0-e12680459e71")}catch{}})();var sS=/^[a-z][a-z0-9+.-]+:\/\//i;function ci(e){return sS.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]="12655e94-6304-56cf-9f5d-387a26572db0")}catch{}})();var cS=["path","scope","note"],dS=["pattern","glob","path","scope","note"],lS=["path"],uS=["from","to"],mS=new Set(["note","scope"]);function jf(e){let t=e??"project";if(!Pe.includes(t))throw new _(`Invalid scope "${e}". Valid scopes: ${Pe.join(", ")} (default: project).`,m.USAGE);return t}function No(e){if(e.startsWith("```")||e.includes(`
|
|
6
|
+
`)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(e))return!0;let t=e.indexOf(","),n=e.slice(0,t>=0?t:e.length),i=n.indexOf("=");return i>=0&&!/\s/u.test(e)&&(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)||/^(?:[A-Za-z]:[\\/]|[\\/]{1,2}|\.\.?(?:[\\/]))/u.test(e)||[e.indexOf("/"),e.indexOf("\\")].some(r=>r>=0&&r<i))?!1:n.includes("=")||on(e)}function _S(e){let t=0;for(let n of e)if(n==="("&&(t+=1),n===")"&&(t-=1),t<0)return!1;return t===0}function pS(e){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)&&!No(e))return{path:e,scope:"project",note:void 0};let t=e.indexOf("](");if(e.startsWith("[")&&t>0&&e.endsWith(")")){let s=e.slice(t+2,-1).trim();if(s.length>0&&_S(s))return{path:s,scope:"project",note:e.slice(1,t).trim()||void 0}}let n=e.indexOf(",");if(n<0)return;let i=e.slice(0,n).trim(),r=e.slice(n+1).trim();if(!(i.length===0||!/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(r)))return{path:r,scope:"project",note:i}}function fS(e,t){return e?e.flatMap(n=>{let i=n.trim();if(t==="doc"){let s=pS(i);if(s!==void 0)return[s]}Kn(i,"--add",`${t} path`,No(i));let r=No(i)?Z(n,"--add"):{path:i};if(we(r,"--add",cS),!r.path)throw new _(`--add requires path=<value> or a bare ${t} path`,m.USAGE);return[{path:r.path,scope:jf(r.scope),note:r.note?.trim()||void 0}]}):[]}function gS(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new _("--add-glob requires a glob pattern value",m.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(n)||n.startsWith("```")){let i=Z(n,"--add-glob");we(i,"--add-glob",dS);let r=i.pattern?.trim()||i.glob?.trim()||i.path?.trim();if(!r)throw new _("--add-glob key/value form requires pattern=<glob>",m.USAGE);return{pattern:r,scope:jf(i.scope),note:i.note?.trim()||void 0}}return{pattern:n,scope:"project"}}):[]}function hS(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new _("--remove requires a path value",m.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(n)||n.startsWith("```")){let i=Z(n,"--remove"),r=Object.keys(i).filter(s=>mS.has(s.toLowerCase()));if(r.length>0)throw new _(`--remove identifies a linked artifact by path only and does not accept ${r.map(s=>`"${s}"`).join(", ")}. Pass just the path (path=<value>, path:<value>, or a bare path); record removal context with --message "<why removed>".`,m.USAGE);if(we(i,"--remove",lS),!i.path)throw new _("--remove key/value form requires path=<value>",m.USAGE);return i.path}return n}):[]}function yS(e){return e?e.map(t=>{let n=Z(t,"--migrate");we(n,"--migrate",uS);let i=n.from?.trim(),r=n.to?.trim();if(!i||!r)throw new _("--migrate requires from=<value> and to=<value>",m.USAGE);return{from:i,to:r}}):[]}function di(e,t){let n=e;for(let i of t)n.startsWith(i.from)&&(n=`${i.to}${n.slice(i.from.length)}`);return n}function vS(e,t,n=[]){if(e.length===0||t.length===0)return;let i=new Set(e.map(s=>di(s.path,n))),r=[...new Set(t.map(s=>di(s,n)).filter(s=>i.has(s)))].sort((s,a)=>s.localeCompare(a));if(r.length!==0)throw new _(`Linked artifact mutation cannot add and remove the same normalized path in one transaction: ${r.join(", ")}. Split the replacement into separate commands so each history event has one unambiguous intent.`,m.USAGE,{code:"linked_artifact_mutation_conflict",reason:"same_path_added_and_removed",required:"Use distinct normalized paths for --add and --remove in one invocation.",why:"Conflicting batch intent cannot be applied deterministically without silently discarding metadata or a removal.",nextSteps:["Run the removal and addition as separate commands with a --message describing each intent."]})}function _t(e){return e.split(Ie.sep).join("/")}function Mo(e,t,n=process.cwd()){let i=e.trim();if(ci(i))return i;if(Ie.isAbsolute(i)||/^[A-Za-z]:[\\/]/.test(i))return _t(i.replaceAll("\\",Ie.sep));let r=Ie.relative(t,n);return r.startsWith(`..${Ie.sep}`)||r===".."||Ie.isAbsolute(r)?_t(Ie.normalize(i)):_t(Ie.relative(t,Ie.resolve(n,i)))}async function wS(e,t=process.cwd(),n=process.cwd()){let i=[];for(let r of e){if(Ie.resolve(n,r.pattern)===Ie.resolve(n))continue;let s=Ie.isAbsolute(r.pattern),a=await oS(r.pattern,{cwd:n,absolute:s,onlyFiles:!0,dot:!0,expandDirectories:!1,followSymbolicLinks:!0}),o=[...new Set(a.map(c=>Mo(c,t,n)))].sort((c,d)=>c.localeCompare(d));for(let c of o)i.push({path:c,scope:r.scope,note:r.note})}return i}function bS(e,t,n){if(t===void 0)return e;if(!n)throw new _("--note requires --add or --add-glob in the same invocation (the note annotates the links being added)",m.USAGE);let i=t.trim();return i.length===0?e:e.map(r=>r.note===void 0?{...r,note:i}:r)}function kS(e){return`${e.path}::${e.scope}`}function Po(e){return[...e].sort((t,n)=>{let i=t.path.localeCompare(n.path);return i!==0?i:t.scope.localeCompare(n.scope)})}function Fo(e){return[...new Map(e.map(t=>[kS(t),t])).values()].map(t=>({...t,note:t.note?.trim()||void 0}))}async function ES(e,t=process.cwd()){let n=[...new Set(e)].sort((o,c)=>o.localeCompare(c)),i=[],r=[],s=[],a=[];for(let o of n){if(ci(o)){a.push(o.trim());continue}let c=Ie.isAbsolute(o)?o:Ie.resolve(t,o);try{(await aS.stat(c)).isFile()?i.push(o):s.push(o)}catch(d){if(typeof d=="object"&&d!==null&&"code"in d&&Ki(d)){r.push(o);continue}s.push(o)}}return{checked:n.length,existing_files:i,missing_paths:r,non_file_paths:s,remote_references:a}}function SS(e,t,n,i){let r=0;for(let s=0;s<e.length;s+=1){let a=di(e[s].path,i);a!==e[s].path&&(e[s]={...e[s],path:a},r+=1)}return{adds:t.map(s=>{let a=di(s.path,i);return a!==s.path&&(r+=1),{...s,path:a}}),removes:n.map(s=>di(s,i)),count:r}}function TS(e,t,n,i){let r=Fo(e);for(let s of t){let a=r.findIndex(o=>o.path===s.path&&o.scope===s.scope);a<0?r.push(s):s.note!==void 0&&(r[a]={...r[a],note:s.note})}if(n.length>0)for(let s=r.length-1;s>=0;s-=1)n.includes(r[s].path)&&r.splice(s,1);return i?r:Po(r)}async function Uf(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||e.changed?await ES(t,e.workspaceRoot):void 0}}async function zr(e,t,n,i){let{metadataKey:r}=i,s=cn(),a=x(process.cwd(),n.path),o=Xe(a),c=process.cwd();await $(a);let d=await I(a),l=F(d,P()),u=await s.resolveList(t.add,"--add"),p=await s.resolveList(t.addGlob,"--add-glob"),g=await s.resolveList(t.remove,"--remove"),f=await s.resolveList(t.migrate,"--migrate"),h=fS(u,i.bareNoun).map(A=>({...A,path:Mo(A.path,o,c)})),y=gS(p),v=await wS(y,o,c),w=bS([...h,...v],t.note,h.length>0||y.length>0),k=hS(g).map(A=>Mo(A,o,c)),S=yS(f);if(vS(w,k,S),!(w.length>0||k.length>0||S.length>0)){let A=await Y(a,e,d.id_prefix,d.item_format,l.type_to_folder);if(!A)throw new _(`Item ${e} not found`,m.NOT_FOUND);let R=(await he(A,{schema:d.schema})).document.metadata[r]??[];return Uf({id:A.id,artifacts:R,changed:!1,options:t,workspaceRoot:o})}let T=U(t.author,d.author_default),C=await se({pmRoot:a,settings:d,id:e,op:i.op,author:T,message:t.message,force:t.force,skipNoop:!0,mutate(A){let R=A.metadata,G=R[r]??[],pe=[...G],ce=SS(pe,w,k,S),de=TS(pe,ce.adds,ce.removes,i.supportsAppendStable&&t.appendStable===!0);de.length>0?R[r]=de:delete R[r];let ue=!Fe(G,de);return{changedFields:ue?[r]:[],warnings:ue&&ce.count>0?[`path_migrations_applied:${ce.count}`]:[]}}}),b=C.item[r]??[],E=C.warnings.find(A=>A.startsWith("path_migrations_applied:")),N=E?Number(E.slice(24)):0;return Uf({id:C.item.id,artifacts:b,changed:C.changedFields.includes(r),migrationsApplied:N,options:t,workspaceRoot:o})}function Wr(e,t){let n={};for(let[i,r]of Object.entries(e))n[i==="artifacts"?t:i]=r;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]="79f1acaf-8ef7-5725-900a-fbeced1c57e6")}catch{}})();async function Gf(e,t,n){let i=await zr(e,t,n,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return Wr(i,"docs")}(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]="67d97df8-6551-52ed-9307-8b573a087831")}catch{}})();var Br=1e6;function $o(e,t=Br,n=.8,i=!1){let r=new Set,s=(l,u)=>{if(r.add(`${l}:${u}`),r.size>t)throw new _(`Duplicate sweep exceeded ${t} candidate pairs; narrow it with statuses or since.`,m.CONFLICT,{code:"duplicate_sweep_cost_limit",required:"Narrow the duplicate query or increase its similarity threshold. No partial result was returned."})};if(i||n===0){for(let l=0;l<e.length;l+=1)for(let u=0;u<l;u+=1)s(u,l);return r}let a=new Map;for(let{prepared:l}of e)for(let u of l.tokens)a.set(u,(a.get(u)??0)+1);let o=new Map,c=new Map,d=new Map;for(let[l,{prepared:u}]of e.entries()){let p=[...u.tokens].sort((h,y)=>a.get(h)-a.get(y)||h.localeCompare(y)),g=p.length-Math.ceil(n*p.length-1e-12)+1,f=[{index:o,keys:[u.normalized],lengthFilter:!1},{index:c,keys:n<=.99?u.issueCodes:[],lengthFilter:!1},{index:d,keys:p.length===0?[""]:p.slice(0,g),lengthFilter:!0}];for(let h of f)AS(e,l,h,n,s)}return r}function AS(e,t,n,i,r){let s=e[t].prepared.tokens.length;for(let a of n.keys){let o=n.index.get(a)??[];for(let c of o){let d=e[c].prepared.tokens.length;n.lengthFilter&&Math.min(d,s)/Math.max(d,s)+1e-12<i||r(c,t)}o.push(t),n.index.set(a,o)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a5f450bd-8970-5b1b-8250-b76b7818e6e1")}catch{}})();var IS=3,qf=20,CS=.8,xS=100,Kf=1e3;function zf(e){return e===void 0?[]:[`likely_duplicates:${e.result.items.map(t=>t.id).join(",")}`,`likely_duplicate_recovery:${e.recovery.action}:${e.recovery.item_id}`]}async function RS(e,t){let n=e.items[0],i=x(t.cwd??process.cwd(),t.pmRoot),r=K((await I(i)).schema);return _e(n.status,r)?{action:"reopen",item_id:n.id,command:`pm item reopen ${n.id} "<recurrence reason>"`,args:["item","reopen",n.id,"<recurrence reason>"]}:{action:"reuse",item_id:n.id,command:`pm get ${n.id} --full`,args:["get",n.id,"--full"]}}function Uo(e){let t=e.limit??IS,n=e.threshold??CS;if(!Number.isSafeInteger(t)||t<0||t>qf)throw new _(`Similarity limit must be an integer from 0 to ${qf}.`,m.USAGE);if(!Number.isFinite(n)||n<0||n>1)throw new _("Similarity threshold must be a number from 0 to 1.",m.USAGE);return{limit:t,threshold:n}}function Wf(e){let t=e.limit??xS;if(!Number.isSafeInteger(t)||t<0||t>Kf)throw new _(`Duplicate cluster limit must be an integer from 0 to ${Kf}.`,m.USAGE);let n=e.since===void 0?void 0:new Date(e.since);if(n&&Number.isNaN(n.getTime()))throw new _("Duplicate cluster --since must be a valid ISO timestamp.",m.USAGE);return{limit:t,since:n}}async function OS(e,t){let n=x(e.cwd??process.cwd(),e.pmRoot),i=await I(n),r=F(i),s=e.statuses?.map(u=>u.trim().toLowerCase()).filter(Boolean);if(e.statuses!==void 0&&s?.length===0)throw new _("Duplicate cluster statuses must include at least one lifecycle status or all.",m.USAGE);let a=K(i.schema),o=s?.map(u=>{if(u==="all")return u;let p=me(u,a);if(!p)throw new _(`Unknown duplicate-cluster status "${u}". Allowed: all, ${a.definitions.map(g=>g.id).join(", ")}.`,m.USAGE);return p}),c=o?.includes("all")===!0;if(c&&o?.some(u=>u!=="all"))throw new _('The "all" status cannot be combined with other statuses.',m.USAGE);let d=c?void 0:o,l=d?new Set(d):void 0;return{items:(await Se(n,i.item_format,r.type_to_folder,void 0,i.schema)).filter(u=>(!l||l.has(u.status))&&(!t||new Date(u.created_at).getTime()>=t.getTime())),statuses:d}}var rU={buildDuplicateClusters:Hf,collectDuplicateCandidatePairs:$o,createDuplicateUnionFind:Bf};function Bf(e){let t=Array.from({length:e},(n,i)=>i);return{parent:t,findRoot:n=>{let i=n;for(;t[i]!==i;)i=t[i];for(;t[n]!==n;){let r=t[n];t[n]=i,n=r}return i}}}function LS(e,t,n,i){let r=[];for(let s of t){let[a,o]=s.split(":").map(u=>Number.parseInt(u,10)),c=so(e[a].prepared,e[o].prepared);if(c.score<n)continue;let d=i.findRoot(a),l=i.findRoot(o);d!==l&&(i.parent[l]=d),r.push({left_id:e[a].item.id,right_id:e[o].item.id,...c})}return r}function Hf(e,t,n,i){let r=new Map;for(let o of e.keys()){let c=n.findRoot(o),d=r.get(c)??[];d.push(o),r.set(c,d)}let s=new Map(e.map(({item:o},c)=>[o.id,n.findRoot(c)])),a=new Map;for(let o of t){let c=s.get(o.left_id),d=a.get(c)??[];d.push(o),a.set(c,d)}return[...r.values()].filter(o=>o.length>1).map(o=>{let c=(a.get(n.findRoot(o[0]))??[]).sort((d,l)=>l.score-d.score||d.left_id.localeCompare(l.left_id)||d.right_id.localeCompare(l.right_id));return{id:e[o[0]].item.id,items:o.map(d=>{let l=e[d].item;return{id:l.id,title:l.title,status:l.status,type:l.type}}),matches:c,max_score:c[0]?.score??0}}).sort((o,c)=>c.max_score-o.max_score||o.id.localeCompare(c.id)).slice(0,i)}function DS(e,t,n,i,r){return t.filter(s=>!n.has(s.id)).map(s=>({id:s.id,title:s.title,status:s.status,type:s.type,...ro(e,s.title)})).filter(s=>s.score>=i).sort((s,a)=>a.score-s.score||s.id.localeCompare(a.id)).slice(0,r)}async function NS(e,t={}){let n=e.title.trim();if(n.length===0)throw new _("Similarity candidate title must not be empty.",m.USAGE);let{limit:i,threshold:r}=Uo(t),s=x(t.cwd??process.cwd(),t.pmRoot),a=await I(s),o=F(a),c=await sr(s,Object.values(o.type_to_folder)),d=no(n),l=c&&d.length>0?await ku({pmRoot:s,expectedSourceCursor:c.source_cursor,query:d.map(g=>`"${g.replaceAll('"','""')}"`).join(" OR "),limit:Math.max(i*10,50)}):null,u=l===null?await Se(s,a.item_format,o.type_to_folder,void 0,a.schema):l.items,p=DS(n,u,new Set(e.excludeIds??[]),r,i);return{items:p,count:p.length,threshold:r,source:l?"persistent_index":"metadata_fallback"}}function MS(e,t={}){let{threshold:n}=Uo({...t,limit:void 0}),{limit:i}=Wf(t),r=new Set;for(let l of e){if(!l.id.trim()||r.has(l.id))throw new _("Duplicate analysis requires unique non-empty item ids.",m.USAGE);r.add(l.id)}let s=[...e].sort((l,u)=>l.id.localeCompare(u.id)).map(l=>({item:l,prepared:io(l.title)})),a=$o(s,Br,n,t.exhaustive===!0),o=Bf(s.length),c=LS(s,a,n,o),d=Hf(s,c,o,i);return{clusters:d,count:d.length,threshold:n,cost:{item_count:s.length,algorithm:t.exhaustive===!0||n===0?"exhaustive":"prefix_exact",possible_pairs:s.length*(s.length-1)/2,pair_limit:Br,recall_guarantee:"exact",candidate_pairs:a.size,scored_pairs:a.size}}}async function Vf(e={}){Uo({...e,limit:void 0});let{since:t}=Wf(e),{items:n,statuses:i}=await OS(e,t);return{...MS(n,e),source:"metadata_scan",filters:{statuses:i??null,since:e.since??null}}}async function jo(e,t){if(t.mode==="off")return;let n=await NS(e,t);if(n.count===0)return;let i=await RS(n,t),r=t.mode==="strict"&&t.allowDuplicate===!0;if(t.mode==="strict"&&!r){let s=n.items.map(o=>`${o.id} (${o.status}): ${o.title}`).join("; "),a=i.action==="reopen"?"Reopen the canonical item":"Reuse the canonical item";throw new _(`Likely duplicate item(s) found: ${s}. ${a} or pass --allow-duplicate with explicit intent.`,m.CONFLICT,{code:"likely_duplicate",required:`${a}, or explicitly acknowledge the duplicate with --allow-duplicate.`,recovery:{suggested_flags:["--allow-duplicate"],suggested_retry:i.command,suggested_retry_args:i.args}})}return{mode:t.mode,bypassed:r,result:n,recovery:i}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="499dfc08-cf70-55fe-8868-65c3107e3a91")}catch{}})();async function cU(e,t={}){let n=await Vf({pmRoot:x(process.cwd(),e.path),exhaustive:t.exhaustive,...t.status===void 0?{}:{statuses:t.status.flatMap(i=>i.split(",").map(r=>r.trim()).filter(Boolean))},...t.since===void 0?{}:{since:t.since},...t.threshold===void 0?{}:{threshold:t.threshold},...t.limit===void 0?{}:{limit:t.limit}});return{...n,clusters:n.clusters.map(i=>{let r=i.id;return{...i,canonical_id:r,close_command:`pm close <duplicate-id> --duplicate-of ${r}`}}),guidance:{strategy:"review_then_close_duplicate",command:"pm close <duplicate-id> --duplicate-of <canonical-id>"}}}import{execFile as PS}from"node:child_process";import Yf 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]="3bb613e2-51f9-5947-8d92-d6207bb62cdc")}catch{}})();function Jf(e,t){return new Promise((n,i)=>{PS("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:4*1024*1024},(r,s)=>{r?i(r):n(s)})})}function Xf(e){if(e&&(!Number.isSafeInteger(e.start)||!Number.isSafeInteger(e.end)||e.start<1||e.end<e.start))throw new RangeError("Source line range must be inclusive positive integers with end >= start.")}function _U(e){let t=/^(\d+):(\d+)$/u.exec(e.trim()),n=t?{start:Number(t[1]),end:Number(t[2])}:void 0;if(Xf(n),!n)throw new RangeError("Source line range must use start:end.");return n}function FS(e){let t=new Map;for(let n of e.split(`
|
|
7
|
+
`)){let i=/^([0-9a-f^]{40,64}) \d+ \d+(?: \d+)?$/u.exec(n)?.[1];i&&t.set(i,(t.get(i)??0)+1)}return t}function $S(e){let t=e.split("\0"),n=new Map;for(let i=0;i+1<t.length;i+=2){let r=t[i]?.trim();if(!r)continue;let s=[...new Set(t[i+1]?.match(/\bpm-[a-z0-9][a-z0-9-]{2,63}\b/gu)??[])].sort((a,o)=>a.localeCompare(o));n.set(r,s)}return n}async function US(e){let t=Yf.relative(e.workspaceRoot,Yf.resolve(e.workspaceRoot,e.sourcePath)),n=await Jf(e.workspaceRoot,["blame","--line-porcelain","-L",`${e.lineRange.start},${e.lineRange.end}`,"--",t]),i=await Jf(e.workspaceRoot,["log","-n","256","--format=%H%x00%B%x00","--",t]);return{commitLines:FS(n),commitItems:$S(i),available:!0}}function jS(e){let t=e.current.nodes.at(-1),n=e.current.kinds.length+1,i;for(let r of e.graph.incidentEdges(t)){let s=r.source===t,a=s?r.target:r.source;if((e.visitedDepth.get(a)??Number.POSITIVE_INFINITY)<n)continue;e.visitedDepth.set(a,n);let o=e.graph.registry().require(r.kind),c={nodes:[...e.current.nodes,a],kinds:[...e.current.kinds,s?r.kind:o.inverse??r.kind]};e.details.get(a)?.type?.toLowerCase()==="decision"?(i=n,e.found.push(c)):e.queue.push(c)}return i}function GS(e){let t=[{nodes:[e.itemId],kinds:[]}],n=new Map([[e.itemId,0]]),i=[],r;for(;t.length>0;){let s=t.shift(),a=s.kinds.length;r!==void 0&&a>=r||a>=e.maxDepth||(r=jS({current:s,graph:e.graph,details:e.details,visitedDepth:n,queue:t,found:i})??r)}return i.sort((s,a)=>s.nodes.join("\0").localeCompare(a.nodes.join("\0"))),i}function qS(e,t,n){let i=V_(t);if(!i.graph.hasNode(e))return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let r=GS({itemId:e,maxDepth:n,graph:i.graph,details:new Map(i.details.map(o=>[o.id,o]))}),s=r[0];if(!s)return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let a=[...new Set(r.map(o=>o.nodes.at(-1)))];return{status:a.length===1?"found":"ambiguous",nodes:s.nodes,kinds:s.kinds,alternative_decision_ids:a.slice(1)}}async function KS(e){if(!e.lineRange)return{commitLines:new Map,commitItems:new Map,available:!0};try{return await US({workspaceRoot:e.workspaceRoot,sourcePath:e.paths[0],lineRange:e.lineRange})}catch{return{commitLines:new Map,commitItems:new Map,available:!1}}}function zS(e){let t=[];return e.hasLineRange&&!e.attributionAvailable&&t.push("git_attribution_unavailable"),e.hasLineRange&&e.contributionLines===0&&t.push("line_attribution_unmapped"),e.decisionStatus==="ambiguous"&&t.push("multiple_governing_decisions"),e.decisionStatus==="not_found"&&t.push("governing_decision_not_found"),t}function WS(e){return[...e.commitLines.keys()].filter(t=>(e.commitItems.get(t)?.length??0)>0)}async function Qf(e){Xf(e.lineRange);let t=e.decisionDepth??8;if(!Number.isSafeInteger(t)||t<1||t>32)throw new RangeError("Decision path depth must be an integer from 1 to 32.");let n=await KS(e),i=WS(n),r=new Map;for(let s of e.candidates){let a=[...n.commitLines.entries()].filter(([l])=>n.commitItems.get(l)?.includes(s.item.id)),o=a.reduce((l,[,u])=>l+u,0),c=qS(s.item.id,e.corpus,t),d=zS({hasLineRange:e.lineRange!==void 0,attributionAvailable:n.available,contributionLines:o,decisionStatus:c.status});r.set(s.item.id,{score:o*100+s.files.length*10+Math.max(0,9-Math.floor((Date.now()-Date.parse(s.item.updated_at))/(720*60*60*1e3))),contribution_lines:o,evidence:[...s.files.map(l=>({kind:"linked_file",reference:l.path})),...a.map(([l,u])=>({kind:"git_commit",reference:l.slice(0,12),contribution_lines:u}))],rationale:{value:s.item.value?.trim()||null,why_now:s.item.why_now?.trim()||null,outcome:s.item.outcome?.trim()||null,objective:s.item.objective?.trim()||null},decision_path:c,ambiguities:d})}return{explanations:r,receipt:{line_range:e.lineRange??null,blamed_commit_count:n.commitLines.size,mapped_commit_count:i.length,unmapped_commit_count:n.commitLines.size-i.length,decision_depth:t}}}import Zf from"node:fs/promises";import je 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]="06b0bd73-d282-5473-a1da-f11c61a0a086")}catch{}})();var BS=32768;function Go(e){return _t(je.normalize(e))}async function Hr(e){try{return await Zf.realpath(e)}catch{return je.resolve(e)}}function vn(e,t){let n=je.isAbsolute(e.path)?je.resolve(e.path):je.resolve(t,e.path);return`${Go(n)}::${e.scope}`}function Vr(e,t,n){if(typeof e=="string"){let i=e.trim();i.length>0&&n.push({field:t,value:i});return}if(Array.isArray(e)){e.forEach((i,r)=>Vr(i,`${t}[${r}]`,n));return}if(typeof e=="object"&&e!==null)for(let[i,r]of Object.entries(e))Vr(r,t?`${t}.${i}`:i,n)}function HS(e){let t=[];return Vr(e.metadata,"metadata",t),Vr(e.body,"body",t),t}function VS(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 YS(e){let t=[],n=/(?:[A-Za-z]:[\\/]|\/)[^\s"'`<>()[\]{},;]+/gu,i=/(?:\.{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 r of e){let s=new Set,a=r.value.slice(0,BS);for(let[o,c]of[[n,r.value],[i,a]]){o.lastIndex=0;for(let d of c.matchAll(o)){let l=VS(d[0]);!l||s.has(l)||(s.add(l),t.push({field:r.field,value:l}))}}}return t}async function JS(e,t,n=t){let i=je.isAbsolute(e)?je.resolve(e):je.resolve(n,e),r;try{r=await Zf.stat(i)}catch{return}if(!r.isFile())return;let[s,a]=await Promise.all([Hr(t),Hr(i)]);if(La(s,a)){let o=je.relative(s,a);return!o||o.startsWith("..")||je.isAbsolute(o)?void 0:{path:Go(o),scope:"project"}}return{path:Go(i),scope:"global"}}async function XS(e,t,n=t){let i=new Set((e.metadata.files??[]).map(c=>vn(c,t))),r=new Map,s=YS(HS(e)),a=new Map;await Promise.all([...new Set(s.map(c=>c.value))].map(async c=>{a.set(c,await JS(c,t,n))}));let o=s.map(c=>({reference:c,resolved:a.get(c.value)}));for(let{reference:c,resolved:d}of o){if(!d)continue;let l=vn(d,t),u=r.get(l)??{path:d.path,scope:d.scope,sourceFields:new Set,originalPaths:new Set,sourceCount:0};u.sourceFields.add(c.field),u.originalPaths.add(c.value),u.sourceCount+=1,r.set(l,u)}return[...r.entries()].map(([c,d])=>({path:d.path,scope:d.scope,status:i.has(c)?"already_linked":"addable",source_count:d.sourceCount,source_fields:[...d.sourceFields].sort((l,u)=>l.localeCompare(u)),original_paths:[...d.originalPaths].sort((l,u)=>l.localeCompare(u))})).sort((c,d)=>{let l=c.status.localeCompare(d.status);if(l!==0)return l;let u=c.path.localeCompare(d.path);return u!==0?u:c.scope.localeCompare(d.scope)})}async function eg(e,t,n){let i=await zr(e,t,n,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return Wr(i,"files")}async function QS(e,t){let n=await Hr(t),i=await Promise.all(e.map(async s=>{let a=s.trim();if(!a)throw new _("Files lookup paths must not be empty.",m.USAGE);if(!je.isAbsolute(a))return _t(a);let o=await Hr(a);return La(n,o)?_t(je.relative(n,o)):_t(o)})),r=[...new Set(i)].sort((s,a)=>s.localeCompare(a));if(r.length===0)throw new _("Files lookup requires at least one path.",m.USAGE);return r}function ZS(e){for(let[i,r]of[["limit",e.limit],["offset",e.offset]])if(r!==void 0&&(!Number.isInteger(r)||r<0))throw new _(`Files lookup ${i} must be a non-negative integer.`,m.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 tg(e){return{id:e.id,title:e.title,type:e.type,status:e.status,priority:e.priority,updated_at:e.updated_at}}function ng(e,t){let n=e.item.priority-t.item.priority;if(n!==0)return n;let i=t.item.updated_at.localeCompare(e.item.updated_at);return i===0?e.item.id.localeCompare(t.item.id):i}function eT(e){return e.metadata.map(t=>({item:t,files:(t.files??[]).filter(n=>e.paths.includes(_t(n.path))&&(e.scope===void 0||n.scope===e.scope)).sort((n,i)=>{let r=n.path.localeCompare(i.path);return r===0?n.scope.localeCompare(i.scope):r})})).filter(t=>t.files.length>0).sort(ng)}async function tT(e){if(e.explain)return Qf({workspaceRoot:e.workspaceRoot,paths:e.paths,candidates:e.matching,corpus:e.metadata,...e.lineRange?{lineRange:e.lineRange}:{},...e.decisionDepth===void 0?{}:{decisionDepth:e.decisionDepth}})}async function nT(e){if([e.strictRead,e.noTruncate,e.explain,zl()].includes(!0))return null;let t=await sr(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]);return t?bu({pmRoot:e.pmRoot,expectedSourceCursor:t.source_cursor,paths:e.paths,scope:e.scope,limit:e.limit,offset:e.offset}):null}async function iT(e){let t=[],n=await ar(e.pmRoot,e.settings.item_format,e.typeToFolder,t,e.settings.schema),i=eT({metadata:n,paths:e.paths,scope:e.scope}),r=t.filter(o=>/^item_list_(?:item|directory)_read_failed:/u.test(o));if(e.strictRead&&r.length>0)throw new _(`Files lookup could not read every item: ${r.join("; ")}`,m.GENERIC_FAILURE);let s=await tT({explain:e.explain,workspaceRoot:e.workspaceRoot,paths:e.paths,matching:i,metadata:n,lineRange:e.lineRange,decisionDepth:e.decisionDepth}),a=(s?[...i].sort((o,c)=>{let d=s.explanations.get(c.item.id).score-s.explanations.get(o.item.id).score;return d!==0?d:ng(o,c)}):i).slice(e.offset,e.limit===void 0?void 0:e.offset+e.limit);return{paths:e.paths,total:i.length,count:a.length,offset:e.offset,limit:e.limit??null,has_more:e.offset+a.length<i.length,truncated:e.offset+a.length<i.length,completeness:{status:r.length===0?"complete":"partial",source:"source_scan"},warnings:t,matches:a.map(o=>({item:tg(o.item),files:o.files,...s?{traceability:s.explanations.get(o.item.id)}:{}})),...s?{traceability_receipt:s.receipt}:{}}}async function OU(e,t){let n=x(process.cwd(),t.path),i=Xe(n);await $(n);let r=await QS(e.paths,i);if(e.lineRange&&r.length!==1)throw new _("Files lookup line attribution requires exactly one source path.",m.USAGE);let s=await I(n),a=F(s,P()),{offset:o,limit:c}=ZS(e),d=await nT({pmRoot:n,typeToFolder:a.type_to_folder,paths:r,scope:e.scope,limit:c,offset:o,strictRead:e.strictRead===!0,noTruncate:e.noTruncate===!0,explain:e.explain===!0||e.lineRange!==void 0});return d?{paths:r,total:d.total,count:d.matches.length,offset:o,limit:c,has_more:o+d.matches.length<d.total,truncated:o+d.matches.length<d.total,completeness:{status:"unchecked",source:"index"},warnings:[],matches:d.matches.map(l=>({item:tg(l.item),files:l.files}))}:iT({pmRoot:n,settings:s,typeToFolder:a.type_to_folder,paths:r,scope:e.scope,limit:c,offset:o,strictRead:e.strictRead===!0,workspaceRoot:i,explain:e.explain===!0||e.lineRange!==void 0,lineRange:e.lineRange,decisionDepth:e.decisionDepth})}async function LU(e,t,n){let i=x(process.cwd(),n.path),r=Xe(i);await $(i);let s=await I(i),a=F(s,P()),o=await Y(i,e,s.id_prefix,s.item_format,a.type_to_folder);if(!o)throw new _(`Item ${e} not found`,m.NOT_FOUND);let c=await he(o,{schema:s.schema}),d=await XS(c.document,r,process.cwd()),l=d.filter(E=>E.status==="addable"),u=d.filter(E=>E.status==="already_linked"),p=t.apply===!0,g=t.note?.trim()||"discovered from item text";if(!p||l.length===0){let E=c.document.metadata.files??[];return{id:o.id,files:E,changed:!1,apply:p,count:E.length,candidate_count:d.length,addable_count:l.length,added_count:0,skipped_existing_count:u.length,candidates:d,added:[],skipped_existing:u}}let f=U(t.author,s.author_default),h=l.map(E=>({path:E.path,scope:E.scope,note:g})),y=[],v=new Set,w=await se({pmRoot:i,settings:s,id:e,op:"files_discover",author:f,message:t.message??"Discover referenced file links",force:t.force,mutate(E){let N=[...E.metadata.files??[]],A=new Set(N.map(pe=>vn(pe,r)));y=[],v.clear();for(let[pe,ce]of h.entries()){let de=vn(ce,r);A.has(de)||(N.push(ce),A.add(de),y.push(ce),v.add(pe))}let R=Fo(N),G=t.appendStable?R:Po(R);return G.length>0?E.metadata.files=G:delete E.metadata.files,{changedFields:y.length>0?["files"]:[],warnings:y.length!==h.length?[`files_discover_skipped_existing:${h.length-y.length}`]:[]}}}),k=w.item.files??[],S=new Set(y.map(E=>vn(E,r))),T=k.filter(E=>S.has(vn(E,r))),C=l.filter((E,N)=>!v.has(N)),b=[...u,...C];return{id:w.item.id,files:k,changed:T.length>0,apply:!0,count:k.length,candidate_count:d.length,addable_count:l.length,added_count:T.length,skipped_existing_count:b.length,candidates:d,added:T,skipped_existing:b}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bee6d15d-ca4a-538c-bb70-fd3dc7e2a8ec")}catch{}})();var li=["software-delivery","research","agent-evaluation","operations"];function ig(e,t,n,i,r){return{id:e,measurement_id:t,owner_item_id:n,scope:{kind:"active"},ceiling:i,lifetime:"hold",enforcement:r,negative_control:{cases:[{observed:i,expected:"pass"},{observed:i+1,expected:"fail"}]}}}function Yr(e,t,n,i,r){let s=`preset-${e}`,a=r.map(c=>({id:`${s}-missing-${c}`,description:`Active items missing ${c} evidence.`,source:{kind:"links",link:c,state:"missing"}})),o=a.map(c=>ig(`${c.id}-zero`,c.id,i,0,"warn"));return{id:e,title:t,description:n,declarations:{measurements:a,assertions:o,gates:[{id:`${s}-readiness`,description:n,assertion_ids:o.map(c=>c.id),triggers:["ci","scheduled"]}]}}}function Jr(e,t){return e==="software-delivery"?Yr(e,"Software delivery","Warn when active delivery work lacks executable tests or documentation.",t,["tests","docs"]):e==="research"?Yr(e,"Research","Warn when active research work lacks reproducibility files or documentation.",t,["files","docs"]):e==="agent-evaluation"?Yr(e,"Agent evaluation","Warn when active evaluation work lacks executable scenarios or recorded artifacts.",t,["tests","files"]):Yr(e,"Operations","Warn when active operational work lacks runbook documentation or repair evidence.",t,["docs","files"])}function rg(e,t,n,i={}){return To(e,Jr(t,n).declarations,i)}async function sg(e,t){let n=new Set(e.terminal_statuses??["closed","canceled"]),i={...e,items:e.items.filter(r=>!n.has(r.status))};return await Promise.all(["files","tests","docs"].map(async r=>{let s={id:`derived-active-missing-${r}`,description:`Observed active items missing ${r} evidence.`,source:{kind:"links",link:r,state:"missing"}},a=(await Eo(s,i)).value,o=ig(`${s.id}-ceiling`,s.id,t,a,"observe"),c=`active-missing-${r}`;return{id:c,population_size:i.items.length,scope:{kind:"active"},observed:a,declarations:{measurements:[s],assertions:[o],gates:[{id:`derived-${c}`,description:`Observe the accepted ${r} evidence baseline.`,assertion_ids:[o.id],triggers:["ci","scheduled"]}]}}}))}function ag(e,t,n={}){return To(e,{measurements:t.flatMap(i=>i.declarations.measurements),assertions:t.flatMap(i=>i.declarations.assertions),gates:t.flatMap(i=>i.declarations.gates)},n)}async function og(e,t,n,i={}){let r=t.enforcement==="observe"?"warn":"block";if(t.enforcement==="block"||n!==r)throw new TypeError(`assurance assertion ${t.id} promotion must be ${t.enforcement} -> ${r}`);return Pr(e,"assertion",{...t,enforcement:n},{...i,message:i.message??`Promote assurance assertion ${t.id} from ${t.enforcement} to ${n}`})}import lg from"node:fs/promises";import{createRequire as rT}from"node:module";import De 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]="32adaa7c-f0aa-5aff-8d88-d7c0ccfbd971")}catch{}})();function cg(e,t){let n=De.relative(t,e);if(n.length>0&&n!==".."&&!n.startsWith(`..${De.sep}`)&&!De.isAbsolute(n))return n.split(De.sep).join("/");let i=De.resolve(e),r=0xcbf29ce484222325n;for(let s=0;s<i.length;s+=1)r^=BigInt(i.charCodeAt(s)),r=BigInt.asUintN(64,r*0x100000001b3n);return`<external>/${r.toString(16).padStart(16,"0")}/${De.basename(De.dirname(e))}/package.json`}function sT(e){return e.includes(`${De.sep}.pnpm${De.sep}`)?"pnpm":e.includes(`${De.sep}node_modules${De.sep}`)?"npm":"other"}async function dg(e){try{let t=JSON.parse(await lg.readFile(e,"utf8"));return t.name==="@unbrained/pm-cli"&&typeof t.version=="string"&&t.version.trim().length>0?t.version.trim():void 0}catch{return}}async function qo(e){try{return await lg.realpath(e)}catch{return De.resolve(e)}}async function ug(e,t,n=ol(import.meta.url,["../../.."])){let i=await qo(t),r=await qo(De.join(n,"package.json")),s=await dg(r),a=new Map;s!==void 0&&a.set(r,{version:s,path:cg(r,i),layout:"host",consumers:["pm-cli-host"]});for(let d of e)try{let l=rT(d.entry_path).resolve("@unbrained/pm-cli/package.json"),u=await qo(l),p=await dg(u);if(p===void 0)continue;let g=u,f=a.get(g);if(f){f.consumers.includes(d.name)||(f.consumers.push(d.name),f.consumers.sort((h,y)=>h.localeCompare(y)));continue}a.set(g,{version:p,path:cg(u,i),layout:sT(u),consumers:[d.name]})}catch{}let o=[...a.values()].sort((d,l)=>d.path.localeCompare(l.path)),c=s===void 0?[]:o.filter(d=>d.version!==s);return{host_version:s??null,copies:o,mismatches:c,warnings:c.map(d=>`extension_host_pm_cli_version_skew:${s}:${d.version}:${d.consumers.join("+")}`)}}import{createHash as aT}from"node:crypto";import Xr 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]="36749195-9194-546a-bc3e-718f09c3b8d6")}catch{}})();var oT="2026-08-09T16:15:18.000Z",_g=Symbol("pre-durable-disposition-eligible");function pt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ko(e){if(!Array.isArray(e)||e.length>256)return!1;let t=new Set;for(let n=0;n<e.length;n+=1){let i=e[n];if(!(n in e)||typeof i!="string"||i.length===0||i.length>256||i.includes("\0")||t.has(i))return!1;t.add(i)}return!0}function mg(e){return pt(e)?typeof e.field=="string"&&e.field.length>0&&e.field.length<=256&&!e.field.includes("\0")&&typeof e.retained_hash=="string"&&/^[a-f0-9]{64}$/u.test(e.retained_hash)&&typeof e.discarded_hash=="string"&&/^[a-f0-9]{64}$/u.test(e.discarded_hash):!1}function pg(e,t){if(typeof e!="string")return!1;let n=Xr.posix.normalize(e);return e.length<=4096&&!e.includes("\\")&&!e.includes("\0")&&!Xr.posix.isAbsolute(e)&&n===e&&!n.startsWith("../")&&(Xr.posix.basename(n)===`${t}.toon`||Xr.posix.basename(n)===`${t}.md`)}function cT(e,t){return typeof e.receipt_id=="string"&&Jn(e.receipt_id)&&(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0&&e.conflict_resolution===void 0&&e.item_id===t&&pg(e.item_path,t)}function fg(e){let t=e.conflict_fields,n=e.fields_from_theirs,i=e.union_fields,r=e.decisions,s=Array.isArray(r)?new Set(r.flatMap(a=>mg(a)?[a.field]:[])):new Set;return Ko(t)&&Ko(n)&&Ko(i)&&Array.isArray(r)&&r.length>0&&r.length<=256&&Object.keys(r).length===r.length&&r.every(mg)&&s.size===r.length&&t.length===s.size&&t.every(a=>s.has(a))}function dT(e,t){return cT(e,t)&&fg(e)}function lT(e,t){return typeof e.receipt_id=="string"&&Jn(e.receipt_id)&&(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0&&(e.conflict_resolution==="preferred_side"||e.conflict_resolution==="stable_value_order")&&e.item_id===t&&pg(e.item_path,t)&&fg(e)}function uT(e){return e[_g]===!0}function gg(e,t){if(!pt(e)||!pt(e.context))return[];let n=e.context.merge;return!pt(n)||!Array.isArray(n.receipts)?[]:n.receipts.flatMap(i=>!pt(i)||typeof i.receipt_id!="string"||i.receipt_id.trim().length===0?[]:[{receiptId:i.receipt_id,legacySummaryAccepted:dT(i,t),[_g]:lT(i,t),...typeof e.ts=="string"&&Ga(e.ts)?{eventTimestamp:e.ts}:{}}])}function hg(e,t,n){if(!pt(e)||e.op!=="merge_reconcile")return[];if(!pt(e.context)||!pt(e.context.merge))return[];let i=e.context.merge.missing_receipt_dispositions;return!Array.isArray(i)||i.length>256?[]:i.flatMap(r=>!pt(r)||typeof r.receipt_id!="string"||!Jn(r.receipt_id)||typeof r.original_history_line!="number"||!Number.isSafeInteger(r.original_history_line)||r.original_history_line<1||typeof r.original_event_ts!="string"||!Ga(r.original_event_ts)||r.reason!=="legacy_clone_local_only"?[]:[{itemId:t,receiptId:r.receipt_id,originalHistoryLine:r.original_history_line,originalEventTimestamp:r.original_event_ts,auditHistoryLine:n,reason:r.reason}])}function yg(e,t,n=[]){let i=new Map;for(let s of n){let a=`${s.itemId}\0${s.originalHistoryLine}\0${s.receiptId}\0${s.originalEventTimestamp}`;i.set(a,Math.max(i.get(a)??0,s.auditHistoryLine))}let r=s=>uT(s)&&s.eventTimestamp!==void 0&&Ji(s.eventTimestamp,oT)<0&&(i.get(`${s.itemId}\0${s.line}\0${s.receiptId}\0${s.eventTimestamp}`)??0)>s.line;return{missing:e.filter(s=>!s.legacySummaryAccepted&&!t.has(s.receiptId)&&!r(s)).map(s=>({item_id:s.itemId,history_line:s.line,...Jn(s.receiptId)?{receipt_id:s.receiptId}:{receipt_reference_hash:aT("sha256").update(s.receiptId).digest("hex")}})),acceptedLegacyCount:e.filter(s=>s.legacySummaryAccepted).length,acceptedDispositionCount:e.filter(r).length}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d8f1968e-a030-5a3c-b766-60a409163745")}catch{}})();function Qr(e,t,n=25){let i=e.definitions.filter(a=>a.roles.length===0).map(a=>a.id).sort((a,o)=>a.localeCompare(o)),r=new Set(i),s=t.filter(a=>{let o=Ke(a.status,e);return o!==void 0&&r.has(o)}).map(a=>a.id).sort((a,o)=>a.localeCompare(o));return{roleless_status_count:i.length,roleless_statuses:i.slice(0,n),roleless_statuses_truncated:i.length>n,affected_item_count:s.length,affected_item_ids:s.slice(0,n),affected_item_ids_truncated:s.length>n}}function Zr(e){return e.roleless_status_count===0?[]:[`schema_status_missing_lifecycle_role:${e.roleless_status_count}`]}(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]="717434ef-3c62-50a8-8887-e2bbc3851eff")}catch{}})();var wg=8,zo=100;function bg(e,t){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function ze(e,t){return Array.isArray(e)?{count:e.length,sample:e.slice(0,t),truncated:e.length>t}:{count:0,sample:[],truncated:!1}}function mT(e){if(typeof e!="object"||e===null||Array.isArray(e))return{};let t=e;return{layer:t.layer,directory:t.directory,name:t.name,version:t.version,enabled:t.enabled,status:t.status,has_activate:t.has_activate,capabilities:t.capabilities}}function ui(e,t){let n=ze(e,t);return{...n,sample:n.sample.map(i=>mT(i))}}function W(e,t){if(!Array.isArray(e))return{count:0,sample:[],truncated:!1};let n=e.filter(i=>typeof i=="string");return{count:n.length,sample:n.slice(0,t),truncated:n.length>t}}function _T(e){if(typeof e!="object"||e===null)return null;let t=e;return{applied_count:t.applied_count,pending_count:t.pending_count,failed_count:t.failed_count}}var pT={settings:(e,t)=>({version:e.version,id_prefix:e.id_prefix,locks_ttl_seconds:e.locks_ttl_seconds,warnings:W(e.warnings,t)}),directories:(e,t)=>({required_count:Array.isArray(e.required)?e.required.length:0,optional_count:Array.isArray(e.optional)?e.optional.length:0,missing_required:W(e.missing_required,t),missing_optional:W(e.missing_optional,t),missing:W(e.missing,t),strict_directories:e.strict_directories}),settings_values:(e,t)=>({warnings:W(e.warnings,t)}),telemetry:e=>({enabled:e.enabled,capture_level:e.capture_level,endpoint:e.endpoint,queue_exists:e.queue_exists,queue_entries:e.queue_entries,queue_draining:e.queue_draining,queue_invalid_rows:e.queue_invalid_rows,queue_rows_total:e.queue_rows_total,last_successful_flush_at:e.last_successful_flush_at,last_failed_flush_at:e.last_failed_flush_at,endpoint_probe:e.endpoint_probe,env_overrides:e.env_overrides}),extensions:(e,t)=>{let n=typeof e.activation=="object"&&e.activation!==null?e.activation:{};return{disabled_by_flag:e.disabled_by_flag,discovered:ui(e.discovered,t),effective:ui(e.effective,t),loaded:ui(e.loaded,t),failed:ze(e.failed,t),warnings:W(e.warnings,t),activation:{failed:ze(n.failed,t),warnings:W(n.warnings,t),hook_counts:n.hook_counts,command_handler_count:n.command_handler_count,service_override_count:n.service_override_count,renderer_override_count:n.renderer_override_count,registration_counts:n.registration_counts,migration_status:_T(n.migration_status)},author_manifest:e.author_manifest,triage:e.triage,capability_contract:e.capability_contract,capability_guidance:ze(e.capability_guidance,t),host_version_census:e.host_version_census}},storage:(e,t)=>{let n=typeof e.author_attribution=="object"&&e.author_attribution!==null?e.author_attribution:void 0;return{...e,...n?{author_attribution:{...n,affected_item_ids:W(n.affected_item_ids,t),samples:ze(n.samples,t)}}:{}}},locks:e=>({active_lock_count:e.active_lock_count,stale_lock_count:e.stale_lock_count,unreadable_lock_count:e.unreadable_lock_count,unparseable_lock_count:e.unparseable_lock_count}),integrity:(e,t)=>{let n=typeof e.tracked_runtime_cache=="object"&&e.tracked_runtime_cache!==null?e.tracked_runtime_cache:void 0;return{checked_item_files:e.checked_item_files,checked_history_streams:e.checked_history_streams,counts:e.counts,item_unreadable:W(e.item_unreadable,t),item_conflict_markers:ze(e.item_conflict_markers,t),item_parse_failures:W(e.item_parse_failures,t),tracked_runtime_cache:n===void 0?e.tracked_runtime_cache:{...n,tracked_paths:W(n.tracked_paths,t)},history_unreadable:W(e.history_unreadable,t),history_conflict_markers:ze(e.history_conflict_markers,t),history_invalid_json:ze(e.history_invalid_json,t),skipped:e.skipped}},history_drift:(e,t)=>{let n=typeof e.cache_confirmation=="object"&&e.cache_confirmation!==null?e.cache_confirmation:void 0;return{checked_items:e.checked_items,cache_hit_verification:e.cache_hit_verification,cache_confirmation:n===void 0?e.cache_confirmation:{...n,candidate_items:W(n.candidate_items,t),confirmed_items:W(n.confirmed_items,t),resolved_false_positive_items:W(n.resolved_false_positive_items,t)},counts:e.counts,drifted_items:W(e.drifted_items,t),merge_receipt_attributed_items:W(e.merge_receipt_attributed_items,t),missing_streams:W(e.missing_streams,t),unreadable_streams:W(e.unreadable_streams,t),hash_mismatches:W(e.hash_mismatches,t),chain_mismatches:W(e.chain_mismatches,t),version_skews:W(e.version_skews,t),workspace_state_mismatches:W(e.workspace_state_mismatches,t),workspace_state_missing:W(e.workspace_state_missing,t),workspace_state_unreadable:W(e.workspace_state_unreadable,t),skipped:e.skipped}},vectorization:(e,t)=>({semantic_runtime_available:e.semantic_runtime_available,compatibility_mode_auto_defaults:e.compatibility_mode_auto_defaults,auto_ollama_defaults_applied:e.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:e.auto_ollama_defaults_skipped_reason,auto_ollama_defaults_remediation:e.auto_ollama_defaults_remediation,refresh_policy:e.refresh_policy,provider_active:e.provider_active,vector_store_active:e.vector_store_active,items:e.items,ledger_entries_before:e.ledger_entries_before,stale_items_before_total:e.stale_items_before_total,stale_items_before:W(e.stale_items_before,t),refresh_attempted:e.refresh_attempted,refresh_skipped_reason:e.refresh_skipped_reason,refresh_result:e.refresh_result,ledger_entries_after:e.ledger_entries_after,stale_items_after_total:e.stale_items_after_total,stale_items_after:W(e.stale_items_after,t),skipped:e.skipped})};function Wo(e,t){let n=pT[e.name];return n?n(e.details,t):e.details}function kg(e){return{disabled_by_flag:e.details.disabled_by_flag,loaded_count:Array.isArray(e.details.loaded)?e.details.loaded.length:0,failed_count:0,warning_count:0,restore_with:"pm health --full"}}function fT(e){if(e.name==="extensions"&&e.status==="ok")return kg(e);let t=Wo(e,8);return Buffer.byteLength(JSON.stringify(t))<Buffer.byteLength(JSON.stringify(e.details))?t:e.details}function Bo(e,t){let n=new Set([...t,...e.failed_because]);return(e.findings??[]).filter(i=>n.has(i.warning))}function gT(e){let t=W(e.warnings,8);return{ok:e.ok,...e.verdict?{verdict:e.verdict}:{},checks:e.checks.map(n=>({name:n.name,status:n.status,ok:n.ok,details:fT(n)})),warnings:t.sample,findings:Bo(e,t.sample),failed_because:e.failed_because,projection:{mode:"brief",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:8},generated_at:e.generated_at}}function vg(e){return e.details.skipped===!0}function hT(e){let t=W(e.warnings,8),n=e.checks.filter(vg).map(i=>i.name);return{ok:e.ok,...e.verdict?{verdict:e.verdict}:{},checks:e.checks.filter(i=>!vg(i)).map(i=>({name:i.name,status:i.status,ok:i.ok,details:{}})),warning_count:t.count,warnings:t.sample,findings:Bo(e,t.sample),failed_because:e.failed_because,projection:{mode:"summary",warning_count:t.count,warnings_truncated:t.truncated,detail_limit:8,omitted_checks:n},generated_at:e.generated_at}}function yT(e,t,n){return t.full===!0?e:n?hT(e):t.brief===!0?gT(e):{...e,checks:e.checks.map(i=>i.name==="extensions"&&i.status==="ok"?{...i,details:kg(i)}:i),projection:{mode:"standard",warning_count:e.warning_count,warnings_truncated:e.warnings_truncated===!0,detail_limit:8}}}function Ho(e,t,n){let i=e.warning_count??e.warnings.length,r=e.warnings.slice(0,100),s={...e,warning_count:i,warning_limit:100,warnings_truncated:i>100,warnings:r,findings:Bo(e,r)},a=yT(s,t,n);return{...a,warning_count:i,warning_limit:100,warnings_truncated:i>a.warnings.length,...a.projection?{projection:{...a.projection,warning_count:i,warnings_truncated:i>a.warnings.length}}:{}}}import ft from"node:fs/promises";import Ce from"node:path";import mi from"node:fs/promises";import es 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]="b5974276-3b45-5ad6-a7aa-e05a33807ee7")}catch{}})();function vT(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t,{id:i,owner:r,created_at:s,ttl_seconds:a}=n;return typeof i!="string"||typeof r!="string"||typeof s!="string"||typeof a!="number"||!Number.isFinite(a)?null:{id:i,owner:r,created_at:s,ttl_seconds:a}}function Eg(e,t,n){let i=vT(t);if(i===null)return{detail:"unparseable_json",entry:{file:e,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"}};let r=Date.parse(i.created_at);if(!Number.isFinite(r))return{detail:"invalid_timestamp",entry:{file:e,id:i.id,owner:i.owner,created_at:i.created_at,ttl_seconds:i.ttl_seconds,age_seconds:null,stale:!1,reason:"unparseable"}};let s=n-r,a=Math.floor(s/1e3),o=s>i.ttl_seconds*1e3;return{detail:o?"expired":"active",entry:{file:e,id:i.id,owner:i.owner,created_at:i.created_at,ttl_seconds:i.ttl_seconds,age_seconds:a,stale:o,reason:o?"expired":"active"}}}async function Sg(e,t){let n=t??Date.now(),i=es.join(e,"locks"),r={scanned:0,active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0},s;try{s=(await mi.readdir(i)).filter(a=>a.endsWith(".lock")).sort()}catch(a){if(q(a))return r;throw a}for(let a of s){let o;try{o=await mi.readFile(es.join(i,a),"utf8")}catch(d){if(q(d))continue;r.scanned+=1,r.unreadable_lock_count+=1;continue}r.scanned+=1;let{detail:c}=Eg(a,o,n);c==="active"?r.active_lock_count+=1:c==="expired"?r.stale_lock_count+=1:r.unparseable_lock_count+=1}return r}async function Tg(e,t){let{dryRun:n,hooks:i}=t,r=t.now??Date.now(),s=es.join(e,"locks"),a={scanned:0,removed:[],retained:[],warnings:[],entries:[]},o;try{o=(await mi.readdir(s)).filter(c=>c.endsWith(".lock")).sort()}catch(c){if(q(c))return a;throw c}for(let c of o){a.scanned+=1;let d=es.join(s,c),l=`locks/${c}`;if(i?.onRead){let g=await i.onRead(d);a.warnings.push(...g)}let u;try{u=await mi.readFile(d,"utf8")}catch(g){if(q(g)){a.scanned-=1;continue}a.warnings.push(`lock_unreadable:${c}`),a.retained.push(l),a.entries.push({file:c,id:null,owner:null,created_at:null,ttl_seconds:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let p=Eg(c,u,r);if(p.detail==="unparseable_json"){a.warnings.push(`lock_unparseable:${c}`),a.retained.push(l),a.entries.push(p.entry);continue}if(p.detail==="invalid_timestamp"){a.warnings.push(`lock_invalid_timestamp:${c}`),a.retained.push(l),a.entries.push(p.entry);continue}if(p.detail==="active"){a.retained.push(l),a.entries.push(p.entry);continue}if(!n){try{await mi.unlink(d)}catch(g){if(!q(g)){a.warnings.push(`lock_remove_failed:${c}`),a.retained.push(l),a.entries.push(p.entry);continue}}if(i?.onWrite){let g=await i.onWrite(d);a.warnings.push(...g)}}a.removed.push(l),a.entries.push(p.entry)}return 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]="270d544f-ac42-559f-ba6a-82f3d3b6c187")}catch{}})();var wT=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:"merge_driver_configuration_missing",command:"pm merge install",summary:"Install the clone-local Git drivers required by the tracker merge fence."},{code:"merge_driver_configuration_drift",command:"pm merge install",summary:"Reinstall clone-local Git drivers after runtime or package paths change."},{code:"merge_fence_missing",command:"pm merge install",summary:"Install the active tracker's committed Git merge attributes."},{code:"merge_fence_drift",command:"pm merge install",summary:"Restore the active tracker's merge mappings while retaining sibling tracker fences."},{code:"validate_merge_driver_configuration",command:"pm merge install",summary:"Restore missing or drifted clone-local Git merge driver commands."},{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 pending receipt summaries, re-apply intended discarded values, then run pm merge reconcile. If proof is unavailable or receipt decisions are lossy, explicit review authority is required for pm merge reconcile --force --message "<reviewed receipt disposition and rationale>"; this records acceptance rather than restoring discarded values.'},{code:"merge_receipts_pending",command:"pm merge reconcile",summary:'A lossless receipt is pending; preview with pm merge reconcile --dry-run, then apply. If no receipt set proves the snapshot, review the summaries and only with explicit authority run pm merge reconcile --force --message "<reviewed receipt disposition and rationale>" to record an audited acceptance.'},{code:"merge_receipt_evidence_invalid",command:"pm merge report --include-reconciled --json",summary:"One or more receipt candidates failed bounded-file, schema, identity, or copy-consistency validation; inspect the report's privacy-safe source, receipt id, and reason before repairing only the named evidence."},{code:"merge_receipt_history_reference_missing",command:"pm merge reconcile --dry-run",summary:"Review the bounded coordinates and recover available evidence first; for exact pre-durable clone-local-only references, rerun with --force so pm appends an audited disposition and proves the health finding is cleared without rewriting history."},{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_drift_version_skew",command:"npm install -g @unbrained/pm-cli@latest",summary:"A history stream declares an item hash version this runtime does not support; upgrade pm to verify the chain instead of re-anchoring it."},{code:"history_drift_merge_receipt",command:"pm merge reconcile",summary:"Canonical path, changed-field, and merged-value hash evidence attributes this drift to a pending receipt; run reconciliation (optionally preview first with --dry-run) instead of repairing history directly."},{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:"provenance_value_domain_invalid",command:"pm history-repair --all --normalize-provenance",summary:"Remove invalid bounded provenance observations from affected streams and append privacy-safe aggregate repair receipts."},{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_closed_at",command:"pm validate --check-metadata --auto-fix --fix-scope timestamps --dry-run",summary:"Preview closure dates proven by verified lifecycle history; inspect residuals and omit --dry-run to apply only proven dates."},{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_history_drift_version_skews",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more history streams declare an item hash version this runtime does not support; upgrade pm to verify the chains instead of re-anchoring them."},{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 Vo(e){if(typeof e!="string")return;let t=e.trim();for(let n of wT)if(t===n.code||t.startsWith(`${n.code}:`))return n}function Yo(e){let t={};for(let n of e){let i=Vo(n);i!==void 0&&!Object.prototype.hasOwnProperty.call(t,i.code)&&(t[i.code]=i.command)}return t}function Ag(e){return Object.values(Yo(e))}import{execFile as bT}from"node:child_process";import{realpath as kT}from"node:fs/promises";import Ig from"node:path";import{promisify as ET}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]="9af87d55-dbe2-561b-9f3f-6f12c0416147")}catch{}})();var ST=ET(bT),TT=32*1024*1024,AT=1e4,IT=["search/eval-queries.json"];function Jo(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}function CT(e){return`'${e.replaceAll("'","'\\''")}'`}async function xT(e,t=kT){return t(e).catch(()=>Ig.resolve(e))}async function ts(e){let t=await Tt(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 xT(e),i=Jo(Ig.relative(t,n));if(i.length===0)return{git_workspace_root:t,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let r=Z_.map(s=>`${i}/${Jo(s)}`);try{let{stdout:s}=await ST("git",["ls-files","-z","--",...r.map(d=>`:(literal)${d}`)],{cwd:t,encoding:"utf8",maxBuffer:TT,windowsHide:!0,timeout:AT}),a=new Set(IT.map(d=>`${i}/${d}`)),o=[...new Set(s.split("\0").filter(d=>d.length>0&&!a.has(Jo(d))))].sort((d,l)=>d.localeCompare(l)),c=r.filter(d=>o.some(l=>l===d||l.startsWith(`${d}/`)));return{git_workspace_root:t,tracker_relative_root:i,tracked_paths:o,tracked_path_count:o.length,remediation_command:o.length===0?null:`git rm --cached -r -- ${c.map(d=>CT(`:(literal)${d}`)).join(" ")}`}}catch{return{git_workspace_root:t,tracker_relative_root:i,tracked_paths:[],tracked_path_count:0,remediation_command:null}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2e510b32-f27f-5ba5-94b2-8268343359dc")}catch{}})();async function Cg(e,t,n,i){if(t===null)return{audit:null,count:0,warnings:[]};let r=await ln(e,dn(n));if(r.status==="ok")return{audit:r,count:0,warnings:[]};let s=Math.max(1,r.missing_patterns.length+r.stale_patterns.length);return{audit:r,count:s,warnings:i?[`merge_fence_${r.status==="not_installed"?"missing":"drift"}:${s}`]:[]}}function xg(e){let t=[];return e.invalidEvidenceCount>0&&t.push(`merge_receipt_evidence_invalid:${e.invalidEvidenceCount}`),e.missingHistoryReferenceCount>0&&t.push(`merge_receipt_history_reference_missing:${e.missingHistoryReferenceCount}`),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]="688b552b-3d10-521e-b695-b3edfbfed36e")}catch{}})();var RT=new Set(k_),Rg=25,OT=Ce.join("runtime","telemetry","events.jsonl"),LT=Ce.join("runtime","telemetry","state.json"),DT=2500,NT=500,Og=A_-3,MT=["x-pm-telemetry-max-schema-version","x-pm-telemetry-max-version"];function nc(e,t=!1){return e.startsWith("agent_guidance_")||e.startsWith("telemetry_")||e.startsWith("history_stream_over_compact_threshold:")||e.startsWith("integrity_legacy_hierarchy_")||e.startsWith("stale_in_progress_items:")||e.startsWith("provenance_resolver_zero_success:")||e.startsWith("provenance_value_domain_invalid:")||!t&&e.startsWith("merge_driver_configuration_missing:")}function ic(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function wn(e){return e.trim().toLowerCase()}function Zo(e,t){let n=wn(e),i=wn(t);return n.startsWith("builtin-")?!0:i==="beads"||i==="todos"}async function rc(e){try{return(await ft.stat(e)).isDirectory()}catch{return!1}}async function PT(e){let t=(await ft.readdir(e,{withFileTypes:!0})).filter(i=>i.isDirectory()),n=await Promise.all(t.map(i=>ft.readdir(Ce.join(e,i.name),{withFileTypes:!0})));return new Set(n.flatMap(i=>i.filter(r=>r.isFile()).filter(r=>Dt.some(s=>r.name.endsWith(s))).map(r=>Ce.parse(r.name).name)))}async function FT(e,t,n,i){let r=await $e({path:e,scope:"project"}),s=t!=="_workspace"&&!i.has(t);if(!n.enabled&&!s)return{warnings:r,overThreshold:!1,classification:"live"};let a;try{a=await ft.readFile(e,"utf8")}catch{return{warnings:r,overThreshold:!1,classification:"unreadable"}}let o="live";if(s){let d=a.split(/\r?\n/).map(l=>l.trim()).filter(Boolean).at(-1);try{o=JSON.parse(d??"{}").op==="delete"?"tombstone":"orphaned"}catch{o="orphaned"}}let c=n.enabled?a.split(/\r?\n/).filter(d=>d.trim().length>0).length:0;return{warnings:r,overThreshold:n.enabled&&c>n.max_entries,classification:o}}async function $T(e,t,n){let i=Ce.join(e,"history");if(!await rc(i))return{count:0,warnings:[],over_threshold:[],max_entries:null,tombstones:[],orphaned:[]};let r=(await ft.readdir(i)).filter(l=>l.endsWith(".jsonl")).sort((l,u)=>l.localeCompare(u)),s=t.enabled?t.max_entries:null,a=[],o=[],c=[],d=[];for(let l of r){let u=Ce.join(i,l),p=l.slice(0,-6),g=await FT(u,p,t,n);a.push(...g.warnings),g.classification==="tombstone"&&c.push(p),g.classification==="orphaned"&&d.push(p),g.overThreshold&&o.push(p)}return{count:r.length,warnings:[...a,...o.map(l=>`history_stream_over_compact_threshold:${l}`),...d.map(l=>`history_orphaned_stream:${l}`)],over_threshold:o,max_entries:s,tombstones:c,orphaned:d}}function ec(e,t){return Ce.relative(e,t).replaceAll("\\","/")}async function Lg(e,t){let n=[...new Set(Object.values(t))].sort((r,s)=>r.localeCompare(s)),i=[];for(let r of n){let s=Ce.join(e,r),a=[];try{a=await ft.readdir(s)}catch(o){if(typeof o=="object"&&o!==null&&"code"in o&&q(o))continue;continue}for(let o of a)Dt.some(c=>o.toLowerCase().endsWith(c))&&i.push(Ce.join(s,o))}return i.sort((r,s)=>ec(e,r).localeCompare(ec(e,s))),i}function UT(e){return!(typeof e=="object"&&e!==null&&"code"in e&&q(e))}async function jT(e,t,n){let i=await Lg(e,t),r=[],s=[],a=[],o=[],c=Et(P());for(let d of i){let l=ec(e,d),u;try{u=await ft.readFile(d,"utf8")}catch{r.push(l);continue}let p=rn(u);if(p){s.push({path:l,...p});continue}try{let g=tr(u,{format:yl(d),schema:n,extensionFieldNames:c});o.push({ref:l,version:Zi(g.metadata)})}catch{a.push(l)}}return{paths:i,unreadable:r,conflictMarkers:s,parseFailures:a,formatVersions:o}}async function GT(e){let t=Ce.join(e,"history"),n=[],i=[],r=[],s=[],a=[],o=[];try{o=(await ft.readdir(t)).filter(c=>c.endsWith(".jsonl")).sort((c,d)=>c.localeCompare(d))}catch(c){UT(c)&&n.push("history")}for(let c of o){let d=c.slice(0,-6),l;try{l=await ft.readFile(Ce.join(t,c),"utf8")}catch{n.push(d);continue}let u=rn(l);if(u){i.push({id:d,...u});continue}l.split(/\r?\n/).forEach((p,g)=>{if(p.trim())try{let f=JSON.parse(p);s.push(...gg(f,d).map(h=>({itemId:d,line:g+1,...h}))),a.push(...hg(f,d,g+1))}catch{r.push({id:d,line:g+1})}})}return{files:o,unreadable:n,conflictMarkers:i,invalidJson:r,mergeReceiptReferences:s,mergeReceiptDispositions:a}}function Dg(e){return[...e.cycles.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_cycle:${t.item_ids.join(",")}`:`integrity_hierarchy_cycle:${t.item_ids.join(",")}`),...e.cardinality_violations.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_cardinality:${t.child_id}`:`integrity_hierarchy_cardinality:${t.child_id}`),...e.divergences.map(t=>t.legacy_terminal?`integrity_legacy_hierarchy_divergence:${t.child_id}`:`integrity_hierarchy_divergence:${t.child_id}`)]}async function qT(e,t,n,i,r,s){let a=await jT(e,t,n),o=await GT(e),c=er(a.formatVersions,$n,Qi),d=K(n),l=Cr(s,A=>_e(A,d),ae()),u=await ts(e),p=await Tt(e),g=await Cg(e,p,i,r),f=p===null?null:await un(p),h=await mn(p??e,{includeReconciled:!0,includeLossless:!0,pmRoot:e}),y=new Set(h.durable_receipt_ids),v=yg(o.mergeReceiptReferences,y,o.mergeReceiptDispositions),w=v.missing,k=h.receipts.filter(A=>A.state==="pending"),{pendingDecisions:S,lossless:T}=_n(k),C=f?.status==="missing"&&f.missing_keys.length===5&&f.drifted_keys.length===0,b=[...a.unreadable.map(A=>`integrity_item_unreadable:${A}`),...a.conflictMarkers.map(A=>`integrity_item_conflict_marker:${A.path}:L${A.line}`),...a.parseFailures.map(A=>`integrity_item_parse_failed:${A}`),...o.unreadable.map(A=>`integrity_history_unreadable:${A}`),...o.conflictMarkers.map(A=>`integrity_history_conflict_marker:${A.id}:L${A.line}`),...o.invalidJson.map(A=>`integrity_history_invalid_json:${A.id}:L${A.line}`),...c.outdated.map(A=>`integrity_item_outdated_format_version:${A}`),...c.ahead.map(A=>`integrity_item_ahead_format_version:${A}`),...Dg(l),...u.tracked_path_count>0?[`tracked_runtime_cache_files:${u.tracked_path_count}`]:[],...f!==null&&f.status!=="ok"?[`merge_driver_configuration_${C?"missing":"drift"}:${f.missing_keys.length+f.drifted_keys.length}`]:[],...g.warnings,...S.length>0?[`merge_decisions_unreviewed:${S.length}`]:[],...T.length>0?[`merge_receipts_pending:${T.length}`]:[],...xg({invalidEvidenceCount:h.invalid_evidence_count,missingHistoryReferenceCount:w.length})],E=[...new Set(b)].sort((A,R)=>A.localeCompare(R)),N=E.filter(A=>!A.startsWith("integrity_legacy_hierarchy_"));return{check:{name:"integrity",status:N.length===0?"ok":"warn",ok:N.length===0,details:{checked_item_files:a.paths.length,checked_history_streams:o.files.length,counts:{item_unreadable:a.unreadable.length,item_conflict_markers:a.conflictMarkers.length,item_parse_failures:a.parseFailures.length,history_unreadable:o.unreadable.length,history_conflict_markers:o.conflictMarkers.length,history_invalid_json:o.invalidJson.length,item_outdated_format_version:c.outdated.length,item_ahead_format_version:c.ahead.length,hierarchy_cycles:l.cycles.length,hierarchy_cardinality_violations:l.cardinality_violations.length,hierarchy_parent_divergences:l.divergences.length,tracked_runtime_cache_files:u.tracked_path_count,merge_driver_configuration:f===null||f.status==="ok"?0:f.missing_keys.length+f.drifted_keys.length,merge_fence:g.count,pending_merge_decisions:S.length,lossless_merge_receipts:T.length,invalid_merge_receipt_evidence:h.invalid_evidence_count,missing_merge_receipt_history_references:w.length,accepted_legacy_merge_receipt_references:v.acceptedLegacyCount,accepted_missing_merge_receipt_dispositions:v.acceptedDispositionCount},item_unreadable:a.unreadable,item_conflict_markers:a.conflictMarkers,item_parse_failures:a.parseFailures,item_outdated_format_version:c.outdated,item_ahead_format_version:c.ahead,hierarchy_integrity:{...l,relations:ze(l.relations,wg)},history_unreadable:o.unreadable,history_conflict_markers:o.conflictMarkers,history_invalid_json:o.invalidJson,tracked_runtime_cache:{tracker_relative_root:u.tracker_relative_root,tracked_paths:u.tracked_paths,tracked_path_count:u.tracked_path_count,remediation_command:u.remediation_command},merge_driver_configuration:f===null?null:{...f,required:r},merge_fence:g.audit,pending_merge_decision_items:[...new Set(S.map(A=>A.item_id))].sort((A,R)=>A.localeCompare(R)),lossless_merge_receipt_items:[...new Set(T.map(A=>A.item_id))].sort((A,R)=>A.localeCompare(R)),invalid_merge_receipt_evidence_details:h.invalid_evidence,invalid_merge_receipt_evidence_details_truncated:h.invalid_evidence_truncated,missing_merge_receipt_history_reference_details:w.slice(0,zo),missing_merge_receipt_history_reference_details_truncated:w.length>zo}},warnings:E,gitWorkspaceRoot:p,pendingMergeReceipts:k}}function KT(e){if(typeof e.activate=="function")return!0;let t=e.default;return typeof t!="object"||t===null?!1:typeof t.activate=="function"}function zT(e){let t={layer:e.layer,directory:e.directory,manifest_path:e.manifest_path,name:e.name,version:e.version,entry:e.entry,priority:e.priority,entry_path:e.entry_path,has_activate:KT(e.module)};return Array.isArray(e.capabilities)&&(t.capabilities=[...e.capabilities]),t}function WT(e,t){return ne(e.id)||`migration-${String(t+1).padStart(3,"0")}`}function BT(e){let t=ne(e.status)?.toLowerCase();return t==="failed"?"failed":t==="applied"?"applied":"pending"}function HT(e){return ne(e.reason)??ne(e.error)??ne(e.message)}function Xo(e,t){let n=(e.layer??"").localeCompare(t.layer??"");if(n!==0)return n;let i=(e.name??"").localeCompare(t.name??"");return i!==0?i:(e.id??"").localeCompare(t.id??"")}function VT(e){let t=[],n=[],i=[];e.forEach((s,a)=>{let o=WT(s.definition,a),c=BT(s.definition);if(c==="applied"){t.push({layer:s.layer,name:s.name,id:o,status:c});return}if(c==="failed"){i.push({layer:s.layer,name:s.name,id:o,status:c,reason:HT(s.definition)});return}n.push({layer:s.layer,name:s.name,id:o,status:c})}),t.sort(Xo),n.sort(Xo),i.sort(Xo);let r=[...i.map(s=>`extension_migration_failed:${s.layer}:${s.name}:${s.id}`),...n.map(s=>`extension_migration_pending:${s.layer}:${s.name}:${s.id}`)];return{summary:{applied:t,pending:n,failed:i,applied_count:t.length,pending_count:n.length,failed_count:i.length},warnings:r}}function Ng(e,t,n,i,r,s,a,o,c){let d=[...new Set(e)].sort((y,v)=>y.localeCompare(v)),l=[...new Set(d.map(y=>ic(y)))].sort((y,v)=>y.localeCompare(v)),u=d.filter(y=>y.startsWith("extension_capability_unknown:")).length,p=c.length>0,g=p?"partial":"full",f=[],h=np(d,{deactivate:"pm extension --deactivate <name> --project/--global",doctor:"pm extension --doctor --project/--global --detail deep --trace"});return h&&f.push(h),t>0&&f.push("Run pm extension --explore --project and pm extension --explore --global to inspect load failures."),n>0&&f.push("Review checks[name=extensions].details.activation.failed in pm health --json for activation error details."),(i.failed_count>0||i.pending_count>0)&&f.push("Resolve pending/failed extension migrations before write commands; use --force only when policy allows."),r>0&&f.push("Run pm extension --manage --project and pm extension --manage --global to refresh managed-state diagnostics."),u>0&&f.push(`Unknown extension capabilities detected. Allowed capabilities: ${el.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`),d.some(y=>y.startsWith("extension_capability_legacy_alias:"))&&f.push("Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema)."),d.some(y=>y.startsWith("extension_command_definition_legacy_handler_alias:"))&&f.push("Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."),p?f.push("Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via pm extension --manage --project/--global --fix-managed-state, pm extension --adopt-all --project/--global, or pm extension --adopt <name>."):a.length>0&&f.push("Loaded unmanaged extensions are currently treated as informational. Use pm extension --manage --project/--global --fix-managed-state to adopt them for update checks."),f.length===0&&f.push("No immediate action required. Re-run pm health after extension configuration changes."),{status:d.length===0?"ok":"warn",warning_count:d.length,warning_codes:l,load_failure_count:t,activation_failure_count:n,migration_failed_count:i.failed_count,migration_pending_count:i.pending_count,managed_state_warning_count:r,managed_extension_entries_count:s,unmanaged_loaded_extension_count:a.length,unmanaged_loaded_extensions:a,unmanaged_expected_extension_count:o.length,unmanaged_expected_extensions:o,unmanaged_action_required_extension_count:c.length,unmanaged_action_required_extensions:c,update_health_coverage:g,update_health_partial:p,unknown_capability_count:u,top_warnings:d.slice(0,8),remediation:f}}async function YT(e,t,n){let i=await ip(Xe(e)),r=await Vi({pmRoot:e,settings:t,cwd:process.cwd(),noExtensions:n}),s=r.loaded.map(b=>zT(b)),a=await ug(r.loaded,Xe(e)),o=await Yi({...r,loaded:r.loaded}),[c,d]=await Promise.all([uo(r.roots.project),uo(r.roots.global)]);await Iu(e,o.registrations.migrations);let l=VT(o.registrations.migrations),u={failed:o.failed,warnings:o.warnings,hook_counts:o.hook_counts,command_override_count:o.command_override_count,command_handler_count:o.command_handler_count,parser_override_count:o.parser_override_count,preflight_override_count:o.preflight_override_count,service_override_count:o.service_override_count,renderer_override_count:o.renderer_override_count,registration_counts:o.registration_counts,registrations:o.registrations,migration_status:l.summary,managed_extensions:{project:{path:c.path,count:c.state.entries.length,entries:c.state.entries},global:{path:d.path,count:d.state.entries.length,entries:d.state.entries}}},p=new Set(c.state.entries.map(b=>wn(b.name))),g=new Set(d.state.entries.map(b=>wn(b.name))),f=[...new Map(r.loaded.filter(b=>!(b.layer==="project"?p:g).has(wn(b.name))).map(b=>[`${b.layer}:${b.name}`,{layer:b.layer,name:b.name,directory:b.directory}])).values()].sort((b,E)=>{let N=`${b.layer}:${b.name}`,A=`${E.layer}:${E.name}`;return N.localeCompare(A)}),h=f.map(b=>`${b.layer}:${b.name}`).sort((b,E)=>b.localeCompare(E)),y=f.filter(b=>Zo(b.name,b.directory)).map(b=>`${b.layer}:${b.name}`).sort((b,E)=>b.localeCompare(E)),v=f.filter(b=>!Zo(b.name,b.directory)).map(b=>`${b.layer}:${b.name}`).sort((b,E)=>b.localeCompare(E)),w=v.length>0?[`extension_update_health_partial_coverage:skipped_unmanaged:${v.length}`]:[],k=[...i.warnings,...r.warnings,...u.warnings,...l.warnings,...c.warnings,...d.warnings,...w,...a.warnings],S=mo(k),T=_o(),C=Ng(k,r.failed.length,o.failed.length,l.summary,c.warnings.length+d.warnings.length,c.state.entries.length+d.state.entries.length,h,y,v);return{check:{name:"extensions",status:k.length===0?"ok":"warn",ok:k.length===0,details:{...r,loaded:s,warnings:k,activation:u,author_manifest:i,triage:C,...l.summary.pending_count>0?{remediation_map:{extension_migration_pending:"pm extension migrate --project"}}:{},capability_contract:T,capability_guidance:S,host_version_census:a}},warnings:k}}function tc(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=bg(e,Rg);return{values:n.values,truncated:n.truncated,total:e.length}}function ns(e){let t=(process.env[e]??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function JT(){let e=(process.env.PM_TELEMETRY_SOURCE_CONTEXT??"").trim().toLowerCase();return RT.has(e)?e:null}function is(e){let t=e.trim();if(t.length===0)return"";try{let n=new URL(t);return n.username="",n.password="",n.search="",n.hash="",n.toString()}catch{return t}}function Mg(e){let t=0,n=0,i=0,r=0,s=0;for(let a of e.split(`
|
|
8
|
+
`)){let o=a.trim();if(o.length!==0){i+=1;try{let c=JSON.parse(o);if(typeof c=="object"&&c!==null&&typeof c.attempts=="number"&&Number.isFinite(c.attempts)){let d=Math.max(0,Math.trunc(c.attempts));t+=1,s=Math.max(s,d),d>=Og&&(r+=1)}else n+=1}catch{n+=1}}}return{validEntries:t,invalidRows:n,totalRows:i,highRetryEntries:r,maxAttempts:s}}function XT(){return{validEntries:0,invalidRows:0,totalRows:0,highRetryEntries:0,maxAttempts:0}}function QT(e){if(!e||e.trim().length===0)return{runtimeState:{},stateParseFailed:!1};try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)?{runtimeState:t,stateParseFailed:!1}:{runtimeState:{},stateParseFailed:!0}}catch{return{runtimeState:{},stateParseFailed:!0}}}async function ZT(e,t){let n=e.telemetry.endpoint.trim();return!t||!e.telemetry.enabled||n.length===0||$t().telemetry_disabled?void 0:{attempted:!0,...await Pg(n)}}function eA(e,t,n){let i=[];if(t.invalidRows>0&&i.push(`telemetry_queue_invalid_rows:${t.invalidRows}`),!e.telemetry.enabled||t.validEntries===0)return i;let r=n.last_successful_flush_at,s=n.last_failed_flush_at,a=s&&(!r||s>r),o=!r,c=t.validEntries>=NT;return(a||o||c)&&i.push(`telemetry_queue_pending:${t.validEntries}`),t.highRetryEntries>0&&i.push(`telemetry_queue_high_retries:${t.highRetryEntries}`),i}function tA(e){return!e||e.ok!==!1?[]:typeof e.status=="number"?[`telemetry_endpoint_probe_http_status:${e.status}`]:["telemetry_endpoint_probe_failed"]}function nA(e){let t=Number.parseInt(e?.max_schema_version??"",10);return e?.ok===!0&&Number.isInteger(t)&&t>T_?[`telemetry_schema_version_behind:${t}`]:[]}function iA(e,t){let n=typeof t.pending_otel_spans=="number"?t.pending_otel_spans:0,i=t.last_otel_success_at,r=t.last_otel_failure_at;return e.telemetry.enabled&&n>0&&r&&(!i||r>=i)?[`telemetry_otel_export_failing:${n}`]:[]}function rA(){return{...$t(),pm_no_telemetry:ns("PM_NO_TELEMETRY"),telemetry_otel_disabled:ns("PM_TELEMETRY_OTEL_DISABLED"),telemetry_inline_flush:ns("PM_TELEMETRY_INLINE_FLUSH"),telemetry_source_context:JT()}}function sA(e,t){return e.telemetry.enabled&&t.validEntries>0}function aA(e,t){return e&&t.every(n=>!n.startsWith("telemetry_queue_pending:")&&!n.startsWith("telemetry_queue_high_retries:"))}async function Pg(e){let t=e;try{let n=new URL(e);n.pathname="/healthz",n.search="",n.hash="",t=n.toString()}catch{}try{let n=await fetch(t,{method:"GET",signal:AbortSignal.timeout(DT)});return{probe_url:is(t),ok:n.ok,status:n.status,max_schema_version:(()=>{for(let i of MT){let r=n.headers.get(i)?.trim();if(r&&r.length>0)return r}})()}}catch(n){return{probe_url:is(t),ok:!1,error:n instanceof Error?n.message:"probe_failed"}}}async function oA(e,t){let n=qe(process.cwd()),i=Ce.join(n,OT),r=Ce.join(n,LT),s=await Q(i),a=s!==null,o=s?Buffer.byteLength(s,"utf8"):0,c=s?Mg(s):XT(),d=await Q(r),{runtimeState:l,stateParseFailed:u}=QT(d),p=e.telemetry.endpoint.trim(),g=is(p),f=await ZT(e,t.checkTelemetry),h=[];u&&h.push("telemetry_state_invalid_json"),h.push(...eA(e,c,l),...tA(f),...nA(f),...iA(e,l));let y=sA(e,c),v=typeof l.pending_otel_spans=="number"?l.pending_otel_spans:0;return{check:{name:"telemetry",status:h.length===0?"ok":"warn",ok:h.length===0,details:{enabled:e.telemetry.enabled,capture_level:e.telemetry.capture_level,endpoint:g,global_pm_root:n,queue_path:i,queue_exists:a,queue_entries:c.validEntries,queue_draining:aA(y,h),queue_invalid_rows:c.invalidRows,queue_rows_total:c.totalRows,queue_size_bytes:o,queue_high_retry_entries:c.highRetryEntries,queue_high_retry_threshold:Og,queue_max_attempts:c.maxAttempts,runtime_state_path:r,last_attempted_flush_at:l.last_attempted_flush_at??null,last_successful_flush_at:l.last_successful_flush_at??null,last_failed_flush_at:l.last_failed_flush_at??null,last_failed_flush_error:l.last_failed_flush_error??null,pending_otel_spans:v,last_otel_attempt_at:l.last_otel_attempt_at??null,last_otel_success_at:l.last_otel_success_at??null,last_otel_failure_at:l.last_otel_failure_at??null,last_otel_failure_error:l.last_otel_failure_error??null,endpoint_probe:f??{attempted:!1},env_overrides:rA()}},warnings:h}}async function cA(e){let t;try{t=await Sg(e)}catch(i){let r=i instanceof Error?i.message:String(i);return{check:{name:"locks",status:"warn",ok:!1,details:{active_lock_count:0,stale_lock_count:0,unreadable_lock_count:0,unparseable_lock_count:0,scan_failed:!0,error:r,pm_root:e}},warnings:[`locks_scan_failed:${r}`]}}let n=[];return t.stale_lock_count>0&&n.push(`locks_stale_count:${t.stale_lock_count}`),t.unreadable_lock_count>0&&n.push(`locks_unreadable:${t.unreadable_lock_count}`),{check:{name:"locks",status:n.length===0?"ok":"warn",ok:n.length===0,details:{active_lock_count:t.active_lock_count,stale_lock_count:t.stale_lock_count,unreadable_lock_count:t.unreadable_lock_count,unparseable_lock_count:t.unparseable_lock_count}},warnings:n}}async function dA(e){let t="metadata",n=e.items,i=await Yn(e.pmRoot,n,{cacheHitVerification:t}),r=[...new Set([...i.hashMismatches,...i.chainMismatches,...i.versionSkews])].sort((v,w)=>v.localeCompare(w)),s=[],a=[];if(r.length>0){n=await dt(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema,{forceSourceScan:!0}),i=await Yn(e.pmRoot,n),s=[...new Set([...i.hashMismatches,...i.chainMismatches,...i.versionSkews])].sort((w,k)=>w.localeCompare(k));let v=new Set(s);a=r.filter(w=>!v.has(w))}let{missingStreams:o,unreadableStreams:c,hashMismatches:d,chainMismatches:l,versionSkews:u,driftedItems:p,workspaceStateMismatches:g,workspaceStateMissing:f,workspaceStateUnreadable:h}=i,y=[...o.map(v=>`history_drift_missing_stream:${v}`),...c.map(v=>`history_drift_unreadable_stream:${v}`),...d.map(v=>`history_drift_hash_mismatch:${v}`),...l.map(v=>`history_drift_chain_mismatch:${v}`),...u.map(v=>`history_drift_version_skew:${v}`),...g.map(v=>`history_drift_workspace_state_mismatch:${v}`),...f.map(v=>`history_drift_workspace_state_missing:${v}`),...h.map(v=>`history_drift_workspace_state_unreadable:${v}`)];return{check:{name:"history_drift",status:y.length===0?"ok":"warn",ok:y.length===0,details:{checked_items:n.length,cache_hit_verification:r.length>0?"metadata_then_content_hash":t,cache_confirmation:{triggered:r.length>0,reason:r.length>0?"cached_corruption_candidate":null,candidate_items:r,confirmed_items:s,resolved_false_positive_items:a,authoritative_item_source:r.length>0},drifted_items:p,counts:{drifted:p.length,missing_streams:o.length,unreadable_streams:c.length,hash_mismatches:d.length,chain_mismatches:l.length,version_skews:u.length,workspace_state_mismatches:g.length,workspace_state_missing:f.length,workspace_state_unreadable:h.length},missing_streams:o,unreadable_streams:c,hash_mismatches:d,chain_mismatches:l,version_skews:u,workspace_state_mismatches:g,workspace_state_missing:f,workspace_state_unreadable:h}},warnings:y}}function lA(e,t){let n=g_(e),i=h_(n.settings),r=y_(n.settings,t),s=i.active?v_(i.active.name,i.active.model):null;return{runtimeDefaults:n,providerResolution:i,vectorStoreResolution:r,runtimeEmbeddingIdentity:s,semanticRuntimeAvailable:!!(i.active&&r.active)}}function uA(){return{refreshed:[],skipped:[],warnings:[]}}async function mA(e){return!e.refreshPolicy.enabled||!e.snapshot.semanticRuntimeAvailable||e.staleBefore.length===0?uA():b_(e.pmRoot,e.staleBefore,{settings:e.snapshot.runtimeDefaults.settings,apply_runtime_defaults:!1})}function _A(e){return e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&!!(e.ledgerBefore.embedding&&e.runtimeEmbeddingIdentity&&w_(e.ledgerBefore.embedding,e.runtimeEmbeddingIdentity))}function pA(e){let t=new Set([...e.ledgerBefore.warnings,...e.ledgerAfter.warnings]);if(e.strictVectorizationWarnings)for(let n of e.refreshResult.warnings)t.add(n);return e.embeddingIdentityChanged&&t.add("vectorization_embedding_identity_changed"),e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&e.staleAfter.length>0&&t.add(`vectorization_stale_items_remaining:${e.staleAfter.length}`),[...t].sort((n,i)=>n.localeCompare(i))}function fA(e,t,n){return e.enabled&&t&&n.length>0?null:e.enabled?t?"no_stale_items":"semantic_runtime_unavailable":"refresh_disabled"}function Fg(e,t){let n=t.providerResolution.active?.name??null,i=t.vectorStoreResolution.active?.name??null;return{provider_active:n,provider_configured:typeof e.search?.provider=="string"?e.search.provider:null,provider_source:eo(n,e.search?.provider??null),vector_store_active:i,vector_store_configured:typeof e.vector_store?.adapter=="string"?e.vector_store.adapter:null,vector_store_source:eo(i,e.vector_store?.adapter??null)}}function gA(e){return{enabled:e.enabled,check_only:e.checkOnly,no_refresh:e.noRefresh,refresh_vectors:e.refreshVectors}}function hA(e,t,n){return e.enabled&&n.length>0&&t}async function yA(e,t,n,i,r){let s=lA(t,e),a=await to(e),o=s.semanticRuntimeAvailable?fo(n,a.entries):[],c=await mA({pmRoot:e,snapshot:s,refreshPolicy:i,staleBefore:o}),d=await to(e),l=s.semanticRuntimeAvailable?fo(n,d.entries):[],u=!s.runtimeDefaults.auto_ollama_defaults_applied,p=_A({strictVectorizationWarnings:u,semanticRuntimeAvailable:s.semanticRuntimeAvailable,ledgerBefore:a,runtimeEmbeddingIdentity:s.runtimeEmbeddingIdentity}),g=pA({ledgerBefore:a,ledgerAfter:d,refreshResult:c,strictVectorizationWarnings:u,semanticRuntimeAvailable:s.semanticRuntimeAvailable,embeddingIdentityChanged:p,staleAfter:l}),f=tc(o,r),h=tc(l,r),y=hA(i,s.semanticRuntimeAvailable,o);return{check:{name:"vectorization",status:g.length===0?"ok":"warn",ok:g.length===0,details:{semantic_runtime_available:s.semanticRuntimeAvailable,compatibility_mode_auto_defaults:s.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_applied:s.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:s.runtimeDefaults.auto_ollama_defaults_skipped_reason??null,auto_ollama_defaults_remediation:s.runtimeDefaults.auto_ollama_defaults_remediation??null,refresh_policy:gA(i),...Fg(t,s),embedding_identity_changed:p,embedding_identity_before:a.embedding??null,embedding_identity_runtime:s.runtimeEmbeddingIdentity??null,items:n.length,ledger_entries_before:Object.keys(a.entries).length,stale_items_detail_mode:r?"full":"summary",stale_items_summary_limit:Rg,stale_items_before_total:f.total,stale_items_before:f.values,stale_items_before_truncated:f.truncated,refresh_attempted:y,refresh_skipped_reason:fA(i,s.semanticRuntimeAvailable,o),refresh_result:c,ledger_entries_after:Object.keys(d.entries).length,stale_items_after_total:h.total,stale_items_after:h.values,stale_items_after_truncated:h.truncated}},warnings:g}}function vA(e){let t=[];return e.id_prefix.trim().length===0&&t.push("settings:id_prefix_empty"),e.locks.ttl_seconds<=0&&t.push("settings:locks_ttl_non_positive"),t}function $g(e){let t=e.checkOnly===!0,n=e.refreshVectors===!0;if(n&&t)throw new _("--check-only cannot be combined with --refresh-vectors",m.USAGE);if(n&&e.noRefresh===!0)throw new _("--no-refresh cannot be combined with --refresh-vectors",m.USAGE);return{enabled:n,checkOnly:t,noRefresh:!n,refreshVectors:n}}var wA=new Set(["extensions","locks","search"]);function bA(e){let t=new Set(il.filter(r=>r.length>0)),n=new Set,i=new Set(Object.values(rl));for(let r of e.folders)t.has(r)&&!i.has(r)||(t.delete(r),n.add(r));for(let r of wA)t.delete(r),n.add(r);return{requiredDirs:[...t].sort((r,s)=>r.localeCompare(s)),optionalDirs:[...n].sort((r,s)=>r.localeCompare(s)),optionalDirSet:n}}async function kA(e,t,n){let{requiredDirs:i,optionalDirs:r,optionalDirSet:s}=bA(t),a=[],o=[],c=[];for(let d of[...i,...r]){let l=Ce.join(e,d);c.push(...await $e({path:l,scope:"project"})),!await rc(l)&&(s.has(d)?o.push(d):a.push(d))}return{requiredDirs:i,optionalDirs:r,missingRequiredDirs:a,missingOptionalDirs:o,missingDirs:n?[...a,...o]:[...a],hookWarnings:c}}function Ug(e){let t=e.checkOnly===!0&&e.brief!==!0&&e.summary!==!0&&e.full!==!0,n=(e.summary===!0||t)&&e.full!==!0,i=e.checkOnly===!0&&(e.brief===!0||e.summary===!0)&&e.full!==!0;return{summaryMode:n,skipIntegrity:(e.skipIntegrity===!0||i)&&e.full!==!0,skipDrift:(e.skipDrift===!0||i)&&e.full!==!0,skipVectors:(e.skipVectors===!0||i)&&e.full!==!0}}async function EA(e){return e.skipPolicy.skipDrift&&e.skipPolicy.skipVectors?Se(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema):dt(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema)}function Qo(e){return{check:{name:e,status:"ok",ok:!0,details:{skipped:!0}},warnings:[]}}function SA(e,t,n){return{name:"settings",status:n.length===0?"ok":"warn",ok:n.length===0,details:{path:e,version:t.version,id_prefix:t.id_prefix,locks_ttl_seconds:t.locks.ttl_seconds,warnings:n}}}function TA(e,t){return{name:"directories",status:e.missingDirs.length===0?"ok":"warn",ok:e.missingDirs.length===0,details:{required:e.requiredDirs,optional:e.optionalDirs,missing_required:e.missingRequiredDirs,missing_optional:e.missingOptionalDirs,missing:e.missingDirs,strict_directories:t}}}function AA(e,t){return{name:"settings_values",status:e.length===0?"ok":"warn",ok:e.length===0,details:{warnings:e,...t.roleless_status_count>0?{lifecycle_status_roles:t}:{}}}}var sc=e=>e.unknown_event_count??0,ac=e=>e.actionable_unknown_event_count??sc(e);function IA(e,t,n,i,r,s){let a=sc(i),o=ac(i),c=a>0,d=o>0,l=r.count>0;return{name:"storage",status:n.over_threshold.length===0&&n.orphaned.length===0&&!d&&!l?"ok":"warn",ok:n.over_threshold.length===0&&n.orphaned.length===0&&!d&&!l,details:{items:e.length,history_streams:n.count,tombstones:{retention_policy:"retain_append_only",gc_enabled:!1,count:n.tombstones.length,ids:n.tombstones.slice(0,25),truncated:n.tombstones.length>25},orphaned_history_streams:{count:n.orphaned.length,ids:n.orphaned.slice(0,25),truncated:n.orphaned.length>25},...c?{author_attribution:i}:{},...l?{stale_in_progress:r}:{},...s.outcomes.length>0?{provenance_resolver_outcomes:s.outcomes}:{},...s.invalid_values.length>0?{provenance_invalid_values:s.invalid_values}:{},provenance_sample:s.sample,...n.max_entries!==null?{compact_policy:{enabled:t.history.compact_policy.enabled,max_entries:n.max_entries,trigger:t.history.compact_policy.trigger,over_threshold_count:n.over_threshold.length,over_threshold:n.over_threshold}}:{}}}}function jg(e){let t=e.count===0?[]:[`stale_in_progress_items:${e.count}`];return{scan:e,warnings:t}}function CA(e){let t=[...e.directoryState.missingDirs.map(n=>`missing_directory:${n}`),...e.normalizedSettingsReadWarnings,...e.settingWarnings,...e.normalizedItemReadWarnings,...e.telemetryCheck.warnings,...e.extensionCheck.warnings,...e.historyPolicyWarnings,...e.historySummary.warnings,...e.authorAttributionWarnings,...e.staleInProgressWarnings,...e.provenanceWarnings,...e.locksCheck.warnings,...e.integrityCheck.warnings,...e.historyDriftCheck.warnings,...e.vectorizationCheck.warnings,...e.directoryState.hookWarnings];return[...new Set(t)]}function xA(e){let t=e.check.details.counts;return typeof t?.drifted=="number"?t.drifted:0}function RA(e){return{settings:e.normalizedSettingsReadWarnings,directories:e.directoryState.missingDirs.map(t=>`missing_directory:${t}`).concat(e.directoryState.hookWarnings),settings_values:e.settingWarnings,telemetry:e.telemetryCheck.warnings,extensions:e.extensionCheck.warnings,storage:[...e.historyPolicyWarnings,...e.historySummary.warnings,...e.authorAttributionWarnings,...e.staleInProgressWarnings,...e.provenanceWarnings],locks:e.locksCheck.warnings,integrity:[...e.normalizedItemReadWarnings,...e.integrityCheck.warnings],history_drift:e.historyDriftCheck.warnings,vectorization:e.vectorizationCheck.warnings}}function Gg(e){let t=new Map;for(let[i,r]of Object.entries(e.remediationSources))for(let s of r)t.has(s)||t.set(s,i);let n=new Map(e.checks.map(i=>[i.name,i]));return e.warnings.map(i=>{let r=t.get(i)??"integrity",s=Vo(i)?.code??ic(i),a=n.get(r)?.details,o=typeof a?.remediation_map=="object"&&a.remediation_map!==null?a.remediation_map:{},c=s==="agent_guidance_outdated"?"pm init --agent-guidance add":s==="agent_guidance_unreadable"?"Check AGENTS.md and CLAUDE.md read permissions and file types, then retry pm health.":o[s],d=nc(i,e.requireMergeDrivers)?"advisory":"gate_failing";return{warning:i,code:s,check:r,severity:d,...typeof c=="string"?{remediation:c}:d==="gate_failing"?{disposition:"no_safe_automatic_remediation"}:{}}})}function OA(e){if(e.check.name==="history_drift"&&e.historyDriftedCount>1)for(let t of Object.keys(e.remediationMap))t!=="history_drift_merge_receipt"&&t!=="history_drift_version_skew"&&(e.remediationMap[t]="pm history-repair --all");if(e.check.name==="storage"&&e.overThresholdCount>1)for(let t of Object.keys(e.remediationMap))e.remediationMap[t]="pm history-compact --all-streams"}function LA(e){for(let t of e.checks){let n=Yo(e.remediationSources[t.name]);OA({check:t,remediationMap:n,historyDriftedCount:e.historyDriftedCount,overThresholdCount:e.overThresholdCount}),Object.keys(n).length>0&&(t.details={...t.details,remediation_map:n})}}async function DA(e){if(e.gitWorkspaceRoot===null||e.pendingMergeReceipts.length===0)return[];let t=e.historyDriftCheck.check.details,n=Array.isArray(t.hash_mismatches)?t.hash_mismatches.filter(a=>typeof a=="string"):[],i=new Set([t.missing_streams,t.unreadable_streams,t.chain_mismatches].flatMap(a=>Array.isArray(a)?a:[])),r=new Map;for(let a of e.pendingMergeReceipts){let o=r.get(a.item_id)??[];o.push(a),r.set(a.item_id,o)}let s=[];for(let a of n){if(i.has(a))continue;let o=r.get(a);if(!(!o||o.length===0))try{await _p(a,{dryRun:!0,mergeReceiptProof:{gitWorkspaceRoot:e.gitWorkspaceRoot,receipts:o}},e.global),s.push(a)}catch{}}return[...new Set(s)].sort((a,o)=>a.localeCompare(o))}function NA(e,t){let n=new Set(t);e.warnings=[...e.warnings.filter(i=>i.startsWith("history_drift_hash_mismatch:")?!n.has(i.slice(i.indexOf(":")+1)):!0),...t.map(i=>`history_drift_merge_receipt:${i}`)].sort((i,r)=>i.localeCompare(r)),e.check.details={...e.check.details,merge_receipt_attributed_items:t}}async function qg(e,t={}){let n=x(process.cwd(),e.path);await $(n);let i=Ae(n),{settings:r,warnings:s}=await gu(n),a=[...new Set(s)],o=F(r,P()),c=t.strictDirectories===!0,d=t.strictExit===!0||t.failOnWarn===!0,l=t.requireMergeDrivers===!0||d,u=$g(t),p=await kA(n,o,c),g=vA(r),f=await oA(r,{checkTelemetry:t.checkTelemetry===!0}),h=await YT(n,r,!!e.noExtensions),y=Ug(t),v=[],w=await EA({pmRoot:n,settings:r,typeRegistry:o,skipPolicy:y,itemReadWarnings:v}),k=w,S=Qr(K(r.schema),w),T=[...(await rp({pm_root:n,cwd:process.cwd(),mode:"status",interactive:!1,settings:r}).catch(()=>({warnings:["agent_guidance_unreadable:AGENTS.md,CLAUDE.md"]}))).warnings.filter(V=>V.startsWith("agent_guidance_")),...g,...Zr(S)],C=y.skipDrift?{warnings:[]}:await rr({pmRoot:n,settings:r,itemIds:w.map(V=>V.id),commandLabel:"health"}),b=await $T(n,r.history.compact_policy,await PT(n)),E=await oi(n,20,t.verboseAuthorEvents===!0),N=ac(E),A=N>0?[`history_unknown_author_events:${N}`]:[],R=jg(await E_(n,w,{in_progress_status:r.schema.workflow.in_progress_status,threshold_hours:r.mutation_guard.stale_in_progress_hours})),G=await mp(n),pe=G.warnings,ce=await cA(n),de=y.skipIntegrity&&!l?{...Qo("integrity"),gitWorkspaceRoot:null,pendingMergeReceipts:[]}:await qT(n,o.type_to_folder,r.schema,r,l,w),ue=y.skipDrift?Qo("history_drift"):await dA({pmRoot:n,items:k,settings:r,typeRegistry:o,itemReadWarnings:v}),en=[...new Set(v)],Nn=await DA({gitWorkspaceRoot:de.gitWorkspaceRoot,pendingMergeReceipts:de.pendingMergeReceipts,historyDriftCheck:ue,global:e});NA(ue,Nn);let it=y.skipVectors?Qo("vectorization"):await yA(n,r,k,u,t.verboseStaleItems===!0),Ne=[SA(i,r,a),TA(p,c),AA(T,S),f.check,h.check,IA(w,r,b,E,R.scan,G),ce.check,de.check,ue.check,it.check],ht=CA({directoryState:p,normalizedSettingsReadWarnings:a,settingWarnings:T,normalizedItemReadWarnings:en,telemetryCheck:f,extensionCheck:h,historyPolicyWarnings:C.warnings,historySummary:b,authorAttributionWarnings:A,staleInProgressWarnings:R.warnings,provenanceWarnings:pe,locksCheck:ce,integrityCheck:de,historyDriftCheck:ue,vectorizationCheck:it}),Ee=RA({directoryState:p,normalizedSettingsReadWarnings:a,settingWarnings:T,normalizedItemReadWarnings:en,telemetryCheck:f,extensionCheck:h,historyPolicyWarnings:C.warnings,historySummary:b,authorAttributionWarnings:A,staleInProgressWarnings:R.warnings,provenanceWarnings:pe,locksCheck:ce,integrityCheck:de,historyDriftCheck:ue,vectorizationCheck:it});LA({checks:Ne,remediationSources:Ee,historyDriftedCount:xA(ue),overThresholdCount:b.over_threshold.length});let Me=ht.filter(V=>!nc(V,l)),yt=Gg({warnings:ht,checks:Ne,remediationSources:Ee,requireMergeDrivers:l}),D=new Set(yt.filter(V=>V.severity==="gate_failing").map(V=>V.check)),rt=new Set(yt.map(V=>V.check));for(let V of Ne)V.ok=!D.has(V.name),rt.has(V.name)&&(V.status="warn");let vt={ok:Me.length===0,verdict:{authority:"ok",...d?{strict_exit:!0}:{},...l?{require_merge_drivers:!0}:{},exit_code:d&&Me.length>0?m.GENERIC_FAILURE:0},checks:Ne,warnings:ht,findings:yt,failed_because:Me,generated_at:O()};return Ho(vt,t,y.summaryMode)}var aG={buildHierarchyIntegrityWarnings:Dg,buildExtensionHealthTriageSummary:Ng,buildHealthFindings:Gg,buildCapabilityContractMetadata:_o,buildStaleInProgressHealthSummary:jg,buildVectorizationProviderDetails:Fg,collectUnknownCapabilityGuidance:mo,isAdvisoryHealthWarning:nc,isDirectory:rc,isExpectedUnmanagedExtension:Zo,listItemDocumentPaths:Lg,normalizeEndpointForDisplay:is,normalizeExtensionNameForMatch:wn,parseTelemetryQueue:Mg,probeTelemetryEndpointHealth:Pg,projectHealthResult:Ho,resolveActionableUnknownAuthorEventCount:ac,resolveHealthSkipPolicy:Ug,resolveUnknownAuthorEventCount:sc,resolveVectorRefreshPolicy:$g,selectStaleItemDetail:tc,summarizeHealthCheckDetails:Wo,summarizeExtensionList:ui,summarizeRecordList:ze,summarizeStringList:W,telemetryEnvFlagEnabled:ns,warningCode:ic};(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]="a07d2f98-7c1d-5d0a-be70-5181ed0f7b4f")}catch{}})();function Kg(e,t,n){if(!n.has(t.metadata.status))return{reason:"not_terminal"};if(e.length===0)return{reason:"missing_history"};if(!Au(e,t).ok)return{reason:"unverified_history"};let i=pu(),r={reason:"no_proven_transition"};for(let[s,a]of e.entries()){let o=n.has(String(i.metadata.status));i=yu(i,a.patch,s+1,a.op),n.has(String(i.metadata.status))?o||(r=["create","close","cancel","update","update_audit"].includes(a.op)&&eu(a.ts)?{timestamp:a.ts,source_index:s+1}:{reason:"no_proven_transition"}):r={reason:"no_proven_transition"}}return r}function zg(e){return new Set([...e.terminal_statuses,...[...e.alias_to_id].filter(([,t])=>e.terminal_statuses.has(t)).map(([t])=>t)])}async function Wg(e,t,n,i,r){let s=zg(n),a=t.filter(d=>s.has(d.status)&&!d.closed_at),o=[],c=[];for(let d of i?a:[]){let l;try{let u=await ct(at(e,d.id),d.id),{body:p,...g}=d;l=Kg(u,{metadata:g,body:p},s)}catch{c.push({id:d.id,reason:"unreadable_history"});continue}if("reason"in l){c.push({id:d.id,reason:l.reason});continue}o.push({item_id:d.id,check:"metadata",field:"closed_at",kind:"set_closed_at",value:l.timestamp,gate:"timestamps",command:"pm validate --check-metadata --auto-fix --fix-scope timestamps"})}return{details:{missing_closed_at_count:a.length,missing_closed_at_item_ids:a.slice(0,r).map(d=>d.id),missing_closed_at_item_ids_truncated:a.length>r,closure_history_inspected:i,closure_timestamp_derivable_count:o.length,closure_timestamp_residual_count:c.length,closure_timestamp_residual:c.slice(0,r),closure_timestamp_residual_truncated:c.length>r,...a.length>0?{closure_timestamp_fix_hint:"pm validate --check-metadata --auto-fix --fix-scope timestamps --dry-run"}:{}},fixes:o,warnings:a.length>0?[`validate_metadata_missing_closed_at:${a.length}`]:[]}}async function Bg(e,t){let n=x(process.cwd(),t.path),i=await I(n),r=K(i.schema);await se({pmRoot:n,settings:i,id:e.item_id,op:"update",author:U(t.author,i.author_default),message:"Backfill closed_at from verified lifecycle history",skipNoop:!0,async mutate(s){if(s.metadata.closed_at)return{changedFields:[]};let a=await ct(at(n,s.metadata.id),s.metadata.id),o=zg(r),c=Kg(a,s,o);if(!("timestamp"in c)||c.timestamp!==e.value)throw new _("Closure timestamp evidence changed or cannot be verified; rerun the timestamp repair preview.",m.GENERIC_FAILURE);return s.metadata.closed_at=c.timestamp,{changedFields:["closed_at"]}}})}(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]="34d28b31-b098-5ffd-b39b-2e11de150ac1")}catch{}})();function MA(e,t){return e==="malformed"||t==="malformed"?"malformed":e==="moved"||t==="moved"?"moved":"deleted"}function Hg(e){return`${e.item_id} ${e.link_kind}`}function Vg(e,t){let n=new Map;for(let i of e){let r=n.get(i.path);r?(r.classification=MA(r.classification,i.classification),r.owners.set(Hg(i),i)):n.set(i.path,{classification:i.classification,owners:new Map([[Hg(i),i]])})}return[...n.entries()].sort(([i],[r])=>i.localeCompare(r)).map(([i,r])=>({path:i,classification:r.classification,items:[...r.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(){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]="00f8052d-480b-5e38-86cf-4574a8ad1e92")}catch{}})();function Yg(e,t,n,i,r=40){let s=r===1/0?1/0:Number.isFinite(r)?Math.max(0,Math.floor(r)):40,a=new Map(t.map(d=>[d.path,d])),o={missing_linked_path_rows_count:0,missing_linked_path_rows:[],missing_linked_path_rows_truncated:!1,missing_linked_links_count:0,active_missing_linked_links_count:0,legacy_closed_missing_linked_links_count:0,legacy_terminal_missing_linked_links_count:0,active_missing_linked_paths_count:0},c=Vg(e,n).map(d=>{let l=[],u=[];for(let g of d.items){let f=me(g.status,i)??g.status;i.terminal_statuses.has(f)?(u.push(g),f===i.close_status&&(o.legacy_closed_missing_linked_links_count+=1)):l.push(g)}o.missing_linked_links_count+=d.items.length,o.active_missing_linked_links_count+=l.length,o.legacy_terminal_missing_linked_links_count+=u.length,l.length>0&&(o.active_missing_linked_paths_count+=1);let p=a.get(d.path);return{...d,candidates:p?.candidates??[],candidates_truncated:p?.candidates_truncated??!1,link_count:d.items.length,active_link_count:l.length,items:[...l,...u].slice(0,s),items_truncated:d.items.length>s}});return c.sort((d,l)=>+(l.active_link_count>0)-+(d.active_link_count>0)||d.path.localeCompare(l.path)),o.missing_linked_path_rows_count=c.length,o.missing_linked_path_rows=c.slice(0,s),o.missing_linked_path_rows_truncated=c.length>s,o}import bn from"node:fs/promises";import kn 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]="7ff2e182-d84c-5e1c-8b63-daea17d55af4")}catch{}})();async function PA(e,t){let n=[...new Set(Object.values(t))],i=[];return await Promise.all(n.map(async r=>{let s;try{s=await bn.readdir(kn.join(e,r))}catch{return}for(let a of s)for(let o of Dt)if(a.toLowerCase().endsWith(o)){i.push({relativePath:`${r}/${a}`,id:a.slice(0,-o.length)});break}})),i.sort((r,s)=>r.relativePath.localeCompare(s.relativePath))}function FA(e,t){let{id:n,relativePath:i,liveItemIds:r,out:s}=e,a=rn(t);if(a){s.conflictMarkers.push({id:n,path:i,line:a.line,detail:`unresolved merge conflict marker ${a.marker}`});return}let o=$A(e,t);o!==null&&(o.op==="delete"&&r.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 $A(e,t){let{id:n,relativePath:i,out:r}=e,s=null,a=!1,o=t.split(/\r?\n/).map((c,d)=>({content:c.trim(),number:d+1})).filter(c=>c.content.length>0);for(let c of o){try{let d=JSON.parse(c.content);if(typeof d!="object"||d===null||Array.isArray(d))throw new TypeError("history entry must be an object");s=d}catch{return r.unparseable.push({id:n,path:i,line:c.number,detail:"history line is not a valid JSON object"}),null}if(s.op==="create"){if(a)return r.unparseable.push({id:n,path:i,line:c.number,detail:"duplicate item identity: more than one create event in one history stream"}),null;a=!0}}return s}function oc(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 UA(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},i;try{i=await bn.readdir(kn.join(e,"history"))}catch{return n}for(let r of i.sort((s,a)=>s.localeCompare(a))){if(!r.endsWith(".jsonl"))continue;n.scanned+=1;let s;try{s=await bn.readFile(kn.join(e,"history",r),"utf8")}catch(a){n.unparseable.push({id:r.slice(0,-6),path:`history/${r}`,detail:oc("history stream",a)});continue}FA({id:r.slice(0,-6),relativePath:`history/${r}`,liveItemIds:t,out:n},s)}return n}function Jg(e){let t=rn(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 jA(e){let t=[],n=0,i=null;try{i=await Q(Ae(e))}catch(s){n+=1,t.push({path:"settings.json",detail:oc("configuration file",s)})}if(i!==null){n+=1;let s=Jg(i);s!==null&&t.push({path:"settings.json",detail:s})}let r;try{r=await bn.readdir(kn.join(e,"schema"))}catch{return{scanned:n,unparseable:t}}for(let s of r.sort((a,o)=>a.localeCompare(o))){if(!s.endsWith(".json"))continue;n+=1;let a;try{a=await bn.readFile(kn.join(e,"schema",s),"utf8")}catch(c){t.push({path:`schema/${s}`,detail:oc("configuration file",c)});continue}let o=Jg(a);o!==null&&t.push({path:`schema/${s}`,detail:o})}return{scanned:n,unparseable:t}}async function Xg(e,t,n,i={}){let r=await PA(e,n),s=new Set(r.map(u=>u.id)),a=new Map;for(let u of r){let p=a.get(u.id);p===void 0?a.set(u.id,[u.relativePath]):p.push(u.relativePath)}let o=[...a.entries()].filter(([,u])=>u.length>1).map(([u,p])=>({id:u,paths:[...p].sort((g,f)=>g.localeCompare(f))})).sort((u,p)=>u.id.localeCompare(p.id)),c=(await Promise.all(r.map(async u=>{if(!t.has(u.id))return{path:u.relativePath,id:u.id};try{let p=kn.join(e,u.relativePath);return tr(await bn.readFile(p,"utf8"),{format:p.toLowerCase().endsWith(".md")?"json_markdown":"toon",schema:i.schema,extensionFieldNames:i.extensionFieldNames}),null}catch{return{path:u.relativePath,id:u.id}}}))).filter(u=>u!==null),d=await UA(e,s),l=await jA(e);return{item_files_on_disk:r.length,item_ids_on_disk:s.size,parsed_items:t.size,unreadable_item_files:c,duplicate_item_ids:o,history_streams_scanned:d.scanned,history_conflict_marker_streams:d.conflictMarkers,history_unparseable_streams:d.unparseable,resurrected_items:d.resurrected,history_repair_reconciliations:d.repairReconciliations,config_files_scanned:l.scanned,unparseable_config_files:l.unparseable}}import{readFileSync as GA}from"node:fs";import rs 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]="597a781e-a00d-5083-8d57-3fae870f9ccd")}catch{}})();var qA=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),cc=new Set(["--pm-path","--path","--author"]),KA={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"])},zA=new Set(["-p","--package"]),WA=new Set(["-c","--call"]),dc=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),lc=new Set(["-C","--prefix","--userconfig","--cache"]),Qg=new Set(["--cwd"]),Zg=new Set(["--cwd"]),BA=new Set(["exec","x"]),eh=new Set(["run","run-script"]),th=new Set(["-C","--dir","--cwd","-w","--workspace","--filter"]);function Gt(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function ss(e,t=process.cwd()){let n=as(e.split(" ").filter(a=>a.length>0));if(n.length===0)return null;let[i,...r]=n;if(_i(i)||pi(i,t))return r;if(i==="node"&&r[0]&&pi(r[0],t))return r.slice(1);let s=i==="npx"||i==="bunx"?qt(r):i==="pnpm"?cs(r):i==="npm"?ds(r):null;return s&&(_i(s.command)||mc(s.command))?s.args:null}var uc=(e,t="pm")=>{let n=t.trim().toLowerCase(),i=n.length;for(;i>0&&n[i-1]==="-";)i-=1;let r=n.slice(0,i);if(r.length===0)return[];let s=e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase(),a=new Set;for(let o of Gt(s)){let c=ss(o),d=c?_c(c):null,l=d&&qA.has(d.subcommand)?VA(d.remaining,KA[d.subcommand]):void 0,u=l?.trim().toLowerCase();u?.startsWith(`${r}-`)===!0&&u.length>r.length+1&&a.add(l)}return[...a].sort((o,c)=>o.localeCompare(c))};function as(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 os(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(cc.has(n)){t+=2;continue}t+=1;continue}return n}}function _i(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function HA(e){let t=e.trim();if(!t.startsWith("@")){let r=t.indexOf("@");return r===-1?t:t.slice(0,r)}let n=t.indexOf("/");if(n===-1)return t;let i=t.indexOf("@",n+1);return i===-1?t:t.slice(0,i)}function mc(e){let t=HA(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function pi(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 i=rs.resolve(t,e);try{return JSON.parse(GA(rs.join(rs.dirname(rs.dirname(i)),"package.json"),"utf8")).name==="@unbrained/pm-cli"}catch{return!1}}function qt(e){let t=0;for(;t<e.length;){let i=e[t];if(i==="--"){t+=1;break}if(!i.startsWith("-"))break;let r=/^(?:-c|--call)=(.*)$/.exec(i);if(r){let s=r[1];return s?{command:s,args:e.slice(t+1)}:null}if(WA.has(i)){t+=1;break}t+=zA.has(i)&&!i.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function It(e,t){let n=0;for(;n<e.length;){let i=e[n];if(i==="--"){n+=1;continue}if(i.startsWith("-")){if(i.includes("=")){n+=1;continue}if(t.has(i)){n+=2;continue}n+=1;continue}return{subcommand:i,args:e.slice(n+1)}}return null}function cs(e){let t=It(e,dc);return t?.subcommand!=="dlx"?null:qt(t.args)}function ds(e){let t=It(e,lc);return!t||!BA.has(t.subcommand)?null:qt(t.args)}function _c(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(cc.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function VA(e,t=new Set){for(let n=0;n<e.length;n+=1){let i=e[n];if(i==="--")return e[n+1];if(!i.startsWith("-"))return i;!i.includes("=")&&(cc.has(i)||t.has(i))&&(n+=1)}}import{execFile as JA}from"node:child_process";import{readFile as XA}from"node:fs/promises";import rh from"node:path";import{promisify as QA}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]="4025e3fb-f2f2-57f1-a981-5bbb2381fe67")}catch{}})();function ls(e){if(!(e.pm_context_mode!=="none"||e.workspace_context_mode==="isolated"||e.workspace_context_mode==="snapshot"))throw new _("pm_context_mode=none requires workspace_context_mode=isolated or snapshot so implicit tracker discovery cannot reach the source workspace.",m.USAGE,{code:"linked_test_context_invalid",required:"Set workspace_context_mode to isolated or snapshot when pm_context_mode is none.",examples:[fe(["test","<id>","--add-json",JSON.stringify({command:e.command,pm_context_mode:"none",workspace_context_mode:"isolated"})])]})}var Ge=["command","cmd","path","scope","timeout","timeout_seconds","pm_context_mode","workspace_context_mode","env_set","env_clear","shared_host_safe","assert_stdout_contains","assert_stdout_regex","assert_stderr_contains","assert_stderr_regex","assert_stdout_min_lines","assert_json_field_equals","assert_json_field_gte","note"],YA=new Set(Ge);function nh(e){return dr(e,Ge)}function us(e,t){let n={},i=[];for(let[r,s]of Object.entries(e)){let a=r.toLowerCase();if(!YA.has(a)){i.push(r);continue}if(Object.hasOwn(n,a))throw new _(`${t} provides key "${r}" more than once after case normalization`,m.USAGE);n[a]=s}if(i.length>0)throw new _(`${t} does not recognize key${i.length>1?"s":""} ${i.map(r=>`"${r}"`).join(", ")}. Allowed keys: ${Ge.join(", ")}.`,m.USAGE);if(n.cmd!==void 0){if(n.command!==void 0&&n.command.trim()!==n.cmd.trim())throw new _(`${t} command and cmd must match when both are provided`,m.USAGE);let{cmd:r,...s}=n;return{...s,command:s.command??r}}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]="8f1a3301-8938-5208-9177-72ee29f3d174")}catch{}})();var ZA=QA(JA),pc=1,eI="linked-test-trust.json";function fc(e){return rh.join(vl(e),eI)}function ih(){return{version:pc,acknowledged:{}}}async function gc(e){try{let t=JSON.parse(await XA(fc(e),"utf8"));return t.version!==pc||typeof t.acknowledged!="object"||t.acknowledged===null||Array.isArray(t.acknowledged)?ih():{version:pc,acknowledged:t.acknowledged}}catch{return ih()}}async function gi(e=process.cwd()){let t=process.env.GITHUB_HEAD_REF?.trim()||process.env.GITHUB_REF_NAME?.trim();if(t&&t!=="merge")return t;try{let{stdout:n}=await ZA("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),i=n.trim();return i.length===0?void 0:i}catch{return}}function hi(e=process.cwd()){return process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||e}function tI(e){return e===null||typeof e!="object"?!1:typeof e.author=="string"&&e.author.trim().length>0&&typeof e.created_at=="string"&&Zl(e.created_at)&&(e.source_kind==="local_mutation"||e.source_kind==="merge_union")}function fi(e,t){return{...e?{source_ref:e}:{},...t?{current_source_ref:t}:{}}}function nI(e,t,n,i){return e?.map(r=>r.command&&!r.provenance?{...r,provenance:{author:t,created_at:n,source_kind:"local_mutation",...i?{source_ref:i}:{}}}:r)}async function En(e,t,n){if(!e||e.length===0)return e;for(let r of e)ls(r);let i=hi();return nI(e,t,n,await gi(i))}function sh(e){return Il(ie({command:e.command??null,path:e.path??null,scope:e.scope,pm_context_mode:e.pm_context_mode??null,workspace_context_mode:e.workspace_context_mode??null,env_set:e.env_set??null,env_clear:e.env_clear??null,shared_host_safe:e.shared_host_safe??null,provenance:e.provenance??null,provenance_invalid:e.provenance_invalid??null}))}async function hc(e,t,n){let i=await gc(e);return ah(t,n,i)}function ah(e,t,n){let i=sh(e),r=e.provenance?.source_ref;if(e.provenance===void 0&&e.provenance_invalid!==!0)return{fingerprint:i,trusted:!0,reason:"legacy"};let s=Object.hasOwn(n.acknowledged,i);return e.provenance_invalid===!0||!tI(e.provenance)?s?{fingerprint:i,trusted:!0,reason:"acknowledged",...fi(void 0,t)}:{fingerprint:i,trusted:!1,reason:"invalid_provenance",...fi(void 0,t)}:e.provenance.source_kind==="local_mutation"&&r===void 0?{fingerprint:i,trusted:!0,reason:"local_mutation",...fi(void 0,t)}:e.provenance.source_kind==="local_mutation"&&r!==void 0&&r===t?{fingerprint:i,trusted:!0,reason:"local_source_ref",source_ref:r,current_source_ref:t}:s?{fingerprint:i,trusted:!0,reason:"acknowledged",...fi(r,t)}:{fingerprint:i,trusted:!1,reason:"foreign_source_ref",...fi(r,t)}}async function oh(e,t,n){let i=await gc(e);return t.map(r=>ah(r,n,i))}async function ch(e,t,n){let i=await gc(e),r=t.filter(s=>typeof s.command=="string"&&s.command.length>0).map(sh);for(let s of r)i.acknowledged[s]={acknowledged_at:n};return await wt(rh.dirname(fc(e))),await Oe(fc(e),`${JSON.stringify(i,null,2)}
|
|
9
|
+
`),{acknowledged:r.length,fingerprints:r}}import Oc from"node:fs/promises";import{realpathSync as mI}from"node:fs";import{execFile as _I}from"node:child_process";import xe from"node:path";import{promisify as pI}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]="8c3bbe6d-dcce-5b1a-8352-1472ab1ed6e2")}catch{}})();var iI=["metadata","resolution"],yc=["metadata","resolution","estimates","timestamps","lifecycle"],rI="completed";function vc(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function dh(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function lh(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let i=dh(n.close_reason)??rI;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:i,command:`pm update ${n.id} --resolution ${vc(i)}`,gate:"resolution"})}return t}function uh(e){let t=[];for(let n of e){let i=dh(n.resolution);i!==void 0&&t.push({item_id:n.id,check:"metadata",field:"close_reason",kind:"set_close_reason",value:i,command:`pm update ${n.id} --close-reason ${vc(i)}`,gate:"metadata"})}return t}function mh(e,t){return e.map(n=>{let i=fu(n.type,t);return{item_id:n.id,check:"metadata",field:"estimated_minutes",kind:"set_estimate",value:String(i),command:`pm update ${n.id} --estimate ${i}`,gate:"estimates"}})}function _h(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 ph(e){let t=[];for(let n of e){if(n.classification!=="deleted")continue;let i=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 ${i} ${n.item_id} --remove ${vc(n.path)}`})}return t}function fh(e){let t=(e??[]).flatMap(i=>i.split(",")).map(i=>i.trim()).filter(i=>i.length>0);if(t.length===0){if(e!==void 0&&e.length>0)throw new _(`--fix-scope values must not be empty. Supported values: ${yc.join(", ")}.`,m.USAGE);return new Set(iI)}let n=new Set;for(let i of t){let r=i.toLowerCase().replaceAll("-","_");if(yc.includes(r)){n.add(r);continue}throw new _(`Unknown --fix-scope value "${i}". Supported values: ${yc.join(", ")}.`,m.USAGE)}return n}function gh(e,t){let n=[],i=[];for(let r of e)r.gate!==void 0&&!t.has(r.gate)?i.push(r):n.push(r);return{applicable:n,gated:i}}function yi(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]="e93db1eb-e524-58bf-af2e-cb5f22f3047b")}catch{}})();var sI=/^([A-Z][A-Z0-9]*-\d+)\b/iu;function aI(e,t={}){if(typeof e!="string")return null;let n=e.trim();if(n.length===0)return null;let i=sI.exec(n);if(!i)return null;let r=i[1],s=r.toUpperCase(),a=r.slice(0,r.lastIndexOf("-")),o=new Set((t.configuredPrefixes??[]).map(u=>u.trim().replace(/-+$/u,"").toUpperCase())),c=n.slice(r.length),d=t.evidenceText?.toUpperCase()??"",l=d.includes(`ISSUE CODE: ${s}`)||d.includes(`ISSUE CODE \`${s}\``)||d.includes(`\`${s}\``)||d.includes(`[${s}]`);return a===a.toUpperCase()||/^\s*(?::|—|–|\])/u.test(c)||o.has(a.toUpperCase())||l?s:null}function hh(e){return typeof e=="string"&&e.trim().length>0}function oI(e){let t=new Set(e.map(a=>a.id.toLowerCase())),n=new Map,i=new Map;for(let a of e){let o=a.id.toLowerCase(),c=new Set([...a.parent===null?[]:[a.parent.toLowerCase()],...a.derivations].filter(d=>d!==o&&t.has(d)));n.set(o,c);for(let d of c){let l=i.get(d)??[];l.push(o),i.set(d,l)}}let r=[...[...n].filter(([,a])=>a.size===0).map(([a])=>a)],s=new Set;for(let a=0;a<r.length;a+=1)for(let o of i.get(r[a])??[]){let c=n.get(o);c.delete(r[a]),c.size===0&&(s.add(o),r.push(o))}return e.filter(a=>!s.has(a.id.toLowerCase()))}function yh(e,t={}){let n=new Map;for(let r of e){if(typeof r.title!="string"||hh(r.duplicate_of))continue;let s=aI(r.title,{...t,evidenceText:r.body});if(s===null)continue;let a=n.get(s);a||(a=[],n.set(s,a)),a.some(o=>o.id===r.id)||a.push({id:r.id,title:r.title,parent:hh(r.parent)?r.parent.trim():null,derivations:(r.dependencies??[]).filter(o=>["discovered_from","supersedes","incident_from"].includes(o.kind)).map(o=>o.id.trim().toLowerCase()).filter(o=>o!==r.id.toLowerCase())})}let i=[];for(let[r,s]of n){if(s.length<2)continue;let a=oI(s);if(a.length<2)continue;let o=[...a].sort((c,d)=>c.id.localeCompare(d.id));i.push({code:r,count:o.length,ids:o.map(c=>c.id),titles:o.map(c=>c.title)})}return i.sort((r,s)=>r.code.localeCompare(s.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]="3c32504d-254c-5156-a41f-8ffd8e49107f")}catch{}})();function vh(e){let t=new Map;for(let i of e){let r=t.get(i.item_type);r||(r=new Map,t.set(i.item_type,r)),r.set(i.field,(r.get(i.field)??0)+1)}let n={};for(let i of[...t.keys()].sort((r,s)=>r.localeCompare(s))){let r=t.get(i),s={};for(let a of[...r.keys()].sort((o,c)=>o.localeCompare(c)))s[a]=r.get(a);n[i]=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]="c577e41b-6642-554a-bc4d-0c22170c1e24")}catch{}})();function wh(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function bh(e,t,n=3){let i=Number.isFinite(n)&&n>=1?Math.floor(n):3,r=new Map;for(let s of t){let a=wh(s);if(a.length===0)continue;let o=r.get(a);o?o.push(s):r.set(a,[s])}return e.map(s=>{if(s.includes(",")||s.replace(/^[a-z]:[\\/]/i,"").includes(":"))return{path:s,classification:"malformed",candidates:[],candidates_truncated:!1};let a=(r.get(wh(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,i),candidates_truncated:a.length>i}})}function kh(e){return e.map(t=>t.classification==="moved"?`${t.path}:moved:${t.candidates[0]}`:`${t.path}:${t.classification}`)}(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]="8cca9707-86a7-5ab5-8c7b-92be560254d0")}catch{}})();async function ms(e){return e.includeBody?dt(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema,{forceSourceScan:!0}):ar(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]="6322c4ff-92bd-59e5-aa64-ef8d3ef4b57f")}catch{}})();var cI=5;async function dI(e,t){let n=t.hashMismatches.filter(s=>s!==Mt);if(n.length===0)return;let i=await I(e),r=F(i,P());for(let s of n){let a=await bt(e,s,i.locks.ttl_seconds,"history-drift-read",!1,!0,i.locks.wait_ms);try{let o=await Y(e,s,i.id_prefix,i.item_format,r.type_to_folder);if(o===null)throw new _(`Item ${s} not found`,m.NOT_FOUND,{code:"item_not_found",required:"Repeat validation after writers finish; each item-hash discrepancy requires readable canonical source."});let{document:c}=await he(o,{schema:i.schema});if(c.metadata.id!==s)throw new _(`Item identity changed while validating ${s}`,m.CONFLICT,{code:"item_identity_conflict",required:"Restore the canonical item identity and validate storage integrity before retrying history validation."});let d=await up(e,{...c.metadata,body:c.body});for(let u of["missingStreams","unreadableStreams","hashMismatches","chainMismatches","versionSkews","driftedItems"])t[u]=[...t[u].filter(p=>p!==s),...d[u].filter(p=>p===s)].sort((p,g)=>p.localeCompare(g));let l=[...(t.identityDiscontinuities??[]).filter(u=>u.item_id!==s),...(d.identityDiscontinuities??[]).filter(u=>u.item_id===s)];l.length>0?t.identityDiscontinuities=l:delete t.identityDiscontinuities}finally{await a()}}}async function _s(e,t,n){let i=await Yn(e,t);await dI(e,i);let r=[["validate_history_drift_missing_streams",i.missingStreams.length],["validate_history_drift_unreadable_streams",i.unreadableStreams.length],["validate_history_drift_hash_mismatches",i.hashMismatches.length],["validate_history_drift_chain_mismatches",i.chainMismatches.length],["validate_history_drift_version_skews",i.versionSkews.length],["validate_history_drift_workspace_state_mismatches",i.workspaceStateMismatches.length],["validate_history_drift_workspace_state_missing",i.workspaceStateMissing.length],["validate_history_drift_workspace_state_unreadable",i.workspaceStateUnreadable.length]].filter(([,c])=>c>0).map(([c,d])=>`${c}:${d}`),s=n?Number.POSITIVE_INFINITY:cI,a=i.driftedItems.slice(0,s),o=i.identityDiscontinuities??[];return{check:{name:"history_drift",status:o.length>0?"error":r.length===0?"ok":"warn",ok:o.length===0&&r.length===0,details:{identity_discontinuities:o.slice(0,s),identity_discontinuities_count:o.length,identity_discontinuities_truncated:o.length>s,checked_items:t.length,drifted_items_count:i.driftedItems.length,drifted_items:a,drifted_items_truncated:a.length<i.driftedItems.length,counts:{missing_streams:i.missingStreams.length,unreadable_streams:i.unreadableStreams.length,hash_mismatches:i.hashMismatches.length,chain_mismatches:i.chainMismatches.length,version_skews:i.versionSkews.length,workspace_state_mismatches:i.workspaceStateMismatches.length,workspace_state_missing:i.workspaceStateMissing.length,workspace_state_unreadable:i.workspaceStateUnreadable.length},workspace_state_mismatches:i.workspaceStateMismatches,workspace_state_missing:i.workspaceStateMissing,workspace_state_unreadable:i.workspaceStateUnreadable,version_skews:i.versionSkews.slice(0,s)}},warnings: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]="3caaa82b-d8c7-5bc4-94e5-6699da27fa3c")}catch{}})();function ps(e,t){let n=e[0];if(e.length===1)return[n,n];let i=new Set(e),r=[n],s=new Set([n]),a=o=>{for(let c of(t.get(o)??[]).filter(d=>i.has(d))){if(c===n&&r.length>1)return r.push(n),!0;if(!s.has(c)){if(s.add(c),r.push(c),a(c))return!0;r.pop(),s.delete(c)}}return!1};return a(n)?[...r]:[...e,n]}function lI(e,t){if(typeof e!="string")return;let n=e.trim().toLowerCase();return n.length>0?t.get(n):void 0}function uI(e,t,n,i){for(let r of e.dependencies??[]){if(typeof r!="object"||r===null||typeof r.id!="string")continue;let s=i.resolve(r.kind);if(!s?.hierarchy)continue;let a=n.get(r.id.toLowerCase());a&&(s.hierarchyDirection==="source_parent"?t.get(a).push(e.id):t.get(e.id).push(a))}}function wc(e,t=ae()){let n=new Map(e.map(r=>[r.id.toLowerCase(),r.id])),i=new Map(e.map(r=>[r.id,[]]));for(let r of[...e].sort((s,a)=>s.id.localeCompare(a.id))){let s=i.get(r.id),a=lI(r.parent,n);a&&s.push(a),uI(r,i,n,t)}for(let[r,s]of i)i.set(r,[...new Set(s)].sort());return i}function bc(e,t,n=ae()){let i=Cr(e,a=>t?Nt(a,t):a==="closed"||a==="canceled",n),r=wc(e,n),s=i.cycles.map(a=>a.item_ids);return{cycle_count:s.length,active_cycle_count:i.cycles.filter(a=>!a.legacy_terminal).length,legacy_cycle_count:i.cycles.filter(a=>a.legacy_terminal).length,cycle_item_ids:[...new Set(s.flat())].sort(),cycle_sample_paths:s.map(a=>ps(a,r).join("->")),cardinality_violation_count:i.cardinality_violations.length,active_cardinality_violation_count:i.cardinality_violations.filter(a=>!a.legacy_terminal).length,legacy_cardinality_violation_count:i.cardinality_violations.filter(a=>a.legacy_terminal).length,cardinality_violation_rows:i.cardinality_violations.map(a=>`${a.child_id}:${a.parent_ids.join(",")}:${a.legacy_terminal?"legacy":"active"}`),parent_divergence_count:i.divergences.length,active_parent_divergence_count:i.divergences.filter(a=>!a.legacy_terminal).length,legacy_parent_divergence_count:i.divergences.filter(a=>a.legacy_terminal).length,parent_divergence_rows:i.divergences.map(a=>`${a.child_id}:scalar=${a.scalar_parent_id}:dependencies=${a.dependency_parent_ids.join(",")}:${a.legacy_terminal?"legacy":"active"}`)}}(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]="f2840c80-38f5-5563-b2c0-ef5596cf8f62")}catch{}})();function Ct(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function kc(e){return Ct(e).replace(/\/+$/,"")}function We(e){let t=ne(e);if(!t)return;let n=t.toLowerCase();if(!(n==="none"||n==="null"||n==="n/a"||n==="na"))return t}function Ec(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length>120?`${t.slice(0,117)}...`: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]="9ef196b2-3eef-5bac-b949-bcb3e947c44d")}catch{}})();var fI=["src","tests","docs"],gI=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],hI=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),yI=["resolution","expected_result","actual_result"],vI=["default","tracked-all","tracked-all-strict"],Eh=["core","strict","custom"],hs=["off","warn","error"],Ac=["author","acceptance_criteria","estimated_minutes","close_reason"],Ah=[...Ac,"reviewer","risk","confidence","sprint","release"],Ic=Array.from(new Set(Ah)),wI={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"},bI={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"},kI={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"},EI={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"},SI={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"},TI=32*1024*1024,AI=1e4,Cc=40,Be=5,II=4096,CI=255,xI=pI(_I);function Ih(e){let t={};for(let[n,i]of Object.entries(e))Array.isArray(i)||i===!1&&n.endsWith("_truncated")||(t[n]=typeof i=="object"&&i!==null?Ih(i):i);return t}function RI(e){return{...e,checks:e.checks.map(t=>({...t,details:Ih(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 vs(e,t){return me(e,t)??e}function vi(e,t){return t.terminal_statuses.has(vs(e,t))}function xt(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function fs(e,t){return e.length!==t.length?!1:e.every((n,i)=>n===t[i])}function OI(e){let t=xt(sl),n={blocked_reason:xt(qi.blocked_reason),resolution:xt(qi.resolution),actual_result:xt(qi.actual_result)},i=xt(e.validation.lifecycle_stale_blocker_reason_patterns),r={blocked_reason:xt(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:xt(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:xt(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:i,stale_blocker_reason_pattern_source:fs(i,t)?"default":"settings",closure_like_metadata_field_patterns:r,closure_like_metadata_field_pattern_sources:{blocked_reason:fs(r.blocked_reason,n.blocked_reason)?"default":"settings",resolution:fs(r.resolution,n.resolution)?"default":"settings",actual_result:fs(r.actual_result,n.actual_result)?"default":"settings"}}}function Ch(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(Eh.includes(t))return t;throw new _(`Unknown --metadata-profile value "${e}". Supported values: ${Eh.join(", ")}.`,m.USAGE)}function xh(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(hs.includes(t))return t;throw new _(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${hs.join(", ")}.`,m.USAGE)}function Rh(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(hs.includes(t))return t;throw new _(`Unknown --parent-cycle-severity value "${e}". Supported values: ${hs.join(", ")}.`,m.USAGE)}function LI(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase().replaceAll("-","_")))].map(t=>wI[t]).filter(t=>t!==void 0).sort((t,n)=>t.localeCompare(n))}function DI(e,t,n){let i=LI(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...Ac],configured_custom_fields:i,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...Ah],configured_custom_fields:i,fallback_to_core:!1,warnings:[]}:i.length>0?{profile:e,profile_source:t,required_fields:i,configured_custom_fields:i,fallback_to_core:!1,warnings:[]}:{profile:e,profile_source:t,required_fields:[...Ac],configured_custom_fields:i,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var NI=new Set(["acceptance_criteria","estimated_minutes"]);function Oh(e,t,n,i){return!i&&NI.has(t)&&vi(e.status,n)?!1:t==="author"?!ne(e.author):t==="acceptance_criteria"?!ne(e.acceptance_criteria):t==="estimated_minutes"?!Number.isFinite(e.estimated_minutes):t==="close_reason"?vs(e.status,n)===n.close_status&&!ne(e.close_reason):t==="reviewer"?!ne(e.reviewer):t==="risk"?!ne(e.risk):t==="confidence"?typeof e.confidence=="number"?!Number.isFinite(e.confidence):!ne(e.confidence):t==="sprint"?!ne(e.sprint):!ne(e.release)}function Lh(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 _(`Unknown --scan-mode value "${e}". Supported values: ${vI.join(", ")}.`,m.USAGE)}function Dh(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim();if(t)return xe.resolve(t);let n=xe.resolve(e);if(n.replaceAll("\\","/").endsWith("/.agents/pm"))return xe.dirname(xe.dirname(n));let i=xe.resolve(process.cwd()),r=Sh(n),s=Sh(i),a=xe.relative(r,s);return a.length===0||!a.startsWith("..")&&!xe.isAbsolute(a)?n:i}function Sh(e){try{return mI.native(e)}catch{return xe.resolve(e)}}function MI(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function Lc(e,t,n){let i=t.length>0?xe.join(e,t):e,r;try{r=await Oc.readdir(i,{withFileTypes:!0})}catch(s){if(q(s))return;throw s}for(let s of r){if(s.name.startsWith("."))continue;let a=t.length>0?xe.join(t,s.name):s.name;if(s.isDirectory()){if(hI.has(s.name))continue;await Lc(e,a,n);continue}s.isFile()&&n.push(Ct(a))}}async function xc(e){let t=[];for(let n of fI)await Lc(e,n,t);for(let n of gI){let i=xe.join(e,n);try{(await Oc.stat(i)).isFile()&&t.push(Ct(n))}catch{}}return[...new Set(t)].sort((n,i)=>n.localeCompare(i))}async function Nh(e){try{let{stdout:t}=await xI("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:TI,windowsHide:!0,timeout:AI}),n=t.split("\0").map(i=>Ct(i)).filter(i=>i.length>0);return[...new Set(n)].sort((i,r)=>i.localeCompare(r))}catch{return null}}function PI(e,t){let n=new Set,i=kc(nl);i.length>0&&n.add(i);let r=kc(xe.relative(t,e));return r.length>0&&!r.startsWith("..")&&n.add(r),[...n].sort((s,a)=>s.localeCompare(a))}function Th(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function FI(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let i=await Nh(e);if(i)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:i,candidateTotal:i.length,candidateScanned:i.length};let r=await xc(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length}}let n=await xc(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function ee(e,t=Be){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function Kt(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=ee(e,Cc);return{values:n.values,truncated:n.truncated,total:e.length}}var $I={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},UI={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function jI(e){let t=e.missing_fields.map(n=>`${$I[n]} "${UI[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function Mh(e,t){let n=e.details?.missing_resolution_remediation_hints,i=Array.isArray(n)&&n.length>0,r=i?n.filter(a=>typeof a=="string"):Ag(t);if(r.length===0)return;let s=i&&e.details?.missing_resolution_remediation_hints_truncated===!0;e.details={...e.details,fix_hints:r,...s?{fix_hints_truncated:!0}:{}}}function Ph(e){let t=new Set;return e.checkCompleteness&&t.add("completeness"),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("completeness"),t.add("storage_integrity")),t):(e.pruneMissing&&t.add("files"),t)}var GI="validate_metadata_duplicate_issue_codes";function Fh(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:Be,i=e.slice(0,n);return{rows:i.map(r=>({code:r.code,count:r.count,ids:r.ids,titles:r.titles,remediation_hint:`Items ${r.ids.join(", ")} share issue code "${r.code}"; rename or merge so each logical code maps to one item.`})),truncated:i.length<e.length,warnings:[`${GI}:${e.length}`]}}function qI(e,t,n){let i=Object.fromEntries(Ic.map(r=>[r,[]]));for(let r of e)for(let s of Ic)Oh(r,s,t,n)&&i[s].push(r.id);return i}function KI(e,t,n){let i=[...e.warnings];for(let r of e.required_fields){let s=t[r];s.length>0&&i.push(`${bI[r]}:${s.length}`)}return i.push(...n),i}function $h(e,t){let n={};for(let i of e.required_fields){let r=t[i],s=r?r.length:0,a=kI[i];n[a]=s}return n}function Uh(e,t,n){let i=[];for(let r of e.required_fields){let s=t[r];if(s)for(let a of s){let o=n.get(a)?.type,c=typeof o=="string"&&o.length>0?o:"Unknown";i.push({item_type:c,field:r})}}return i}function zI(e,t,n,i){for(let r of t.required_fields){let s=n[r];if(!s||s.length===0)continue;let a=EI[r],o=SI[r];if(!a||!o)continue;let c=ee(s,i?s.length:Be);e[a]=c.values,e[o]=c.truncated}}function jh(e,t,n){if(!e.required_fields.includes("close_reason"))return[];let i=t.close_reason;return i?i.map(r=>({id:r,resolution:ne(n.get(r)?.resolution)})):[]}function Gh(e,t,n){if(!e.required_fields.includes("estimated_minutes"))return[];let i=t.estimated_minutes;return i?i.map(r=>({id:r,type:ne(n.get(r)?.type)})):[]}function WI(e,t,n,i,r){let s=new Map(e.map(v=>[v.id,v])),a=t.profile==="strict",o=qI(e,n,a),c=yh(e,{configuredPrefixes:r}),d=Fh(c,i),l=KI(t,o,d.warnings),u=$h(t,o),p=Uh(t,o,s),g=vh(p),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:[...Ic],counts:u,missing_by_type:g,duplicate_issue_codes_count:c.length,duplicate_issue_codes:d.rows,duplicate_issue_codes_truncated:d.truncated};t.configured_custom_fields.length>0&&(f.configured_custom_required_fields=[...t.configured_custom_fields]),zI(f,t,o,i);let h=jh(t,o,s),y=Gh(t,o,s);return{check:{name:"metadata",status:l.length===0?"ok":"warn",ok:l.length===0,details:f},warnings:l,closeReasonBackfillRows:h,estimateBackfillRows:y}}function BI(e,t,n){let i=new Set(t.terminal_done_statuses);i.add(t.close_status);let r=e.filter(p=>i.has(vs(p.status,t))),s=[],a=[];for(let p of r){let g=yI.filter(f=>!ne(p[f]));g.length!==0&&(s.push({id:p.id,missing_fields:g}),a.push({id:p.id,missing_fields:g,close_reason:ne(p.close_reason)}))}let o=s.length>0?[`validate_resolution_missing_fields:${s.length}`]:[],c=n?Number.POSITIVE_INFINITY:Be,d=ee(s.map(p=>`${p.id}:${p.missing_fields.join(",")}`),c),l=s.map(p=>jI(p)),u=ee(l,c);return{check:{name:"resolution",status:o.length===0?"ok":"warn",ok:o.length===0,details:{checked_closed_items:r.length,missing_resolution_items:s.length,missing_resolution_rows:d.values,missing_resolution_rows_truncated:d.truncated,missing_resolution_remediation_hints:u.values,missing_resolution_remediation_hints_truncated:u.truncated}},warnings:o,resolutionBackfillRows:a}}function qh(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Kh(e,t="pm",n=Qd()){let i=new Set(e.map(s=>s.id)),r=[...e].sort((s,a)=>s.id.localeCompare(a.id));return new Map(r.map(s=>{let a=new Set,o=We(s.blocked_by);o&&i.has(o)&&a.add(o),(s.dependencies??[]).filter(d=>{let l=We(d.kind);return l!==void 0&&n.resolve(l)?.ordering===!0}).map(d=>We(d.id)).filter(d=>d!==void 0&&i.has(d)).forEach(d=>a.add(d));let c=We(s.definition_of_ready);return Wh(c??"",t).filter(d=>i.has(d)).forEach(d=>a.add(d)),[s.id,[...a].sort((d,l)=>d.localeCompare(l))]}))}function zh(e,t,n){let i=H_(e,n?l=>vi(l,n):void 0),r=i.active.map(l=>`${l.holder_id}:${l.target_id}:${l.kind}`),s=i.legacy_terminal.map(l=>`${l.holder_id}:${l.target_id}:${l.kind}:${l.holder_status}`),a=t?Number.POSITIVE_INFINITY:Be,o=ee(r,a),c=ee(s,a),d=ee(i.active.map(l=>l.source==="parent"?`pm update ${l.holder_id} --unset parent`:l.source==="blocked_by"?`pm update ${l.holder_id} --unset blocked_by`:`pm update ${l.holder_id} --replace-deps '<correct dependency edges>'`),a);return{check:{name:"dependency_references",status:r.length===0?"ok":"warn",ok:r.length===0,details:{checked_items:e.length,dangling_reference_count:r.length+s.length,active_dangling_reference_count:r.length,dangling_reference_rows:o.values,dangling_reference_rows_truncated:o.truncated,legacy_terminal_dangling_reference_count:s.length,legacy_closed_dangling_reference_count:i.legacy_terminal.filter(l=>l.holder_status==="closed").length,legacy_terminal_dangling_reference_rows:c.values,legacy_terminal_dangling_reference_rows_truncated:c.truncated,no_active_blocker_sentinel_count:i.no_active_blocker_sentinels.length,remediation_hints:d.values,remediation_hints_truncated:d.truncated}},warnings:r.length>0?[`validate_dangling_dependency_references:${r.length}`]:[]}}function Wh(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),i=new RegExp(`(?:^|[^a-z0-9-])(${qh(n)}-[a-z0-9][a-z0-9-]*)`,"gi");return[...new Set([...e.matchAll(i)].map(r=>r[1].toLowerCase()))].sort((r,s)=>r.localeCompare(s))}function Bh(e){let t=0,n=new Map,i=new Map,r=[],s=new Set,a=[],o=d=>{n.set(d,t),i.set(d,t),t+=1,r.push(d),s.add(d);for(let u of e.get(d)??[])n.has(u)?s.has(u)&&i.set(d,Math.min(i.get(d),n.get(u))):(o(u),i.set(d,Math.min(i.get(d),i.get(u))));if(i.get(d)!==n.get(d))return;let l=[];for(;r.length>0;){let u=r.pop();if(s.delete(u),l.push(u),u===d)break}l.sort((u,p)=>u.localeCompare(p)),a.push(l)},c=[...e.keys()].sort((d,l)=>d.localeCompare(l));for(let d of c)n.has(d)||o(d);return a.filter(d=>{if(d.length>1)return!0;let l=d[0];return(e.get(l)??[]).includes(l)}).sort((d,l)=>d[0].localeCompare(l[0])||d.length-l.length||d.join(",").localeCompare(l.join(",")))}function Hh(e,t="pm"){let n=Kh(e,t),i=Bh(n),r=[...new Set(i.flat())].sort((a,o)=>a.localeCompare(o)),s=i.map(a=>ps(a,n).join("->"));return{cycle_count:i.length,cycle_item_ids:r,cycle_sample_paths:s}}function Vh(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 ys(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function Yh(e,t){let n=ys(e).split("/").filter(Boolean),i=ys(t).split("/").filter(Boolean),r=0;for(;r<n.length&&r<i.length&&n[r]===i[r];)r+=1;return r}function HI(e,t){let n=ys(t),i=ys(e),r=t.endsWith("/")?t:`${t}/`,s=e.startsWith(r),a=n.length>0&&n===i,o=Yh(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 VI(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function YI(e,t,n){let i=t==="docs_unowned"?"docs":"files",r;return n.flatMap(s=>(i==="docs"?s.docs??[]:s.files??[]).map(a=>({item:s,link:a}))).forEach(({item:s,link:a})=>{if(a.scope!=="project")return;let o=Ct(a.path);if(o.length===0||o===e)return;let c=HI(e,o);c!==null&&VI(r,s,c.score)&&(r={item:s,score:c.score,confidence:c.confidence})}),r?{id:r.item.id,type:r.item.type,title:r.item.title,status:r.item.status,confidence:r.confidence}:null}function Jh(e,t){return e.map(n=>{let i=Vh(n),r=i==="docs_unowned"?"docs":"files",s=YI(n,i,t),a=s?.id??"<id>";return{path:n,classification:i,owner_candidate:s,remediation_hint:`pm ${r} ${a} --add path=${n},scope=project,note="<why this artifact belongs to the item>"`}})}function Xh(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function JI(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,i])=>{let r=We(e[n]);return r?i.some(s=>r.toLowerCase().includes(s)):!1}).map(([n])=>n).sort((n,i)=>n.localeCompare(i))}function XI(e,t,n,i,r){let s=We(t.parent),a=s?n.get(i.get(s.toLowerCase())??s):void 0;return{id:e.id,parent_id:t.id,grandparent_id:a?.id,grandparent_active:a!==void 0&&!vi(a.status,r)}}function QI(e,t,n,i){let r=We(e.blocked_by),s=We(e.blocked_reason),a=s?.toLowerCase(),o=vs(e.status,n),c=[];return t.has(o)?(!r&&!s&&c.push("blocked_status_missing_blocker_context"),a?.includes("no active blocker")&&c.push("blocked_status_reason_reports_no_active_blocker"),a&&i.stale_blocker_reason_patterns.some(d=>a.includes(d))&&c.push("blocked_status_reason_matches_stale_pattern"),c):(r&&c.push("non_blocked_status_has_blocked_by"),s&&c.push("non_blocked_status_has_blocked_reason"),c)}function ZI(e,t,n,i){let r=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=>!vi(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of o.activeItems){let d=JI(c,i);d.length>0&&o.closureLikeRows.push({id:c.id,fields:d});let l=We(c.parent),u=l?r.get(s.get(l.toLowerCase())??l):void 0;if(u&&vi(u.status,n)&&(o.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),o.terminalParentFixRows.push(XI(c,u,r,s,n))),t){let p=QI(c,a,n,i);p.length>0&&o.staleBlockerRows.push({id:c.id,status:c.status,reasons:[...new Set(p)].sort((g,f)=>g.localeCompare(f))})}}return o}function eC(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 gs(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function Sc(e,t,n){return n>0&&t!=="off"?`${e}:${n}`:null}function tC(e,t,n,i,r){let s=[];e.closureLikeRows.length>0&&s.push(`validate_lifecycle_active_closure_like_metadata:${e.closureLikeRows.length}`),e.terminalParentRows.length>0&&s.push(`validate_lifecycle_active_terminal_parent:${e.terminalParentRows.length}`),t&&e.staleBlockerRows.length>0&&s.push(`validate_lifecycle_stale_blockers:${e.staleBlockerRows.length}`);let a=gs("validate_lifecycle_dependency_cycles",n,r.dependencyCycles),o=gs("validate_hierarchy_parent_cycle",i,r.activeHierarchyCycles),c=gs("validate_hierarchy_cardinality_violation",i,r.activeHierarchyCardinality),d=gs("validate_hierarchy_parent_divergence",i,r.activeHierarchyDivergence),l=Sc("validate_legacy_hierarchy_parent_cycle",i,r.legacyHierarchyCycles),u=Sc("validate_legacy_hierarchy_cardinality_violation",i,r.legacyHierarchyCardinality),p=Sc("validate_legacy_hierarchy_parent_divergence",i,r.legacyHierarchyDivergence);return[...s,...a?[a]:[],...o?[o]:[],...c?[c]:[],...d?[d]:[],...l?[l]:[],...u?[u]:[],...p?[p]:[]]}function Qh(e){let t=Ct(e);return t.length>II||t.split(/[\\/]/).some(n=>n.length>CI)}async function nC(e,t){let n=xe.isAbsolute(t)?t:xe.resolve(e,t);if(Qh(n))return!1;try{let i=await Oc.stat(n);return!i.isFile()&&!i.isDirectory()}catch(i){return MI(i,["ENOENT","ENOTDIR"])}}async function iC(e,t){let n={linkedProjectPaths:new Set,remoteLinkedPaths:new Set,missingLinkedPaths:[],staleLinkRows:[]},i=e.flatMap(r=>[...(r.files??[]).map(s=>({item:r,artifact:s,link_kind:"files"})),...(r.docs??[]).map(s=>({item:r,artifact:s,link_kind:"docs"}))]);for(let{item:r,artifact:s,link_kind:a}of i){if(s.scope!=="project")continue;if(ci(s.path)){n.remoteLinkedPaths.add(s.path.trim());continue}let o=Ct(s.path);o.length!==0&&(n.linkedProjectPaths.add(o),await nC(t,s.path)&&(n.missingLinkedPaths.push(o),n.staleLinkRows.push({item_id:r.id,path:o,link_kind:a})))}return n}function rC(e,t,n,i,r,s){let a=i==="tracked-all-strict",o=a&&!r,c=r||a,d=c?[]:PI(t,n),l=d.length===0?[]:e.candidateFiles.filter(g=>Th(g,d)),u=d.length===0?e.candidateFiles:e.candidateFiles.filter(g=>!Th(g,d)),p={};if(l.length>0){let g=Kt(l,s);p.pm_internals={count:l.length,paths:g.values,paths_truncated:g.truncated,paths_total:g.total}}return{strictTrackedAllMode:a,strictModeForcesPmInternals:o,includePmInternalsEffective:c,pmInternalCandidatePrefixes:d,excludedPmInternalPaths:l,candidateFiles:u,excludedByReason:p}}function Zh(e,t,n,i,r,s,a,o="pm"){let c=ZI(e,t,r,s);eC(c);let d=Hh(c.activeItems,o),l=bc(e,r),u=Qr(r,e,a?Number.POSITIVE_INFINITY:Be),p=[...tC(c,t,n,i,{dependencyCycles:d.cycle_count,activeHierarchyCycles:l.active_cycle_count,activeHierarchyCardinality:l.active_cardinality_violation_count,activeHierarchyDivergence:l.active_parent_divergence_count,legacyHierarchyCycles:l.legacy_cycle_count,legacyHierarchyCardinality:l.legacy_cardinality_violation_count,legacyHierarchyDivergence:l.legacy_parent_divergence_count}),...Zr(u)],g=a?Number.POSITIVE_INFINITY:Be,f=ee(c.closureLikeRows.map(E=>`${E.id}:${E.fields.join(",")}`),g),h=ee(c.terminalParentRows.map(E=>`${E.id}:${E.parent_id}:${E.parent_status}`),g),y=ee(c.staleBlockerRows.map(E=>`${E.id}:${E.status}:${E.reasons.join(",")}`),g),v=ee(d.cycle_item_ids,g),w=ee(d.cycle_sample_paths,g),k=ee(l.cycle_item_ids,g),S=ee(l.cycle_sample_paths,g),T=ee(l.cardinality_violation_rows,g),C=ee(l.parent_divergence_rows,g),b=d.cycle_count>0&&n==="error"||(l.active_cycle_count>0||l.active_cardinality_violation_count>0||l.active_parent_divergence_count>0)&&i==="error";return{check:{name:"lifecycle",status:b?"error":p.length===0?"ok":"warn",ok:!b&&p.length===0,details:{checked_active_items:c.activeItems.length,lifecycle_status_roles:u,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:h.values,active_terminal_parent_rows_truncated:h.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:d.cycle_count,dependency_cycle_item_count:d.cycle_item_ids.length,dependency_cycle_item_ids:v.values,dependency_cycle_item_ids_truncated:v.truncated,dependency_cycle_sample_paths:w.values,dependency_cycle_sample_paths_truncated:w.truncated,parent_cycle_severity_policy:i,parent_cycle_count:l.cycle_count,active_parent_cycle_count:l.active_cycle_count,legacy_parent_cycle_count:l.legacy_cycle_count,parent_cycle_item_count:l.cycle_item_ids.length,parent_cycle_item_ids:k.values,parent_cycle_item_ids_truncated:k.truncated,parent_cycle_sample_paths:S.values,parent_cycle_sample_paths_truncated:S.truncated,hierarchy_cardinality_violation_count:l.cardinality_violation_count,active_hierarchy_cardinality_violation_count:l.active_cardinality_violation_count,legacy_hierarchy_cardinality_violation_count:l.legacy_cardinality_violation_count,hierarchy_cardinality_violation_rows:T.values,hierarchy_cardinality_violation_rows_truncated:T.truncated,hierarchy_parent_divergence_count:l.parent_divergence_count,active_hierarchy_parent_divergence_count:l.active_parent_divergence_count,legacy_hierarchy_parent_divergence_count:l.legacy_parent_divergence_count,hierarchy_parent_divergence_rows:C.values,hierarchy_parent_divergence_rows_truncated:C.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:p,terminalParentFixRows:c.terminalParentFixRows}}async function ey(e,t,n,i,r,s,a=K(Lt.schema)){let o=await iC(e,t),c=new Map(e.map(R=>[R.id,R])),d=[...new Set(o.missingLinkedPaths)].sort((R,G)=>R.localeCompare(G)),l=await FI(t,i),u=rC(l,n,t,i,r,s),p=u.candidateFiles.filter(R=>!o.linkedProjectPaths.has(R)),g=Jh(p,e),f=bh(d,u.candidateFiles),h=new Map(f.map(R=>[R.path,R.classification])),y=f.filter(R=>R.classification==="moved").length,v=o.staleLinkRows.map(R=>({...R,classification:h.get(R.path)??"deleted"})).sort((R,G)=>R.item_id.localeCompare(G.item_id)||R.path.localeCompare(G.path)||R.link_kind.localeCompare(G.link_kind)),w=[];u.strictModeForcesPmInternals&&w.push("validate_files_tracked_all_strict_forces_pm_internals"),p.length>0&&w.push(`validate_files_orphaned_paths:${p.length}`);let k=[...o.remoteLinkedPaths].sort((R,G)=>R.localeCompare(G)),S=Kt(k,s),T=Kt(d,s),C=Kt(p,s),b=Kt(g.map(R=>`${R.path}:${R.classification}:owner_candidate=${R.owner_candidate?.id??"unowned"}`),s),E=s?g:Kt(Xh(g),!1).values,N=Kt(kh(f),s),A=Yg(v,f,R=>c.get(R),a,s?1/0:Cc);return A.active_missing_linked_paths_count>0&&w.push(`validate_files_missing_linked_paths:${A.active_missing_linked_paths_count}`),{check:{name:"files",status:w.length===0?"ok":"warn",ok:w.length===0,details:{workspace_root:t,scan_mode_requested:l.requestedMode,scan_mode_applied:l.appliedMode,strict_tracked_all_mode:u.strictTrackedAllMode,strict_mode_forces_pm_internals:u.strictModeForcesPmInternals,strict_mode_forces_pm_internals_notice:u.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:Cc,candidate_scan_source:l.source,include_pm_internals:u.includePmInternalsEffective,include_pm_internals_requested:r,pm_internal_candidate_prefixes:u.pmInternalCandidatePrefixes,pm_internal_excluded_count:u.excludedPmInternalPaths.length,excluded_total:u.excludedPmInternalPaths.length,excluded_by_reason:u.excludedByReason,linked_project_paths:o.linkedProjectPaths.size,remote_linked_paths_count:k.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:u.candidateFiles.length,candidate_scanned:u.candidateFiles.length,scanned_candidate_files:u.candidateFiles.length,missing_linked_paths_count:d.length,missing_linked_paths_total:T.total,missing_linked_paths:T.values,missing_linked_paths_truncated:T.truncated,missing_linked_paths_moved_count:y,missing_linked_paths_deleted_count:f.filter(R=>R.classification==="deleted").length,missing_linked_paths_malformed_count:f.filter(R=>R.classification==="malformed").length,missing_linked_path_classifications:N.values,missing_linked_path_classifications_truncated:N.truncated,...A,orphaned_paths_count:p.length,orphaned_paths_total:C.total,orphaned_paths:C.values,orphaned_paths_truncated:C.truncated,orphaned_path_classifications:b.values,orphaned_path_classifications_truncated:b.truncated,orphaned_path_rows_count:g.length,orphaned_path_rows:E}},warnings:w,staleLinkPruneRows:v}}function sC(e,t){let n=[];return e.forEach(({item:i,linkedTest:r},s)=>{let a=t[s];if(a.trusted)return;let o=Ec(r.command??"");n.push(`${i.id}:${a.source_ref??"unknown"}->${a.current_source_ref??"unknown"}:${o}`)}),n}async function ty(e,t,n,i){let r=new Set(e.map(T=>T.id.toLowerCase())),s=0,a=0,o=new Set,c=[],d=e.flatMap(T=>(T.tests??[]).map(C=>({item:T,linkedTest:C}))),l=await gi(hi()),u=await oh(i,d.map(({linkedTest:T})=>T),l),p=sC(d,u);for(let{item:T,linkedTest:C}of d){if(typeof C.command!="string"||C.command.trim().length===0)continue;s+=1;let b=uc(C.command,t);if(b.length!==0){a+=b.length;for(let E of b)o.add(E),r.has(E.toLowerCase())||c.push(`${T.id}:${E}:${Ec(C.command)}`)}}let g=[...new Set(c)].sort((T,C)=>T.localeCompare(C)),f=[...new Set(g.map(T=>T.split(":")[1]??""))].filter(T=>T.length>0).sort((T,C)=>T.localeCompare(C)),h=[];g.length>0&&h.push(`validate_command_references_stale_pm_ids:${g.length}`),p.length>0&&h.push(`validate_linked_test_trust_unacknowledged:${p.length}`);let y=n?Number.POSITIVE_INFINITY:Be,v=ee(g,y),w=ee(f,y),k=ee([...o].sort((T,C)=>T.localeCompare(C)),y),S=ee(p,y);return{check:{name:"command_references",status:h.length===0?"ok":"warn",ok:h.length===0,details:{checked_items:e.length,linked_commands_scanned:s,referenced_pm_ids_count:a,unique_referenced_pm_ids_count:o.size,unique_referenced_pm_ids:k.values,unique_referenced_pm_ids_truncated:k.truncated,linked_test_trust_current_source_ref:l??null,untrusted_linked_tests_count:p.length,untrusted_linked_tests:S.values,untrusted_linked_tests_truncated:S.truncated,stale_pm_id_references_count:g.length,stale_pm_ids_count:f.length,stale_pm_ids:w.values,stale_pm_ids_truncated:w.truncated,stale_pm_id_reference_rows:v.values,stale_pm_id_reference_rows_truncated:v.truncated}},warnings:h}}function aC(e,t){let n=er(e.map(c=>({ref:c.id,version:Zi(c)})),$n,Qi),i=[];n.outdated.length>0&&i.push(`validate_format_version_outdated_items:${n.outdated.length}`),n.ahead.length>0&&i.push(`validate_format_version_ahead_items:${n.ahead.length}`);let r=t?Number.POSITIVE_INFINITY:Be,s=ee(n.outdated,r),a=ee(n.ahead,r),o=n.ahead.length>0?"error":n.outdated.length>0?"warn":"ok";return{check:{name:"format_version",status:o,ok:o==="ok",details:{checked_items:e.length,current_format_version:$n,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:i}}var Rc="pm validate auto-fix";async function ny(e,t,n){switch(e.kind){case"set_closed_at":await Bg(e,t);return;case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let i={message:Rc};if(e.kind==="set_resolution"?i.resolution=e.value:e.kind==="set_close_reason"?i.closeReason=e.value:e.kind==="set_estimate"?i.estimatedMinutes=e.value:e.kind==="reparent"?i.parent=e.parent_id:i.unset=["parent"],!n.runUpdate)throw new _("Applying validate metadata/lifecycle fixes requires a runUpdate mutation service.",m.USAGE);await n.runUpdate(e.item_id,i,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 Tc(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function iy(e,t,n){let i=[],r=[],s=new Map;for(let a of e.filter(o=>Tc(o)===null))try{await ny(a,t,n),i.push(a)}catch(o){r.push({fix:a,error:o})}for(let a of e.filter(o=>Tc(o)!==null)){let o=Tc(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(d=>d.path).filter(d=>typeof d=="string"&&d.length>0);try{o.kind==="prune_file_link"?await eg(o.item_id,{remove:c,message:Rc},t):await Gf(o.item_id,{remove:c,message:Rc},t),i.push(...a)}catch(d){r.push(...a.map(l=>({fix:l,error:d})))}}return{applied:i,failed:r}}var lK={applyValidateFix:ny,applyValidateFixes:iy,attachValidateFixHints:Mh,buildCommandReferencesCheck:ty,buildDependencyReferencesCheck:zh,buildCloseReasonBackfillRows:jh,buildFilesCheck:ey,buildLifecycleCheck:Zh,buildLifecycleDependencyGraph:Kh,buildLifecycleParentGraph:wc,buildEstimateBackfillRows:Gh,buildMetadataCounts:$h,buildMissingFieldOccurrences:Uh,buildOrphanedPathRows:Jh,classifyOrphanedPath:Vh,collectDefaultProjectFileCandidates:xc,collectTrackedGitFileCandidates:Nh,detectLifecycleDependencyCycles:Hh,detectLifecycleParentCycles:bc,escapeRegExp:qh,extractItemIds:Wh,findLifecycleDependencyCycleComponents:Bh,isMetadataFieldMissing:Oh,linkedArtifactPathExceedsFilesystemLimits:Qh,listFilesRecursive:Lc,resolveDependencyCycleSeverity:xh,resolveParentCycleSeverity:Rh,resolveFileScanMode:Lh,resolveLifecycleDependencyCycleSamplePath:ps,resolveRequestedChecks:Ph,resolveValidateMetadataProfile:Ch,resolveWorkspaceRoot:Dh,sharedDirectoryPrefixLength:Yh,summarizeOrphanedPathRows:Xh,summarizeDuplicateIssueCodes:Fh,toMeaningfulString:We};function oC(e,t){t>0&&e.push(`merge_receipt_evidence_invalid:${t}`)}async function cC(e,t,n,i){let r=await Xg(e,new Set(t.map(y=>y.id)),n,{schema:i.schema,extensionFieldNames:Et(P())}),s=[];r.unreadable_item_files.length>0&&s.push(`validate_storage_unreadable_items:${r.unreadable_item_files.length}`),r.duplicate_item_ids.length>0&&s.push(`validate_storage_duplicate_item_ids:${r.duplicate_item_ids.length}`),r.history_conflict_marker_streams.length>0&&s.push(`validate_storage_history_conflict_markers:${r.history_conflict_marker_streams.length}`),r.history_unparseable_streams.length>0&&s.push(`validate_storage_unparseable_history:${r.history_unparseable_streams.length}`),r.resurrected_items.length>0&&s.push(`validate_storage_resurrected_items:${r.resurrected_items.length}`),r.unparseable_config_files.length>0&&s.push(`validate_storage_unparseable_config:${r.unparseable_config_files.length}`);let a=s.length,o=await ts(e);o.tracked_path_count>0&&s.push(`validate_storage_tracked_runtime_cache_files:${o.tracked_path_count}`);let c=await ln(e,dn(i));c.status==="drift"&&s.push(`validate_merge_fence_drift:${c.missing_patterns.length+c.stale_patterns.length}`);let d=await Tt(e),l=d===null?null:await un(d);l!==null&&l.status!=="ok"&&s.push(`validate_merge_driver_configuration:${l.missing_keys.length+l.drifted_keys.length}`);let u=await mn(d??e,{includeLossless:!0,pmRoot:e}),p=u.receipts,{pendingDecisions:g,lossless:f}=_n(p);g.length>0&&s.push(`validate_merge_decisions_unreviewed:${g.length}`),oC(s,u.invalid_evidence_count);let h=a>0?"error":s.length>0?"warn":"ok";return{check:{name:"storage_integrity",status:h,ok:h==="ok",details:{...r,merge_fence:c,merge_driver_configuration:l,pending_merge_decision_count:g.length,pending_merge_decision_items:[...new Set(g.map(y=>y.item_id))].sort((y,v)=>y.localeCompare(v)),lossless_merge_receipt_count:f.length,invalid_merge_receipt_evidence_count:u.invalid_evidence_count,invalid_merge_receipt_evidence_details:u.invalid_evidence,invalid_merge_receipt_evidence_details_truncated:u.invalid_evidence_truncated,lossless_merge_receipt_items:[...new Set(f.map(y=>y.item_id))].sort((y,v)=>y.localeCompare(v)),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 tt(e,t,n){n&&Mh(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function dC(e){let t={closureTimestampFixes:[],checks:[],warnings:[...e.initialWarnings],closeReasonBackfillRows:[],estimateBackfillRows:[],resolutionBackfillRows:[],terminalParentFixRows:[],staleLinkPruneRows:[]},n=e.options.fixHints===!0,i=e.options.verboseDiagnostics===!0||e.options.allAffectedIds===!0||e.global.json===!0;if(e.requestedChecks.has("completeness")){let r=await tp(e.pmRoot,e.items,i?1/0:Be,e.sourceIncomplete);tt(t,r,n)}if(e.requestedChecks.has("metadata")){let r=WI(e.items,e.metadataPolicy,e.statusRegistry,i,[e.settings.id_prefix]);t.closeReasonBackfillRows=r.closeReasonBackfillRows,t.estimateBackfillRows=r.estimateBackfillRows;let s=await Wg(e.pmRoot,e.items,e.statusRegistry,e.options.autoFix===!0||n,i?1/0:Be);t.closureTimestampFixes=s.fixes,Object.assign(r.check.details,s.details),r.warnings.push(...s.warnings),r.check.ok=r.warnings.length===0,r.check.status=r.check.ok?"ok":"warn",tt(t,r,n)}if(e.requestedChecks.has("resolution")){let r=BI(e.items,e.statusRegistry,i);t.resolutionBackfillRows=r.resolutionBackfillRows,tt(t,r,n)}if(e.requestedChecks.has("lifecycle")){let r=Zh(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,i,e.settings.id_prefix);t.terminalParentFixRows=r.terminalParentFixRows,tt(t,r,n),tt(t,zh(e.items,i,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let r=await ey(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists,e.statusRegistry);t.staleLinkPruneRows=r.staleLinkPruneRows,tt(t,r,n)}return e.requestedChecks.has("command_references")&&tt(t,await ty(e.items,e.settings.id_prefix,i,e.pmRoot),n),e.requestedChecks.has("history_drift")&&tt(t,await _s(e.pmRoot,e.items,i),n),e.requestedChecks.has("format_version")&&tt(t,aC(e.items,i),n),e.requestedChecks.has("storage_integrity")&&tt(t,await cC(e.pmRoot,e.items,F(e.settings,P()).type_to_folder,e.settings),n),t}function lC(e,t,n){let i=[];return e.autoFix===!0&&(i.push(...t.closureTimestampFixes),i.push(...uh(t.closeReasonBackfillRows)),i.push(...lh(t.resolutionBackfillRows)),i.push(...mh(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),i.push(..._h(t.terminalParentFixRows))),e.pruneMissing===!0&&i.push(...ph(t.staleLinkPruneRows)),i}async function uC(e,t,n,i,r,s){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let a=lC(e,t,n),{applicable:o,gated:c}=gh(a,i),d=e.dryRun===!0,l=[],u=[];if(!d){let p=await iy(o,r,s);l.push(...p.applied.map(yi)),u.push(...p.failed.map(({fix:g,error:f})=>({...yi(g),error:f instanceof Error?f.message:String(f)})))}return{mode:d?"dry_run":"apply",auto_fix:e.autoFix===!0,prune_missing:e.pruneMissing===!0,granted_fix_scopes:[...i].sort((p,g)=>p.localeCompare(g)),planned_count:a.length,applied_count:l.length,gated_count:c.length,failed_count:u.length,planned_fixes:a.map(yi),applied_fixes:l,gated_fixes:c.map(p=>({...yi(p),gate_hint:`Withheld: re-run with --fix-scope ${p.gate} to apply.`})),failed_fixes:u}}async function ry(e,t,n={}){Hl(e.counts===!0,e.full===!0,"--counts");let i=e.autoFix===!0||e.pruneMissing===!0;if(e.dryRun===!0&&!i)throw new _("--dry-run requires --auto-fix or --prune-missing (there is nothing to preview otherwise).",m.USAGE);if(e.fixScope!==void 0&&e.fixScope.length>0&&e.autoFix!==!0)throw new _("--fix-scope requires --auto-fix.",m.USAGE);let r=fh(e.fixScope),s=x(process.cwd(),t.path);await $(s);let a=await I(s),o=K(a.schema),c=F(a,P()),d=Ph(e),l=[],u=await ms({includeBody:["history_drift","metadata","completeness"].some(N=>d.has(N)),pmRoot:s,settings:a,typeToFolder:c.type_to_folder,warnings:l}),p=l.length>0;if(d.has("history_drift")){let N=await oi(s);N.actionable_unknown_event_count>0&&l.push(`validate_history_unknown_author_events:${N.actionable_unknown_event_count}`)}let g=typeof e.metadataProfile=="string"?"option":"settings",f=Ch(typeof e.metadataProfile=="string"?e.metadataProfile:a.validation.metadata_profile),h=DI(f,g,a.validation.metadata_required_fields),y=OI(a),v=xh(e.dependencyCycleSeverity),w=Rh(e.parentCycleSeverity),k=Lh(e.scanMode),S=Dh(s),T=await dC({requestedChecks:d,options:e,global:t,pmRoot:s,workspaceRoot:S,settings:a,items:u,statusRegistry:o,metadataPolicy:h,lifecyclePatternPolicy:y,dependencyCycleSeverity:v,parentCycleSeverity:w,fileScanMode:k,initialWarnings:[...new Set(l)],sourceIncomplete:p}),C=i?await uC(e,T,a,r,t,n):void 0,b=[...new Set(T.warnings)].sort((N,A)=>N.localeCompare(A)),E={ok:!T.checks.some(N=>N.status==="error"),has_warnings:b.length>0,checks:T.checks,warnings:b,...C!==void 0?{fixes:C}:{},generated_at:O(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return e.counts!==!0?E:{...RI(E),projection:{mode:"counts",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:[]}}}import{execFile as mC}from"node:child_process";import{promisify as _C}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]="d50f9868-5c11-51dc-967e-61ce41225ef1")}catch{}})();var pC=_C(mC),fC=16,gC=3e4;function hC(e,t,n){if(!(e.keys[t].value_type==="number"?typeof n.value=="number"&&Number.isFinite(n.value):Array.isArray(n.value)&&n.value.every(i=>typeof i=="string")))throw new TypeError(`assurance provider ${e.id} key ${t} returned the wrong value type`);if(!Number.isInteger(n.population_size)||n.population_size<0||!Number.isFinite(n.cost)||n.cost<0)throw new TypeError(`assurance provider ${e.id} returned an invalid population or cost`);return n}function yC(e,t){let n=e.keys[t.key];if(!n)throw new TypeError(`assurance provider ${e.id} does not declare key ${t.key}`);let i=t.parameters??{},r=n.parameters??{};for(let s of Object.entries(r).filter(([,a])=>a.required===!0).map(([a])=>a))if(!Object.hasOwn(i,s))throw new TypeError(`assurance provider ${e.id} key ${t.key} requires parameter ${s}`);for(let[s,a]of Object.entries(i)){let o=r[s];if(!o)throw new TypeError(`assurance provider ${e.id} key ${t.key} does not declare parameter ${s}`);if(a===null||typeof a!==o.type)throw new TypeError(`assurance provider ${e.id} parameter ${s} must be ${o.type}`)}return{...i}}async function vC(e,t,n,i){let r=yC(e,t),s=Promise.resolve().then(()=>e.resolve({provider:e.id,key:t.key,parameters:r,trigger:i,pm_root:n,...jl(n)}));s.catch(()=>{});let a;try{let o=await Promise.race([s,new Promise((c,d)=>{a=setTimeout(()=>d(new TypeError(`assurance provider ${e.id} timed out`)),e.timeout_ms??gC),a.unref?.()})]);return hC(e,t.key,o)}finally{clearTimeout(a)}}function ay(e,t,n,i){let r=e;for(let s of t.split(".")){if(typeof r!="object"||r===null||Array.isArray(r))throw new et(`assurance field ${t} is not present`,{source_kind:n,field:t,...i?{check:i}:{}});r=r[s]}if(typeof r=="number"&&Number.isFinite(r)||Array.isArray(r)&&r.every(s=>typeof s=="string"))return r;throw new et(`assurance field ${t} must resolve to a finite number or string array`,{source_kind:n,field:t,...i?{check:i}:{}})}function sy(e,t,n,i){let r=e.checks.find(s=>s.name===t);if(!r)throw new et(`assurance check ${t} is not present`,{source_kind:i,field:n,check:t});return{value:n==="status"||n==="ok"?r.ok?0:1:ay(r.details,n,i,t),population_size:1,cost:e.checks.length}}async function wC(e,t){if(t?.trim())return t.trim();try{let{stdout:n}=await pC("git",["rev-parse","HEAD^{commit}"],{cwd:e,encoding:"utf8",timeout:5e3,windowsHide:!0});return n.trim()}catch{return"working-copy"}}async function bC(e,t){let n=new Array(t.length),i=0,r=Array.from({length:Math.min(fC,t.length)},async()=>{for(;i<t.length;){let s=i;i+=1;let a=t[s],o=await ct(at(e,a.id),a.id);n[s]=o.map(c=>({op:c.op,author:c.author,agent_harness:c.agent_harness,agent_model:c.agent_model}))}});return await Promise.all(r),n.flat()}async function wi(e,t={}){let n=await I(e),i=F(n),r=K(n.schema),s=(t.strict_read===!0?(await Q_(void 0,{status:"all",full:!0,includeBody:!0,noTruncate:!0,strictRead:!0},{path:e})).items:await dt(e,n.item_format,i.type_to_folder,void 0,n.schema)).map(p=>({...p,id:p.id,status:p.status,type:p.type})),a={path:e},o=P(),c=Object.fromEntries((o?.assurance_providers??[]).map(p=>[p.definition.id,{cost_class:p.runtime_definition.cost_class,network:p.runtime_definition.network}])),d=new Map,l,u;return{tree_id:t.resolve_tree===!1?t.tree_id??"working-copy":await wC(e,t.tree_id),items:s,history:t.include_history===!1?[]:await bC(e,s),terminal_statuses:[...r.terminal_statuses],provider_capabilities:{...c,...t.provider_capabilities},external:async p=>{if(p.kind==="graph"){let h=ie({operation:p.operation,parameters:p.parameters??{}}),y=d.get(h);y===void 0&&(y=lp(p.operation,void 0,void 0,{...p.parameters,full:!0},a),d.set(h,y));let v=await y;return{value:ay(v,p.field,p.kind),population_size:s.length,cost:s.length}}if(p.kind==="validate"){l??=ry({counts:!0},a);let h=await l;return sy(h,p.check,p.field,p.kind)}if(p.kind==="health"){u??=qg(a,{checkOnly:!0,full:!0});let h=await u;return sy(h,p.check,p.field,p.kind)}let g=t.providers?.[p.provider];if(g)return g(p);let f=o_(o,p.provider);if(!f)throw new TypeError(`assurance provider ${p.provider} is not registered`);return vC(f.runtime_definition,p,e,t.trigger??"sdk")}}}import{createHash as kC}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]="c72d246d-a7ff-5c9d-8c36-4ebd45b8a69f")}catch{}})();function oy(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new TypeError("recurrence coverage request must be an object");let t=e;if(Object.hasOwn(t,"change"))throw new TypeError("recurrence coverage request does not accept change");if(t.uncoveredOnly!==void 0&&typeof t.uncoveredOnly!="boolean")throw new TypeError("recurrence coverage request.uncoveredOnly must be a boolean");let{policy:n,cursor:i,limit:r}=Tr({...t,change:{}});return{policy:n,...i===void 0?{}:{cursor:i},...r===void 0?{}:{limit:r},...t.uncoveredOnly===void 0?{}:{uncoveredOnly:t.uncoveredOnly}}}function EC(e,t){if(e===void 0)return 0;let n;try{n=JSON.parse(Buffer.from(e,"base64url").toString("utf8"))}catch{throw new TypeError("recurrence coverage cursor is invalid")}if(typeof n!="object"||n===null||Array.isArray(n))throw new TypeError("recurrence coverage cursor is invalid");let i=n;if(i.fingerprint!==t||typeof i.offset!="number"||!Number.isSafeInteger(i.offset)||i.offset<0)throw new TypeError("recurrence coverage cursor does not match this evidence and filter");return i.offset}function SC(e,t,n,i,r,s){let a=Object.fromEntries(oo.map(g=>[g,0])),o=0,c=0,d=0,l=0,u=[],p=kC("sha256").update(r);for(let g of i){let f=e.membership.get(g),h=n.has(g),y=f.family_ids.length>0;y&&h&&(o+=1),y||(c+=1),h||(d+=1);let v=t.get(g)?.escape_class;v!==void 0&&oo.includes(v)&&(a[v]+=1,l+=1),p.update(ie([g,h,t.get(g)??null,f.id,f.family_ids])),(!s||!y||!h)&&u.push(g)}return{classCounts:a,coveredCount:o,uncoveredCount:c,missingCount:d,classifiedCount:l,selected:u,fingerprint:p.digest("hex")}}function cy(e,t,n={}){N_(e);let i=n.limit??25;if(!Number.isSafeInteger(i)||i<1||i>100)throw new TypeError("recurrence coverage limit must be an integer from 1 through 100");let r=new Set,s=new Map;for(let S of t){if(r.has(S.id))throw new TypeError(`Duplicate recurrence item ${S.id}`);r.add(S.id);let T=Sr(S);T!==void 0&&s.set(S.id,T)}let a=R_(e.families,s),o=[...a.membership.keys()].sort(),c=ie({policy:e,uncoveredOnly:n.uncoveredOnly===!0}),{classCounts:d,coveredCount:l,uncoveredCount:u,missingCount:p,classifiedCount:g,selected:f,fingerprint:h}=SC(a,s,r,o,c,n.uncoveredOnly===!0),y=EC(n.cursor,h);if(y>f.length)throw new TypeError("recurrence coverage cursor offset exceeds the selected population");let v=f.slice(y,y+i).map(S=>{let T=a.membership.get(S),C=r.has(S);return{item_id:S,lineage_id:T.id,lineage_item_count:T.item_ids.length,family_ids:T.family_ids,present:C,...C?T.family_ids.length===0?{finding:"unregistered_recurrence_item"}:{}:{finding:"missing_recurrence_item"}}}),w=y+v.length,k=o.length===0?null:d.production_defect/o.length;return{ok:u===0&&p===0,fingerprint:h,items:v,total:f.length,has_more:w<f.length,...w<f.length?{next_cursor:Buffer.from(JSON.stringify({fingerprint:h,offset:w})).toString("base64url")}:{},population:{scope:"all_recorded_recurrence_items",item_count:o.length,lineage_count:a.lineages.length,edge_count:a.edge_count,covered_item_count:l,uncovered_item_count:u,missing_item_count:p,classified_item_count:g,unclassified_item_count:o.length-g,class_counts:d,escape_rate:g===o.length?k:null,escape_rate_lower_bound:k},budget_scope:"registered_families_only",cost:{items_scanned:t.length,edges_scanned:a.edge_count,row_limit:i},row_contract:{row_keys:["items"],jq_selector:".items[]"}}}import{createHash as TC}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]="676125a5-e16e-5fa2-819f-f4028dc0c3c2")}catch{}})();var Dc,dy=["list","show","put","remove","run","verdicts","presets","apply","derive","promote","risk","lineages"],Nc=["measurement","assertion","gate"];function AC(e){if(dy.includes(e))return e;throw cr({command_path:"assurance",token:e,allowed:dy,display_name:"assurance action"})}function Sn(e,t,n){throw new _(t,m.USAGE,{code:"missing_required_argument",required:`Provide the missing assurance operand: ${e}.`,examples:[n],recovery:{missing:[e]}})}function IC(e){if(!e)return Sn("kind",`Assurance declaration kind is required. Expected: ${Nc.join(", ")}`,"pm assurance list measurement");if(Nc.includes(e))return e;throw new _(`Assurance declaration kind is required. Expected: ${Nc.join(", ")}`,m.USAGE)}function ly(e){if(!e)return Sn("preset",`Assurance preset is required. Expected: ${li.join(", ")}`,"pm assurance apply software-delivery --owner <pm-item-id>");if(li.includes(e))return e;throw new _(`Assurance preset is required. Expected: ${li.join(", ")}`,m.USAGE)}function Mc(e){return e.owner?.trim()?e.owner.trim():Sn("owner","assurance preset and derivation actions require --owner <pm-item-id>","pm assurance apply software-delivery --owner <pm-item-id>")}function CC(e,t){let n=t;if(typeof t=="string")if(!t.trim())n=void 0;else try{n=JSON.parse(t)}catch(i){throw new _("assurance definition must be valid JSON",m.USAGE,{reason:i instanceof Error?i.message:"invalid_json"})}if(typeof n!="object"||n===null||Array.isArray(n))throw new _("assurance put requires a JSON object definition",m.USAGE);return n}async function xC(e){let[t,n,i]=await Promise.all([ti(e,"measurement"),ti(e,"assertion"),ti(e,"gate")]);return{version:1,measurements:t.items,assertions:n.items,gates:i.items}}function uy(e,t){return t===!0?{id:e.id}:e}async function RC(e,t){let n=t.authorization_decision;if(!n)return[];let i=await wi(e,{include_history:!1,resolve_tree:!1}),r=i.items.find(a=>a.id===n),s=new Set(i.terminal_statuses);if(!r||r.type.toLowerCase()!=="decision"||!s.has(r.status))throw new _(`Assurance authorization ${n} must name a terminal Decision item`,m.USAGE);return[r.id]}async function OC(e,t){let n=Lo(e.limit,"assurance verdict limit");if(n!==void 0&&(n<1||n>gn))throw new _(`assurance verdict limit must be an integer from 1 through ${gn}`,m.USAGE);let i=await Xp(t,{gate_id:e.id??e.gate,limit:n});return{items:i,count:i.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function LC(e,t,n){if(e==="presets"){if(t.preset??t.id)return Jr(ly(t.preset??t.id),Mc(t));let r=li.map(s=>{let a=Jr(s,"pm-owner");return{id:s,title:a.title,description:a.description}});return{items:r,count:r.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}if(e==="apply")return fn(()=>rg(n,ly(t.preset??t.id),Mc(t),{author:t.author,message:t.message}));if(e==="derive"){let r=await sg(await wi(n,{resolve_tree:!1,trigger:"derive"}),Mc(t)),s=t.apply?await fn(()=>ag(n,r,{author:t.author,message:t.message??"Accept observation-derived assurance proposals"})):void 0;return{items:r,count:r.length,...s?{applied:s}:{}}}if(!t.id)return Sn("assertion-id","assurance promote requires an assertion id","pm assurance promote <assertion-id> --enforcement warn");if(t.enforcement!=="warn"&&t.enforcement!=="block")throw new _("assurance promote requires --enforcement warn|block",m.USAGE);let i=await So(n,"assertion",t.id);return fn(()=>og(n,i,t.enforcement,{author:t.author,message:t.message}))}async function DC(e,t,n){if(!e.id)return Sn("gate-id","assurance run requires a gate id","pm assurance run <gate-id> --trigger ci --dry-run");let i=e.id;if(!e.trigger)throw new _("assurance run requires a trigger",m.USAGE);if(!lt.includes(e.trigger))throw new _(`Unknown assurance trigger ${e.trigger}. Expected: ${lt.join(", ")}`,m.USAGE);let r=e.trigger,[s,a]=await Promise.all([xC(t),wi(t,{...n.workspace,tree_id:e.tree,trigger:r})]),o=await Mp(()=>Hp(i,s,a,{trigger:r,dry_run:e.dry_run===!0}));return o.dry_run||await Jp(t,o,{author:e.author,message:e.message}),o}function my(e){throw e instanceof _?e:new _(e instanceof Error?e.message:"assurance risk request is invalid",m.USAGE)}function NC(e){if(e.limit!==void 0)throw new _(`assurance ${e.action} does not accept --limit; set limit inside the definition`,m.USAGE);let t=e.definition;if(typeof t=="string")try{t=JSON.parse(t)}catch(n){throw new _(`assurance ${e.action} definition must be valid JSON`,m.USAGE,{reason:n instanceof Error?n.message:"invalid_json"})}try{return e.action==="lineages"?oy(t):Tr(t)}catch(n){if(e.action==="risk"&&n instanceof D_)throw new _(n.message,m.USAGE,{required:"Supply definition.policy with the project's declared recurrence policy and definition.change with the proposed change; no policy is inferred.",recovery:{suggested_retry:`pm assurance ${e.action} --help`,suggested_retry_args:["assurance",e.action,"--help"]}});return my(n)}}function MC(e,t){let n=new Set;for(let[i,r]of t)e.item_fingerprints.get(i)!==r&&n.add(i);for(let i of e.item_fingerprints.keys())t.has(i)||n.add(i);return n}function PC(e,t,n){let i=ie(t.policy),r=Dc?.pm_root===e?Dc:void 0,s=new Map(n.map(d=>[d.id,TC("sha256").update(ie([C_(d),Sr(d)])).digest("hex")])),a=r?.policy_serialized===i?r:void 0,o=a?MC(a,s):new Set,c=O_(t.policy,a?n.filter(d=>o.has(d.id)):n,a?{previous_index:a.index,changed_item_ids:[...o]}:{});return Dc={pm_root:e,policy_serialized:i,item_fingerprints:s,index:c},c}async function FC(e,t){let n=NC(e),i=await wi(t,{strict_read:!0,include_history:!1,resolve_tree:!1});try{return"change"in n?L_(PC(t,n,i.items),n.change,{cursor:n.cursor,limit:n.limit}):cy(n.policy,i.items,n)}catch(r){return my(r)}}async function $C(e,t={},n={}){let i=AC(e.action),r=x(process.cwd(),t.path);if(i==="presets"||i==="apply"||i==="derive"||i==="promote")return LC(i,e,r);if(i==="verdicts")return OC(e,r);if(i==="run")return DC(e,r,n);if(["risk","lineages"].includes(i))return FC(e,r);let s=IC(e.kind);if(i==="list")return ti(r,s);if(!e.id)return Sn("id",`assurance ${i} requires an id`,`pm assurance ${i} ${s} <id>`);let a=e.id;if(i==="show")return So(r,s,a);if(i==="remove"){let l=await fn(()=>Yp(r,s,a,{author:e.author,message:e.message}));return uy(l,e.idOnly)}let o=CC(s,e.definition);if(o.id!==a)throw new _(`Assurance definition id ${o.id} does not match requested id ${a}`,m.USAGE);let c={author:e.author,message:e.message,...s==="assertion"?{authorized_decision_ids:await RC(r,o)}:{}},d=await fn(()=>Pr(r,s,o,c));return uy(d,e.idOnly)}function BK(e,t,n){let i={...e,...t};return $C({action:L(i,"subcommand")??L(i,"assuranceAction")??L(i,"operation")??"",kind:L(i,"kind"),id:L(i,"id"),definition:i.definition,trigger:L(i,"trigger"),tree:L(i,"treeId")??L(i,"tree"),gate:L(i,"gate"),limit:Lo(i.limit,"assurance verdict limit"),dry_run:i.dryRun===!0||i.dry_run===!0,fullChangedFields:i.fullChangedFields===!0,idOnly:i.idOnly===!0,author:L(i,"author"),message:L(i,"message"),preset:L(i,"preset"),owner:L(i,"owner"),apply:i.apply===!0,enforcement:L(i,"enforcement")},n)}import Pc from"node:fs/promises";import _y 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]="9c0640f0-505c-5f4a-bb7a-daa3cc775239")}catch{}})();var UC=1440*60*1e3,jC=new Set(["committed","compensated"]);function GC(e){let t;try{t=JSON.parse(e)}catch{return{status:null,updatedAt:null}}if(typeof t!="object"||t===null||Array.isArray(t))return{status:null,updatedAt:null};let n=t;return{status:typeof n.status=="string"?n.status:null,updatedAt:typeof n.updatedAt=="string"?n.updatedAt:null}}function qC(e,t,n,i,r){let s=n===null?Number.NaN:Date.parse(n);if(t===null||!Number.isFinite(s))return{entry:{file:e,status:t,age_seconds:null,stale:!1,reason:"unparseable"},remove:!1};let a=i-s;return jC.has(t)?a>r?{entry:{file:e,status:t,age_seconds:Math.floor(a/1e3),stale:!0},remove:!0}:{entry:{file:e,status:t,age_seconds:Math.floor(a/1e3),stale:!1,reason:"fresh"},remove:!1}:{entry:{file:e,status:t,age_seconds:Math.floor(a/1e3),stale:!1,reason:"active"},remove:!1}}async function KC(e,t,n,i){let r=i.hooks?.onRead?await i.hooks.onRead(e):[],s=GC(await Pc.readFile(e,"utf8")),a=qC(t,s.status,s.updatedAt,i.nowMs,i.retentionMs);return a.entry.reason==="unparseable"&&r.push(`transaction_journal_unparseable:${n}`),a.remove&&!i.dryRun&&(await Pc.rm(e,{force:!0}),i.hooks?.onWrite&&r.push(...await i.hooks.onWrite(e))),{decision:a,warnings:r}}async function py(e,t){let{dryRun:n,hooks:i}=t,r=t.now??Date.now(),s=Math.max(0,t.retentionDays)*UC,a=_y.join(e,"transactions","sdk"),o={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c;try{c=(await Pc.readdir(a)).filter(d=>d.endsWith(".json")).sort((d,l)=>d.localeCompare(l))}catch(d){if(q(d))return o;throw d}for(let d of c){let l=_y.join(a,d),u=`transactions/sdk/${d}`,p=await KC(l,u,d,{dryRun:n,hooks:i,nowMs:r,retentionMs:s});o.warnings.push(...p.warnings),o.scanned+=1;let{decision:g}=p;if(!g.remove){o.retained.push(u),o.entries.push(g.entry);continue}o.removed.push(u),o.entries.push(g.entry)}return o}import Tn from"node:fs/promises";import bs from"node:path";import ws from"node:fs/promises";import Fc 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]="4fe37a62-2d0f-55f6-bb98-7162e7e8b8fe")}catch{}})();var zC=864e5;function WC(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t.created_at;return typeof n=="string"?n:null}async function BC(e,t){let n;try{n=await ws.readdir(e,{withFileTypes:!0})}catch(r){if(q(r))return[];throw r}let i=[];for(let r of n)if(r.isDirectory()){let s=Fc.join(e,r.name),a;try{a=await ws.readdir(s)}catch(o){q(o)||t.push(`checkpoint_subdir_unreadable:${r.name}`);continue}for(let o of a)o.endsWith(".json")&&i.push(`${r.name}/${o}`)}else r.name.endsWith(".json")&&i.push(r.name);return i.sort()}async function fy(e,t){let{dryRun:n,hooks:i}=t,r=t.now??Date.now(),s=Math.max(0,t.retentionDays)*zC,a=Fc.join(e,"checkpoints"),o={scanned:0,removed:[],retained:[],warnings:[],entries:[]},c=await BC(a,o.warnings);for(let d of c){let l=Fc.join(a,d),u=`checkpoints/${d}`;o.scanned+=1,i?.onRead&&o.warnings.push(...await i.onRead(l));let p;try{p=await ws.readFile(l,"utf8")}catch(v){if(q(v)){o.scanned-=1;continue}o.warnings.push(`checkpoint_unreadable:${d}`),o.retained.push(u),o.entries.push({file:u,created_at:null,age_seconds:null,stale:!1,reason:"unparseable"});continue}let g=WC(p),f=g===null?Number.NaN:Date.parse(g);if(!Number.isFinite(f)){o.warnings.push(`checkpoint_unparseable:${d}`),o.retained.push(u),o.entries.push({file:u,created_at:g,age_seconds:null,stale:!1,reason:"unparseable"});continue}let h=r-f,y={file:u,created_at:g,age_seconds:Math.floor(h/1e3),stale:h>s,reason:h>s?"expired":"active"};if(!y.stale){o.retained.push(u),o.entries.push(y);continue}if(!n){try{await ws.unlink(l)}catch(v){if(!q(v)){o.warnings.push(`checkpoint_remove_failed:${d}`),o.retained.push(u),o.entries.push(y);continue}}i?.onWrite&&o.warnings.push(...await i.onWrite(l))}o.removed.push(u),o.entries.push(y)}return o}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="38736716-2644-5166-bfec-4ed4bca951b9")}catch{}})();var bi=["index","embeddings","runtime","locks","checkpoints","transactions"],HC=1440*60*1e3,VC=[{scope:"index",relativePath:"index/manifest.json",kind:"file"},{scope:"embeddings",relativePath:"search/embeddings.jsonl",kind:"file"},{scope:"embeddings",relativePath:"search/vectorization-status.json",kind:"file"},{scope:"embeddings",relativePath:"search/lancedb",kind:"directory"},{scope:"embeddings",relativePath:"search/pending-refresh.json",kind:"file"},{scope:"embeddings",relativePath:"search/pending-refresh.gate.lock",kind:"directory"},{scope:"runtime",relativePath:"runtime/test-runs",kind:"directory"},{scope:"runtime",relativePath:"runtime/history-drift-cache.json",kind:"file"}];async function YC(e,t,n){let i=t.relativePath,r=bs.join(e,i),s=await $e({path:r,scope:"project"});try{let a=await Tn.stat(r);if(t.kind==="file"&&!a.isFile())return{removed:!1,warnings:[...s,`not_a_file:${i}`]};if(t.kind==="directory"&&!a.isDirectory())return{removed:!1,warnings:[...s,`not_a_directory:${i}`]};if(n)return{removed:!0,warnings:s};t.kind==="file"?await Tn.unlink(r):await Tn.rm(r,{recursive:!0,force:!0});let o=await ot({path:r,scope:"project",op:"gc:remove"});return{removed:!0,warnings:[...s,...o]}}catch(a){if(q(a))return{removed:!1,warnings:s};throw a}}async function JC(e,t){let n=[{relativePath:"runtime/workspace-snapshots/objects",prefix:".create-"},{relativePath:"runtime/workspace-snapshots/refs",prefix:".ref-"}],i=[],r=[],s=[],a=Date.now()-HC;for(let o of n){let c=bs.join(e,o.relativePath);if(!await te(c))continue;let d=(await Tn.readdir(c)).filter(l=>l.startsWith(o.prefix)).sort();for(let l of d){let u=bs.posix.join(o.relativePath,l),p=bs.join(c,l);s.push(...await $e({path:p,scope:"project"}));let g=await Tn.stat(p).catch(f=>{if(!q(f))throw f});if(g){if(g.mtimeMs>a){r.push(u);continue}i.push(u),!t&&(await Tn.rm(p,{recursive:!0,force:!0}),s.push(...await ot({path:p,scope:"project",op:"gc:workspace_snapshot_temp_remove"})))}}}return{removed:i,retained:r,warnings:s}}function XC(e){if(!e||e.length===0)return[...bi];let t=e.flatMap(i=>i.split(",")).map(i=>i.trim().toLowerCase()).filter(i=>i.length>0);if(t.length===0)throw new _(`--scope requires at least one value (${bi.join(",")})`,m.USAGE);let n=new Set;for(let i of t){if(!bi.includes(i))throw new _(`Invalid --scope value "${i}". Expected one or more of: ${bi.join(", ")}`,m.USAGE);n.add(i)}return bi.filter(i=>n.has(i))}function QC(e){let t=[];e.dryRun&&t.push("Dry-run preview only: no cache artifacts were deleted.");let n=e.scopes.includes("index")||e.scopes.includes("embeddings"),i=e.removed.some(r=>r==="index/manifest.json"||r==="search/embeddings.jsonl"||r==="search/vectorization-status.json"||r==="search/lancedb"||r==="search/pending-refresh.json"||r==="search/pending-refresh.gate.lock");return n&&i&&t.push('Search artifacts were removed; the semantic index (including any queued background refresh) is invalidated. Run "pm install search-advanced --project" if reindex is unavailable, then "pm reindex --mode keyword" (and "--mode semantic" when semantic search is enabled) before search-heavy workflows.'),e.removed.includes("runtime/history-drift-cache.json")&&t.push('History drift cache was removed; the next "pm health" run performs a full history-drift re-scan.'),!e.dryRun&&e.removed.some(r=>r.startsWith("checkpoints/"))&&t.push('Aged rollback checkpoints were removed; their "pm update-many"/"pm close-many --rollback" windows are no longer recoverable.'),!e.dryRun&&e.removed.some(r=>r.startsWith("transactions/"))&&t.push("Aged terminal workspace-transaction journals were removed; replaying those transactionIds re-executes their idempotent steps instead of short-circuiting."),t}async function fz(e,t={}){let n=x(process.cwd(),e.path);await $(n);let i=await I(n),r=t.dryRun===!0,s=XC(t.scope),a=VC.filter(f=>s.includes(f.scope)),o=[],c=[],d=[];for(let f of a){let h=await YC(n,f,r);h.removed?o.push(f.relativePath):c.push(f.relativePath),d.push(...h.warnings)}if(s.includes("runtime")){let f=await JC(n,r);o.push(...f.removed),c.push(...f.retained),d.push(...f.warnings)}let l;if(s.includes("locks")){let f=await Tg(n,{dryRun:r,hooks:{onRead:h=>$e({path:h,scope:"project"}),onWrite:h=>ot({path:h,scope:"project",op:"gc:lock_remove"})}});o.push(...f.removed),c.push(...f.retained),d.push(...f.warnings),l={scanned:f.scanned,removed:f.removed.length,retained:f.retained.length}}let u;if(s.includes("transactions")){let f=i.checkpoints.retention_days,h=await py(n,{dryRun:r,retentionDays:f,hooks:{onRead:y=>$e({path:y,scope:"project"}),onWrite:y=>ot({path:y,scope:"project",op:"gc:transaction_journal_remove"})}});o.push(...h.removed),c.push(...h.retained),d.push(...h.warnings),u={scanned:h.scanned,removed:h.removed.length,retained:h.retained.length,retention_days:f}}let p;if(s.includes("checkpoints")){let f=i.checkpoints.retention_days,h=await fy(n,{dryRun:r,retentionDays:f,hooks:{onRead:y=>$e({path:y,scope:"project"}),onWrite:y=>ot({path:y,scope:"project",op:"gc:checkpoint_remove"})}});o.push(...h.removed),c.push(...h.retained),d.push(...h.warnings),p={scanned:h.scanned,removed:h.removed.length,retained:h.retained.length,retention_days:f}}d.push(...await Wl({mode:r?"gc:dry-run":"gc",total_items:a.length}));let g=QC({dryRun:r,scopes:s,removed:o});return{ok:d.length===0,dry_run:r,scope:s,removed:o,retained:c,warnings:d,...l?{locks:l}:{},...p?{checkpoints:p}:{},...u?{transactions:u}:{},guidance:g,generated_at:O()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8e07b07a-fde3-5173-bb7c-7e8ade88570c")}catch{}})();var vz=Object.freeze({requireCloseReason:!0,orderingEdges:"preserve"});function ZC(e){let t=[{source:"explicit",value:e.explicit},{source:"duplicate",value:e.duplicateOf===void 0?void 0:`Duplicate of ${e.duplicateOf}`},{source:"resolution",value:e.resolution},{source:"message",value:e.message}];for(let n of t){let i=n.value?.trim();if(i)return{closeReason:i,source:n.source}}return{source:"none"}}function gy(e,t){return $c(e,t,{operation:"close"})}function $c(e,t,n){let i=ZC(e);if(!t||i.closeReason!==void 0)return i;let r=n.operation==="create"?[`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --close-reason "<closing summary>"`,`pm create --title "<title>" --type <type> --status ${n.status??"closed"} --resolution "<resolution summary>"`,"pm create --stdin-json < item.json"]:['pm close <id> "Done: <what changed and why>"','pm close <id> --reason "<closing summary>"','pm close <id> -m "<closing summary>"',"pm close <id> --duplicate-of <canonical-id>"];throw new _("Close reason text is required because governance.require_close_reason is enabled",m.USAGE,{code:"close_reason_required",required:"Provide an author-controlled closing summary as the reason, message, resolution, or duplicate target.",why:"governance.require_close_reason is enabled, so tools must not invent immutable closure evidence.",examples:r,nextSteps:[`Re-run the ${n.operation} operation with a closing summary.`,"To stop requiring reasons, run: pm config set governance-require-close-reason --policy disabled"]})}function hy(e,t){let n=typeof e.blocked_by=="string"?e.blocked_by.trim():"",i=e.blocked_by!==void 0,r=e.dependencies??[],s=r.filter(d=>d.kind==="blocked_by"),a=e.blocked_reason!==void 0,o=[];if(i&&(delete e.blocked_by,o.push("blocked_by")),a&&(delete e.blocked_reason,o.push("blocked_reason")),t.orderingEdges==="remove"&&s.length>0){let d=new Set(s),l=r.filter(u=>!d.has(u));l.length>0?e.dependencies=l:delete e.dependencies,o.push("dependencies")}if(t.orderingEdges==="remove")return{changedFields:o,warnings:[...n?[`closed_cleared_blocked_by:${e.id}:${n}`]:[],...s.length>0?[`closed_removed_predecessors:${e.id}:${s.map(d=>d.id).join(",")}`,`closed_removed_predecessors_count:${e.id}:${s.length}`]:[]]};let c=[...new Set([...n?[n]:[],...s.map(d=>d.id)])];return c.length===0?{changedFields:o,warnings:[]}:{changedFields:o,warnings:[`closed_preserved_predecessors:${e.id}:${c.join(",")}`]}}(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]="6b7f5ee8-94ca-574f-b660-963eb574d571")}catch{}})();var ex=[{key:"resolution",label:"resolution (--resolution)"},{key:"expected_result",label:"expected_result (--expected-result)"},{key:"actual_result",label:"actual_result (--actual-result)"}];function tx(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0||t==="warn")return"warn";if(t==="off"||t==="none"||t==="disabled")return"off";if(t==="strict")return"strict";throw new _(`Invalid --validate-close mode "${e}" (expected "off", "warn", or "strict")`,m.USAGE)}function vy(e){let t=[];for(let n of ex){let i=e[n.key];(typeof i!="string"||i.trim().length===0)&&t.push(n)}return t}function wy(e,t,n={}){let i=vy(e);if(i.length===0)return;let r={resolution:n.resolution,expected_result:n.expectedResult,actual_result:n.actualResult},s=i.map(o=>`--${o.key.replaceAll("_","-")}`),a=["--pm-path",t,"update",e.id,...i.flatMap((o,c)=>[s[c],r[o.key]?.trim()||"<value>"])];return{missing:s,suggested_retry:fe(a),suggested_retry_args:a}}async function nx(e,t,n){let i=new Set,r=t;for(;typeof r=="string"&&r.trim().length>0;){let s=r.trim();if(s===n)return!0;if(i.has(s))return!1;i.add(s),r=(await e(s))?.duplicate_of}return!1}function ix(e){return typeof e!="string"||e.trim().length===0}async function rx(e,t,n,i){let r=n?.trim();if(!r)return;if(r===i)throw new _("An item cannot be closed as a duplicate of itself.",m.USAGE,{code:"duplicate_target_self",why:"--duplicate-of must identify the canonical item that should remain open or already represent the work."});let s=F(t,P()),a=new Map,o=async d=>{if(a.has(d))return a.get(d)??null;let l=await Y(e,d,t.id_prefix,t.item_format,s.type_to_folder);if(!l)return a.set(d,null),null;let{document:u}=await he(l,{schema:t.schema});return a.set(d,u.metadata),u.metadata},c=await o(r);if(!c)throw new _(`Duplicate target "${r}" was not found. Create or locate the canonical item first.`,m.USAGE,{code:"duplicate_target_missing",why:"Duplicate closure should point at a real canonical pm item so future dedupe and changelog tooling can trace the relationship.",examples:[`pm close ${i} "Duplicate of ${r}" --duplicate-of ${r}`],nextSteps:["Run pm search/list to find the canonical item, then retry with --duplicate-of <id>."]});if(await nx(o,c.duplicate_of,i))throw new _(`Circular duplicate reference detected. Target "${r}" points back to "${i}".`,m.USAGE,{code:"duplicate_target_circular",why:"Circular duplicate relationships create loops for dedupe and status propagation tooling.",nextSteps:["Choose the existing canonical item, or clear the target duplicate_of metadata before closing this item as a duplicate."]});if(typeof c.duplicate_of=="string"&&c.duplicate_of.trim().length>0)throw new _(`Duplicate target "${r}" is already marked as a duplicate of "${c.duplicate_of.trim()}".`,m.USAGE,{code:"duplicate_target_is_duplicate",why:"Duplicate closure should point directly at the canonical item, not another duplicate.",examples:[`pm close ${i} "Duplicate of ${c.duplicate_of.trim()}" --duplicate-of ${c.duplicate_of.trim()}`],nextSteps:["Use the canonical item referenced by duplicate_of as the --duplicate-of target."]});return c.id}function sx(e,t,n){return e.filter(i=>i.parent===t&&!_e(i.status,n)).map(i=>i.id).sort((i,r)=>i.localeCompare(r))}function ax(e,t,n){let i=new Map(e.map(o=>[o.id.trim().toLowerCase(),o])),r=q_(e),s=t.trim().toLowerCase(),a=n.blocked_statuses;return e.filter(o=>a.has(o.status)).map(o=>({item:o,blockerIds:r.get(o.id.trim().toLowerCase())})).filter(({blockerIds:o})=>o.includes(s)).filter(({blockerIds:o})=>o.every(c=>{if(c===s)return!0;let d=i.get(c);return d!==void 0&&_e(d.status,n)})).map(({item:o,blockerIds:c})=>({id:o.id,blocker_ids:c})).sort((o,c)=>o.id.localeCompare(c.id))}async function ox(e,t,n,i,r,s){let a=ax(n,i,s),o=[];for(let c of a)try{let d=await se({pmRoot:e,settings:t,id:c.id,op:"update",author:r,message:`Auto-unblocked after blocker ${i} closed`,mutate(l){let u=l.metadata.dependencies??[],p=u.filter(f=>{let h=f.id.trim().toLowerCase();return f.kind!=="blocked_by"||!c.blocker_ids.includes(h)});l.metadata.status=s.open_status,delete l.metadata.blocked_by,delete l.metadata.blocked_reason,l.metadata.unblock_note=`Auto-unblocked after blocker ${i} closed; all blockers resolved (${c.blocker_ids.join(", ")}).`,p.length>0?l.metadata.dependencies=p:delete l.metadata.dependencies;let g=["status","blocked_by","blocked_reason","unblock_note"];return p.length!==u.length&&g.push("dependencies"),{changedFields:g}}});o.push(`auto_unblocked:${d.item.id}:resolved_blockers=${c.blocker_ids.join(",")}`)}catch(d){let l=d instanceof Error?d.message.replace(/\s+/g," ").trim():"unknown";o.push(`auto_unblock_failed:${c.id}:${l}`)}return o}function cx(e,t){let n=[],i=[{option:t.resolution,key:"resolution"},{option:t.expectedResult,key:"expected_result"},{option:t.actualResult,key:"actual_result"}];for(let{option:r,key:s}of i){if(typeof r!="string")continue;let a=r.trim();a.length!==0&&(e[s]=a,n.push(s))}return n}function dx(e,t){if(t===void 0)return[];e.duplicate_of=t;let n=[],i=[{key:"resolution",value:`Duplicate of ${t}`},{key:"expected_result",value:`Canonical item ${t} tracks the work.`},{key:"actual_result",value:`Closed as duplicate of ${t}.`}];for(let{key:r,value:s}of i)ix(e[r])&&(e[r]=s,n.push(r));return n}function lx(e,t,n,i){let r=[];if(t!=="off"){let s=vy(e);if(s.length>0){let a=s.map(o=>o.label);if(t==="strict"){let o=s.map(d=>`--${d.key.replaceAll("_","-")}`),c=["--pm-path",i,"update",e.id,...o.flatMap(d=>[d,"<value>"])];throw new _(`Cannot close item ${e.id}: missing ${a.join(", ")}. Populate fields or use --validate-close warn.`,m.USAGE,{code:"close_validation_missing_fields",recovery:{missing:o,suggested_retry:fe(c)},nextSteps:["Run the suggested pm update, then retry the original pm close invocation.","Use --validate-close warn only when governance permits an evidenced exception."]})}r.push(`close_validation_missing_fields:${e.id}:${a.join(",")}`)}if(n.length>0){if(t==="strict")throw new _(`Cannot close item ${e.id}: active child items remain open (${n.join(", ")}). Close, cancel, or re-parent them first, or use --validate-close warn.`,m.USAGE);r.push(`close_validation_active_children:${e.id}:${n.join(",")}`)}return r}return n.length>0&&r.push(`closed_with_active_children:${e.id}:${n.join(",")}`),r}function ux(e,t){return t!==void 0?(e.close_reason=t,["close_reason"]):[]}function mx(e){return e.assignee===void 0?[]:(delete e.assignee,["assignee"])}function _x(e,t){if(_e(e.status,t.statusRegistry)&&!t.force)throw new _(`Item ${e.id} is already terminal; use pm update to append acceptance evidence, or --force only for an intentional repeat closure.`,m.CONFLICT,{recovery:wy(e,t.pmRoot,t.options)});let n=cx(e,t.options),i=dx(e,t.duplicateOf),r=lx(e,t.validateCloseMode,t.activeChildIds,t.pmRoot);e.status=t.statusRegistry.close_status,e.closed_at=t.closedAt;let s=t.options.completedAt!==void 0||e.completed_at===void 0;s&&(e.completed_at=t.completedAt);let a=["status","closed_at",...s?["completed_at"]:[],...ux(e,t.closeReason),...n];if(S_(e)&&(e.plan_mode="completed",a.push("plan_mode")),t.duplicateOf!==void 0){a.push("duplicate_of");for(let c of i)a.includes(c)||a.push(c)}a.push(...mx(e));let o=hy(e,t.lifecyclePolicy);return a.push(...o.changedFields),r.push(...o.warnings),{changedFields:a,...r.length>0?{warnings:r}:{}}}async function px(e,t,n,i){let r=x(process.cwd(),i.path);await $(r);let s=await I(r),a=K(s.schema),o=U(n.author,s.author_default),c=F(s,P()).type_to_folder,d=await Y(r,e,s.id_prefix,s.item_format,c);if(!d)throw await qn(r,e,s.id_prefix,c);let l=await rx(r,s,n.duplicateOf,d.id),u={requireCloseReason:n.lifecyclePolicy?.requireCloseReason??s.governance.require_close_reason,orderingEdges:n.lifecyclePolicy?.orderingEdges??"preserve"},p=gy({explicit:t,duplicateOf:l,resolution:n.resolution,message:n.message},u.requireCloseReason).closeReason,g=tx(n.validateClose)??s.governance.close_validation_default,f=await Se(r,s.item_format,c,void 0,s.schema),h=sx(f,d.id,a),y=O(),v=n.completedAt===void 0?y:ge(n.completedAt,new Date(y),"completed-at"),w=await se({pmRoot:r,settings:s,id:d.id,op:"close",author:o,message:n.message,force:n.force,mutate(S){return _x(S.metadata,{pmRoot:r,statusRegistry:a,force:n.force,options:n,duplicateOf:l,validateCloseMode:g,activeChildIds:h,closeReason:p,closedAt:y,completedAt:v,lifecyclePolicy:u})}}),k=g==="warn"?wy(w.item,r):void 0;return{item:w.item,changed_fields:w.changedFields,...k?{follow_up:{kind:"complete_close_evidence",missing:k.missing,suggested_command:k.suggested_retry,suggested_command_args:k.suggested_retry_args}}:{},warnings:[...w.warnings,...await ox(r,s,f,d.id,o,a)]}}function ks(e,t,n,i){return px(e,t,n,i)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="73852fdf-f072-51ab-9449-d7922712eeb4")}catch{}})();function by(e){return[...e].sort().join("\0")}function fx(e,t,n){let i=e.successors.get(t);i?i.push(n):e.successors.set(t,[n]);let r=e.predecessors.get(n);r?r.push(t):e.predecessors.set(n,[t])}function ky(e,t,n,i,r){let s=t.resolve(r);if(s?.ordering!==!0)return;let a=B_(i),o=a===void 0?void 0:e.canonicalIds.get(a.toLowerCase());if(o===void 0)return;let c=(s.precedence??"source_before_target")==="source_before_target";fx(e,c?n:o,c?o:n)}function gx(e,t){let n={successors:new Map,predecessors:new Map,canonicalIds:new Map},i=e.filter(r=>typeof r?.id=="string"&&r.id.trim().length>0);for(let r of i){let s=r.id.trim();n.canonicalIds.set(s.toLowerCase(),s)}for(let r of i){let s=r.id.trim();ky(n,t,s,r.blocked_by,"blocked_by");for(let a of r.dependencies??[])typeof a!="object"||a===null||ky(n,t,s,a.id,typeof a.kind=="string"?a.kind:"related")}for(let r of[n.successors,n.predecessors])for(let s of r.values())s.sort();return n}function hx(e,t){let n=new Set([t]),i=[t];for(;i.length>0;){let r=i.pop();for(let s of[e.successors,e.predecessors])for(let a of s.get(r)??[])n.has(a)||(n.add(a),i.push(a))}return n}function yx(e,t){let n=new Map;for(let i of t){let r=(e.successors.get(i)??[]).filter(s=>t.has(s));r.length>0&&n.set(i,r)}return n}function Ey(e,t,n){let i=gx(e,t),r=i.canonicalIds.get(n.trim().toLowerCase());if(r===void 0)return{cycles:[],successors:new Map,canonical:n};let s=yx(i,hx(i,r));return{cycles:cp(s).filter(a=>a.includes(r)),successors:s,canonical:r}}function vx(e,t,n){let i=new Set(t),r=i.has(n)?n:t[0];if(e.get(r)?.includes(r))return[r,r];for(let s of e.get(r)??[]){if(!i.has(s))continue;let a=wx(e,i,r,s);if(a)return a}return[...t,t[0]]}function wx(e,t,n,i){let r=[[i]],s=new Set([n,i]);for(;r.length>0;){let a=r.shift(),o=a.at(-1);for(let c of e.get(o)??[]){if(c===n)return[n,...a,n];!t.has(c)||s.has(c)||(s.add(c),r.push([...a,c]))}}}function Es(e,t,n){let i=ae(),r=Ey(e,i,n),s=Ey(t,i,n),a=new Set(r.cycles.map(by)),o=new Set(lo(e,void 0,i).map(c=>`${c.holder_id.toLowerCase()}\0${c.target_id.toLowerCase()}\0${c.dependency_kind}`));return[...lo(t,void 0,i).filter(c=>c.holder_id.toLowerCase()===n.trim().toLowerCase()&&!o.has(`${c.holder_id.toLowerCase()}\0${c.target_id.toLowerCase()}\0${c.dependency_kind}`)).map(c=>`ordering_storage_contradiction_created:${dp(c)}:remove_contradicting_dependency_row:run_pm_graph_audit`),...s.cycles.filter(c=>!a.has(by(c))).map(c=>`ordering_cycle_created:${vx(s.successors,c,s.canonical).join(" -> ")}:items_will_not_be_ready:run_pm_graph_audit`)]}(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]="5f2ca18e-450d-5b6e-9e07-7bbf080764f9")}catch{}})();function Ss(e,t){let n=t.resolve(e);return n?.hierarchy===!0||n?.outgoing==="one"||n?.incoming==="one"}function Sy(e,t,n,i,r){let s=JSON.stringify([t,n,i]),a=e.get(s);a===void 0&&(a={kind:t,direction:n,node_id:i,endpoints:new Set},e.set(s,a)),a.endpoints.add(r)}function Ty(e,t){let n=new Map;for(let i of e)for(let r of i.dependencies??[]){let s=t.resolve(r.kind);s===void 0||s.hierarchy||(s.outgoing==="one"&&Sy(n,s.kind,"outgoing",i.id,r.id),s.incoming==="one"&&Sy(n,s.kind,"incoming",r.id,i.id))}return n}function Ts(e,t,n=ae()){let i=Ty(e,n),r=Ty(t,n);for(let s of[...r.keys()].sort()){let a=r.get(s);if(a.endpoints.size<=1)continue;let o=i.get(s);if(![...a.endpoints].every(c=>o?.endpoints.has(c)))throw new _(`Relationship ${a.kind} permits only one ${a.direction} endpoint for ${a.node_id}.`,m.USAGE,{code:"dependency_cardinality_created",field:"dependencies",value:a.kind,relationship_cardinality:{kind:a.kind,direction:a.direction,node_id:a.node_id,endpoint_ids:[...a.endpoints].sort()},required:"The final dependency set must satisfy the active relationship kind's one-edge cardinality.",nextSteps:["Drop extra --dep seeds, or remove conflicting rows with update --dep-remove before adding another edge.","Choose another kind only when its declared semantics match the intended relationship."]})}}(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]="1ce8c06c-cdc7-57bb-b4c3-477b2e07d71c")}catch{}})();var Bt=new Set(["PM_PATH","PM_GLOBAL_PATH","PM_SOURCE_PM_PATH","PM_SOURCE_WORKSPACE_ROOT","PM_BUILD_CONSUMER_LEASE","PM_BUILD_CONSUMER_LEASE_ROOT",Vn,ep,"FORCE_COLOR"]),Cs=/^[A-Za-z_][A-Za-z0-9_]*$/,Wt=["schema","tracker","auto","none"],Ay=["source","isolated","snapshot"];function ki(e,t){if(!e)return;let n=e.split(/[;\n]/).map(r=>r.trim()).filter(r=>r.length>0);if(n.length===0)throw new _(`${t} env_set must include at least one KEY=VALUE assignment`,m.USAGE);let i=Object.create(null);for(let r of n){let s=r.indexOf("=");if(s<=0)throw new _(`${t} env_set entries must use KEY=VALUE and be separated by semicolons. Example: env_set=PORT=0;PLAYWRIGHT_BASE_URL=http://127.0.0.1:4173`,m.USAGE);let a=r.slice(0,s).trim(),o=r.slice(s+1);if(!Cs.test(a))throw new _(`${t} env_set key "${a}" is invalid`,m.USAGE);if(Bt.has(a.toUpperCase()))throw new _(`${t} env_set key "${a}" is reserved for sandbox safety`,m.USAGE);i[a]=o}return Object.keys(i).length>0?i:void 0}function Ei(e,t){if(!e)return;let n=ao(e,{separators:/[;,\n]/});if(n.length===0)throw new _(`${t} env_clear must include at least one environment variable name`,m.USAGE);for(let i of n){if(!Cs.test(i))throw new _(`${t} env_clear key "${i}" is invalid`,m.USAGE);if(Bt.has(i.toUpperCase()))throw new _(`${t} env_clear key "${i}" is reserved for sandbox safety`,m.USAGE)}return n}function xs(e,t,n){if(!e)return;let i=e.trim().toLowerCase();if(i==="true"||i==="1"||i==="yes")return!0;if(i==="false"||i==="0"||i==="no")return!1;throw new _(`${t} ${n} must be one of true|false|1|0|yes|no`,m.USAGE)}function Rs(e,t){if(!e)return;let n=e.trim().toLowerCase();if(Wt.includes(n))return n;throw new _(`${t} pm_context_mode must be one of: ${Wt.join(", ")}`,m.USAGE)}function Ht(e,t){if(!e)return;let n=e.trim().toLowerCase();if(Ay.includes(n))return n;throw new _(`${t} workspace_context_mode must be one of: ${Ay.join(", ")}`,m.USAGE)}function Vt(e){if(!e)return;let t=ao(e,{separators:/[;\n]/});return t.length>0?t:void 0}function An(e,t,n){let i=Vt(e);if(!(!i||i.length===0)){for(let r of i)try{new RegExp(r,"m")}catch(s){throw new _(`${t} ${n} includes invalid regex "${r}": ${s instanceof Error?s.message:String(s)}`,m.USAGE)}return i}}function Os(e,t){if(!e)return;let n=ye(e,"assert_stdout_min_lines");if(!Number.isInteger(n)||n<0)throw new _(`${t} assert_stdout_min_lines must be an integer >= 0`,m.USAGE);return n}function Ls(e,t){if(!e)return;let n=e.split(/[;\n]/).map(r=>r.trim()).filter(r=>r.length>0);if(n.length===0)throw new _(`${t} assert_json_field_equals must include at least one path=value assignment`,m.USAGE);let i=Object.create(null);for(let r of n){let s=r.indexOf("=");if(s<=0)throw new _(`${t} assert_json_field_equals entries must use path=value and be separated by semicolons`,m.USAGE);let a=r.slice(0,s).trim(),o=r.slice(s+1).trim();if(a.length===0||o.length===0)throw new _(`${t} assert_json_field_equals entries must include non-empty path and value`,m.USAGE);i[a]=o}return Object.keys(i).length>0?i:void 0}function Ds(e,t){if(!e)return;let n=e.split(/[;\n]/).map(r=>r.trim()).filter(r=>r.length>0);if(n.length===0)throw new _(`${t} assert_json_field_gte must include at least one path=value assignment`,m.USAGE);let i=Object.create(null);for(let r of n){let s=r.indexOf("=");if(s<=0)throw new _(`${t} assert_json_field_gte entries must use path=value and be separated by semicolons`,m.USAGE);let a=r.slice(0,s).trim(),o=r.slice(s+1).trim();if(a.length===0||o.length===0)throw new _(`${t} assert_json_field_gte entries must include non-empty path and value`,m.USAGE);let c=Number(o);if(!Number.isFinite(c))throw new _(`${t} assert_json_field_gte value for "${a}" must be numeric`,m.USAGE);i[a]=c}return Object.keys(i).length>0?i:void 0}var bx=new Set(Ge);function Ns(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function kx(e,t){let n={},i=[];for(let[r,s]of Object.entries(e)){let a=r.toLowerCase();if(!bx.has(a)){i.push(r);continue}if(Object.hasOwn(n,a))throw t(`provides key "${r}" more than once after case normalization`);n[a]=s}if(i.length>0)throw t(`does not recognize key${i.length>1?"s":""} ${i.map(r=>`"${r}"`).join(", ")}. Allowed keys: ${Ge.join(", ")}.`);return n}function zt(e,t,n){if(!Object.hasOwn(e,t))return;let i=e[t];if(i!==void 0){if(typeof i!="string")throw n(`field "${t}" must be a JSON string`);return i}}function As(e,t,n){if(!Object.hasOwn(e,t))return;let i=e[t];if(i===void 0)return;let r=typeof i=="string"?[i]:i;if(!Array.isArray(r)||r.some(a=>typeof a!="string"))throw n(`field "${t}" must be a string or an array of strings`);let s=r.filter(a=>a.length>0);return s.length>0?s:void 0}function Iy(e,t,n){let i=As(e,t,n);if(i){for(let r of i)try{new RegExp(r,"m")}catch(s){throw n(`field "${t}" includes invalid regex "${r}": ${s instanceof Error?s.message:String(s)}`)}return i}}function Is(e,t,n){let i=typeof e=="number"?e:typeof e=="string"&&e.trim().length>0?Number(e.trim()):Number.NaN;if(typeof e=="boolean"||!Number.isFinite(i))throw n(`field "${t}" must be a finite number (or numeric string)`);return i}function Ex(e,t){let n=e.timeout_seconds,i=e.timeout;if(n===void 0&&i===void 0)return;let r=n===void 0?void 0:Is(n,"timeout_seconds",t),s=i===void 0?void 0:Is(i,"timeout",t);if(r!==void 0&&s!==void 0&&r!==s)throw t("timeout and timeout_seconds must match when both are provided");let a=r??s;if(!Number.isInteger(a)||a<=0)throw t("timeout_seconds must be a positive integer");return a}function Sx(e,t){let n=zt(e,"scope",t);if(n===void 0)return"project";if(!Pe.includes(n))throw t(`field "scope" must be one of: ${Pe.join(", ")}`);return n}function Tx(e,t){if(!Object.hasOwn(e,"env_set"))return;let n=e.env_set;if(n===void 0)return;if(!Ns(n))throw t('field "env_set" must be a JSON object mapping environment names to string values');let i=Object.create(null);for(let[r,s]of Object.entries(n)){if(typeof s!="string")throw t(`field "env_set" value for "${r}" must be a string`);if(!Cs.test(r))throw t(`field "env_set" key "${r}" is invalid`);if(Bt.has(r.toUpperCase()))throw t(`field "env_set" key "${r}" is reserved for sandbox safety`);i[r]=s}return Object.keys(i).length>0?i:void 0}function Ax(e,t){let n=As(e,"env_clear",t);if(n){for(let i of n){if(!Cs.test(i))throw t(`field "env_clear" key "${i}" is invalid`);if(Bt.has(i.toUpperCase()))throw t(`field "env_clear" key "${i}" is reserved for sandbox safety`)}return n}}function Ix(e,t,n){if(!Object.hasOwn(e,t))return;let i=e[t];if(i!==void 0){if(typeof i!="boolean")throw n(`field "${t}" must be a JSON boolean (true or false)`);return i}}function Cx(e,t){if(!Object.hasOwn(e,"assert_stdout_min_lines"))return;let n=e.assert_stdout_min_lines;if(n===void 0)return;let i=Is(n,"assert_stdout_min_lines",t);if(!Number.isInteger(i)||i<0)throw t('field "assert_stdout_min_lines" must be an integer >= 0');return i}function xx(e,t){if(!Object.hasOwn(e,"assert_json_field_equals"))return;let n=e.assert_json_field_equals;if(n===void 0)return;if(!Ns(n))throw t('field "assert_json_field_equals" must be a JSON object mapping field paths to expected values');let i=Object.create(null);for(let[r,s]of Object.entries(n)){if(r.trim().length===0)throw t('field "assert_json_field_equals" keys must be non-empty field paths');if(typeof s!="string"&&typeof s!="number"&&typeof s!="boolean")throw t(`field "assert_json_field_equals" value for "${r}" must be a string, number, or boolean`);i[r]=String(s)}return Object.keys(i).length>0?i:void 0}function Rx(e,t){if(!Object.hasOwn(e,"assert_json_field_gte"))return;let n=e.assert_json_field_gte;if(n===void 0)return;if(!Ns(n))throw t('field "assert_json_field_gte" must be a JSON object mapping field paths to numeric minimums');let i=Object.create(null);for(let[r,s]of Object.entries(n)){if(r.trim().length===0)throw t('field "assert_json_field_gte" keys must be non-empty field paths');i[r]=Is(s,`assert_json_field_gte.${r}`,t)}return Object.keys(i).length>0?i:void 0}function Ox(e,t,n){let i=p=>new _(`${n} ${t} ${p}`,m.USAGE);if(!Ns(e))throw i(`must be a JSON object with linked-test fields. Allowed keys: ${Ge.join(", ")}.`);let r=kx(e,i),s=zt(r,"command",i),a=zt(r,"cmd",i);if(s!==void 0&&a!==void 0&&s!==a)throw i("command and cmd must match when both are provided");let o=s??a;if(o===void 0||o.trim().length===0)throw i('requires a non-empty "command" string');let c=zt(r,"path",i),d=zt(r,"pm_context_mode",i);if(d!==void 0&&!Wt.includes(d))throw i(`field "pm_context_mode" must be one of: ${Wt.join(", ")}`);let l=Ht(zt(r,"workspace_context_mode",i),`${n} ${t}`),u=zt(r,"note",i);return{command:o,path:c!==void 0&&c.length>0?c:void 0,scope:Sx(r,i),timeout_seconds:Ex(r,i),pm_context_mode:d,workspace_context_mode:l,env_set:Tx(r,i),env_clear:Ax(r,i),shared_host_safe:Ix(r,"shared_host_safe",i),assert_stdout_contains:As(r,"assert_stdout_contains",i),assert_stdout_regex:Iy(r,"assert_stdout_regex",i),assert_stderr_contains:As(r,"assert_stderr_contains",i),assert_stderr_regex:Iy(r,"assert_stderr_regex",i),assert_stdout_min_lines:Cx(r,i),assert_json_field_equals:xx(r,i),assert_json_field_gte:Rx(r,i),note:u!==void 0&&u.trim().length>0?u.trim():void 0}}function Ms(e,t){let n=e.trim();if(n.length===0)throw new _(`${t} requires a JSON object or array of objects describing linked-test entries`,m.USAGE);let i;try{i=JSON.parse(n)}catch(s){throw new _(`${t} value is not valid JSON: ${s instanceof Error?s.message:String(s)}. Provide a JSON object or array of objects, e.g. '{"command":"node scripts/check.js --flag value, with commas","timeout_seconds":120}'.`,m.USAGE)}let r=Array.isArray(i)?i:[i];if(r.length===0)throw new _(`${t} array must include at least one linked-test entry object`,m.USAGE);return r.map((s,a)=>Ox(s,r.length>1?`entry ${a+1}`:"entry",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]="a9b9f4df-2129-5230-af20-16bef3754d39")}catch{}})();var Lx={comment:"--clear-comments",dep:"--clear-deps",doc:"--clear-docs",event:"--clear-events",file:"--clear-files",learning:"--clear-learnings",note:"--clear-notes",reminder:"--clear-reminders",test:"--clear-tests",typeOption:"--clear-type-options"};function Dx(e){return Lx[e]}function Uc(e){return Dx(e)!==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]="1e808776-dd0e-507f-9214-e3f5fa846874")}catch{}})();var Nx="hierarchy-integrity";async function Ps(e){let t=e.required?await bt(e.pmRoot,Nx,e.ttlSeconds,e.author,!1,!1,e.waitMs):async()=>{},n=!1;return async()=>{n||(n=!0,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]="01a312de-88fc-514f-b37b-2e717222a8ed")}catch{}})();function Fs(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function $s(e){let t=e.trim();return t.toLowerCase()==="med"?"medium":t}function Us(e){let t=e.trim().toLowerCase();if(t==="med")return"medium";if(ll.includes(t))return t;let n=ye(e,"confidence");if(!Number.isInteger(n)||n<0||n>100)throw new _("Confidence must be an integer 0..100 or one of low|med|medium|high",m.USAGE);return n}function js(e){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1;throw new _("Regression must be one of true|false|1|0",m.USAGE)}(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]="6ccfe6c7-3911-5623-aa29-5eff0293f816")}catch{}})();var Cy=[["dependencies","dep",["id","kind","created_at","author","source_kind"]],["comments","comment",["text","created_at","author"]],["notes","note",["text","created_at","author"]],["learnings","learning",["text","created_at","author"]],["files","file",["path","scope","note"]],["tests","test",["command","scope","timeout_seconds"]],["docs","doc",["path","scope","note"]],["reminders","reminder",["at","text","created_at"]],["events","event",["start_at","end_at","title","location"]],["type_options","typeOption",["key","value"]]];(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]="2167160d-d7ba-5096-b0b5-7e9e795af0a6")}catch{}})();function Gs(e){let t=Cy.find(([i])=>i===e)?.[1]??e.replaceAll(/_([a-z])/gu,(i,r)=>r.toUpperCase()),n=[["update",j_],["create",F_]].flatMap(([i,r])=>r.flatMap(s=>{if(s.target!==t)return[];let a=s.option.match(/--[a-z][a-z0-9-]*/u)[0];return[{command:i,flag:a}]}));return{recovery:{provided_fields:[e],...n.length>0?{suggested_flags:[...new Set(n.map(i=>i.flag))]}:{}},nextSteps:n.length>0?n.map(({command:i,flag:r})=>`Use the declared core mutation: pm ${i}${i==="update"?" <id>":""} ${r} <value>; inspect its help for other required options.`):[`No dedicated create/update CLI mutation flag is declared for "${e}". Use its owning lifecycle, evidence, or importer API; --field cannot mutate core metadata.`]}}(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]="c22dc1f8-285a-5858-9087-17a8deed6db8")}catch{}})();var Mx=new Set(["none","null"]);function qs(e={}){return[{optionKey:"dep",clearFlagKey:"clearDeps",valueFlag:"--dep",clearFlag:"--clear-deps",...e.depDisableFlagKey===void 0?{}:{disableFlagKey:e.depDisableFlagKey}},{optionKey:"comment",clearFlagKey:"clearComments",valueFlag:"--comment",clearFlag:"--clear-comments"},{optionKey:"note",clearFlagKey:"clearNotes",valueFlag:"--note",clearFlag:"--clear-notes"},{optionKey:"learning",clearFlagKey:"clearLearnings",valueFlag:"--learning",clearFlag:"--clear-learnings"},{optionKey:"file",clearFlagKey:"clearFiles",valueFlag:"--file",clearFlag:"--clear-files",...e.fileDisableFlagKey===void 0?{}:{disableFlagKey:e.fileDisableFlagKey}},{optionKey:"test",clearFlagKey:"clearTests",valueFlag:"--test",clearFlag:"--clear-tests",...e.testDisableFlagKey===void 0?{}:{disableFlagKey:e.testDisableFlagKey}},{optionKey:"doc",clearFlagKey:"clearDocs",valueFlag:"--doc",clearFlag:"--clear-docs",...e.docDisableFlagKey===void 0?{}:{disableFlagKey:e.docDisableFlagKey}},{optionKey:"reminder",clearFlagKey:"clearReminders",valueFlag:"--reminder",clearFlag:"--clear-reminders"},{optionKey:"event",clearFlagKey:"clearEvents",valueFlag:"--event",clearFlag:"--clear-events"},{optionKey:"typeOption",clearFlagKey:"clearTypeOptions",valueFlag:"--type-option",clearFlag:"--clear-type-options"}]}function He(e){return e===void 0?!1:Mx.has(e.trim().toLowerCase())}function Ks(e,t,n){if(!He(e))return;let i=n?` ${n}`:"";throw new _(`${t} no longer accepts "none" or "null".${i}`.trim(),m.USAGE)}function Re(e,t,n){if(!e||e.length===0||!e.some(r=>He(r)))return;let i=n?` ${n}`:"";throw new _(`${t} no longer accepts "none" or "null".${i}`.trim(),m.USAGE)}function zs(e,t){for(let n of t){let i=e[n.optionKey];if(!Array.isArray(i)||i.length===0)continue;if(!i.every(s=>typeof s=="string"))throw new _(`${n.valueFlag} entries must be strings.`,m.USAGE);let r=i;if(r.some(s=>He(s))){if(r.filter(s=>!He(s)).length>0)throw new _(`Cannot mix legacy clear token "none"/"null" with concrete ${n.valueFlag} entries. Use ${n.clearFlag} to clear or provide explicit entries.`,m.USAGE);e[n.optionKey]=void 0,e[n.clearFlagKey]=!0,n.disableFlagKey&&(e[n.disableFlagKey]=!1)}}return e}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="daa816a5-05d4-5e0a-90aa-9d96afdb2117")}catch{}})();var Px=new Set(["event","meeting","reminder","milestone","decision","adr"]);function xy(e,t,n,i){if(Px.has(t.trim().toLowerCase())||n!==i.open_status)return;let r=Ke("in_progress",i);if(!(r===void 0||r===i.open_status))return{command:`pm claim ${e} --start`,to_status: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]="1ffee31a-c272-5494-a04a-01a17b78dd2d")}catch{}})();var jc=[{canonical:"tags",aliases:["tags"],optionKey:"tags",metadataKey:"tags"}],Gc=[{canonical:"deadline",aliases:["deadline"],optionKey:"deadline",metadataKey:"deadline"},{canonical:"estimate",aliases:["estimate","estimated_minutes","estimated-minutes"],optionKey:"estimatedMinutes",metadataKey:"estimated_minutes"},{canonical:"acceptance-criteria",aliases:["acceptance_criteria","acceptance-criteria","ac"],optionKey:"acceptanceCriteria",metadataKey:"acceptance_criteria"},{canonical:"definition-of-ready",aliases:["definition_of_ready","definition-of-ready"],optionKey:"definitionOfReady",metadataKey:"definition_of_ready"},{canonical:"order",aliases:["order","rank"],optionKey:"order",metadataKey:"order"},{canonical:"goal",aliases:["goal"],optionKey:"goal",metadataKey:"goal"},{canonical:"objective",aliases:["objective"],optionKey:"objective",metadataKey:"objective"},{canonical:"value",aliases:["value"],optionKey:"value",metadataKey:"value"},{canonical:"impact",aliases:["impact"],optionKey:"impact",metadataKey:"impact"},{canonical:"outcome",aliases:["outcome"],optionKey:"outcome",metadataKey:"outcome"},{canonical:"why-now",aliases:["why_now","why-now"],optionKey:"whyNow",metadataKey:"why_now"}],Ry=[...jc,...Gc],Ws=[{canonical:"assignee",aliases:["assignee"],optionKey:"assignee",metadataKey:"assignee"},{canonical:"parent",aliases:["parent"],optionKey:"parent",metadataKey:"parent"},{canonical:"reviewer",aliases:["reviewer"],optionKey:"reviewer",metadataKey:"reviewer"},{canonical:"risk",aliases:["risk"],optionKey:"risk",metadataKey:"risk"},{canonical:"confidence",aliases:["confidence"],optionKey:"confidence",metadataKey:"confidence"},{canonical:"sprint",aliases:["sprint"],optionKey:"sprint",metadataKey:"sprint"},{canonical:"release",aliases:["release"],optionKey:"release",metadataKey:"release"},{canonical:"blocked-by",aliases:["blocked_by","blocked-by"],optionKey:"blockedBy",metadataKey:"blocked_by"},{canonical:"blocked-reason",aliases:["blocked_reason","blocked-reason"],optionKey:"blockedReason",metadataKey:"blocked_reason"},{canonical:"unblock-note",aliases:["unblock_note","unblock-note"],optionKey:"unblockNote",metadataKey:"unblock_note"},{canonical:"reporter",aliases:["reporter"],optionKey:"reporter",metadataKey:"reporter"},{canonical:"severity",aliases:["severity"],optionKey:"severity",metadataKey:"severity"},{canonical:"environment",aliases:["environment"],optionKey:"environment",metadataKey:"environment"},{canonical:"repro-steps",aliases:["repro_steps","repro-steps"],optionKey:"reproSteps",metadataKey:"repro_steps"},{canonical:"resolution",aliases:["resolution"],optionKey:"resolution",metadataKey:"resolution"},{canonical:"expected-result",aliases:["expected_result","expected-result"],optionKey:"expectedResult",metadataKey:"expected_result"},{canonical:"actual-result",aliases:["actual_result","actual-result"],optionKey:"actualResult",metadataKey:"actual_result"},{canonical:"affected-version",aliases:["affected_version","affected-version"],optionKey:"affectedVersion",metadataKey:"affected_version"},{canonical:"fixed-version",aliases:["fixed_version","fixed-version"],optionKey:"fixedVersion",metadataKey:"fixed_version"},{canonical:"component",aliases:["component"],optionKey:"component",metadataKey:"component"},{canonical:"regression",aliases:["regression"],optionKey:"regression",metadataKey:"regression"},{canonical:"customer-impact",aliases:["customer_impact","customer-impact"],optionKey:"customerImpact",metadataKey:"customer_impact"}];function Bs(e){let t=new Set,n=new Set;if(!e.raw||e.raw.length===0)return{metadataKeys:t,optionKeys:n};for(let i of e.raw){let r=i.trim().toLowerCase();if(!r)throw new _("--unset values must not be empty",m.USAGE);if(He(r))throw new _('--unset no longer accepts "none" or "null". Specify concrete field names such as --unset deadline',m.USAGE);let s=e.resolveDefinition(r);if(!s)throw new _(`Unsupported --unset field "${i}". Supported fields: ${e.supportedFields}`,m.USAGE);t.add(s.metadataKey),n.add(s.optionKey)}return{metadataKeys:t,optionKeys:n}}function Hs(e,t,n){let i=e.trim().toLowerCase();if(!n)return;let r=n.command_to_fields?.get(t)??[];for(let s of r){if(s.allow_unset===!1)continue;let a=new Set;if(typeof s.key=="string"&&s.key.length>0&&a.add(s.key.toLowerCase()),typeof s.metadata_key=="string"&&s.metadata_key.length>0&&a.add(s.metadata_key.toLowerCase()),typeof s.cli_flag=="string"&&s.cli_flag.length>0&&(a.add(s.cli_flag.replaceAll("-","_").toLowerCase()),a.add(s.cli_flag.toLowerCase())),Array.isArray(s.cli_aliases))for(let o of s.cli_aliases)typeof o!="string"||o.length===0||(a.add(o.replaceAll("-","_").toLowerCase()),a.add(o.toLowerCase()));if(a.has(i))return{optionKey:s.key,metadataKey:s.metadata_key}}}(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]="48975dc8-636f-51a1-858a-f97c7a037688")}catch{}})();function Ly(e,t){let n=e.trim().toLowerCase();if(n==="true"||n==="1"||n==="yes")return!0;if(n==="false"||n==="0"||n==="no")return!1;throw new _(`${t} must be one of true|false|1|0|yes|no`,m.USAGE)}function qc(e){return e?e.split("|").map(t=>t.trim()).filter(t=>t.length>0):[]}function Ve(e,t,n,i=n){if(!t.includes(e))throw new _(`Invalid ${n} value "${e}". Allowed: ${t.join(", ")}`,m.USAGE,{field:i,value:e,recovery:{allowed_values:[...t]},required:`${n} must be one of: ${t.join(", ")}.`,nextSteps:[`Choose an allowed ${n} and retry the mutation.`]});return e}var Dy=["recur_freq","recur_interval","recur_count","recur_until","recur_by_weekday","recur_by_month_day","recur_exdates"];function Fx(e,t){return t==="defined"?e!==void 0:!!e}function Oy(e,t,n){if(!Fx(e,n))return;let i=ye(e,`event ${t}`);if(!Number.isInteger(i)||i<1)throw new _(`--event ${t} must be an integer >= 1`,m.USAGE);return i}function $x(e,t,n){let i=e?ge(e,n,"event.recur_until"):void 0;if(i&&i<t)throw new _("--event recur_until must be at or after start",m.USAGE);return i}function Ux(e){return Array.from(new Set(qc(e).map(t=>Ve(t.toLowerCase(),gl,"event weekday")))).sort((t,n)=>Ma(t)-Ma(n))}function jx(e){return Array.from(new Set(qc(e).map(t=>{let n=ye(t,"event recur_by_month_day");if(!Number.isInteger(n)||n<1||n>31)throw new _("--event recur_by_month_day values must be integers 1..31",m.USAGE);return n}))).sort((t,n)=>t-n)}function Gx(e,t){return Array.from(new Set(qc(e).map(n=>ge(n,t,"event.recur_exdates")))).sort((n,i)=>n.localeCompare(i))}function Ny(e,t,n,i){let r=e.recur_freq?.trim(),s=e.recur_interval?.trim(),a=e.recur_count?.trim(),o=e.recur_until?.trim(),c=e.recur_by_weekday?.trim(),d=e.recur_by_month_day?.trim(),l=e.recur_exdates?.trim();if(![r,s,a,o,c,d,l].some(w=>w!==void 0))return;if(!r)throw new _("--event recurrence fields require recur_freq=<daily|weekly|monthly|yearly>",m.USAGE);let u=Ve(r.toLowerCase(),fl,"event recurrence frequency"),p=Oy(s,"recur_interval",i),g=Oy(a,"recur_count",i),f=$x(o,t,n),h=Ux(c),y=jx(d),v=Gx(l,n);return{freq:u,interval:p,count:g,until:f,by_weekday:h.length>0?h:void 0,by_month_day:y.length>0?y:void 0,exdates:v.length>0?v: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]="414326ff-8d4d-577d-b724-ab32b3f311ac")}catch{}})();function Si(e,t=ae()){let n=t.resolve(e);if(n)return n.kind;let i=new Set(Na),r=[...Na,...t.list().filter(({kind:s})=>!i.has(s)).flatMap(({kind:s,aliases:a})=>[s,...a])];throw new _(`Invalid dependency kind value "${e}". Allowed: ${r.join(", ")}`,m.USAGE,{field:"kind",value:e,recovery:{allowed_values:r},required:`dependency kind must be one of: ${r.join(", ")}.`,nextSteps:["Choose a registered kind, or install and enable the extension that registers this kind before retrying."]})}function Ti(e,t,n="--dep"){if(!t&&/[:,=]/.test(e))throw new _(`Invalid ${n} value "${e}". Use a bare item id or id=<id>,kind=<kind>.`,m.USAGE,{code:"dependency_flag_value_invalid",reason:"malformed_dependency_shorthand",flag:n,value:e,required:"Use a bare item id or an explicit id=<id>,kind=<kind> entry."})}function Ai(e,t,n=ae()){for(let i of t??[])try{Zd(e,i.id,i.kind,n)}catch(r){throw new _(cl(r),m.USAGE,{code:"dependency_edge_not_allowed",why:`${e} -> ${i.id} (${i.kind}) violates the active relationship-kind policy`})}}async function My(e,t){return(await he(e,{schema:t})).document.metadata.created_at}async function qx(e,t){if(e.createdAt!==void 0)return e.createdAt;let n=await Y(t.pmRoot,e.id,t.idPrefix,t.itemFormat,t.typeToFolder);return n===null?void 0:My(n,t.schema)}function Kx(e){let t=e.registry.require(e.dependency.kind);return new _(`${t.kind} requires source ${e.holder.id} to be created after target ${e.dependency.id}`,m.USAGE,{code:"dependency_temporal_order_invalid",reason:"source_not_after_target",required:`${e.holder.id}.created_at must be later than ${e.dependency.id}.created_at for ${t.kind}.`,why:"Chronological recurrence direction must be validated before the relationship is persisted.",source_id:e.holder.id,source_created_at:e.sourceCreatedAt,target_id:e.dependency.id,target_created_at:e.targetCreatedAt,temporal_order:t.temporalOrder})}async function zx(e){let t=e.dependencies.filter(r=>e.registry.resolve(r.kind)?.temporalOrder==="source_after_target"&&!e.missingTargets.includes(r.id));if(t.length===0||e.holders.length===0)return;let n=new Map(e.resolutions.flatMap(({target:r,located:s})=>s===null?[]:[[r,s]])),i=new Map(await Promise.all([...new Set(t.map(({id:r})=>r))].map(async r=>[r,await My(n.get(r),e.context.schema)])));for(let r of e.holders){let s=await qx(r,e.context);if(s!==void 0)for(let a of t){let o=i.get(a.id),c=Date.parse(s),d=Date.parse(o);if(!(Number.isFinite(c)&&Number.isFinite(d)&&c>d))throw Kx({holder:r,dependency:a,sourceCreatedAt:s,targetCreatedAt:o,registry:e.registry})}}}async function Vs(e){let t=e.registry??ae(),n=(e.dependencies??[]).filter(a=>!x_(a.source_kind)),i=[...new Set(n.map(a=>a.id))],r=await Promise.all(i.map(async a=>({target:a,located:await Y(e.pmRoot,a,e.idPrefix,e.itemFormat,e.typeToFolder)}))),s=r.filter(({located:a})=>a===null).map(({target:a})=>a).sort((a,o)=>a<o?-1:1);if(s.length>0&&e.allowUnresolved!==!0)throw new _(`Dependency target${s.length===1?"":"s"} not found: ${s.join(", ")}`,m.NOT_FOUND,{code:"dependency_target_not_found",reason:"unresolved_local_dependency",required:"Every local dependency target must exist before the edge is committed.",why:"Fail-fast target resolution prevents dangling graph nodes and preserves reliable traversal semantics.",unresolved_targets:s,examples:["--dep id=<existing-item-id>,kind=related","--dep id=<external-id>,kind=related,source_kind=external","--allow-unresolved-deps --dep id=<future-item-id>,kind=related"],nextSteps:[`Create or correct ${s.length===1?"the target":"the targets"}, then retry the mutation.`,"Use source_kind=external for a cross-workspace reference.","Use --allow-unresolved-deps only when the dangling local edge is intentional."],recovery:{recovery_mode:"compact",missing:s,suggested_flags:["--allow-unresolved-deps"],suggested_retry:`pm search "${s[0]}" --limit 10`}});return await zx({dependencies:n,missingTargets:s,resolutions:r,holders:e.holders??[],registry:t,context:e}),s.map(a=>`dependency_target_unresolved:${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]="3950ef46-cc2b-5b8e-97d6-34c739bd816e")}catch{}})();var Py="--event end must be strictly after start. Equal start/end timestamps are treated as an instant event (end is dropped); an end earlier than start is rejected. Omit end for an instant event or set end later than start.",Wx="--event end and duration are mutually exclusive; provide only one (use duration=<relative> like duration=2h, duration=30min, or duration=PT30M, or set an explicit end).",Bx=/^([+-]?)(\d+)(min|mins|minute|minutes)$/i,Hx=/^([+-]?)[Pp][Tt](?:(\d+)[Hh])?(?:(\d+)[Mm])?(?:(\d+)[Ss])?$/,$y=1e3,Kc=60*$y,Vx=60*Kc;function Fy(e,t){let n=new Date(e);if(!Number.isFinite(n.getTime()))throw new _(`Invalid event.duration value "${t}". Duration is out of supported timestamp range.`,m.USAGE);return n.toISOString()}function Yx(e,t){let n=new Date(e),i=t.trim();if(/^[+-]?\d+m$/i.test(i))throw new _(`Event duration "${i}" is ambiguous. Use min for minutes or mo for months (for example 5min or 5mo).`,m.USAGE);let r=i.replace(/^([+-]?\d+)mo$/i,"$1m"),s=Bx.exec(i);if(s){let c=s[1]==="-"?-1:1,d=Number.parseInt(s[2],10)*c;return Fy(n.getTime()+d*Kc,i)}let a=Hx.exec(i);if(a){let[,c,d,l,u]=a;if(d||l||u){let p=c==="-"?-1:1,g=Number.parseInt(d??"0",10),f=Number.parseInt(l??"0",10),h=Number.parseInt(u??"0",10),y=g*Vx+f*Kc+h*$y;return Fy(n.getTime()+p*y,i)}}let o=r.startsWith("+")||r.startsWith("-")?r:`+${r}`;return ge(o,n,"event.duration")}function Uy(e,t,n,i){if(t&&n)throw new _(Wx,m.USAGE);if(n){let s=Yx(e,n);if(s<e)throw new _(Py,m.USAGE);return s===e?void 0:s}if(!t)return;let r=ge(t,i,"event.end");if(r<e)throw new _(Py,m.USAGE);if(r!==e)return r}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8288d6e7-a027-5bfa-9b4a-3c8b581f31ce")}catch{}})();var Jx=["at","date","text","title"],Xx=["start","date","end","duration","title","description","location","timezone","all_day",...Dy],Qx=["key","value"];function jy(e,t){return t==="trimmed"?e?.trim():e}function Zx(e,t){return t==="defined"?e!==void 0:!!e}function Ys(e,t,n){return e.map(i=>{let r=Z(i,"--reminder");we(r,"--reminder",Jx);let s=jy(r.at??r.date,n.valueMode),a=jy(r.text??r.title,n.valueMode);if(!s||!a)throw new _("--reminder requires at=<iso|relative> or date=<iso|relative>, plus text=<value> or title=<value>",m.USAGE);let o=a.trim();if(!o)throw new _("--reminder text must not be empty",m.USAGE);return{at:ge(s,t,"reminder.at"),text:o}})}function Js(e,t,n){return e.map(i=>{let r=Z(i,"--event");we(r,"--event",Xx);let s=(r.start??r.date)?.trim();if(!s)throw new _("--event requires start=<iso|relative> or date=<iso|relative>",m.USAGE);let a=ge(s,t,"event.start"),o=r.end?.trim(),c=r.duration?.trim(),d=Uy(a,o,c,t),l=r.title,u=r.description,p=r.location,g=r.timezone,f=l?.trim(),h=u?.trim(),y=p?.trim(),v=g?.trim(),w=[["title",l,f],["description",u,h],["location",p,y],["timezone",g,v]];for(let[C,b,E]of w)if(b!==void 0&&!E)throw new _(`--event ${C} must not be empty`,m.USAGE);let k=r.all_day?.trim(),S=Ny(r,a,t,n.recurrenceEmptyNumericGuard),T=Zx(k,n.allDayEmptyGuard)?Ly(k,"--event all_day"):void 0;return{start_at:a,end_at:d,title:f,description:h,location:y,all_day:T,timezone:v,recurrence:S}})}function Xs(e){let t={};for(let n of e){let i=n.trim();if(i.length===0)throw new _("--type-option values must not be empty",m.USAGE);let r,s;if(i.includes(",")||i.includes(`
|
|
10
|
+
`)||i.startsWith("```")||/^(?:[-*+]\s+)?(?:key|value)\s*[:=]/i.test(i)){let a=Z(i,"--type-option");we(a,"--type-option",Qx),r=a.key?.trim(),s=a.value?.trim()}else{let a=i.indexOf("="),o=i.indexOf(":"),c=a;if(a<=0&&o>0&&(c=o),c<=0||c===i.length-1)throw new _("--type-option requires key=value or key=<name>,value=<value> entries",m.USAGE);r=i.slice(0,c).trim(),s=i.slice(c+1).trim()}if(!r||!s)throw new _("--type-option requires key and value",m.USAGE);t[r]=s}return Object.fromEntries(Object.entries(t).sort((n,i)=>n[0].localeCompare(i[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]="2eb7f7bc-c23a-5ea2-a050-c81c2fa88456")}catch{}})();var eR=["strict","progressive"],tR=["lightweight"],zy=new Set(["Reminder","Meeting","Event"]),nR=new Set(["author","created_at","text"]),Wc=[...Ry,{canonical:"author",aliases:["author"],optionKey:"author",metadataKey:"author"},...Ws],iR=(()=>{let e=new Map;for(let t of Wc)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),Qs=new Map(Wc.map(e=>[e.optionKey,e.canonical])),rR=Wc.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", ");function sR(e,t){let n=me(e,t);if(!n){let i=t.definitions.map(r=>r.id);throw new _(`Invalid status value "${e}". Allowed: ${i.join(", ")}`,m.USAGE)}return n}function aR(e,t){let n=e.default_status;if(n!==void 0){let i=me(n,t);if(i)return i}return t.open_status}function zc(e,t){if(!e||e.trim()===""||e.trim().toLowerCase()==="now")return t;let n=Date.parse(e);if(!Number.isFinite(n))throw new _(`Invalid created_at timestamp "${e}"`,m.USAGE);return new Date(n).toISOString()}var oR=qs();function Wy(e){let t={...e,unset:e.unset?[...e.unset]:void 0},n=r=>{let s=t.unset?[...t.unset]:[];s.includes(r)||s.push(r),t.unset=s};He(t.template)&&(t.template=void 0);let i=new Set([...Qs.keys(),"rank"]);for(let r of i){let s=t[r];if(typeof s!="string"||!He(s))continue;let a=r==="rank"?"order":Qs.get(r)??r;n(a),t[r]=void 0}return Ze(e,zs(t,oR))}function ke(e){if(e!==void 0)return e}function cR(e,t){return Bs({raw:e,supportedFields:rR,resolveDefinition:n=>iR.get(n)??Hs(n,"create",t)})}var Gy=["id","kind","type","author","created_at","source_kind"],Zs=["path","scope","note"];function dR(e,t,n,i){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Re(e,"--dep","Use --clear-deps to clear dependencies."),{values:e.map(r=>{let s=r.trim(),a=ea(s,Gy);Ti(s,a);let o=a?Z(r,"--dep"):{id:s,kind:"related"};a&&we(o,"--dep",Gy);let c=ke(o.id),d=lR(ke(o.kind??o.type));if(!c||!d)throw new _("--dep requires id and kind, or a bare item id to create a related dependency",m.USAGE);if(c.trim().toLowerCase()==="undefined")throw new _(`--dep id must not use placeholder token "${c}". Use --clear-deps to clear dependencies.`,m.USAGE);let l=Bn(ke(o.source_kind)),u=ke(o.author);return{id:Hn(c,n,l),kind:Si(d),created_at:zc(o.created_at,t),author:u??i,source_kind:l??"cli:create:dep",author_source:u?"asserted":"detected"}}),explicitEmpty:!1})}function lR(e){return typeof e=="string"?ae().resolve(e)?.kind??e.trim():e}function ea(e,t){return dr(e,t)?!0:on(e)}function Jt(e,t,n,i){return!t||t.length===0?{values:void 0,explicitEmpty:!1}:(Re(t,e,e==="--comment"?"Use --clear-comments to clear comments.":e==="--note"?"Use --clear-notes to clear notes.":"Use --clear-learnings to clear learnings."),{values:t.map(r=>{let s=r.trim(),a=()=>{if(s.length===0)throw new _(`${e} requires text=<value>`,m.USAGE);return{created_at:n,author:i,text:s}},o;try{o=Z(r,e)}catch(d){if(e==="--comment"||e==="--note"||e==="--learning")return a();throw d}if(Object.keys(o).filter(d=>!nR.has(d)).length>0)return{created_at:zc(o.created_at,n),author:ke(o.author)??i,text:s};let c=o.text??"";if(c==="")throw new _(`${e} requires text=<value>`,m.USAGE);return{created_at:zc(o.created_at,n),author:ke(o.author)??i,text:c}}),explicitEmpty:!1})}function Bc(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Re(e,"--file","Use --clear-files to clear linked files."),{values:e.map(t=>{let n=t.trim(),i=ea(n,Zs);Kn(n,"--file","file path",i);let r=i?Z(t,"--file"):{path:n};if(i&&we(r,"--file",Zs),!r.path)throw new _("--file requires path=<value> or a bare file path",m.USAGE);return{path:r.path,scope:Ve(r.scope??"project",Pe,"file scope"),note:ke(r.note)}}),explicitEmpty:!1})}function Hc(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Re(e,"--test","Use --clear-tests to clear linked tests."),{values:e.map(t=>{let n=t.trim(),i=ea(n,Ge);Kn(n,"--test","test command",i);let r=i?us(Z(t,"--test"),"--test"):{command:n},s=ke(r.command),a=ke(r.path);if(!s)throw new _("--test requires command=<value> or a bare command (path=<value> is optional metadata)",m.USAGE);let o=ke(r.timeout_seconds),c=ke(r.timeout);if(o&&c&&o!==c)throw new _("--test timeout and timeout_seconds must match when both are provided",m.USAGE);let d=o??c;return{command:s,path:a,scope:Ve(r.scope??"project",Pe,"test scope"),timeout_seconds:d?ye(d,"timeout_seconds"):void 0,pm_context_mode:Rs(r.pm_context_mode,"--test"),workspace_context_mode:Ht(r.workspace_context_mode,"--test"),env_set:ki(r.env_set,"--test"),env_clear:Ei(r.env_clear,"--test"),shared_host_safe:xs(r.shared_host_safe,"--test","shared_host_safe"),assert_stdout_contains:Vt(r.assert_stdout_contains),assert_stdout_regex:An(r.assert_stdout_regex,"--test","assert_stdout_regex"),assert_stderr_contains:Vt(r.assert_stderr_contains),assert_stderr_regex:An(r.assert_stderr_regex,"--test","assert_stderr_regex"),assert_stdout_min_lines:Os(r.assert_stdout_min_lines,"--test"),assert_json_field_equals:Ls(r.assert_json_field_equals,"--test"),assert_json_field_gte:Ds(r.assert_json_field_gte,"--test"),note:ke(r.note)}}),explicitEmpty:!1})}function Vc(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Re(e,"--doc","Use --clear-docs to clear linked docs."),{values:e.map(t=>{let n=t.trim(),i=ea(n,Zs),r=i?Z(t,"--doc"):{path:n};if(i&&we(r,"--doc",Zs),!r.path)throw new _("--doc requires path=<value> or a bare doc path",m.USAGE);return{path:r.path,scope:Ve(r.scope??"project",Pe,"doc scope"),note:ke(r.note)}}),explicitEmpty:!1})}function uR(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Re(e,"--reminder","Use --clear-reminders to clear reminders."),{values:Ys(e,new Date(t),{valueMode:"raw"}),explicitEmpty:!1})}function mR(e,t){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Re(e,"--event","Use --clear-events to clear linked events."),{values:Js(e,new Date(t),{allDayEmptyGuard:"defined",recurrenceEmptyNumericGuard:"defined"}),explicitEmpty:!1})}function _R(e,t,n,i=[]){let r=[...tl.filter(s=>e[s]!==void 0),...i.filter(s=>e[s]!==void 0),...t.length>0?["body"]:[],...n.map(s=>`unset:${s}`)];return Array.from(new Set(r))}function pR(e,t){let n=e??"";if(t.length===0)return n;let i=`explicit_unset=${t.join(",")}`;return n?`${n} | ${i}`:i}function qy(e,t,n){let i=Mn("create",e);if(!i)throw new _(`Unsupported ${n} entry "${e}" for type "${t}"`,m.CONFLICT);return i}function fR(e){return{scalarValues:{title:e.title,description:e.description,type:e.type,status:e.status,priority:e.priority,tags:e.tags,body:e.body,deadline:e.deadline,estimatedMinutes:e.estimatedMinutes,acceptanceCriteria:e.acceptanceCriteria,definitionOfReady:e.definitionOfReady,order:e.order??e.rank,goal:e.goal,objective:e.objective,value:e.value,impact:e.impact,outcome:e.outcome,whyNow:e.whyNow,author:e.author,message:e.message,assignee:e.assignee,parent:e.parent,reviewer:e.reviewer,risk:e.risk,confidence:e.confidence,sprint:e.sprint,release:e.release,blockedBy:e.blockedBy,blockedReason:e.blockedReason,unblockNote:e.unblockNote,reporter:e.reporter,severity:e.severity,environment:e.environment,reproSteps:e.reproSteps,resolution:e.resolution,expectedResult:e.expectedResult,actualResult:e.actualResult,affectedVersion:e.affectedVersion,fixedVersion:e.fixedVersion,component:e.component,regression:e.regression,customerImpact:e.customerImpact},repeatableValues:{dep:e.dep,comment:e.comment,note:e.note,learning:e.learning,file:e.file,test:e.test,doc:e.doc,reminder:e.reminder,event:e.event,typeOption:e.typeOption,field:e.field},addTags:e.addTags}}function By(e,t){if(t==="tags")return e.scalarValues.tags!==void 0||Array.isArray(e.addTags)&&e.addTags.length>0;if(Object.prototype.hasOwnProperty.call(e.scalarValues,t))return e.scalarValues[t]!==void 0;if(Object.prototype.hasOwnProperty.call(e.repeatableValues,t)){let n=e.repeatableValues[t];return Array.isArray(n)&&n.length>0}return!1}function gR(e,t){let n=new Set(["title","type"]);if(t!=="strict")return n;for(let i of e.required_create_fields)n.add(qy(i,e.name,"required_create_fields"));for(let i of e.required_create_repeatables)n.add(qy(i,e.name,"required_create_repeatables"));return n}function hR(e,t,n,i){for(let r of e)if(!(!By(t,r)&&!n.has(r)))throw new _(`Option ${Te("create",r)} is disabled for type "${i}" by command_option_policies`,m.USAGE)}function yR(e,t,n){if(t!=="strict")return;let i=e.filter(s=>n.has(s)&&!Uc(s));if(i.length===0)return;let r=[...new Set(i.map(s=>Te("create",s)))].sort((s,a)=>s.localeCompare(a));throw new _(`Strict create mode requires concrete values for ${r.join(", ")}; --unset/--clear-* directives cannot satisfy required options`,m.USAGE)}function vR(e){return!e||e.length===0?{values:void 0,explicitEmpty:!1}:(Re(e,"--type-option","Use --clear-type-options to clear existing type options."),{values:Xs(e),explicitEmpty:!1})}async function wR(e){return await _r(e,[["body","--body"],["description","--description"]],[["dep","--dep"],["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"],["field","--field"]])}async function bR(e){return Ft(e)?await wR(e):e}function kR(e,t){if(e===void 0)return t;let n=e.trim().toLowerCase();if(n.length===0)return t;if(n==="strict"||n==="progressive")return n;throw new _(`Invalid --create-mode value "${e}". Allowed: ${eR.join(", ")}`,m.USAGE)}function ER(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t.length===0)throw new _("--schedule-preset must not be empty",m.USAGE);if(t==="lightweight"||t==="lite"||t==="schedule-lite")return"lightweight";throw new _(`Invalid --schedule-preset value "${e}". Allowed: ${tR.join(", ")}`,m.USAGE)}function SR(e,t,n){let i=kR(e,n);if(t===void 0)return i;if(typeof e=="string"&&e.trim().length>0&&i==="strict")throw new _("--schedule-preset lightweight cannot be combined with --create-mode strict. Use --create-mode progressive or omit --create-mode.",m.USAGE);return"progressive"}function TR(e,t,n,i,r){let s=e.name,a=fR(t),o=gR(e,n),c=tn(e,"create",o);if(c.errors.length>0)throw new _(c.errors.join("; "),m.CONFLICT);hR(c.disabled,a,i,s),yR(c.required,n,i);let d=u=>u==="author"&&r!=="unknown"||u==="status"&&e.default_status!==void 0||i.has(u)&&Uc(u)?!0:By(a,u),l=c.required.filter(u=>!d(u));return[...new Set(l.map(u=>Te("create",u)))].sort((u,p)=>u.localeCompare(p))}var Hy=/^Missing required type option "([^"]+)" for type "([^"]+)"$/;function AR(e,t){let n=[];for(let i of e){let r=i.match(Hy);r&&r[2]===t&&n.push(r[1])}return[...new Set(n)].sort((i,r)=>i.localeCompare(r))}function IR(e,t){return e.filter(n=>{let i=n.match(Hy);return!i||i[2]!==t})}function CR(e,t,n,i){let r=IR(e,t);if(r.length===0)return;let s=Vy(n,[],[],i.open_status);throw new _(r.join("; "),m.USAGE,{code:"invalid_argument_value",required:`Provide valid --type-option key/value pairs for type "${t}".`,examples:[s],nextSteps:[`Run "pm create --help --type ${t}" to review allowed type-option keys and values.`]})}function xR(e,t){let n=e.options.find(i=>i.key===t)?.values[0];return typeof n=="string"&&n.trim().length>0?n:"<value>"}function RR(e,t,n){let i=e.split("/")[0];switch(i){case"--title":return["--title",`"${t} example title"`];case"--description":return["--description",`"${t} example description"`];case"--type":return["--type",t];case"--status":return["--status",n];case"--priority":return["--priority","1"];case"--message":return["--message",`"Create ${t} item"`];case"--comment":return["--comment",'"author=maintainer,created_at=now,text=Implementation context"'];default:return[i,'"<value>"']}}function Vy(e,t,n,i){let r=["pm","create","--title",`"${e.name} example title"`,"--description",`"${e.name} example description"`,"--type",e.name],s=["--status","--priority","--message"],a=[...new Set([...s,...t])],o=new Set(["--title","--description","--type"]);for(let c of a){if(o.has(c))continue;let d=Jy[c];r.push(...d?[d]:RR(c,e.name,i)),o.add(c)}for(let c of n){let d=xR(e,c);r.push("--type-option",`${c}=${d}`)}return r.join(" ")}function Yc(e,t){let n=e?.trim();if(!n)throw t==="--title"?e!==void 0?new _("Title cannot be empty or whitespace-only. Retry: pass a non-empty title with --title.",m.USAGE):new _('Missing required option --title. Why required: every item needs a human-readable title for lookup, search, and reporting. Retry: pass the title as the first positional argument (example: pm create "Fix login bug" --type Issue) or with --title.',m.USAGE):new _(`Missing required option ${t}`,m.USAGE);return n}function OR(e,t){let n={};for(let[i,r]of Object.entries(e))n[i]=Array.isArray(r)?[...r]:r;for(let[i,r]of Object.entries(t))r!==void 0&&(n[i]=Array.isArray(r)?[...r]:r);return n}function LR(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function DR(){let e=P();return e?e.commands.some(t=>t.action==="templates-show"||LR(t.command)==="templates show"):!1}function NR(e,t){if(typeof e!="object"||e===null||!("options"in e))throw new _(`Templates package returned invalid payload for template "${t}". Expected an options object.`,m.GENERIC_FAILURE);let n=e.options;if(typeof n!="object"||n===null||Array.isArray(n))throw new _(`Templates package returned invalid options for template "${t}".`,m.GENERIC_FAILURE);let i={};for(let[r,s]of Object.entries(n)){if(typeof s=="string"||typeof s=="number"||typeof s=="boolean"){i[r]=s;continue}if(Array.isArray(s)&&s.every(a=>typeof a=="string")){i[r]=[...s];continue}throw new _(`Templates package returned unsupported option value for "${r}" in template "${t}".`,m.GENERIC_FAILURE)}return i}async function MR(e,t,n){if(!DR())throw new _("--template requires the templates package. Install it first (for example: pm install templates --project).",m.USAGE);let i=await Bl({command:"templates show",args:[e],options:{},global:t,pm_root:n});if(!i.handled){let r=i.warnings.length>0?` (${i.warnings.join(", ")})`:"";throw new _(`Unable to resolve template "${e}" via templates package. Run "pm templates show ${e}" for details.${r}`,m.USAGE)}return NR(i.result,e)}function J(e,t,n){return e.has(t)||n===void 0?void 0:ke(n)}function Yt(e,t,n,i){return e.has(t)||n===void 0?void 0:i(n)}var PR=new Set(["milestone","meeting","reminder","event"]);function Yy(e,t,n,i){let r=t!==void 0,s=n!==void 0&&n.length>0,a=i!==void 0&&i.length>0;return PR.has(e.toLowerCase())&&!r&&!s&&!a}function FR(e,t,n,i,r){let s=[];return e.toLowerCase()==="event"&&(r===void 0||r.length===0)&&s.push(`event_without_schedule:${t}:no_time_set`),Yy(e,n,i,r)&&s.push(`calendar_item_without_schedule:${t}:no_deadline_or_reminder_or_event (hint: set --deadline <ISO> or --reminder "<when>", or link an Event via --event "start=<ISO>,end=<ISO>"; otherwise this item never appears on pm calendar)`),s}async function $R(e,t,n,i){if(e!==void 0||n.has("parent")||t.parent!==void 0)return{parent:e,parentSource:void 0};let r=await lu(i);return r===void 0?{parent:e,parentSource:void 0}:{parent:r,parentSource:"focus"}}async function UR(e,t,n,i,r,s){let a=Ir(fr(r),t.id_prefix);if(Er(a))return{parent:a,warnings:[]};if(hr(i,a,t.id_prefix),await Y(e,a,t.id_prefix,t.item_format,n.type_to_folder))return{parent:a,warnings:[]};let o=kt(a,t.id_prefix);return{parent:a,warnings:gr(o,s).warnings}}async function jR(e){return e.parent===void 0?{parent:void 0,warnings:[]}:await UR(e.pmRoot,e.settings,e.typeRegistry,e.itemId,e.parent,e.policy)}async function GR(e){if(e.explicitId===void 0)return vu(e.pmRoot,e.settings.id_prefix,{tokenLength:e.settings.ids.token_length,typeToFolder:e.typeRegistry.type_to_folder,probeExisting:!1});if(typeof e.explicitId!="string")throw new _("--id must be a string",m.USAGE);let t=e.explicitId.trim();if(t.length===0||m_(t))throw new _("--id must not be empty or use a placeholder token",m.USAGE);let n=kt(t,e.settings.id_prefix);if(!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(n))throw new _("--id must contain only letters, numbers, and dashes after normalization",m.USAGE);return n}function Ky(e,t,n,i,r){let s=J(e,t,n);if(s===void 0)return{value:void 0,warnings:[]};let a=vr(i,s,r);return{value:a.value,warnings:a.warnings}}async function qR(e){let{pmRoot:t,settings:n,typeRegistry:i,statusRegistry:r,blockedBy:s,status:a,statusExplicit:o,nowValue:c,author:d}=e,l=e.dependencyValues;if(s===void 0)return{dependencyValues:l,status:a};let u=kt(s,n.id_prefix),p=await Y(t,u,n.id_prefix,n.item_format,i.type_to_folder);if(!p)return{dependencyValues:l,status:a};if((l??[]).some(f=>f.id===p.id&&f.kind==="blocked_by")||(l=[...l??[],{id:p.id,kind:"blocked_by",created_at:c,author:d,source_kind:"cli:create:blocked_by",author_source:"detected"}]),o)return{dependencyValues:l,status:a};let g=r.blocked_statuses.has("blocked")?"blocked":[...r.blocked_statuses].sort((f,h)=>f.localeCompare(h))[0]??r.open_status;return{dependencyValues:l,status:g}}function KR(e,t,n){if(typeof e.createMode=="string"&&e.createMode.trim().toLowerCase()==="strict")return;let i=t.governance.create_default_type?.trim();if(i&&i.length>0&&st(i,n)){e.type=i;return}st("Task",n)&&(e.type="Task")}function zR(e,t){return e.options.filter(n=>Mn("create",n.key)===void 0).flatMap(n=>{let i=t[n.key];if(i===void 0)return[];if(typeof i=="string"||typeof i=="number"||typeof i=="boolean")return[n];throw new _(`Template custom type option "${n.key}" must be a string, number, or boolean value`,m.USAGE)})}async function WR(e,t,n,i,r){let s=e,a=[];if(s.template!==void 0){let f=s.template.trim();if(f.length===0)throw new _("--template must not be empty. Omit --template to disable template usage.",m.USAGE);let h=await MR(f,t,n);s=Wy(OR(h,s))}if(s.type===void 0&&KR(s,i,r),s.type===void 0)throw new _("Missing required option --type <value>",m.USAGE);let o=st(s.type,r);if(!o){let f=__(s.type),h=f?st(f,r):void 0;if(h)a.push(`type_coercion:${s.type.trim()}:${h}`),s.type=h,o=h;else throw new _(wr(s.type,r.types,Xi(n,i.schema)),m.USAGE)}let c=Bi(o,r);if(!c)throw new _(`Invalid type value "${s.type}"`,m.USAGE);let d=c.name,l=zR(c,s),u=l.map(f=>`${f.key}=${String(s[f.key])}`);if(u.length>0){s.typeOption=[...u,...s.typeOption??[]];for(let f of l)delete s[f.key]}let p=ER(s.schedulePreset);if(p!==void 0&&!zy.has(d))throw new _(`--schedule-preset ${p} is only supported for Reminder, Meeting, or Event types`,m.USAGE);let g=SR(s.createMode,p,i.governance.create_mode_default);return{resolvedOptions:s,typeDefinition:c,type:d,schedulePreset:p,createMode:g,warnings:a}}function BR(e,t){let n=new Set(t.metadataKeys),i=new Set(t.optionKeys),r=[{enabled:e.clearDeps,optionKey:"dep",clearFlag:"--clear-deps",valueFlag:"--dep",values:e.dep,metadataKey:"dependencies"},{enabled:e.clearComments,optionKey:"comment",clearFlag:"--clear-comments",valueFlag:"--comment",values:e.comment,metadataKey:"comments"},{enabled:e.clearNotes,optionKey:"note",clearFlag:"--clear-notes",valueFlag:"--note",values:e.note,metadataKey:"notes"},{enabled:e.clearLearnings,optionKey:"learning",clearFlag:"--clear-learnings",valueFlag:"--learning",values:e.learning,metadataKey:"learnings"},{enabled:e.clearFiles,optionKey:"file",clearFlag:"--clear-files",valueFlag:"--file",values:e.file,metadataKey:"files"},{enabled:e.clearTests,optionKey:"test",clearFlag:"--clear-tests",valueFlag:"--test",values:e.test,metadataKey:"tests"},{enabled:e.clearDocs,optionKey:"doc",clearFlag:"--clear-docs",valueFlag:"--doc",values:e.doc,metadataKey:"docs"},{enabled:e.clearReminders,optionKey:"reminder",clearFlag:"--clear-reminders",valueFlag:"--reminder",values:e.reminder,metadataKey:"reminders"},{enabled:e.clearEvents,optionKey:"event",clearFlag:"--clear-events",valueFlag:"--event",values:e.event,metadataKey:"events"},{enabled:e.clearTypeOptions,optionKey:"typeOption",clearFlag:"--clear-type-options",valueFlag:"--type-option",values:e.typeOption,metadataKey:"type_options"}];for(let s of r)if(s.enabled){if(s.values&&s.values.length>0)throw new _(`Cannot combine ${s.clearFlag} with ${s.valueFlag}`,m.USAGE);n.add(s.metadataKey),i.add(s.optionKey)}return{explicitUnsets:n,clearOptionKeys:i}}function HR(e,t){let n={tags:e.tags!==void 0,deadline:e.deadline!==void 0,estimatedMinutes:e.estimatedMinutes!==void 0,acceptanceCriteria:e.acceptanceCriteria!==void 0,definitionOfReady:e.definitionOfReady!==void 0,order:e.order!==void 0||e.rank!==void 0,goal:e.goal!==void 0,objective:e.objective!==void 0,value:e.value!==void 0,impact:e.impact!==void 0,outcome:e.outcome!==void 0,whyNow:e.whyNow!==void 0,author:e.author!==void 0,assignee:e.assignee!==void 0,parent:e.parent!==void 0,reviewer:e.reviewer!==void 0,risk:e.risk!==void 0,confidence:e.confidence!==void 0,sprint:e.sprint!==void 0,release:e.release!==void 0,blockedBy:e.blockedBy!==void 0,blockedReason:e.blockedReason!==void 0,unblockNote:e.unblockNote!==void 0,reporter:e.reporter!==void 0,severity:e.severity!==void 0,environment:e.environment!==void 0,reproSteps:e.reproSteps!==void 0,resolution:e.resolution!==void 0,expectedResult:e.expectedResult!==void 0,actualResult:e.actualResult!==void 0,affectedVersion:e.affectedVersion!==void 0,fixedVersion:e.fixedVersion!==void 0,component:e.component!==void 0,regression:e.regression!==void 0,customerImpact:e.customerImpact!==void 0};for(let[i,r]of Object.entries(n)){if(!r||!t.optionKeys.has(i))continue;let s=Qs.get(i)??i;throw new _(`Cannot combine --unset ${s} with ${Te("create",i)}`,m.USAGE)}}function VR(e){let t=(n,i)=>{let r=Qs.get(i),s=r?`Use --unset ${r} to clear this field.`:void 0;Ks(n,Te("create",i),s)};t(e.tags,"tags"),t(e.deadline,"deadline"),t(e.estimatedMinutes,"estimatedMinutes"),t(e.acceptanceCriteria,"acceptanceCriteria"),t(e.definitionOfReady,"definitionOfReady"),t(e.order??e.rank,"order"),t(e.goal,"goal"),t(e.objective,"objective"),t(e.value,"value"),t(e.impact,"impact"),t(e.outcome,"outcome"),t(e.whyNow,"whyNow"),t(e.author,"author"),t(e.assignee,"assignee"),t(e.parent,"parent"),t(e.reviewer,"reviewer"),t(e.risk,"risk"),t(e.confidence,"confidence"),t(e.sprint,"sprint"),t(e.release,"release"),t(e.blockedBy,"blockedBy"),t(e.blockedReason,"blockedReason"),t(e.unblockNote,"unblockNote"),t(e.reporter,"reporter"),t(e.severity,"severity"),t(e.environment,"environment"),t(e.reproSteps,"reproSteps"),t(e.resolution,"resolution"),t(e.expectedResult,"expectedResult"),t(e.actualResult,"actualResult"),t(e.affectedVersion,"affectedVersion"),t(e.fixedVersion,"fixedVersion"),t(e.component,"component"),t(e.regression,"regression"),t(e.customerImpact,"customerImpact")}function YR(e,t,n){for(let i of Object.keys(e))if(n.metadataKeys.has(i))throw new _(`Cannot combine --unset ${i.replaceAll("_","-")} with --field ${i}=...`,m.USAGE);for(let i of Object.keys(t.values??{}))if(n.metadataKeys.has(i))throw new _(`Cannot combine --unset ${i.replaceAll("_","-")} with its value flag`,m.USAGE)}var Jy={"--comment":"--clear-comments","--dep":"--clear-deps","--doc":"--clear-docs","--event":"--clear-events","--file":"--clear-files","--learning":"--clear-learnings","--note":"--clear-notes","--reminder":"--clear-reminders","--test":"--clear-tests","--type-option":"--clear-type-options"};function JR(e){let{combinedMissingFlags:t,typeDefinition:n,missingRequiredCreateFlags:i,missingRequiredTypeOptionKeys:r,openStatus:s,type:a,createMode:o,missingRequiredRuntimeFields:c}=e;if(t.length===0)return;let d=c.map(f=>{let h=f.type==="boolean"?"<true|false>":f.type==="array"?"<json-array>":f.type==="object"?"<json-object>":f.type==="number"?"<number>":f.type==="string_array"||f.repeatable?"<value>":"<string>";return{example:`--${f.cli_flag} ${h}`,description:`--${f.cli_flag} maps to ${f.metadata_key} (${f.type}${f.repeatable?", repeatable":""})`}}),l=[Vy(n,i,r,s),...d.map(f=>f.example)].join(" "),u=[`Run "pm create --help --type ${a}" for type-aware required option guidance.`,...t.filter(f=>f==="--title").map(()=>'Title can also be passed as the first positional argument (example: pm create "Your title" --type '+a+").")];o==="strict"&&(u.push('For staged onboarding, retry with "--create-mode progressive".'),zy.has(a)&&u.push('For minimal scheduling inputs, try "--schedule-preset lightweight".')),d.length>0&&u.push(`Required custom field formats: ${d.map(f=>f.description).join("; ")}.`);let p=[...new Set(t.flatMap(f=>{let h=f.split(" ",1)[0],y=Jy[h];return y?[y]:[]}))];p.length>0&&u.push(`If the truthful value is an empty collection, use ${p.join(", ")} instead of inventing metadata.`);let g=t.length===1?`Missing required option ${t[0]} for type "${a}"`:`Missing required options ${t.join(", ")} for type "${a}"`;throw new _(g,m.USAGE,{code:"missing_required_option",required:`Provide all required create options and type options for type "${a}" in one invocation.`,examples:[...p.map(f=>`pm create --type ${a} ${f} ...`),l],nextSteps:u,recovery:o==="strict"?{recovery_mode:"compact",missing_required_fields:t,suggested_flags:[...p,...t,"--create-mode progressive"]}:void 0})}function XR(e,t){if(e.has("tags")&&Array.isArray(t.addTags)&&t.addTags.length>0)throw new _("Cannot combine --unset tags with --add-tags",m.USAGE);let n=e.has("tags")?[]:t.tags!==void 0?lr(t.tags):[];return mr(n,t.addTags)}function QR(e,t){if(t.order!==void 0&&t.rank!==void 0&&t.order!==t.rank)throw new _("--order and --rank must match when both are provided",m.USAGE);let n=t.order??t.rank,i=Yt(e,"order",n,r=>ye(r,"order"));if(i!==void 0&&!Number.isInteger(i))throw new _("Order must be an integer",m.USAGE);return i}function ZR(e,t,n,i,r,s){if(i.completedAt!==void 0&&e!==t.close_status)throw new _("--completed-at requires a terminal create status.",m.USAGE);let a=e!==t.close_status?void 0:i.completedAt===void 0?s:ge(i.completedAt,new Date(s),"completed-at");if(e!==t.close_status)return{closeReason:void 0,completedAt:a,warnings:[]};let o=n.governance.require_close_reason?{explicit:i.closeReason??i.message,resolution:r}:{explicit:i.closeReason};return{closeReason:$c(o,n.governance.require_close_reason,{operation:"create",status:e}).closeReason,completedAt:a,warnings:[]}}async function eO(e){let{pmRoot:t,type:n,id:i,settings:r,typeRegistry:s,author:a,extensionFieldNames:o,afterDocument:c,beforeDocument:d,historyMessage:l,changedFields:u,nowValue:p,similarityCandidate:g,allowDuplicate:f}=e,h=hl(t,n,i,r.item_format,s.type_to_folder),y=at(t,i),v=ae(),w=c.metadata.parent!==void 0||(c.metadata.dependencies??[]).some(C=>Ss(C.kind,v)),k=await Ps({pmRoot:t,author:a,ttlSeconds:r.locks.ttl_seconds,waitMs:r.locks.wait_ms,required:w}),S=w,T=[];try{let C=await bt(t,i,r.locks.ttl_seconds,a,!1,r.governance.force_required_for_stale_lock,r.locks.wait_ms);try{let b=c.metadata.parent!==void 0||c.metadata.dependencies!==void 0&&c.metadata.dependencies.length>0?await Se(t,r.item_format,s.type_to_folder,void 0,r.schema):void 0,E=await Y(t,i,r.id_prefix,r.item_format,s.type_to_folder);if(E)throw new _(`Item "${i}" already exists`,m.CONFLICT,{code:"item_already_exists",id:E.id,path:E.itemPath,required:"Read the existing item before deciding whether to update it or create a different ID.",nextSteps:[`Inspect the existing item with pm get ${E.id}.`]});if(b){Ts(b,[...b,c.metadata],v);let G=K(r.schema);xr(b,[...b,c.metadata],i,pe=>_e(pe,G),v)}let N=await wu({pmRoot:t,settings:r,operation:"create",author:a,before:null,after:c});await Kl({pm_root:t,operation:"create",before:null,after:c,changed_fields:u,sdk:Tu({pmRoot:t,settings:r,typeToFolder:s.type_to_folder})});let A=await Eu(t,a,{required:r.governance.duplicate_detection_mode==="strict"&&f!==!0}),R=[];try{r.governance.duplicate_detection_mode==="strict"&&f!==!0&&await jo(g,{pmRoot:t,mode:"strict",threshold:r.governance.duplicate_detection_threshold,limit:r.governance.duplicate_detection_limit,allowDuplicate:!1}),await Oe(h,cu(c,{format:r.item_format,schema:r.schema,extensionFieldNames:o}));try{let G=mu({nowIso:p,author:a,op:"create",before:d,after:c,message:l,context:N.decisions.length===0?void 0:{workflow_policies:N.decisions}});await _u(y,G)}catch(G){throw await al(h),G}S&&(await k(),S=!1),R=await Su({pmRoot:t,preferredFormat:r.item_format,typeToFolder:s.type_to_folder,schema:r.schema,itemPath:h,document:c})}finally{await A()}T=[...N.warnings,...b?Es(b,[...b,c.metadata],i):[],...R,...await ot({path:h,scope:"project",op:"create",item_id:c.metadata.id,item_type:c.metadata.type,before:d,after:c,changed_fields:u}),...await ot({path:y,scope:"project",op:"create:history",item_id:c.metadata.id,item_type:c.metadata.type,before:d,after:c,changed_fields:u})],Gl({id:c.metadata.id,op:"create",item_type:c.metadata.type,status:c.metadata.status,current:ql(c.metadata,u),changed_fields:u})}finally{await C()}}finally{S&&await k()}return T}async function XW(e,t){let n=Wy(await bR(e)),i=x(process.cwd(),t.path);await $(i);let r=await I(i),s=K(r.schema),a=nn(r.schema),o=F(r,P()),c=await WR(n,t,i,r,o);n=c.resolvedOptions;let{typeDefinition:d,type:l,createMode:u}=c,p=cR(n.unset,a),{explicitUnsets:g,clearOptionKeys:f}=BR(n,p);HR(n,p),VR(n);let h=U(ke(n.author),r.author_default),y=TR(d,n,u,f,h),v=O(),w=dR(n.dep,v,r.id_prefix,h),k=Jt("--comment",n.comment,v,h),S=Jt("--note",n.note,v,h),T=Jt("--learning",n.learning,v,h),C=Bc(n.file),b=Hc(n.test);b.values=await En(b.values,h,v);let E=Vc(n.doc),N=uR(n.reminder,v),A=mR(n.event,v),R=vR(n.typeOption),G=Pn(l,R.values,o),pe=P(),ce=Et(pe),de=nr(n.field,pe,Gs),ue=ru(n,a,l),en=new Set(ue.missing_required_flags),Nn=a.definitions.filter(X=>en.has(`--${X.cli_flag}`));YR(de,ue,p);let it=AR(G.errors,l),Ne=it.map(X=>`--type-option ${X}=<value>`),ht=[...new Set([...y,...Ne,...ue.missing_required_flags])].sort((X,Ra)=>X.localeCompare(Ra));JR({combinedMissingFlags:ht,typeDefinition:d,missingRequiredCreateFlags:y,missingRequiredTypeOptionKeys:it,openStatus:s.open_status,type:l,createMode:u,missingRequiredRuntimeFields:Nn}),CR(G.errors,l,d,s);let Ee=await GR({pmRoot:i,settings:r,typeRegistry:o,explicitId:n.id}),Me=n.status!==void 0?sR(n.status,s):aR(d,s),yt=n.priority!==void 0?yr(n.priority):2,D=p.metadataKeys,rt=XR(D,n),vt=Yt(D,"deadline",n.deadline,X=>ge(X,new Date(v),"deadline")),V=Yt(D,"estimated_minutes",n.estimatedMinutes,X=>pr(X,"estimated-minutes")),Ea=J(D,"acceptance_criteria",n.acceptanceCriteria),Ye=J(D,"definition_of_ready",n.definitionOfReady),Sa=QR(D,n),$i=J(D,"goal",n.goal),_b=J(D,"objective",n.objective),pb=J(D,"value",n.value),fb=J(D,"impact",n.impact),gb=J(D,"outcome",n.outcome),hb=J(D,"why_now",n.whyNow),yb=J(D,"assignee",n.assignee),vb=D.has("author")?void 0:ke(n.author)??h,wb=J(D,"parent",n.parent),Ud=await $R(wb,n,D,i),Ta=Ud.parent,bb=Ud.parentSource,kb=J(D,"reviewer",n.reviewer),Eb=Yt(D,"risk",n.risk,X=>Ve(Fs(X),zi,"risk")),Sb=Yt(D,"confidence",n.confidence,X=>Us(X)),Tb=n.allowMissingParent===!0&&r.validation.parent_reference==="strict_error"?"warn":r.validation.parent_reference,jd=r.validation.sprint_release_format,Rt=[...c.warnings,...FR(l,Ee,vt,N.values,A.values)],Gd=await jR({itemId:Ee,parent:Ta,pmRoot:i,settings:r,typeRegistry:o,policy:Tb});Ta=Gd.parent,Rt.push(...Gd.warnings);let qd=Ky(D,"sprint",n.sprint,"sprint",jd),Ab=qd.value;Rt.push(...qd.warnings);let Kd=Ky(D,"release",n.release,"release",jd),Ib=Kd.value;Rt.push(...Kd.warnings);let zd=J(D,"blocked_by",n.blockedBy),Wd=await qR({pmRoot:i,settings:r,typeRegistry:o,statusRegistry:s,blockedBy:zd,dependencyValues:w.values,status:Me,statusExplicit:n.status!==void 0,nowValue:v,author:h}),Aa=Wd.dependencyValues;Ai(Ee,Aa),Rt.push(...await Vs({pmRoot:i,dependencies:Aa,idPrefix:r.id_prefix,itemFormat:r.item_format,typeToFolder:o.type_to_folder,allowUnresolved:n.allowUnresolvedDeps,holders:[{id:Ee,createdAt:v}],schema:r.schema})),Me=Wd.status;let Cb=J(D,"blocked_reason",n.blockedReason),xb=J(D,"unblock_note",n.unblockNote),Rb=J(D,"reporter",n.reporter),Ob=Yt(D,"severity",n.severity,X=>Ve($s(X),Wi,"severity")),Lb=J(D,"environment",n.environment),Db=J(D,"repro_steps",n.reproSteps),Bd=J(D,"resolution",n.resolution),Nb=J(D,"expected_result",n.expectedResult),Mb=J(D,"actual_result",n.actualResult),Pb=J(D,"affected_version",n.affectedVersion),Fb=J(D,"fixed_version",n.fixedVersion),$b=J(D,"component",n.component),Ub=Yt(D,"regression",n.regression,X=>js(X)),jb=J(D,"customer_impact",n.customerImpact),Ia=Yc(n.title,"--title"),Ca=n.description??"",Ui=n.body??"",Hd=await jo({title:Ia,description:Ca,body:Ui},{pmRoot:i,mode:r.governance.duplicate_detection_mode,threshold:r.governance.duplicate_detection_threshold,limit:r.governance.duplicate_detection_limit,allowDuplicate:n.allowDuplicate});Rt.push(...zf(Hd));let xa=ZR(Me,s,r,n,Bd,v),Gb=xa.closeReason,qb=Me===s.close_status?v:void 0,Kb=xa.completedAt;Rt.push(...xa.warnings);let ji=ou({id:Ee,title:Ia,description:Ca,type:l,type_options:G.normalized,status:Me,closed_at:qb,completed_at:Kb,close_reason:Gb,priority:yt,tags:rt,created_at:v,updated_at:v,deadline:vt,assignee:yb,author:vb,estimated_minutes:V,acceptance_criteria:Ea,definition_of_ready:Ye,order:Sa,goal:$i,objective:_b,value:pb,impact:fb,outcome:gb,why_now:hb,parent:Ta,reviewer:kb,risk:Eb,confidence:Sb,sprint:Ab,release:Ib,blocked_by:zd,blocked_reason:Cb,unblock_note:xb,reporter:Rb,severity:Ob,environment:Lb,repro_steps:Db,resolution:Bd,expected_result:Nb,actual_result:Mb,affected_version:Pb,fixed_version:Fb,component:$b,regression:Ub,customer_impact:jb,dependencies:Aa,comments:k.values,notes:S.values,learnings:T.values,files:C.values,tests:b.values,docs:E.values,reminders:N.values,events:A.values,...de,...ue.values});try{ir(ji,pe)}catch(X){throw new _(X instanceof Error?X.message:"Invalid extension item field values",m.USAGE)}let zb=du({metadata:ji,body:Ui},{schema:r.schema,extensionFieldNames:ce}),Wb={metadata:{},body:""},Vd=[...g].sort((X,Ra)=>X.localeCompare(Ra)),Bb=pR(n.message,Vd),Yd=_R(ji,Ui,Vd,[...Object.keys(de),...Object.keys(ue.values??{})]),Hb=await eO({pmRoot:i,type:l,id:Ee,settings:r,typeRegistry:o,author:h,extensionFieldNames:ce,afterDocument:zb,beforeDocument:Wb,historyMessage:Bb,changedFields:Yd,nowValue:v,similarityCandidate:{title:Ia,description:Ca,body:Ui},allowDuplicate:n.allowDuplicate}),Jd=structuredClone(ji);u==="strict"&&g.has("dependencies")&&(Jd.dependencies=[]);let Vb=xy(Ee,l,Me,s);return Yy(l,vt,N.values,A.values)&&nu(`[pm] warning: ${l} '${Ee}' has no deadline/reminder/event \u2014 it will not appear on the calendar. Add one via 'pm update ${Ee} --deadline <ISO>' or 'pm update ${Ee} --event "start=<ISO>,end=<ISO>"'.`),{item:Jd,changed_fields:Yd,warnings:[...Rt,...Hb],...Object.fromEntries([["parent_source",bb],["next_transition",Vb],["similarity_advisory",Hd]].filter(X=>X[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]="961c1918-75f9-5e5d-bbae-b333ca29534f")}catch{}})();function Xy(e){return Ke("in_progress",e)??e.open_status}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4790c318-c305-53d4-895c-e9ac90665376")}catch{}})();function ta(e){if(e.enforcement==="off"||e.typeWorkflows.length===0)return;let t=p_({typeName:e.typeName,fromStatus:e.fromStatus,toStatus:e.toStatus,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry});if(!t.hasRule||t.allowed)return;let n=Ke(e.fromStatus,e.statusRegistry)??e.fromStatus,i=Ke(e.toStatus,e.statusRegistry)??e.toStatus,r=`Disallowed transition for type "${e.typeName}": ${n} -> ${i}. Allowed transitions: ${f_(t.allowedTransitions)}.`;if(e.enforcement==="strict")throw new _(r,m.USAGE);return`workflow_transition_not_allowed: ${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]="f93d880f-109a-51b7-8572-d03841e35803")}catch{}})();var Zc=[...jc,{canonical:"close-reason",aliases:["close_reason","close-reason"],optionKey:"closeReason",metadataKey:"close_reason"},...Gc,...Ws],tO=(()=>{let e=new Map;for(let t of Zc)for(let n of t.aliases)e.set(n,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),na=new Map(Zc.map(e=>[e.optionKey,e.canonical])),nO=Zc.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", "),iO=new Set(["close_reason","assignee","parent","blocked_by","blocked_reason","unblock_note","dependencies","comments","notes","learnings","files","tests","docs","reminders","events"]),rO=qs({depDisableFlagKey:"replaceDeps",fileDisableFlagKey:"replaceFiles",testDisableFlagKey:"replaceTests",docDisableFlagKey:"replaceDocs"});function sv(e){let t={...e,unset:e.unset?[...e.unset]:void 0},n=r=>{let s=t.unset?[...t.unset]:[];s.includes(r)||s.push(r),t.unset=s},i=new Set([...na.keys(),"rank"]);for(let r of i){let s=t[r];if(typeof s!="string"||!He(s))continue;let a=r==="rank"?"order":na.get(r)??r;n(a),t[r]=void 0}return Ze(e,zs(t,rO))}function av(e,t,n=[]){return Bs({raw:e,supportedFields:nO,resolveDefinition:i=>{let r=n.find(s=>{let a=s.toLowerCase();return a===i||a.replaceAll("_","-")===i||a.replaceAll("-","_")===i});return tO.get(i)??Hs(i,"update",t)??(r?{optionKey:"field",metadataKey:r}:void 0)}})}var Qy=new Map([["--comment",e=>`pm comments ${e} --add "<text>" --force`],["--file",e=>`pm files ${e} --add "path=<path>,scope=<scope>,note=<note>" --force`],["--doc",e=>`pm docs ${e} --add "path=<path>,scope=<scope>,note=<note>" --force`]]);function Zy(e){let t=e.disallowedFlags.flatMap(i=>{let r=Qy.get(i);return r?[r(e.id)]:[]}),n=e.disallowedFlags.flatMap(i=>{let r=Qy.get(i);return r?[`Replace ${i} with: ${r(e.id)}`]:[]});return new _(e.message,m.USAGE,{code:e.code,required:e.required,why:e.why,...t.length>0?{examples:t}:{},nextSteps:[`Re-run without: ${e.disallowedFlags.join(", ")}`,...n]})}function sO(e,t,n){let i=t.ownershipMetadataBypass===!0,r=t.ownershipDependencyBypass===!0;if(!i&&!r)return;if(i&&r)throw new _("Choose only one package-provided ownership bypass mode.",m.USAGE);let s=(c,d,l)=>{c&&l.push(d)};if(r){let c=[];if(s(t.title!==void 0,"--title",c),s(t.description!==void 0,"--description",c),s(t.body!==void 0,"--body",c),s(t.status!==void 0,"--status",c),s(t.closeReason!==void 0,"--close-reason",c),s(t.priority!==void 0,"--priority",c),s(t.type!==void 0,"--type",c),s(t.tags!==void 0,"--tags",c),s(Array.isArray(t.addTags)&&t.addTags.length>0,"--add-tags",c),s(Array.isArray(t.removeTags)&&t.removeTags.length>0,"--remove-tags",c),s(t.deadline!==void 0,"--deadline",c),s(t.estimatedMinutes!==void 0,"--estimate",c),s(t.acceptanceCriteria!==void 0,"--acceptance-criteria",c),s(Array.isArray(t.addAc)&&t.addAc.length>0,"--add-ac",c),s(Array.isArray(t.removeAc)&&t.removeAc.length>0,"--remove-ac",c),s(t.definitionOfReady!==void 0,"--definition-of-ready",c),s(t.order!==void 0||t.rank!==void 0,"--order/--rank",c),s(t.goal!==void 0,"--goal",c),s(t.objective!==void 0,"--objective",c),s(t.value!==void 0,"--value",c),s(t.impact!==void 0,"--impact",c),s(t.outcome!==void 0,"--outcome",c),s(t.whyNow!==void 0,"--why-now",c),s(t.assignee!==void 0,"--assignee",c),s(t.parent!==void 0,"--parent",c),s(t.reviewer!==void 0,"--reviewer",c),s(t.risk!==void 0,"--risk",c),s(t.confidence!==void 0,"--confidence",c),s(t.sprint!==void 0,"--sprint",c),s(t.release!==void 0,"--release",c),s(t.blockedBy!==void 0,"--blocked-by",c),s(t.blockedReason!==void 0,"--blocked-reason",c),s(t.unblockNote!==void 0,"--unblock-note",c),s(t.reporter!==void 0,"--reporter",c),s(t.severity!==void 0,"--severity",c),s(t.environment!==void 0,"--environment",c),s(t.reproSteps!==void 0,"--repro-steps",c),s(t.resolution!==void 0,"--resolution",c),s(t.expectedResult!==void 0,"--expected-result",c),s(t.actualResult!==void 0,"--actual-result",c),s(t.affectedVersion!==void 0,"--affected-version",c),s(t.fixedVersion!==void 0,"--fixed-version",c),s(t.component!==void 0,"--component",c),s(t.regression!==void 0,"--regression",c),s(t.customerImpact!==void 0,"--customer-impact",c),s(t.depRemove!==void 0,"--dep-remove",c),s(t.replaceDeps===!0,"--replace-deps",c),s(t.replaceTests===!0,"--replace-tests",c),s(t.replaceFiles===!0,"--replace-files",c),s(t.replaceDocs===!0,"--replace-docs",c),s(t.comment!==void 0,"--comment",c),s(t.note!==void 0,"--note",c),s(t.learning!==void 0,"--learning",c),s(t.file!==void 0,"--file",c),s(t.test!==void 0,"--test",c),s(t.doc!==void 0,"--doc",c),s(t.reminder!==void 0,"--reminder",c),s(t.event!==void 0,"--event",c),s(t.typeOption!==void 0,"--type-option",c),s(t.clearDeps===!0,"--clear-deps",c),s(t.clearComments===!0,"--clear-comments",c),s(t.clearNotes===!0,"--clear-notes",c),s(t.clearLearnings===!0,"--clear-learnings",c),s(t.clearFiles===!0,"--clear-files",c),s(t.clearTests===!0,"--clear-tests",c),s(t.clearDocs===!0,"--clear-docs",c),s(t.clearReminders===!0,"--clear-reminders",c),s(t.clearEvents===!0,"--clear-events",c),s(t.clearTypeOptions===!0,"--clear-type-options",c),s(t.force===!0,"--force",c),s(n.size>0,"--unset",c),t.dep===void 0||t.dep.length===0)throw new _("The dependency ownership bypass requires at least one --dep value",m.USAGE);if(c.length>0)throw Zy({id:e,code:"ownership_dependency_bypass_restricted_options",message:`The dependency ownership bypass supports append-only dependency additions via --dep. Remove restricted options: ${c.join(", ")}`,required:"Pass only --dep additions (plus --message/--author) with the dependency ownership bypass.",why:"the dependency ownership bypass is a narrow non-owner override scoped to append-only dependency additions; every other mutation keeps its normal ownership rules.",disallowedFlags:c});return}let a=[];s(t.status!==void 0,"--status",a),s(t.closeReason!==void 0,"--close-reason",a),s(t.assignee!==void 0,"--assignee",a),s(t.parent!==void 0,"--parent",a),s(t.blockedBy!==void 0,"--blocked-by",a),s(t.blockedReason!==void 0,"--blocked-reason",a),s(t.unblockNote!==void 0,"--unblock-note",a),s(t.dep!==void 0,"--dep",a),s(t.depRemove!==void 0,"--dep-remove",a),s(t.replaceDeps===!0,"--replace-deps",a),s(t.replaceTests===!0,"--replace-tests",a),s(t.replaceFiles===!0,"--replace-files",a),s(t.replaceDocs===!0,"--replace-docs",a),s(t.note!==void 0,"--note",a),s(t.learning!==void 0,"--learning",a),s(t.test!==void 0,"--test",a),s(t.reminder!==void 0,"--reminder",a),s(t.event!==void 0,"--event",a),s(t.clearDeps===!0,"--clear-deps",a),s(t.clearComments===!0,"--clear-comments",a),s(t.clearNotes===!0,"--clear-notes",a),s(t.clearLearnings===!0,"--clear-learnings",a),s(t.clearFiles===!0,"--clear-files",a),s(t.clearTests===!0,"--clear-tests",a),s(t.clearDocs===!0,"--clear-docs",a),s(t.clearReminders===!0,"--clear-reminders",a),s(t.clearEvents===!0,"--clear-events",a);let o=[...n].filter(c=>iO.has(c)).sort((c,d)=>c.localeCompare(d)).map(c=>`--unset ${c.replaceAll("_","-")}`);if(a.push(...o),a.length>0)throw Zy({id:e,code:"ownership_metadata_bypass_restricted_options",message:`The metadata ownership bypass only supports non-lifecycle metadata fields and evidence appends. Remove restricted options: ${a.join(", ")}`,required:"Limit the metadata ownership bypass to non-lifecycle metadata fields plus append-only --comment/--file/--doc evidence; route restricted appends and lifecycle changes through their dedicated commands.",why:"the metadata ownership bypass is a non-owner override scoped to metadata maintenance and append-only evidence; lifecycle, ownership, dependency mutations, restricted append fields, and clear/replace operations keep their normal ownership rules.",disallowedFlags:a})}function aO(e,t){let n=me(e,t);if(!n){let i=t.definitions.map(r=>r.id);throw new _(`Invalid --status value "${e}". Allowed: ${i.join(", ")}`,m.USAGE)}return n}function oO(e,t){return!e||e.trim()===""||e.trim().toLowerCase()==="now"?t:ov(e)}function ov(e){let t=Date.parse(e);if(!Number.isFinite(t))throw new _(`Invalid dependency created_at timestamp "${e}"`,m.USAGE);return new Date(t).toISOString()}function In(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}var cO=["id","kind","type","author","created_at","source_kind"],dO=["id","kind","type","author","created_at","source_kind"];function cv(e){return e.startsWith("```")||e.includes(`
|
|
11
|
+
`)||/^(?:[-*+]\s+)?(?:id|kind|type|author|created_at|source_kind)\s*[:=]/i.test(e)?!0:on(e)}function dv(e){return typeof e=="string"?ae().resolve(e)?.kind??e.trim():e}function lO(e,t,n,i){return e?(Re(e,"--dep","Use --clear-deps to clear dependencies."),{additions:e.map(r=>{let s=r.trim(),a=cv(s);Ti(s,a);let o=a?Z(r,"--dep"):{id:s,kind:"related"};a&&we(o,"--dep",cO);let c=o.id?.trim(),d=dv((o.kind??o.type)?.trim());if(!c||!d)throw new _("--dep requires id and kind, or a bare item id to add a related dependency",m.USAGE);if(c.toLowerCase()==="undefined")throw new _(`--dep id must not use placeholder token "${c}". Use --clear-deps to clear dependencies.`,m.USAGE);let l=Bn(In(o.source_kind)),u=In(o.author);return{id:Hn(c,t,l),kind:Si(d),created_at:oO(o.created_at,n),author:u??i,source_kind:l??"cli:update:dep",author_source:u?"asserted":"detected"}})}):{additions:[]}}function uO(e,t){return e?(Re(e,"--dep-remove"),e.map(n=>{let i=n.trim();if(!i)throw new _("--dep-remove requires id or key/value selectors",m.USAGE);let r=cv(i);if(Ti(i,r,"--dep-remove"),r){let s=Z(i,"--dep-remove");we(s,"--dep-remove",dO);let a=s.id?.trim();if(!a)throw new _("--dep-remove key/value form requires id=<value>",m.USAGE);if(a.toLowerCase()==="undefined")throw new _(`--dep-remove id must not use placeholder token "${a}"`,m.USAGE);let o=dv(In(s.kind??s.type)),c=Bn(In(s.source_kind)),d=In(s.author),l=In(s.created_at);return{id:Hn(a,t,c),kind:o?Si(o):void 0,source_kind:c,author:d,created_at:l?ov(l):void 0}}if(i.toLowerCase()==="undefined")throw new _(`--dep-remove id must not use placeholder token "${i}"`,m.USAGE);return{id:kt(i,t)}})):[]}function ia(e){let t=e.source_kind?.trim().toLowerCase()??"";return[e.id.trim().toLowerCase(),e.kind,t].join("\0")}function mO(e){let t=e.source_kind?.trim().toLowerCase()??"",n=e.author?.trim().toLowerCase()??"",i=e.created_at?.trim()??"",r=Date.parse(i),s=Number.isFinite(r)?new Date(r).toISOString():i;return[e.id.trim().toLowerCase(),e.kind,t,n,s].join("\0")}function _O(e,t,n,i){let r=[...e??[]],s=!1;if(t===void 0){let a=r.filter(o=>o.kind!=="blocked_by");return a.length!==r.length&&(r=a,s=!0),s?{dependencies:r.length>0?r:void 0,changed:!0}:{dependencies:e,changed:!1}}return r.some(a=>a.kind==="blocked_by"&&a.id===t)||(r.push({id:t,kind:"blocked_by",created_at:n,author:i,source_kind:"cli:update:blocked_by",author_source:"detected"}),s=!0),s?{dependencies:r.length>0?r:void 0,changed:!0}:{dependencies:e,changed:!1}}async function pO(e,t,n,i,r,s){if(e===void 0||t)return{};let a=e.trim();if(a.length===0)return{};let o=await Y(n,kt(a,i),i,r,s);return o?{id:o.id}:{unresolved:a}}function fO(e,t,n,i,r){let s=_O(e.dependencies,t,n,i);s.changed&&(s.dependencies===void 0?delete e.dependencies:e.dependencies=s.dependencies,r.includes("dependencies")||r.push("dependencies"))}function gO(e){return`${e.path}::${e.scope}`}function hO(e){return`${e.path}::${e.scope}`}function yO(e){return`${e.command}::${e.path??""}::${e.scope}::${e.pm_context_mode??""}::${e.workspace_context_mode??""}`}function lv(e,t){return!(e.id.trim().toLowerCase()!==t.id.trim().toLowerCase()||t.kind&&e.kind!==t.kind||t.source_kind!==void 0&&e.source_kind?.trim().toLowerCase()!==t.source_kind.trim().toLowerCase()||t.author!==void 0&&e.author?.trim().toLowerCase()!==t.author.trim().toLowerCase()||t.created_at!==void 0&&(e.created_at===void 0||!Number.isFinite(Date.parse(e.created_at))||new Date(Date.parse(e.created_at)).toISOString()!==t.created_at))}function ev(e,t){let n=Mn("update",e);if(!n)throw new _(`Unsupported command_option_policies option "${e}" for update command on type "${t}"`,m.CONFLICT);return n}function vO(e,t,n){let i=new Set,r=(s,a)=>{a&&i.add(s)};if(r("title",e.title!==void 0),r("description",e.description!==void 0),r("body",e.body!==void 0),r("status",e.status!==void 0),r("closeReason",e.closeReason!==void 0),r("priority",e.priority!==void 0),r("type",e.type!==void 0),r("tags",e.tags!==void 0||Array.isArray(e.addTags)&&e.addTags.length>0||Array.isArray(e.removeTags)&&e.removeTags.length>0),r("deadline",e.deadline!==void 0),r("estimatedMinutes",e.estimatedMinutes!==void 0),r("acceptanceCriteria",e.acceptanceCriteria!==void 0||Array.isArray(e.addAc)&&e.addAc.length>0||Array.isArray(e.removeAc)&&e.removeAc.length>0),r("definitionOfReady",e.definitionOfReady!==void 0),r("order",e.order!==void 0||e.rank!==void 0),r("goal",e.goal!==void 0),r("objective",e.objective!==void 0),r("value",e.value!==void 0),r("impact",e.impact!==void 0),r("outcome",e.outcome!==void 0),r("whyNow",e.whyNow!==void 0),r("author",e.author!==void 0),r("message",e.message!==void 0),r("assignee",e.assignee!==void 0),r("parent",e.parent!==void 0),r("reviewer",e.reviewer!==void 0),r("risk",e.risk!==void 0),r("confidence",e.confidence!==void 0),r("sprint",e.sprint!==void 0),r("release",e.release!==void 0),r("blockedBy",e.blockedBy!==void 0),r("blockedReason",e.blockedReason!==void 0),r("unblockNote",e.unblockNote!==void 0),r("reporter",e.reporter!==void 0),r("severity",e.severity!==void 0),r("environment",e.environment!==void 0),r("reproSteps",e.reproSteps!==void 0),r("resolution",e.resolution!==void 0),r("expectedResult",e.expectedResult!==void 0),r("actualResult",e.actualResult!==void 0),r("affectedVersion",e.affectedVersion!==void 0),r("fixedVersion",e.fixedVersion!==void 0),r("component",e.component!==void 0),r("regression",e.regression!==void 0),r("customerImpact",e.customerImpact!==void 0),r("dep",e.dep!==void 0),r("depRemove",e.depRemove!==void 0),r("dep",e.replaceDeps===!0),r("comment",e.comment!==void 0),r("note",e.note!==void 0),r("learning",e.learning!==void 0),r("file",e.file!==void 0),r("test",e.test!==void 0),r("test",e.replaceTests===!0),r("file",e.replaceFiles===!0),r("doc",e.replaceDocs===!0),r("doc",e.doc!==void 0),r("reminder",e.reminder!==void 0),r("event",e.event!==void 0),r("typeOption",e.typeOption!==void 0),r("field",e.field!==void 0),r("force",e.force===!0),r("ownershipMetadataBypass",e.ownershipMetadataBypass===!0),r("ownershipDependencyBypass",e.ownershipDependencyBypass===!0),r("dep",e.clearDeps===!0),r("comment",e.clearComments===!0),r("note",e.clearNotes===!0),r("learning",e.clearLearnings===!0),r("file",e.clearFiles===!0),r("test",e.clearTests===!0),r("doc",e.clearDocs===!0),r("reminder",e.clearReminders===!0),r("event",e.clearEvents===!0),r("typeOption",e.clearTypeOptions===!0),e.unset&&e.unset.length>0){let s=av(e.unset,t,n);for(let a of s.optionKeys)r(a,!0)}return i}function wO(e,t,n,i,r){let s=Bi(e,n);if(!s)throw new _(`Invalid type value "${e}"`,m.USAGE);let a=tn(s,"update",[]);if(a.errors.length>0)throw new _(a.errors.join("; "),m.CONFLICT);let o=vO(t,i,r);for(let c of a.disabled)if(o.has(ev(c,e)))throw new _(`Option ${Te("update",c)} is disabled for type "${e}" by command_option_policies`,m.USAGE);for(let c of a.required)if(!o.has(ev(c,e)))throw new _(`Missing required option ${Te("update",c)} for type "${e}"`,m.USAGE)}var bO=new Set(["order","rank"]),kO=Pa.filter(e=>!bO.has(e)),uv=["tags","closeReason",...kO],EO=["title","description","body","status","closeReason","completedAt","priority","type",...Pa,"dep","depRemove","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],SO=[{optionKey:"deadline",metadataKey:"deadline",transform:(e,t)=>ge(e,t.nowValue,"deadline")},{optionKey:"estimatedMinutes",metadataKey:"estimated_minutes",transform:e=>pr(e,"estimated-minutes")},{optionKey:"acceptanceCriteria",metadataKey:"acceptance_criteria",transform:e=>e},{optionKey:"definitionOfReady",metadataKey:"definition_of_ready"},{optionKey:"goal",metadataKey:"goal"},{optionKey:"objective",metadataKey:"objective"},{optionKey:"value",metadataKey:"value"},{optionKey:"impact",metadataKey:"impact"},{optionKey:"outcome",metadataKey:"outcome"},{optionKey:"whyNow",metadataKey:"why_now"}],TO=[{optionKey:"reviewer",metadataKey:"reviewer"},{optionKey:"risk",metadataKey:"risk",transform:e=>Ve(Fs(e),zi,"risk")},{optionKey:"confidence",metadataKey:"confidence",transform:e=>Us(e)}],AO=[{optionKey:"blockedReason",metadataKey:"blocked_reason"},{optionKey:"unblockNote",metadataKey:"unblock_note"},{optionKey:"reporter",metadataKey:"reporter"},{optionKey:"severity",metadataKey:"severity",transform:e=>Ve($s(e),Wi,"severity")},{optionKey:"environment",metadataKey:"environment"},{optionKey:"reproSteps",metadataKey:"repro_steps"},{optionKey:"resolution",metadataKey:"resolution"},{optionKey:"expectedResult",metadataKey:"expected_result"},{optionKey:"actualResult",metadataKey:"actual_result"},{optionKey:"affectedVersion",metadataKey:"affected_version"},{optionKey:"fixedVersion",metadataKey:"fixed_version"},{optionKey:"component",metadataKey:"component"},{optionKey:"regression",metadataKey:"regression",transform:e=>js(e)},{optionKey:"customerImpact",metadataKey:"customer_impact"}];function Qc(e,t,n){for(let i of e){let r=t[i.optionKey],s=n.clearItemMetadataKeys.has(i.metadataKey);if(!(r===void 0&&!s)){if(s){delete n.metadataRecord[i.metadataKey],n.changedFields.push(i.metadataKey);continue}if(typeof r!="string")throw new _(`${Te("update",String(i.optionKey))} must be a string value`,m.USAGE);n.metadataRecord[i.metadataKey]=i.transform?i.transform(r,n):r.trim(),n.changedFields.push(i.metadataKey)}}}async function IO(e){return sv(await _r(e,[["body","--body"],["description","--description"]],[["dep","--dep"],["depRemove","--dep-remove"],["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"],["field","--field"]]))}async function CO(e){return Ft(e)?await IO(e):sv(e)}function xO(e){return[{enabled:e.clearDeps||e.replaceDeps,optionKey:"dep",clearFlag:"--clear-deps",valueFlag:"--dep",values:e.dep,metadataKey:"dependencies"},{enabled:e.clearComments,optionKey:"comment",clearFlag:"--clear-comments",valueFlag:"--comment",values:e.comment,metadataKey:"comments"},{enabled:e.clearNotes,optionKey:"note",clearFlag:"--clear-notes",valueFlag:"--note",values:e.note,metadataKey:"notes"},{enabled:e.clearLearnings,optionKey:"learning",clearFlag:"--clear-learnings",valueFlag:"--learning",values:e.learning,metadataKey:"learnings"},{enabled:e.clearFiles||e.replaceFiles,optionKey:"file",clearFlag:"--clear-files",valueFlag:"--file",values:e.file,metadataKey:"files"},{enabled:e.clearTests||e.replaceTests,optionKey:"test",clearFlag:"--clear-tests",valueFlag:"--test",values:e.test,metadataKey:"tests"},{enabled:e.clearDocs||e.replaceDocs,optionKey:"doc",clearFlag:"--clear-docs",valueFlag:"--doc",values:e.doc,metadataKey:"docs"},{enabled:e.clearReminders,optionKey:"reminder",clearFlag:"--clear-reminders",valueFlag:"--reminder",values:e.reminder,metadataKey:"reminders"},{enabled:e.clearEvents,optionKey:"event",clearFlag:"--clear-events",valueFlag:"--event",values:e.event,metadataKey:"events"},{enabled:e.clearTypeOptions,optionKey:"typeOption",clearFlag:"--clear-type-options",valueFlag:"--type-option",values:e.typeOption,metadataKey:"type_options"}]}function Jc(e){if(e.enabled&&(!e.values||e.values.length===0))throw new _(`${e.replaceFlag} requires at least one ${e.valueFlag} entry`,m.USAGE);if(e.enabled&&e.clearEnabled)throw new _(`${e.replaceFlag} cannot be combined with ${e.clearFlag}`,m.USAGE)}function RO(e){let t=(e.addAc?.length??0)>0||(e.removeAc?.length??0)>0;if(e.acceptanceCriteria!==void 0&&t)throw new _("Cannot combine --acceptance-criteria replacement with --add-ac or --remove-ac. Use --remove-ac and --add-ac together for an atomic one-entry repair.",m.USAGE,{code:"acceptance_criteria_mutation_conflict",reason:"replacement_and_additive_mutation_combined",nextSteps:["Use --acceptance-criteria alone to replace the complete list.","Use --remove-ac <old> --add-ac <new> to repair one criterion without replacing unrelated entries."]});if(e.replaceDeps===!0&&(e.dep===void 0||e.dep.length===0))throw new _("--replace-deps requires at least one --dep entry",m.USAGE);if(e.replaceDeps===!0&&e.depRemove!==void 0&&e.depRemove.length>0)throw new _("--replace-deps cannot be combined with --dep-remove",m.USAGE);Jc({enabled:e.replaceTests===!0,values:e.test,replaceFlag:"--replace-tests",clearEnabled:e.clearTests===!0,clearFlag:"--clear-tests",valueFlag:"--test"}),Jc({enabled:e.replaceFiles===!0,values:e.file,replaceFlag:"--replace-files",clearEnabled:e.clearFiles===!0,clearFlag:"--clear-files",valueFlag:"--file"}),Jc({enabled:e.replaceDocs===!0,values:e.doc,replaceFlag:"--replace-docs",clearEnabled:e.clearDocs===!0,clearFlag:"--clear-docs",valueFlag:"--doc"})}function OO(e){for(let t of e.definitions){if(!t.enabled)continue;let n=t.optionKey==="dep"&&e.options.replaceDeps===!0||t.optionKey==="test"&&e.options.replaceTests===!0||t.optionKey==="file"&&e.options.replaceFiles===!0||t.optionKey==="doc"&&e.options.replaceDocs===!0;if(t.values&&t.values.length>0&&!n)throw new _(`Cannot combine ${t.clearFlag} with ${t.valueFlag}`,m.USAGE);e.clearOptionKeys.add(t.optionKey),e.clearItemMetadataKeys.add(t.metadataKey)}}function LO(e){let t={};for(let n of uv)t[String(n)]=e[n]!==void 0;return t.order=e.order!==void 0||e.rank!==void 0,t}function DO(e,t){let n=LO(e);for(let[i,r]of Object.entries(n)){if(!r||!t.optionKeys.has(i))continue;let s=na.get(i)??i;throw new _(`Cannot combine --unset ${s} with ${Te("update",i)}`,m.USAGE)}if(t.metadataKeys.has("acceptance_criteria")){if(Array.isArray(e.addAc)&&e.addAc.length>0)throw new _("Cannot combine --unset acceptance-criteria with --add-ac",m.USAGE);if(Array.isArray(e.removeAc)&&e.removeAc.length>0)throw new _("Cannot combine --unset acceptance-criteria with --remove-ac",m.USAGE)}if(t.metadataKeys.has("tags")){if(Array.isArray(e.addTags)&&e.addTags.length>0)throw new _("Cannot combine --unset tags with --add-tags",m.USAGE);if(Array.isArray(e.removeTags)&&e.removeTags.length>0)throw new _("Cannot combine --unset tags with --remove-tags",m.USAGE)}}function NO(e){let t=(n,i)=>{let r=na.get(i),s=r?`Use --unset ${r} to clear this field.`:void 0;Ks(n,Te("update",i),s)};for(let n of uv)t(e[n],String(n));t(e.order??e.rank,"order"),Re(e.reminder,"--reminder","Use --clear-reminders to clear reminders."),Re(e.event,"--event","Use --clear-events to clear linked events.")}function MO(e,t){let n={};for(let i of EO)n[String(i)]=e[i]!==void 0;return n.tags=e.tags!==void 0,n.addTags=Array.isArray(e.addTags)&&e.addTags.length>0,n.removeTags=Array.isArray(e.removeTags)&&e.removeTags.length>0,n.addAc=Array.isArray(e.addAc)&&e.addAc.length>0,n.removeAc=Array.isArray(e.removeAc)&&e.removeAc.length>0,n.order=e.order!==void 0,n.rank=e.rank!==void 0,n.replaceDeps=e.replaceDeps===!0,n.replaceTests=e.replaceTests===!0,n.replaceFiles=e.replaceFiles===!0,n.replaceDocs=e.replaceDocs===!0,n.unset=e.unset!==void 0&&e.unset.length>0,n.clearDeps=e.clearDeps===!0,n.clearComments=e.clearComments===!0,n.clearNotes=e.clearNotes===!0,n.clearLearnings=e.clearLearnings===!0,n.clearFiles=e.clearFiles===!0,n.clearTests=e.clearTests===!0,n.clearDocs=e.clearDocs===!0,n.clearReminders=e.clearReminders===!0,n.clearEvents=e.clearEvents===!0,n.clearTypeOptions=e.clearTypeOptions===!0,n.documentAnnotationSnapshot=e.documentAnnotationSnapshot!==void 0,n.runtimeFields=Object.keys(t).length>0,n}async function PO(e){let t=await Y(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await qn(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await he(t,{schema:e.settings.schema});return{item:n.metadata,changed_fields:[],warnings:["noop_no_update_fields"]}}async function FO(e){if(!(!e.fieldFlags.dep&&!e.fieldFlags.blockedBy&&!e.fieldFlags.parent&&!e.clearedMetadataKeys.has("parent")))return Se(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}function $O(e){e.before&&(Ts(e.before,e.before.map(t=>t.id===e.document.metadata.id?e.document.metadata:t)),xr(e.before,e.before.map(t=>t.id===e.document.metadata.id?e.document.metadata:t),e.document.metadata.id,t=>_e(t,e.statusRegistry),ae()))}function UO(e){if(e.order!==void 0&&e.rank!==void 0&&e.order!==e.rank)throw new _("--order and --rank must match when both are provided",m.USAGE)}async function jO(e){if(e.options.parent===void 0||e.unsetTargets.metadataKeys.has("parent"))return{resolvedParentValue:void 0,warnings:[]};let t=Ir(fr(e.options.parent),e.settings.id_prefix);if(Er(t))return{resolvedParentValue:t,warnings:[]};if(hr(e.id,t,e.settings.id_prefix),await Y(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder))return{resolvedParentValue:t,warnings:[]};let n=kt(t,e.settings.id_prefix);return{resolvedParentValue:t,warnings:gr(n,e.parentReferencePolicy).warnings}}function GO(e){return e.unresolved===void 0?[]:[`blocked_by_unresolved:${e.unresolved}`]}async function qO(e){if(e.workflowEnforcement==="off"||e.typeWorkflows.length===0||!e.fieldFlags.status||e.options.status===void 0)return[];let t=await Y(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await qn(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:n}=await he(t,{schema:e.settings.schema}),i=e.options.type!==void 0?st(e.options.type,e.typeRegistry)??e.options.type:n.metadata?.type??"",r=ta({enforcement:e.workflowEnforcement,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry,typeName:i,fromStatus:n.metadata?.status??"",toStatus:e.options.status});return r?[r]:[]}async function KO(e){if(!e.fieldFlags.status||me(e.options.status,e.statusRegistry)!==e.statusRegistry.close_status)return;let t=Object.entries(e.fieldFlags).filter(([a,o])=>o&&a!=="status"&&a!=="closeReason"&&a!=="completedAt").map(([a])=>a),n=[],i=[];if(t.length>0){let a=Ze(e.options,{...e.options,status:void 0,closeReason:void 0,message:void 0}),o=await ra(e.id,a,e.global);i=o.changed_fields,n.push(...o.warnings)}let r=await ks(e.id,e.options.closeReason,{author:e.options.author,message:e.options.message,force:e.options.force,completedAt:e.options.completedAt},e.global),s=[...e.workflowTransitionWarnings,...n,...r.warnings,"auto_routed_from_update_to_close"];return{item:r.item,changed_fields:[...i,...r.changed_fields],warnings:s}}function zO(e,t,n,i){return t.title!==void 0&&(e.metadata.title=Yc(t.title,"--title"),i.push("title")),t.description!==void 0&&(e.metadata.description=t.description,i.push("description")),t.body!==void 0&&(e.body=t.body,i.push("body")),me(e.metadata.status,n)??e.metadata.status}var WO=["closed_at","completed_at","close_reason","resolution","expected_result","actual_result","fixed_version"];function BO(e,t){for(let n of WO)e[n]!==void 0&&(delete e[n],t.push(n))}function HO(e,t,n,i,r){let s=aO(n,t.statusRegistry);if(e.metadata.status=s,r.push("status"),s===t.statusRegistry.close_status&&(e.metadata.closed_at===void 0||e.metadata.closed_at===null)){e.metadata.closed_at=t.nowIso,e.metadata.completed_at=t.nowIso,r.push("closed_at","completed_at");return}!_e(s,t.statusRegistry)&&_e(i,t.statusRegistry)&&BO(e.metadata,r)}function VO(e,t,n,i){if(t.options.status!==void 0&&HO(e,t,t.options.status,n,i),t.options.completedAt!==void 0){if(!_e(e.metadata.status,t.statusRegistry))throw new _("--completed-at can only be set on a terminal item",m.USAGE);e.metadata.completed_at=ge(t.options.completedAt,new Date(t.nowIso),"completed-at"),i.push("completed_at")}}function YO(e,t,n,i){if(t.options.closeReason!==void 0||t.clearItemMetadataKeys.has("close_reason")){if(t.clearItemMetadataKeys.has("close_reason"))delete e.metadata.close_reason;else{let r=t.options.closeReason?.trim()??"";if(r.length===0)throw new _("--close-reason must not be empty",m.USAGE);e.metadata.close_reason=r}i.push("close_reason");return}t.options.status!==void 0&&_e(n,t.statusRegistry)&&!_e(e.metadata.status,t.statusRegistry)&&e.metadata.close_reason!==void 0&&(delete e.metadata.close_reason,i.push("close_reason"))}function JO(e,t,n,i){VO(e,t,n,i),YO(e,t,n,i)}function XO(e,t,n){let i=st(e.metadata.type,t.typeRegistry)??e.metadata.type;if(t.options.priority!==void 0&&(e.metadata.priority=yr(t.options.priority),n.push("priority")),t.options.type!==void 0){let r=st(t.options.type,t.typeRegistry);if(!r)throw new _(wr(t.options.type,t.typeRegistry.types,Xi(t.pmRoot,t.settings.schema)),m.USAGE);e.metadata.type=r,i=r,n.push("type")}return wO(i,t.options,t.typeRegistry,t.runtimeFieldRegistry,t.extensionFieldNames),QO(e,t,i,n),i}function QO(e,t,n,i){if(t.options.typeOption!==void 0||t.clearItemMetadataKeys.has("type_options")){if(t.clearItemMetadataKeys.has("type_options"))delete e.metadata.type_options;else{let s=Xs(t.options.typeOption??[]),a=Pn(n,s,t.typeRegistry);if(a.errors.length>0)throw new _(a.errors.join("; "),m.USAGE);e.metadata.type_options=a.normalized}i.push("type_options");return}if(t.options.type===void 0||e.metadata.type_options===void 0)return;let r=Pn(n,e.metadata.type_options,t.typeRegistry);if(r.errors.length>0)throw new _(`Current type options are incompatible with type "${n}". ${r.errors.join("; ")}. Use --clear-type-options to clear them.`,m.USAGE);e.metadata.type_options=r.normalized}function ZO(e,t){let n=new Set(t.map(r=>ia(r))),i=new Set;return e.filter(r=>{if(!n.has(ia(r)))return!0;let s=mO(r);return i.has(s)?!1:(i.add(s),!0)})}function eL(e,t,n){let i=t.filter(r=>!e.some(s=>lv(s,r)));if(i.length!==0)throw new _(`Dependency removal did not match ${i.length===1?"a stored edge":"stored edges"}.`,m.NOT_FOUND,{code:"dependency_remove_no_match",reason:"selector_not_found",unmatched_selectors:i,available_dependencies:e.map(r=>({id:r.id,kind:r.kind,source_kind:r.source_kind,author:r.author,created_at:r.created_at})),why:"Failing on a zero-match selector prevents a mistyped dependency removal from being reported as successful.",nextSteps:[`Inspect the current item with: pm get ${n} --full`,"Retry --dep-remove with the exact id plus any kind, source_kind, author, or created_at selectors needed to identify one stored row."]})}function tL(e,t,n){if(t.options.dep===void 0&&t.options.depRemove===void 0&&!t.clearItemMetadataKeys.has("dependencies"))return;let i=t.clearItemMetadataKeys.has("dependencies")?[]:[...e.metadata.dependencies??[]];if(t.dependencyUpdates.additions.length>0){i=ZO(i,t.dependencyUpdates.additions);let r=new Set(i.map(s=>ia(s)));for(let s of t.dependencyUpdates.additions){let a=ia(s);r.has(a)||(i.push(s),r.add(a))}}t.dependencyRemovals.length>0&&(eL(i,t.dependencyRemovals,e.metadata.id),i=i.filter(r=>!t.dependencyRemovals.some(s=>lv(r,s)))),i.length===0?delete e.metadata.dependencies:e.metadata.dependencies=i,n.push("dependencies")}function nL(e,t,n){Xc(e,"comments",t.options.comment,t.commentUpdates.values,t.clearItemMetadataKeys,n),Xc(e,"notes",t.options.note,t.noteUpdates.values,t.clearItemMetadataKeys,n),Xc(e,"learnings",t.options.learning,t.learningUpdates.values,t.clearItemMetadataKeys,n)}function Xc(e,t,n,i,r,s){n===void 0&&!r.has(t)||(r.has(t)||!i||i.length===0?delete e.metadata[t]:e.metadata[t]=[...e.metadata[t]??[],...i],s.push(t))}function iL(e,t,n){tv(e,"files",t.options.file,t.fileUpdates.values,gO,t.options.replaceFiles===!0,t.clearItemMetadataKeys,n),rL(e,t,n),tv(e,"docs",t.options.doc,t.docUpdates.values,hO,t.options.replaceDocs===!0,t.clearItemMetadataKeys,n)}function tv(e,t,n,i,r,s,a,o){if(!(n===void 0&&!a.has(t))){if(s)e.metadata[t]=i;else if(a.has(t)||!i||i.length===0)delete e.metadata[t];else{let c=[...e.metadata[t]??[]],d=new Set(c.map(l=>r(l)));for(let l of i){let u=r(l);d.has(u)||(c.push(l),d.add(u))}e.metadata[t]=c}o.push(t)}}function rL(e,t,n){t.options.test===void 0&&!t.clearItemMetadataKeys.has("tests")||(t.clearItemMetadataKeys.has("tests")&&t.options.replaceTests===!0?e.metadata.tests=nv(t.testUpdates.values)??[]:t.clearItemMetadataKeys.has("tests")||!t.testUpdates.values||t.testUpdates.values.length===0?delete e.metadata.tests:e.metadata.tests=nv([...e.metadata.tests??[],...t.testUpdates.values]),e.metadata.tests!==void 0&&e.metadata.tests.length===0&&delete e.metadata.tests,n.push("tests"))}function nv(e){if(!e||e.length===0)return;let t=[],n=new Set;for(let i of e){let r=yO(i);n.has(r)||(t.push(i),n.add(r))}return t}function sL(e,t,n){let i=t.options.addTags,r=t.options.removeTags,s=Array.isArray(i)&&i.length>0||Array.isArray(r)&&r.length>0;if(t.options.tags!==void 0||t.clearItemMetadataKeys.has("tags")||s){let a=t.clearItemMetadataKeys.has("tags")?[]:t.options.tags!==void 0?lr(t.options.tags):Array.isArray(e.metadata.tags)?[...e.metadata.tags]:[];e.metadata.tags=d_(mr(a,i),r),n.changedFields.push("tags")}Qc(SO,t.options,n),oL(e,t,n.changedFields)}function aL(e,t,n){let i=t.options.addAc,r=t.options.removeAc;if(!(Array.isArray(i)&&i.length>0)&&!(Array.isArray(r)&&r.length>0))return;let s=c_(ur(e.metadata.acceptance_criteria),i,r);if(s.unmatchedRemovals.length>0)throw new _(`Acceptance criteria removal did not match: ${s.unmatchedRemovals.join(", ")}`,m.NOT_FOUND,{code:"acceptance_criteria_remove_unmatched",reason:"exact_match_not_found",field:"acceptance_criteria",unmatched:s.unmatchedRemovals,why:"Lossless removal fails instead of silently applying the remaining mutations when an exact selector is wrong.",nextSteps:["Read the current acceptance_criteria value and retry with the exact criterion text.","Use --acceptance-criteria alone only when replacing the complete list is intentional."]});let a=s.criteria.join("; ");e.metadata.acceptance_criteria!==a&&(a===""&&e.metadata.acceptance_criteria===void 0||(e.metadata.acceptance_criteria=a,n.changedFields.includes("acceptance_criteria")||n.changedFields.push("acceptance_criteria")))}function oL(e,t,n){let i=t.options.order??t.options.rank;if(!(i===void 0&&!t.clearItemMetadataKeys.has("order"))){if(t.clearItemMetadataKeys.has("order"))delete e.metadata.order;else{let r=ye(i??"","order");if(!Number.isInteger(r))throw new _("Order must be an integer",m.USAGE);e.metadata.order=r}n.push("order")}}function cL(e,t,n,i){dL(e,t,n.changedFields),lL(e,t,n.changedFields),Qc(TO,t.options,n),iv(e,t,"sprint",i,n.changedFields),iv(e,t,"release",i,n.changedFields),uL(e,t,n.changedFields),Qc(AO,t.options,n)}function dL(e,t,n){if(!(t.options.assignee===void 0&&!t.clearItemMetadataKeys.has("assignee"))){if(t.clearItemMetadataKeys.has("assignee"))delete e.metadata.assignee;else{let i=t.options.assignee?.trim()??"";if(i==="")throw new _("--assignee must not be empty. Use --unset assignee to clear it.",m.USAGE);e.metadata.assignee=i}n.push("assignee")}}function lL(e,t,n){t.options.parent===void 0&&!t.clearItemMetadataKeys.has("parent")||(t.clearItemMetadataKeys.has("parent")?delete e.metadata.parent:e.metadata.parent=t.resolvedParentValue??"",n.push("parent"))}function iv(e,t,n,i,r){if(!(t.options[n]===void 0&&!t.clearItemMetadataKeys.has(n))){if(t.clearItemMetadataKeys.has(n))delete e.metadata[n];else{let s=vr(n,t.options[n]??"",t.settings.validation.sprint_release_format);e.metadata[n]=s.value,i.push(...s.warnings)}r.push(n)}}function uL(e,t,n){t.options.blockedBy===void 0&&!t.clearItemMetadataKeys.has("blocked_by")||(t.clearItemMetadataKeys.has("blocked_by")?delete e.metadata.blocked_by:e.metadata.blocked_by=t.options.blockedBy?.trim()??"",n.push("blocked_by"),(t.clearItemMetadataKeys.has("blocked_by")||t.resolvedBlockedByDependencyId!==void 0)&&fO(e.metadata,t.resolvedBlockedByDependencyId,t.nowIso,t.author,n))}function mL(e,t,n){(t.options.reminder!==void 0||t.clearItemMetadataKeys.has("reminders"))&&(t.clearItemMetadataKeys.has("reminders")?delete e.metadata.reminders:e.metadata.reminders=Ys(t.options.reminder??[],t.nowValue,{valueMode:"trimmed"}),n.push("reminders")),(t.options.event!==void 0||t.clearItemMetadataKeys.has("events"))&&(t.clearItemMetadataKeys.has("events")?delete e.metadata.events:e.metadata.events=Js(t.options.event??[],t.nowValue,{allDayEmptyGuard:"truthy",recurrenceEmptyNumericGuard:"truthy"}),n.push("events"))}function _L(e,t,n){rv(e,t.runtimeFieldRegistry.definitions.map(r=>r.metadata_key),t.clearItemMetadataKeys,n),rv(e,t.extensionFieldNames,t.clearItemMetadataKeys,n);for(let[r,s]of Object.entries(t.runtimeFieldUpdates)){if(t.clearItemMetadataKeys.has(r)){let a=r.replaceAll("_","-"),o=t.runtimeFieldRegistry.definitions.find(c=>c.metadata_key===r)?.cli_flag??a;throw new _(`Cannot combine --unset ${a} with --${o}`,m.USAGE)}Fe(e[r],s)||(e[r]=s,n.push(r))}let i=nr(t.options.field,t.extensionRegistrations,Gs);for(let r of Object.keys(i))if(t.clearItemMetadataKeys.has(r))throw new _(`Cannot combine --unset ${r.replaceAll("_","-")} with --field ${r}=...`,m.USAGE);for(let[r,s]of Object.entries(i))Fe(e[r],s)||(e[r]=s,n.push(r))}function rv(e,t,n,i){for(let r of t)!n.has(r)||e[r]===void 0||(delete e[r],i.push(r))}function pL(e,t){if(t===void 0)return;let n=e.metadata,i=["comments","notes","learnings"].find(r=>{let s=t[r];return s!==void 0&&(!Array.isArray(s)||!Fe(s,n[r]??[]))});if(i!==void 0)throw new _(`Full-item --stdin-json update changed persisted ${i}; no item fields were written.`,m.USAGE,{code:"stdin_json_persisted_annotation_changed",reason:`${i}_requires_annotation_command`,required:`Use pm ${i} ${e.metadata.id} --edit <index> --add <text> to correct an existing entry.`,why:"Full-item update appends new annotations but cannot replace or remove existing audit entries.",nextSteps:[`Inspect the current ${i} with pm ${i} ${e.metadata.id}.`,`Apply the correction with pm ${i} ${e.metadata.id} --edit <index> --add <text>.`]})}function fL(e,t){pL(e,t.options.documentAnnotationSnapshot);let n=structuredClone(e.metadata),i=e.body,r=[],s=[],a=zO(e,t.options,t.statusRegistry,r),o=e.metadata,c={metadataRecord:o,clearItemMetadataKeys:t.clearItemMetadataKeys,changedFields:r,nowValue:t.nowValue};JO(e,t,a,r),XO(e,t,r),tL(e,t,r),nL(e,t,r),iL(e,t,r),sL(e,t,c),aL(e,t,c),cL(e,t,c,s),(t.options.dep!==void 0||t.options.depRemove!==void 0||t.options.blockedBy!==void 0||t.clearItemMetadataKeys.has("dependencies")||t.clearItemMetadataKeys.has("blocked_by"))&&Ai(e.metadata.id,e.metadata.dependencies),me(e.metadata.status,t.statusRegistry)===t.statusRegistry.canceled_status&&e.metadata.assignee!==void 0&&(delete e.metadata.assignee,r.includes("assignee")||r.push("assignee")),mL(e,t,r),_L(o,t,r);try{ir(o,t.extensionRegistrations,{skipDefaultFields:t.clearItemMetadataKeys})}catch(u){throw new _(u instanceof Error?u.message:"Invalid extension item field values",m.USAGE)}let d=e.metadata,l=[...new Set(r)].filter(u=>u==="body"?e.body!==i:!Fe(n[u],d[u]));return t.options.acceptanceCriteria!==void 0&&l.includes("acceptance_criteria")&&s.push(`acceptance_criteria_replaced:${ur(n.acceptance_criteria).length}:${ur(d.acceptance_criteria).length}`),{changedFields:l,warnings:s}}async function mv(e,t,n,i={}){t=await CO(t);let r=x(process.cwd(),n.path);await $(r);let s=await I(r),a=K(s.schema),o=nn(s.schema),c=P(),d=Et(c),l=F(s,c),u=s.governance.workflow_enforcement??"off",p=u==="off"?[]:br(s.schema),g=[{strict_error:"strict_error",warn:"warn",off:"off"},{strict_error:"warn",warn:"warn",off:"off"}][+(t.allowMissingParent===!0)][s.validation.parent_reference],f=av(t.unset,o,d),h=new Set(f.optionKeys),y=new Set(f.metadataKeys);RO(t),OO({definitions:xO(t),options:t,clearOptionKeys:h,clearItemMetadataKeys:y}),sO(e,t,y),DO(t,f),NO(t);let v=U(t.author,s.author_default),w=new Date,k=w.toISOString(),S=lO(t.dep,s.id_prefix,k,v);Ai(e,S.additions);let T=await Vs({pmRoot:r,dependencies:S.additions,idPrefix:s.id_prefix,itemFormat:s.item_format,typeToFolder:l.type_to_folder,allowUnresolved:t.allowUnresolvedDeps,holders:[{id:e}],schema:s.schema}),C=uO(t.depRemove,s.id_prefix),b=Jt("--comment",t.comment,k,v),E=t.ownershipMetadataBypass===!0&&b.values?{...b,values:b.values.map(D=>({...D,author:v}))}:b,N=Jt("--note",t.note,k,v),A=Jt("--learning",t.learning,k,v),R=Bc(t.file),G=Hc(t.test);G.values=await En(G.values,v,k);let pe=Vc(t.doc),ce=[],de=await jO({id:e,options:t,unsetTargets:f,pmRoot:r,settings:s,typeRegistry:l,parentReferencePolicy:g}),ue=await pO(t.blockedBy,y.has("blocked_by"),r,s.id_prefix,s.item_format,l.type_to_folder),en=ue.id,Nn=[...de.warnings,...GO(ue)],it=su(t,o,t.runtimeFieldCommands),Ne=MO(t,it);if(!Object.values(Ne).some(Boolean))return PO({pmRoot:r,id:e,settings:s,typeRegistry:l});ce.push(...await qO({options:t,fieldFlags:Ne,workflowEnforcement:u,typeWorkflows:p,statusRegistry:a,typeRegistry:l,pmRoot:r,id:e,settings:s}));let ht=await KO({options:t,fieldFlags:Ne,statusRegistry:a,workflowTransitionWarnings:ce,global:n,id:e});if(ht)return ht;UO(t);let Ee=ae(),Me=Ne.parent&&!y.has("parent")||S.additions.some(D=>Ss(D.kind,Ee)),yt=await Ps({pmRoot:r,author:v,ttlSeconds:s.locks.ttl_seconds,waitMs:s.locks.wait_ms,required:Me});try{let D=await FO({fieldFlags:Ne,clearedMetadataKeys:y,pmRoot:r,settings:s,typeToFolder:l.type_to_folder}),rt,vt,V=await or({pmRoot:r,settings:s,typeToFolder:l.type_to_folder,id:e,op:gL(t,i),author:v,message:t.message,resolveHistoryContext:()=>vt,force:t.force,bypassAssigneeConflict:t.ownershipMetadataBypass===!0||t.ownershipDependencyBypass===!0,extensionFieldNames:d,skipNoop:!0,mutate(Ye){rt=hL({document:Ye,recurrenceReason:i.recurrenceReason,requestedStatus:t.status,statusRegistry:a}),vt=rt?{recurrence:rt}:void 0,D=D?.map($i=>$i.id===Ye.metadata.id?structuredClone(Ye.metadata):$i);let Sa=fL(Ye,{options:t,settings:s,typeRegistry:l,statusRegistry:a,runtimeFieldRegistry:o,extensionRegistrations:c,extensionFieldNames:d,clearItemMetadataKeys:y,dependencyUpdates:S,dependencyRemovals:C,commentUpdates:E,noteUpdates:N,learningUpdates:A,fileUpdates:R,testUpdates:G,docUpdates:pe,resolvedParentValue:de.resolvedParentValue,resolvedBlockedByDependencyId:en,runtimeFieldUpdates:it,nowValue:w,nowIso:k,author:v,pmRoot:r});return $O({before:D,document:Ye,statusRegistry:a}),Sa}});await yt();let Ea=D?Es(D,D.map(Ye=>Ye.id===V.item.id?V.item:Ye),V.item.id):[];return{item:V.item,changed_fields:V.changedFields,warnings:[...ce,...Nn,...T,...Ea,...V.warnings],...rt===void 0?{}:{lifecycle_transition:rt}}}finally{await yt()}}function gL(e,t){return e.ownershipMetadataBypass===!0||e.ownershipDependencyBypass===!0?"update_ownership_bypass":t.recurrenceReason===void 0?"update":"reopen"}function hL(e){if(e.recurrenceReason===void 0)return;let t=me(e.document.metadata.status,e.statusRegistry)??e.document.metadata.status;if(!_e(t,e.statusRegistry))throw new _(`Item ${e.document.metadata.id} is already active with status ${t}; recurrence transitions require a terminal item.`,m.CONFLICT,{code:"item_already_active",reason:"recurrence_requires_terminal_item",required:"Use item reopen only for a terminal item whose work has recurred.",why:"Appending a recurrence event to active work would corrupt lifecycle history.",recovery:{suggested_retry:`pm get ${e.document.metadata.id} --full`,suggested_retry_args:["get",e.document.metadata.id,"--full"]},nextSteps:[`Inspect the active item with: pm get ${e.document.metadata.id} --full`,`Continue the existing work with: pm update ${e.document.metadata.id} ...`]});let n=e.requestedStatus??e.statusRegistry.open_status,i=me(n,e.statusRegistry)??n,r=e.document.metadata,s=Object.fromEntries(["close_reason","resolution","expected_result","actual_result","fixed_version"].flatMap(a=>{let o=r[a];return typeof o=="string"?[[a,o]]:[]}));return{reason:e.recurrenceReason,from_status:t,to_status:i,previous_terminal:s}}async function ra(e,t,n){return mv(e,t,n)}async function C2(e,t,n,i){let r=await mv(e,t,n,{recurrenceReason:i});if(r.lifecycle_transition===void 0)throw new _(`Item ${e} did not produce the required recurrence receipt.`,m.GENERIC_FAILURE,{code:"reopen_receipt_missing",reason:"recurrence_transition_not_recorded",required:"A successful reopen must return the terminal-to-active lifecycle transition recorded in immutable history."});return{...r,lifecycle_transition:r.lifecycle_transition}}(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]="56177893-3ccb-5b3f-aa82-9365c26c5d34")}catch{}})();async function _v(e,t,n){return[...await Promise.resolve().then(()=>ct(at(e,t),t)).catch(()=>[])].reverse().find(i=>i.patch.some(r=>r.path==="/metadata/assignee"))?.op==="claim"?`claimed by ${n}`:`assigned to ${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]="e32c9f13-2e6a-5ac6-a1ce-9c839121441a")}catch{}})();function sa(e,t){if(e.handoff===void 0)return;if(e.pause===!0)throw new _("--handoff cannot be combined with --pause. Choose a handoff queue or pause the item.",m.USAGE);let n=typeof e.handoff=="string"?Ke(e.handoff,t):void 0;if(n===void 0||Nt(n,t)||n===t.in_progress_status)throw new _("--handoff must name a configured non-terminal status distinct from the in-progress status. Inspect pm schema statuses or add a project queue with pm schema add-status <queue> --role active.",m.USAGE);if(typeof e.message!="string"||e.message.trim().length===0)throw new _("--handoff requires --message with implementation evidence and the next verification step.",m.USAGE);return n}function pv(e,t,n,i,r){if(Nt(e.status,i)||!e.assignee?.trim())throw new _("Handoff requires a claimed, non-terminal item. Claim the active work before handing it off; use pm item reopen for completed work.",m.CONFLICT);let s=n.governance.workflow_enforcement??"off",a=ta({enforcement:s,typeWorkflows:s==="off"?[]:br(n.schema),statusRegistry:i,typeName:e.type,fromStatus:e.status,toStatus:t}),o={from_status:e.status,to_status:t,message:r},c=e.status===t?[]:["status"];return e.status=t,{receipt:o,warnings:a?[a]:[],changedFields:c}}(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]="ca9fb199-0de6-5eea-bed8-7afac49123bc")}catch{}})();var fv="no_available_next_item";function yL(e){if(!(e instanceof Error)||e.name!=="PmCliError")return!1;let t=e.context;return typeof t=="object"&&t!==null&&"code"in t&&t.code==="already_claimed_by"}async function ed(e,t,n,i={}){let r=x(process.cwd(),n.path);await $(r);let s=await I(r),a=K(s.schema),o=U(i.author,s.author_default),c=Ka(o),d=null,l=!1,u=[],p=await se({pmRoot:r,settings:s,id:e,op:"claim",author:o,message:i.message,force:t,skipNoop:!0,async mutate(g){let f=g.metadata.assignee??"",h=g.metadata.claim_principal?.trim()||f;if(d=f.trim().length>0?f:null,Nt(g.metadata.status,a)&&!t)throw new _(`Cannot claim terminal item ${g.metadata.id} without --force`,m.CONFLICT);if(d!==null&&h!==c){if(i.ifAvailable===!0)return l=!0,u.push(`claim_skipped_held_by:${d}`),{changedFields:[]};if(!t){let w=await _v(r,g.metadata.id,f);throw new _(`Item ${g.metadata.id} is already ${w}. Use --force to take over, or --if-available to skip without failing.`,m.CONFLICT,{code:"already_claimed_by",why:"Claim is an atomic test-and-set so parallel agents never proceed believing they own the same item.",nextSteps:["Run pm next to pick a different unclaimed item.","Re-run with --if-available to treat a held item as a no-op skip.","Re-run with --force only when taking over the item is coordinated."]})}u.push(`claim_takeover:${d}->${o}`)}let y={assignee:o,claim_principal:c},v=["assignee","claim_principal"].filter(w=>g.metadata[w]!==y[w]);return Object.assign(g.metadata,y),{changedFields:v,warnings:u}}});return l||await pp({pmRoot:r,settings:s,principal:c,itemId:p.item.id}),{item:p.item,changed_fields:p.changedFields,claimed_by:l&&d!==null?d:o,previous_assignee:d,forced:t,...l?{skipped:!0}:{},...u.length>0?{warnings:u}:{}}}async function B2(e,t,n={},i={}){let r=vL(n.maxAttempts),s=await I(x(process.cwd(),t.path)),a={...n,author:U(n.author,s.author_default)},o=await gp({...i,callerAuthor:a.author,limit:String(r)},t),c=[o.recommended,...o.ready].filter(d=>d!==null).map(d=>({...d,reasons:"reasons"in d?d.reasons:["ranked ready candidate"]}));return wL(c.slice(0,r),e,t,a)}function vL(e){if(e===void 0)return 10;let t=Number(e);if(!Number.isSafeInteger(t)||t<1||t>100)throw new _("--max-attempts must be an integer from 1 to 100",m.USAGE);return t}async function wL(e,t,n,i={},r=ed){let s=0;for(let o of e){s+=1;try{let c=await r(o.id,t,n,i),d={...c,recommendation:o,attempts:s,available:!0};if(!c.skipped)return d}catch(c){if(!yL(c))throw c}}if(i.ifAvailable===!0)return{available:!1,item:null,claimed_by:U(i.author,""),previous_assignee:null,forced:t,skipped:!0,recommendation:null,attempts:s,warnings:[fv]};let a=s===0;throw new _(a?"No actionable items matched the selection filters":"No actionable item remained available to claim",a?m.NOT_FOUND:m.CONFLICT,{code:fv,why:a?"No ready items matched the specified filters or selection criteria.":"Every ranked candidate was claimed by another agent before this atomic selection completed.",nextSteps:[a?"Verify the filters or run pm next to inspect all ready work.":"Run pm claim --next again to refresh the ranked candidate set."]})}async function td(e,t,n,i={}){let r=x(process.cwd(),n.path);await $(r);let s=await I(r),a=U(i.author,s.author_default),o=Ka(a),c=i.ownershipReleaseBypass===!0,d=null,l=K(s.schema),u=sa(i,l);if(u!==void 0&&c)throw new _("Ownership-release bypass only clears ownership; it cannot change a handoff status.",m.USAGE);let p,g;try{g=await se({pmRoot:r,settings:s,id:e,op:"release",author:a,message:i.message,force:t,bypassAssigneeConflict:c,mutate(h){d=h.metadata.assignee??null;let y=u===void 0?void 0:pv(h.metadata,u,s,l,i.message);return p=y?.receipt,!d&&!h.metadata.claim_principal?{changedFields:[]}:(delete h.metadata.assignee,delete h.metadata.claim_principal,{changedFields:["assignee","claim_principal",...y?.changedFields??[]],warnings:y?.warnings})}})}catch(h){ri(h,{required:"For approved non-owner handoffs, prefer the ownership-release bypass before considering --force.",examples:['pm release pm-a1b2 --author "reviewer" --force'],nextSteps:["Use the package-provided ownership-release bypass for handoffs that only clear assignee metadata.","Use --force only when an explicit override is approved for broader ownership conflicts."]})}await fp({pmRoot:r,principal:o,itemId:g.item.id});let f=qa(g.item.status,l)===qa(l.in_progress_status,l);return{item:g.item,released_by:a,changed_fields:g.changedFields,previous_assignee:d,forced:t,...p===void 0?{}:{handoff:p},...g.warnings.length>0||f?{warnings:[...g.warnings,...f?["released_unclaimed_in_progress"]:[]]}:{},...f?{suggestions:[`${g.item.id} remains ${g.item.status} and unclaimed. If work is paused, run pm release ${g.item.id} --pause to move it to ${l.open_status}.`]}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="23f3ce6b-d536-5df2-92b1-ec756d53aa02")}catch{}})();async function nd(e,t,n){try{return await n()}catch(i){let r=i instanceof _?i.context:{},s=new _(i instanceof Error?i.message:String(i),i instanceof _?i.exitCode:m.GENERIC_FAILURE,{...r,item_id:e,why:`${t} completed for ${e} before the following step failed. No rollback was performed.${r.why?` ${r.why}`:""}`,nextSteps:[`Inspect the persisted state with pm get ${e} and pm history ${e} before retrying the failed step.`,...r.nextSteps??[]]});throw s.cause=i,s}}async function sB(e,t,n){if(t.next===!0||t.ifAvailable===!0)throw new _("--start cannot be combined with --next or --if-available for an explicit item",m.USAGE,{code:"invalid_argument_value",required:"Remove --next and --if-available when starting an explicit item.",nextSteps:["Remove --next and --if-available, keep the explicit item ID and other supplied arguments, then retry."]});let i=await I(x(process.cwd(),n.path)),r=Xy(K(i.schema)),s=await ed(e,t.force===!0,n,t),a=s.item.id,o=await nd(a,"claim",()=>ra(a,Oo(t,{status:r},["assignee","start","next","ifAvailable","maxAttempts"]),n));return{id:a,action:"start_task",claim:s,update:o}}async function aB(e,t,n){let i=await I(x(process.cwd(),n.path)),r=K(i.schema);sa({...t,pause:!0},r);let s=r.open_status,a=await ra(e,Oo(t,{status:s},["assignee","pause"]),n),o=a.item.id,c=await nd(o,"update",()=>td(o,t.force===!0,n,t));return{id:o,action:"pause_task",update:a,release:c}}async function oB(e,t,n,i){let r=await ks(e,t,n,i),s=r.item.id,a=await nd(s,"close",()=>td(s,n.force===!0,i,n));return{id:s,action:"close_task",close:r,release: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]="62b04ebf-f842-5a88-8817-ed9b17350034")}catch{}})();import Ci from"node:crypto";import{cp as gv,lstat as bL,mkdir as Xt,readFile as Cn,readdir as rd,rename as vv,rm as ad,writeFile as aa}from"node:fs/promises";import j 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]="3b4a5521-a665-5f60-8d01-16033b078916")}catch{}})();var wv="https://schema.unbrained.dev/pm/workspace-snapshot/v1",EB=["create","list","inspect","restore","delete"],bv=j.join("runtime","workspace-snapshots"),kL=new Set(["checkpoints","locks","runtime","search","transactions"]),EL=/^[a-z0-9][a-z0-9._-]*$/,Ii="sdk-workspace-transaction",id={capacity:{code:"workspace_snapshot_storage_exhausted"},permission:{code:"workspace_snapshot_permission_denied"},resource:{code:"workspace_snapshot_resource_exhausted"}},kv={renameEntry:vv,removeEntry:async e=>{await ad(e,{recursive:!0,force:!0})}},sd=class{lockPath;owner;intervalMs;timer;refresh;failure;constructor(t,n,i){this.lockPath=t,this.owner=n,this.intervalMs=Math.max(10,Math.floor(i*1e3/3))}start(){this.scheduleRenewal(),this.timer=setInterval(()=>{this.scheduleRenewal()},this.intervalMs),this.timer.unref()}async refreshNow(){this.scheduleRenewal(),await this.refresh,this.assertHealthy()}assertHealthy(){if(this.failure!==void 0)throw new Error("Workspace snapshot restore lost its writer lock",{cause:this.failure})}async stop(){this.timer!==void 0&&clearInterval(this.timer),await this.refresh,this.assertHealthy()}scheduleRenewal(){this.refresh!==void 0||this.failure!==void 0||(this.refresh=this.renew().catch(t=>{this.failure=t}).finally(()=>{this.refresh=void 0}))}async renew(){let t=JSON.parse(await Cn(this.lockPath,"utf8"));if(typeof t!="object"||t===null||Array.isArray(t))throw new Error("Workspace writer lock has invalid structure");let n=t;if(n.id!==Ii||n.owner!==this.owner||n.pid!==process.pid)throw new Error("Workspace writer lock ownership changed");await Oe(this.lockPath,`${JSON.stringify({...n,created_at:new Date().toISOString()},null,2)}
|
|
12
|
+
`)}};async function Ev(e,t=""){let n=await rd(j.join(e,t),{withFileTypes:!0}),i=[];for(let r of n.sort((s,a)=>s.name.localeCompare(a.name))){if(t.length===0&&kL.has(r.name))continue;let s=j.posix.join(t.replaceAll(j.sep,"/"),r.name);if(r.isSymbolicLink())throw new Error(`Workspace snapshots reject symbolic links: ${s}`);if(r.isDirectory())i.push(...await Ev(e,s));else if(r.isFile())i.push(s);else throw new Error(`Workspace snapshots reject unsupported filesystem entries: ${s}`)}return i}async function Sv(e){let t=await Ev(e),n=Ci.createHash("sha256"),i=[],r=0;for(let a of t){let o=await Cn(j.join(e,a));i.push(o),r+=o.byteLength,n.update(a),n.update("\0"),n.update(String(o.byteLength)),n.update("\0"),n.update(o)}let s=n.digest("hex");return{manifest:{schema:wv,fingerprint:s,files:t,bytes:r},contents:i}}function hv(e){return e===void 0||e.byteLength===0?0:e.toString("utf8").split(`
|
|
13
|
+
`).filter(t=>t.trim().length>0).length}async function SL(e,t){let n=new Map;for(let i=0;i<t.length;i+=32){let r=t.slice(i,i+32),s=await Promise.all(r.map(async a=>[a,await Cn(j.join(e,a))]));for(let[a,o]of s)n.set(a,o)}return n}function od(e){if(!EL.test(e))throw new _("Snapshot names and fingerprints must use lowercase letters, digits, dots, underscores, or hyphens",m.USAGE,{code:"invalid_workspace_snapshot_target",required:"Provide a non-empty lowercase snapshot name or 64-character hexadecimal fingerprint.",why:"Snapshot targets are used as portable reference filenames and content identities.",examples:["pm workspace snapshot list --json","pm workspace snapshot inspect baseline --json"],nextSteps:["List available snapshots, then retry with a returned name or fingerprint."],recovery:{suggested_retry:"pm workspace snapshot list --json"}})}async function Tv(e,t){return Fn(`workspace_snapshot_${e}`,t,{codes:{capacity:id.capacity.code,permission:id.permission.code,resource:id.resource.code},why:"Snapshot create and restore copy authoritative tracker state before activation, so the stage needs capacity and write access up front.",nextSteps:["Reclaim rebuildable tracker cache space with pm gc, then retry."],suggestedRetry:"pm gc --json"})}function Qt(e){return j.join(e,bv)}function Av(e){return new _(`Unknown workspace snapshot: ${e}`,m.NOT_FOUND,{code:"workspace_snapshot_not_found",required:"Use a snapshot name or fingerprint returned by snapshot list.",why:"The requested reference or immutable snapshot object does not exist.",examples:["pm workspace snapshot list --json"],nextSteps:["List available snapshots and retry with an exact target."],recovery:{suggested_retry:"pm workspace snapshot list --json"}})}async function Iv(e,t){try{return JSON.parse(await Cn(e,"utf8"))}catch(n){throw q(n)?Av(t):n}}async function yv(e,t,n){try{await ad(e,{recursive:n})}catch(i){throw q(i)?Av(t):i}}async function TL(e,t,n=kv){try{return await n.renameEntry(e,t),!1}catch(i){if(!(i instanceof Error&&"code"in i&&(i.code==="EEXIST"||i.code==="ENOTEMPTY")))throw i;return await n.removeEntry(e),!0}}async function AL(e,t,n,i,r){await i.renameEntry(t,n);try{await i.renameEntry(e,t),await r?.()}catch(s){throw await i.renameEntry(n,t),await i.removeEntry(e),s}await i.removeEntry(n)}async function IL(e,t){return od(t),/^[a-f0-9]{64}$/.test(t)?t:(await Iv(j.join(Qt(e),"refs",`${t}.json`),t)).fingerprint}async function CL(e,t={}){if(t.name!==void 0&&(od(t.name),/^[a-f0-9]{64}$/.test(t.name)))throw new _("Snapshot names must not be 64-character lowercase hexadecimal fingerprints",m.USAGE,{code:"workspace_snapshot_name_reserved_fingerprint",required:"Choose a human-readable reference name that cannot be mistaken for a content fingerprint.",why:"Exact 64-character hexadecimal values address immutable objects.",examples:["pm workspace snapshot create baseline --json"],nextSteps:["Retry with a shorter descriptive snapshot name."]});let{manifest:n,contents:i}=await Sv(e),r=Qt(e),s=j.join(r,"objects",n.fingerprint),a=!1;try{a=(await bL(s)).isDirectory()}catch(o){if(!(o instanceof Error&&"code"in o&&q(o)))throw o}if(!a){let o=j.join(r,"objects",`.create-${process.pid}-${Ci.randomUUID()}`);await Tv("create_object",async()=>{await Xt(j.join(o,"files"),{recursive:!0});for(let[c,d]of n.files.entries()){let l=j.join(o,"files",d);await Xt(j.dirname(l),{recursive:!0}),await aa(l,i[c])}await aa(j.join(o,"manifest.json"),`${JSON.stringify(n,null,2)}
|
|
14
|
+
`,"utf8"),await Xt(j.dirname(s),{recursive:!0})}),a=await TL(o,s)}if(t.name!==void 0){let o={name:t.name,fingerprint:n.fingerprint},c=j.join(r,"refs");await Xt(c,{recursive:!0});let d=j.join(c,`.ref-${process.pid}-${Ci.randomUUID()}`);await aa(d,`${JSON.stringify(o,null,2)}
|
|
15
|
+
`,"utf8"),await vv(d,j.join(c,`${t.name}.json`))}return{manifest:n,...t.name===void 0?{}:{name:t.name},deduplicated:a}}async function cd(e,t){let n=await IL(e,t),i=await Iv(j.join(Qt(e),"objects",n,"manifest.json"),t);if(i.schema!==wv||i.fingerprint!==n)throw new _(`Snapshot manifest identity mismatch: ${t}`,m.CONFLICT,{code:"workspace_snapshot_manifest_mismatch",required:"Use an intact snapshot whose manifest fingerprint matches its object path.",why:"Content identity must be verified before snapshot data is trusted.",examples:["pm workspace snapshot list --json"],nextSteps:["Inspect or recreate the snapshot before restoring it."]});return i}async function xL(e){let t=Qt(e),n=await rd(j.join(t,"objects")).catch(r=>{if(r instanceof Error&&"code"in r&&q(r))return[];throw r}),i=await rd(j.join(t,"refs")).catch(r=>{if(r instanceof Error&&"code"in r&&q(r))return[];throw r});return{objects:await Promise.all(n.filter(r=>/^[a-f0-9]{64}$/.test(r)).sort().map(r=>cd(e,r))),references:await Promise.all(i.filter(r=>r.endsWith(".json")).sort().map(async r=>JSON.parse(await Cn(j.join(t,"refs",r),"utf8"))))}}async function RL(e,t){let n=await cd(e,t),{manifest:i,contents:r}=await Sv(e),s=new Map(i.files.map((u,p)=>[u,r[p]])),a=await SL(j.join(Qt(e),"objects",n.fingerprint,"files"),n.files),o=new Set(i.files),c=new Set(n.files),d=new Set([...o,...c]);for(let u of d){let p=s.get(u),g=a.get(u);p!==void 0&&g!==void 0&&p.equals(g)&&d.delete(u)}let l=i.files.filter(u=>u.startsWith("history/")&&u.endsWith(".jsonl")).map(u=>{let p=hv(s.get(u)),g=hv(a.get(u));return{path:u,current_entries:p,target_entries:g,removed_entries:Math.max(0,p-g)}}).filter(u=>u.removed_entries>0).sort((u,p)=>u.path.localeCompare(p.path));return{target_fingerprint:n.fingerprint,current_fingerprint:i.fingerprint,changed_file_count:d.size,removed_file_count:[...o].filter(u=>!c.has(u)).length,added_file_count:[...c].filter(u=>!o.has(u)).length,removed_item_count:[...o].filter(u=>u.endsWith(".toon")&&!c.has(u)).length,affected_history_stream_count:l.length,removed_history_entry_count:l.reduce((u,p)=>u+p.removed_entries,0),affected_history_streams:l,changes_authoritative_state:i.fingerprint!==n.fingerprint}}async function OL(e,t,n={}){if(n.force!==!0)throw new _("Workspace snapshot restore requires explicit force confirmation; inspect the impact with planWorkspaceSnapshotRestore or pm workspace snapshot restore <target> --dry-run, then retry with force",m.USAGE,{code:"workspace_snapshot_force_required",required:"Preview the destructive impact, then explicitly confirm the restore.",why:"A restore replaces the complete authoritative tracker state.",examples:[`pm workspace snapshot restore ${t} --dry-run --json`,`pm workspace snapshot restore ${t} --force --json`],nextSteps:["Review the dry-run counts before retrying with --force."],recovery:{suggested_retry:`pm workspace snapshot restore ${t} --dry-run --json`}});let i=n.author?.trim()||"pm-sdk",r=n.lockTtlSeconds??60,s=n.lockWaitMs??5e3,a=await bt(e,Ii,r,i,!1,!1,s),o=new sd(Hi(e,Ii),i,r);o.start(),await o.refreshNow();let c,d=!1,l=!1;try{let u=await RL(e,t),p=await cd(e,t),g=await CL(e),f=p.fingerprint,h=Qt(e),y=j.join(h,"objects",f,"files"),v=j.dirname(e),w=j.basename(e);c=j.join(v,`.${w}.restore-${Ci.randomUUID()}`);let k=j.join(v,`.${w}.backup-${Ci.randomUUID()}`);await Tv("restore_stage",async()=>{await Xt(c,{recursive:!0}),await gv(y,c,{recursive:!0,force:!1}),await Xt(j.join(c,"runtime"),{recursive:!0}),await gv(h,j.join(c,bv),{recursive:!0,force:!1})});let S=await sn({pmRoot:c,op:"workspace_snapshot_restore",author:i,message:n.message??`Restore workspace snapshot ${f}; recovery snapshot ${g.manifest.fingerprint}`,context:{target_fingerprint:f,pre_restore_fingerprint:g.manifest.fingerprint,changed_file_count:u.changed_file_count,removed_file_count:u.removed_file_count,removed_item_count:u.removed_item_count,affected_history_stream_count:u.affected_history_stream_count,removed_history_entry_count:u.removed_history_entry_count},lockTtlSeconds:r,lockWaitMs:s}),T=j.relative(c,S.historyPath).replaceAll("\\","/");await o.stop(),l=!0;let C=Hi(c,Ii);return await Xt(j.dirname(C),{recursive:!0}),await aa(C,await Cn(Hi(e,Ii)),{flag:"wx"}),d=!0,await AL(c,e,k,kv,async()=>{o.start(),l=!1,await o.refreshNow()}),await o.stop(),l=!0,{manifest:p,plan:u,recovery_fingerprint:g.manifest.fingerprint,audit_history_path:T,audit_operation:"workspace_snapshot_restore"}}catch(u){throw c!==void 0&&!d&&await Promise.allSettled([ad(c,{recursive:!0,force:!0})]),u}finally{try{l||await o.stop()}catch{}finally{await a()}}}async function SB(e,t){return(await OL(e,t,{force:!0,message:"Restore requested through the compatibility SDK signature"})).manifest}async function TB(e,t){od(t);let n=Qt(e);if(!/^[a-f0-9]{64}$/.test(t))return await yv(j.join(n,"refs",`${t}.json`),t,!1),{deleted:"reference",target:t};let{references:i}=await xL(e);if(i.some(r=>r.fingerprint===t))throw new Error(`Snapshot object ${t} is still referenced`);return await yv(j.join(n,"objects",t),t,!0),{deleted:"object",target: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]="42dc4379-016c-5b5d-a15b-37fe3a80dab5")}catch{}})();function Cv(e){return e.invalidEvidenceCount>0?"merge_evidence_invalid":e.historyEvidenceValid?e.pendingDecisionCount>0||e.losslessCount>0?"merge_reconciliation_required":e.driftedItemCount>0?"history_repair_required":e.fence.status!=="ok"||e.drivers===null||e.drivers.status!=="ok"?"merge_fence_unprepared":"ready":"history_evidence_invalid"}function xv(e,t,n=process.platform){let i=["--pm-path",t];return e==="merge_evidence_invalid"?fe([...i,"merge","report"],n):e==="history_evidence_invalid"?fe([...i,"validate","--check-history-drift","--full"],n):e==="merge_reconciliation_required"?fe([...i,"merge","reconcile"],n):e==="history_repair_required"?fe([...i,"history-repair","--all"],n):e==="merge_fence_unprepared"?fe([...i,"merge","install"],n):null}function Rv(e){let t=Array.isArray(e.drifted_items)?e.drifted_items.filter(n=>typeof n=="string"):[];return{evidence_valid:Array.isArray(e.drifted_items)&&e.drifted_items.every(n=>typeof n=="string")&&typeof e.drifted_items_count=="number"&&Number.isInteger(e.drifted_items_count)&&e.drifted_items_count>=0&&typeof e.drifted_items_truncated=="boolean"&&typeof e.counts=="object"&&e.counts!==null&&!Array.isArray(e.counts),drifted_item_count:typeof e.drifted_items_count=="number"?e.drifted_items_count:t.length,drifted_item_ids:t,drifted_item_ids_truncated:e.drifted_items_truncated===!0,counts:typeof e.counts=="object"&&e.counts!==null?e.counts:{}}}async function $B(e){let t=x(process.cwd(),e.path);await $(t);let n=await I(t),i=F(n,P()),r=[],s=await ms({includeBody:!0,pmRoot:t,settings:n,typeToFolder:i.type_to_folder,warnings:r}),a=await Tt(t),[o,c,d,l]=await Promise.all([ln(t,dn(n)),a===null?Promise.resolve(null):un(a),mn(a??t,{includeLossless:!0,pmRoot:t}),_s(t,s,!1)]),{pendingDecisions:u,lossless:p}=_n(d.receipts),g=[...new Set(u.map(v=>v.item_id))].sort((v,w)=>v.localeCompare(w)),f=l.check.details,h=Rv(f),y=Cv({invalidEvidenceCount:d.invalid_evidence_count,pendingDecisionCount:u.length,losslessCount:p.length,historyEvidenceValid:h.evidence_valid,driftedItemCount:h.drifted_item_count,fence:o,drivers:c});return{ok:y==="ready",state:y,merge_fence:{committed:o,clone_local_drivers:c},merge_receipts:{pending_decision_count:u.length,pending_item_ids:g.slice(0,25),pending_item_ids_truncated:g.length>25,lossless_count:p.length,invalid_evidence_count:d.invalid_evidence_count},history_drift:h,next_action:{command:xv(y,t),reason:y},warnings:[...new Set(r)].sort((v,w)=>v.localeCompare(w)),generated_at:O()}}function UB(e){let t=e.next_action.command??"none";return[`workspace_position: ${e.state}`,`merge_fence: ${e.merge_fence.committed.status}`,`clone_local_drivers: ${e.merge_fence.clone_local_drivers?.status??"unavailable"}`,`pending_merge_decisions: ${e.merge_receipts.pending_decision_count}`,`history_drifted_items: ${e.history_drift.drifted_item_count}`,`next_action: ${t}`].join(`
|
|
16
|
+
`)}var jB={commandForWorkspacePositionState:xv,normalizeWorkspaceHistoryDrift:Rv,selectWorkspacePositionState:Cv};import{createHash as DL}from"node:crypto";import{execFile as NL}from"node:child_process";import Dv from"node:path";import{promisify as ML}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]="ed03b6c8-6275-55a6-8e5f-4f27a23d6696")}catch{}})();var Ov=1;function LL(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.id=="string"&&typeof t.metric=="string"&&typeof t.value=="number"&&Number.isFinite(t.value)&&["higher","lower","target"].includes(String(t.direction))&&typeof t.observed_at=="string"&&typeof t.revision=="string"&&["caller","git","unversioned"].includes(String(t.revision_source))&&typeof t.author=="string"?t.direction!=="target"||typeof t.threshold=="number"&&Number.isFinite(t.threshold):!1}function dd(e){if(e===null)return{format_version:Ov,observations:[]};let t;try{t=JSON.parse(e)}catch{throw new _("Improvement ledger contains invalid JSON.",m.GENERIC_FAILURE,{code:"invalid_improvement_ledger"})}if(typeof t!="object"||t===null||Array.isArray(t)||t.format_version!==Ov||!Array.isArray(t.observations))throw new _("Improvement ledger has an unsupported shape or format version.",m.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});let n=t.observations;for(let i of n)if(!LL(i))throw new _("Improvement ledger contains an invalid observation.",m.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});return 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]="e7ad59ce-5111-5649-9025-340183539b4a")}catch{}})();var PL=ML(NL),FL=50,Lv=1e3,$L=/^[a-z0-9](?:[a-z0-9._/-]{0,126}[a-z0-9])?$/u;function Nv(e){let t=e.trim().toLowerCase();if(!$L.test(t))throw new _(`Invalid metric name "${e}"; use 1-128 lowercase letters, digits, dots, slashes, underscores, or hyphens.`,m.USAGE,{code:"invalid_improvement_metric"});return t}function UL(e){let t=e??"lower";if(!["higher","lower","target"].includes(t))throw new _("Improvement direction must be higher, lower, or target.",m.USAGE,{code:"invalid_improvement_observation"});return t}function xi(e,t){let n=e?.trim();if(n){if(n.length>256)throw new _(`${t} must not exceed 256 characters.`,m.USAGE,{code:"invalid_improvement_observation"});return n}}function jL(e){let t=e??FL;if(!Number.isSafeInteger(t)||t<0||t>Lv)throw new _(`Improvement observation limit must be an integer from 0 to ${Lv}.`,m.USAGE,{code:"invalid_improvement_observation_limit"});return t}function Mv(e,t){let n=Date.parse(e);if(!Number.isFinite(n))throw new _(`${t} must be an ISO timestamp.`,m.USAGE,{code:"invalid_improvement_observation_timestamp"});return new Date(n).toISOString()}async function GL(e,t,n){if(!Number.isFinite(n.value))throw new _("Improvement observation value must be finite.",m.USAGE,{code:"invalid_improvement_observation"});let i=Nv(n.metric),r=UL(n.direction);if(n.threshold!==void 0&&!Number.isFinite(n.threshold)||r==="target"&&n.threshold===void 0)throw new _("Target-directed observations require a finite threshold.",m.USAGE,{code:"invalid_improvement_observation"});let s=await KL(e,n.revision),a=xi(n.source,"source"),o=xi(n.itemId,"itemId"),c=xi(n.unit,"unit"),d=xi(n.idempotencyKey,"idempotencyKey")??(s.revision_source==="unversioned"?void 0:[s.revision,i,a??"manual",o??"workspace"].join(":")),l={metric:i,value:n.value,direction:r,...c===void 0?{}:{unit:c},...n.threshold===void 0?{}:{threshold:n.threshold},observed_at:Mv(n.observedAt??O(),"observedAt"),...s,author:U(n.author,t.author_default),...o===void 0?{}:{item_id:o},...a===void 0?{}:{source:a},...d===void 0?{}:{idempotency_key:d}};return{id:DL("sha256").update(ie(l)).digest("hex").slice(0,24),...l}}function qL(e,t){let n=t.idempotency_key?e.observations.find(r=>r.idempotency_key===t.idempotency_key):e.observations.find(r=>r.id===t.id);if(n){if(n.metric!==t.metric||n.value!==t.value||n.direction!==t.direction||n.threshold!==t.threshold||n.unit!==t.unit)throw new _(`Improvement observation retry key already records a different value for ${t.metric}.`,m.CONFLICT,{code:"improvement_observation_conflict"});return n}let i=e.observations.find(r=>r.metric===t.metric);if(i&&(i.direction!==t.direction||i.unit!==t.unit||t.direction==="target"&&i.threshold!==t.threshold))throw new _(`Metric ${t.metric} is already declared with direction ${i.direction} and unit ${i.unit??"<none>"}.`,m.CONFLICT,{code:"improvement_metric_contract_conflict"})}async function KL(e,t){let n=xi(t,"revision");if(n)return{revision:n,revision_source:"caller"};try{return{revision:(await PL("git",["rev-parse","--verify","HEAD^{commit}"],{cwd:Xe(e),encoding:"utf8",timeout:5e3})).stdout.trim(),revision_source:"git"}}catch{}return{revision:"unversioned",revision_source:"unversioned"}}function zL(e){let t=e[0],n=e[e.length-1],i=n.value-t.value,r=n.direction==="higher"?i>0:n.direction==="lower"?i<0:Math.abs(n.value-n.threshold)<Math.abs(t.value-t.threshold);return{metric:n.metric,direction:n.direction,baseline:t,latest:n,delta:i,improved:r,sample_count:e.length}}async function Pv(e,t={}){let n=x(process.cwd(),t.path);await $(n);let i=await I(n),r=await GL(n,i,e),s=Dv.join(n,"improvement-ledger.json"),a=await an({pmRoot:n,filePath:s,op:"improvement_observe",author:r.author,lockTtlSeconds:i.locks.ttl_seconds,lockWaitMs:i.locks.wait_ms,message:e.message??`Record ${r.metric}=${String(e.value)} improvement observation`,mutate:o=>{let c=dd(o),d=qL(c,r);return d?{raw:o,result:d}:(c.observations.push(r),c.observations.sort((l,u)=>l.observed_at.localeCompare(u.observed_at)||l.metric.localeCompare(u.metric)||l.id.localeCompare(u.id)),{raw:`${ie(c)}
|
|
17
|
+
`,result:r})}});return{changed:a.changed,observation:a.result,ledger_path:"improvement-ledger.json"}}async function Fv(e={}){let t=x(e.cwd??process.cwd(),e.pmRoot);await $(t);let n=e.metric===void 0?void 0:Nv(e.metric),i=e.since===void 0?void 0:Mv(e.since,"since"),r=jL(e.limit),s=dd(await Q(Dv.join(t,"improvement-ledger.json"))).observations.filter(o=>(n===void 0||o.metric===n)&&(e.itemId===void 0||o.item_id===e.itemId)&&(i===void 0||o.observed_at>=i)),a=new Map;for(let o of s){let c=a.get(o.metric)??[];c.push(o),a.set(o.metric,c)}return{observations:[...s].reverse().slice(0,r),total:s.length,truncated:s.length>r,trends:[...a].map(([,o])=>zL(o)).sort((o,c)=>o.metric.localeCompare(c.metric)),source:"audited_workspace_singleton"}}(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]="28dd16ac-2e3b-55ed-98a6-db5f6786cbd7")}catch{}})();function WL(e){return e.agent_episode!==void 0?{id:e.agent_episode.id,source:"declared"}:{id:e.agent_instance?`inferred:instance:${e.agent_instance}`:`inferred:author:${e.author}:${e.ts.slice(0,13)}`,source:"inferred"}}function BL(e,t,n){let i=t,r=new Set([e.id]);for(;i!==void 0&&!r.has(i.id);)r.add(i.id),i=i.parent_id?n.get(i.parent_id):void 0;return i===void 0}function HL(e){let t=[e];for(;t.length>0;){let n=t.pop();n.sort((i,r)=>i.entries[0].ts.localeCompare(r.entries[0].ts)||i.id.localeCompare(r.id)),t.push(...n.map(i=>i.children))}}function $v(e=jn,t=Un){return t.map(n=>{let i=e.filter(r=>((n==="model"?r.model_environment_keys:r.provenance_environment_keys?.[n])?.length??0)>0||r.provenance_resolvers?.[n]!==void 0).map(r=>r.harness).sort();return{dimension:n,harnesses:i,covered:i.length>0}})}function cH(e,t=1){let n=new Map;for(let i of e){if(!i.agent_harness)continue;let r=n.get(i.agent_harness)??{harness:i.agent_harness,entries:0,observed:0,unavailable:0,legacy_missing:0};r.entries+=1,i.agent_model||i.agent_provenance?.model&&i.agent_provenance.model.value.length>0?r.observed+=1:i.agent_provenance?.model===null?r.unavailable+=1:r.legacy_missing+=1,n.set(i.agent_harness,r)}return[...n.values()].map(i=>{let r=i.observed+i.unavailable;return{...i,coverage:r===0?null:i.observed/r,inert:r>=t&&i.observed===0}}).sort((i,r)=>i.harness.localeCompare(r.harness))}function Uv(e,t=Un,n=1){let i=new Map;for(let r of e)if(r.agent_harness)for(let s of t){let a=`${r.agent_harness}\0${s}`,o=i.get(a)??{harness:r.agent_harness,dimension:s,entries:0,observed:0,unavailable:0,legacy_missing:0};o.entries+=1;let c=r.agent_provenance?.[s];c!=null&&c.value.length>0?o.observed+=1:c===null?o.unavailable+=1:o.legacy_missing+=1,i.set(a,o)}return[...i.values()].map(r=>{let s=r.observed+r.unavailable;return{...r,coverage:s===0?null:r.observed/s,inert:s>=n&&r.observed===0}}).sort((r,s)=>r.harness.localeCompare(s.harness)||r.dimension.localeCompare(s.dimension))}function dH(e,t={}){let n=t.minimumCoverage??.8,i=t.minimumEntries??5;if(![Number.isFinite(n),n>=0,n<=1].every(Boolean))throw new RangeError("Semantic attribution minimum coverage must be from 0 to 1.");if(![Number.isSafeInteger(i),i>=1].every(Boolean))throw new RangeError("Semantic attribution minimum entries must be a positive integer.");let r=new Map;for(let c of e)if(c.agent_harness)for(let d of["role","topic"]){let l=`${c.agent_harness}\0${d}`,u=r.get(l)??{harness:c.agent_harness,dimension:d,entries:0,observed:0,by_source:{},coverage:0};u.entries+=1;let p=c.agent_provenance?.[d];p?.value&&(u.observed+=1,u.by_source[p.source]=(u.by_source[p.source]??0)+1),r.set(l,u)}let s=[...r.values()].map(c=>({...c,coverage:c.observed/c.entries,by_source:Object.fromEntries(Object.entries(c.by_source).sort(([d],[l])=>d.localeCompare(l)))})).sort((c,d)=>c.harness.localeCompare(d.harness)||c.dimension.localeCompare(d.dimension)),a=s.filter(c=>c.entries>=i),o=a.filter(c=>c.coverage<n).map(c=>`${c.harness}:${c.dimension}`);return{passed:a.length>0&&o.length===0,minimum_coverage:n,minimum_entries:i,rows:s,failures:o}}function lH(e){let t=[...e].sort((s,a)=>s.ts.localeCompare(a.ts)||s.author.localeCompare(a.author)||s.op.localeCompare(a.op)||s.before_hash.localeCompare(a.before_hash)||s.after_hash.localeCompare(a.after_hash)),n=new Map,i=new Map;for(let s of t){let a=s.agent_episode,o=WL(s),c=`${o.source}:${o.id}`,d=n.get(c);if(d){d.entries.push(s);continue}let l={id:o.id,...a?.label===void 0?{}:{label:a.label},...a?.parent_id===void 0?{}:{parent_id:a.parent_id},source:o.source,entries:[s],children:[]};n.set(c,l),a!==void 0&&i.set(o.id,l)}let r=[];for(let s of n.values()){let a=s.parent_id?i.get(s.parent_id):void 0;a&&BL(s,a,i)?a.children.push(s):r.push(s)}return HL(r),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]="6b51fdd9-9923-53c5-a798-41c15fd847a0")}catch{}})();var VL=1e4,jv=1e5,YL=1e3,JL=30,XL=["append","comment","docs","file","learning","note","test_run"];function QL(e){let t=e??VL;if(!Number.isSafeInteger(t)||t<1||t>jv)throw new _(`History analytics event limit must be an integer from 1 to ${jv}.`,m.USAGE,{code:"invalid_history_analytics_limit"});return t}function Gv(e){let t=e??5;if(!Number.isSafeInteger(t)||t<1||t>1e4)throw new _("History analytics minimum sample must be an integer from 1 to 10000.",m.USAGE,{code:"invalid_history_analytics_minimum_sample"});return t}function ZL(e){let t=e?.trim();if(!t)return new Date(Date.now()-JL*864e5).toISOString();let n=/^-(\d+)([dh])$/u.exec(t);if(n){let r=Number(n[1]),s=n[2]==="d"?864e5:36e5;if(!Number.isSafeInteger(r)||r<1)throw new _("History analytics --since duration must be positive.",m.USAGE,{code:"invalid_history_analytics_since"});return new Date(Date.now()-r*s).toISOString()}let i=Date.parse(t);if(!Number.isFinite(i))throw new _("History analytics --since must be an ISO timestamp or negative duration such as -30d.",m.USAGE,{code:"invalid_history_analytics_since"});return new Date(i).toISOString()}async function oa(e,t){let n=QL(t.eventLimit),i=ZL(t.since),r=[],s=i,a=!1;for(;r.length<n;){let o=await hp({pmRoot:e,since:s,limit:Math.min(YL,n-r.length),full:!0}),c=o.events.map(d=>({item_id:d.item_id,entry:d.entry}));if(r.push(...c),a=o.has_more,s=o.next_cursor,!o.has_more)break}return{events:r,receipt:{since:i,events:r.length,truncated:a,...a?{next_cursor:s}:{},source:"history_event_index"}}}function eD(e,t){return t==="harness"?e.agent_harness:t==="author_source"?e.author_source:e.agent_model??e.agent_provenance?.model?.value}function tD(e){for(let t=e.patch.length-1;t>=0;t-=1){let n=e.patch[t];if(n.path==="/metadata/status"&&"value"in n&&typeof n.value=="string")return n.value}}function nD(e){return XL.some(t=>e.startsWith(t))}function qv(e,t){let n=e.get(t);if(n)return n;let i={events:0,stateEvents:0,annotationEvents:0,closes:0,reopens:0,defectEscapes:0};return e.set(t,i),i}function iD(e,t,n){let i=new Map,r=new Map,s=new Map;for(let a of t){let o=eD(a.entry,e),c=tD(a.entry),d=r.get(a.item_id)===!0,l=c===void 0?d:n.has(c);if(c!==void 0&&r.set(a.item_id,l),!o)continue;let u=qv(i,o);u.events+=1,nD(a.entry.op)?u.annotationEvents+=1:u.stateEvents+=1,c!==void 0&&!d&&l?(u.closes+=1,s.set(a.item_id,o)):c!==void 0&&d&&!l&&(u.reopens+=1)}return{buckets:i,lastCloseValue:s}}function rD(e,t,n){for(let i of n){if(i.type!=="Issue")continue;let r=new Set((i.dependencies??[]).filter(s=>s.kind==="discovered_from").map(s=>s.id));for(let s of r){let a=t.get(s);a&&(qv(e,a).defectEscapes+=1)}}}function sD(e,t,n,i){let r=t.closes>=n?"available":"insufficient";return{value:e,events:t.events,state_events:t.stateEvents,annotation_events:t.annotationEvents,closes:t.closes,reopens:t.reopens,defect_escapes:t.defectEscapes,throughput_per_day:r==="available"?t.closes/i:null,rework_rate:r==="available"?t.reopens/t.closes:null,defect_escape_rate:r==="available"?t.defectEscapes/t.closes:null,sample_status:r}}function aD(e,t,n,i,r,s){let{buckets:a,lastCloseValue:o}=iD(e,t,i);return rD(a,o,n),{dimension:e,status:a.size===0?"unavailable":"available",rows:[...a].map(([c,d])=>sD(c,d,r,s)).sort((c,d)=>d.events-c.events||c.value.localeCompare(d.value))}}function oD(e,t){let n=e[0]?.entry.ts??t,i=e[e.length-1]?.entry.ts??n,r=Date.parse(n),s=Date.parse(i);return!Number.isFinite(r)||!Number.isFinite(s)?1:Math.max(1,(s-r)/864e5)}function cD(e,t,n){let i=$v(t),r=Uv(e,Un,n),s=r.filter(o=>o.inert).map(o=>({harness:o.harness,dimension:o.dimension,explicit_samples:o.observed+o.unavailable})),a=i.filter(o=>!o.covered).map(o=>o.dimension);return{descriptors:i,observations:r,inert:s,undeclared:a,warnings:[...s.map(o=>`provenance_dimension_inert:${o.harness}:${o.dimension}:${String(o.explicit_samples)}`),...a.map(o=>`provenance_dimension_undeclared:${o}`)]}}async function hH(e,t=jn,n={}){return ld(await oa(e,n),t,n)}function ld(e,t=jn,n={}){let i=Gv(n.minimumSample);return{...cD(e.events.map(r=>r.entry),t,i),window:e.receipt}}async function yH(e,t,n,i={}){return ud(await oa(e,i),t,n,i)}function ud(e,t,n,i={}){let r=Gv(i.minimumSample),s=oD(e.events,e.receipt.since);return{dimensions:["harness","model","author_source"].map(a=>aD(a,e.events,t,n,r,s)),minimum_sample:r,policy:"observational_only_not_for_authorization_or_routing",window:e.receipt}}(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]="3e70310d-fc4f-5ea9-b9fb-7c519035301b")}catch{}})();var dD=32;function lD(e){let t=[];for(let n of e??[]){let i=[];for(let r of n.split(",")){let s=r.slice(0,r.indexOf("=")).trim();i.length>0&&s!=="unit"&&s!=="threshold"&&(t.push(i.join(",")),i=[]),i.push(r)}t.push(i.join(","))}return t}function Ri(e,t){let n=lD(e).map(i=>{let[r,...s]=i.split(","),a=r.indexOf("="),o=r.slice(0,a).trim(),c=r.slice(a+1).trim(),d=Number(c);if(a<=0||o.length===0||c.length===0||!Number.isFinite(d))throw new _(`Invalid --measure "${i}"; expected name=value[,unit=...][,threshold=...]`,m.USAGE);let l,u;for(let p of s){let g=p.indexOf("="),f=p.slice(0,g).trim(),h=p.slice(g+1).trim();if(f==="unit"&&h.length>0)l=h;else if(f==="threshold"&&h.length>0&&Number.isFinite(Number(h)))u=Number(h);else throw new _(`Invalid --measure attribute "${p}"`,m.USAGE)}return{name:o,value:d,unit:l,threshold:u,recorded_at:t}});return[...new Map(n.map(i=>[i.name,i])).values()].sort((i,r)=>i.name.localeCompare(r.name)).slice(0,dD)}function Kv(e,t,n){return e.flatMap(i=>(i.measurements??[]).filter(r=>r.name===t&&r.value<n).map(r=>({...r,run_id:i.run_id})))}function zv(e,t){let n=e.flatMap(s=>s.measurements??[]).filter(s=>s.name===t).sort((s,a)=>a.recorded_at.localeCompare(s.recorded_at)),i=n[0],r=n[1];return{name:t,latest:i?.value??null,previous:r?.value??null,delta:i!==void 0&&r!==void 0?i.value-r.value:null,unit:i?.unit}}import mD from"node:fs/promises";import Bv 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]="9cd23db4-2411-5c95-a6a0-fa30dd3a9a18")}catch{}})();function ca(e,t,n,i,r,s="min"){let a=r==="min"?e-t:t-e,o=s==="min"?n.localeCompare(i??n):(i??n).localeCompare(n);return a<0||a===0&&i!==null&&o<0}function uD(e,t){let n=Buffer.byteLength(t,"utf8"),i=0,r=null,s=null,a=Number.POSITIVE_INFINITY,o=Number.NEGATIVE_INFINITY;for(let c of t.split(/\r?\n/)){let d=c.trim();if(d==="")continue;i+=1;let l;try{l=JSON.parse(d)}catch{continue}if(l===null||typeof l!="object"||!("ts"in l)||typeof l.ts!="string")continue;let u=l.ts,p=Date.parse(u);Number.isNaN(p)||(ca(p,a,u,r,"min")&&(a=p,r=u),ca(p,o,u,s,"max","max")&&(o=p,s=u))}return{id:e,bytes:n,lines:i,oldest_ts:r,newest_ts:s}}function Wv(e,t){let n=t?.topN??5,i=Math.max(0,Math.floor(n)),r=e.map(({id:g,raw:f})=>uD(g,f)),s=0,a=0,o=null,c=null,d=Number.POSITIVE_INFINITY,l=Number.NEGATIVE_INFINITY;for(let g of r){if(s+=g.lines,a+=g.bytes,g.oldest_ts!==null){let f=Date.parse(g.oldest_ts);ca(f,d,g.id,o?.id??null,"min")&&(d=f,o={id:g.id,ts:g.oldest_ts})}if(g.newest_ts!==null){let f=Date.parse(g.newest_ts);ca(f,l,g.id,c?.id??null,"max")&&(l=f,c={id:g.id,ts:g.newest_ts})}}let u=i===0?[]:[...r].sort((g,f)=>f.bytes-g.bytes||g.id.localeCompare(f.id)).slice(0,i),p=i===0?[]:[...r].sort((g,f)=>f.lines-g.lines||g.id.localeCompare(f.id)).slice(0,i);return{total_streams:e.length,total_lines:s,total_bytes:a,largest_by_bytes:u,deepest_by_lines:p,oldest_entry:o,newest_entry:c}}(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]="b9d089ef-bca9-547f-a860-4002ec181cd0")}catch{}})();function _D(e){return e.reduce((t,n)=>(t[n]=0,t),{})}function pD(e,t,n,i,r){let s=Wn(e,"type",i),a=new Set(s.rows.map(u=>u.key)),o=t.filter(u=>!a.has(u)),c=(r?[...s.rows,...o.map(u=>({label:u,key:u,total:0,buckets:{open:0,in_progress:0,blocked:0,draft:0,closed:0,canceled:0,other:0}}))]:s.rows).map(u=>({type:u.key??u.label,total:u.total,open:u.buckets.open,in_progress:u.buckets.in_progress,blocked:u.buckets.blocked,draft:u.buckets.draft,closed:u.buckets.closed,canceled:u.buckets.canceled,other:u.buckets.other})),d=_D([...n]);for(let u of e)d[u.status]+=1;let l=Object.fromEntries(Object.entries(d).filter(([,u])=>r||u>0));return{byType:c,byStatus:l,omitted:r?0:o.length+Object.values(d).filter(u=>u===0).length}}function fD(e){return e.trim().length===0?0:e.split(/\r?\n/u).filter(t=>t.trim().length>0).length}async function gD(e){let t=Bv.join(e,"history");if(!await te(t))return[];await $e({path:t,scope:"project"});let n=(await mD.readdir(t)).filter(r=>r.endsWith(".jsonl")).sort((r,s)=>r.localeCompare(s)),i=[];for(let r of n){let s=Bv.join(t,r),a=await Q(s);a!==null&&(await $e({path:s,scope:"project"}),i.push({id:r.slice(0,-6),raw:a}))}return i}async function hD(e,t){let n=[],i=O();for(let r of Ri(t.observe,i))n.push(await Pv({metric:r.name,value:r.value,direction:t.direction,unit:r.unit,threshold:r.threshold,source:t.measurementSource,itemId:t.measurementItem,revision:t.measurementRevision,observedAt:i,author:t.author,message:t.message},e));return n}function yD(e,t,n){let i={};return t.byAssignee&&(i.assignee=Wn(e,"assignee",n)),t.byTag&&(i.tag=Wn(e,"tag",n,{tagPrefix:t.tagPrefix})),t.byPriority&&(i.priority=Wn(e,"priority",n)),i}async function vD(e,t,n,i,r){let s={since:r.since,eventLimit:r.eventLimit,minimumSample:r.minimumSample},a=r.provenanceCoverage||r.fleetAttribution?await oa(e,s):void 0;return{provenanceCoverage:r.provenanceCoverage&&a?ld(a,n.agent_identity?.harness_signals,s):void 0,fleetAttribution:r.fleetAttribution&&a?ud(a,t,i,s):void 0}}function wD(e,t,n,i,r){let s=Object.keys(r.breakdowns).length>0;return{totals:e,by_type:t,by_status:n,omitted_zero_buckets:i,...r.metadataCoverage?{metadata_coverage:r.metadataCoverage}:{},...s?{breakdowns:r.breakdowns}:{},...r.storage?{storage:r.storage}:{},...r.fieldUtilization?{field_utilization:r.fieldUtilization}:{},...r.improvementLedger?{improvement_ledger:r.improvementLedger}:{},...r.recordedObservations.length>0?{recorded_observations:r.recordedObservations}:{},...r.provenanceCoverage?{provenance_coverage:r.provenanceCoverage}:{},...r.fleetAttribution?{fleet_attribution:r.fleetAttribution}:{},generated_at:O()}}async function GH(e,t={}){let n=x(process.cwd(),e.path);await $(n);let i=await I(n),r=await hD(e,t),s=F(i,P()),a=K(i.schema),o=t.fieldUtilization?await dt(n,i.item_format,s.type_to_folder,void 0,i.schema):await Se(n,i.item_format,s.type_to_folder,void 0,i.schema);await rr({pmRoot:n,settings:i,itemIds:o.map(k=>k.id),commandLabel:"stats"});let c=K_(a),d=pD(o,s.types,a.definitions.map(k=>k.id),c,t.includeEmpty===!0),l=await gD(n),u=0;for(let k of l)u+=fD(k.raw);let p=t.storage?Wv(l):void 0,g=t.metadataCoverage?z_(o,c):void 0,f=yD(o,t,c),h=t.fieldUtilization?W_(o):void 0,y=t.measurements===!0||r.length>0?await Fv({pmRoot:n,metric:t.metric,itemId:t.measurementItem,limit:t.measurementLimit}):void 0,{provenanceCoverage:v,fleetAttribution:w}=await vD(n,o,i,a.terminal_statuses,t);return wD({items:o.length,history_streams:l.length,history_entries:u},d.byType,d.byStatus,d.omitted,{metadataCoverage:g,breakdowns:f,storage:p,fieldUtilization:h,improvementLedger:y,recordedObservations:r,provenanceCoverage:v,fleetAttribution:w})}import bD from"node:fs/promises";import gt 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]="a41eaff2-6a15-5e82-b3aa-03ca48fc3eb5")}catch{}})();var Xv=gt.join("runtime","telemetry","events.jsonl"),pd=gt.join("runtime","telemetry","state.json"),kD=gt.join("runtime","telemetry"),ED=20,fd=Ot.filter(e=>e.lifecycle==="deprecated"),Hv=["status","flush","stats","clear"],Vv=(e,t)=>{let n=Math.ceil(t*e.length),i=Math.min(e.length-1,Math.max(0,n-1));return e[i]},md=(e,t)=>typeof e!="string"?t:e.trim().length>0?e:t,Yv=e=>{if(!(typeof e!="number"||!Number.isFinite(e)))return Math.trunc(e)},SD=e=>({command:md(e.event.command,"<unknown>"),eventType:md(e.event.event_type,"unknown"),eventSchemaVersion:Yv(e.event.schema_version),clientSchemaVersion:Yv(e.client_schema_version)}),TD=()=>({count:0,max_attempts:0,event_type_counts:{},event_schema_versions:new Set,client_schema_versions:new Set,finish_durations_ms:[],ok_count:0,error_count:0,resolution_counts:{}}),AD=e=>{let t=e?.duration_ms;return typeof t=="number"&&Number.isFinite(t)?t:void 0},ID=e=>{let t=e?.command_resolution;return md(t,"")||void 0},Qv=(e,t)=>{e[t]=(e[t]??0)+1},CD=(e,t)=>{let n=AD(t);n!==void 0&&e.finish_durations_ms.push(n),t?.ok===!0?e.ok_count+=1:e.error_count+=1;let i=ID(t);i!==void 0&&Qv(e.resolution_counts,i)},xD=e=>Number.isFinite(e)?Math.max(0,Math.trunc(e)):0,Jv=(e,t)=>{t!==void 0&&e.add(t)},RD=(e,t)=>{let n=SD(t),i=e.get(n.command)??TD();i.count+=1,i.max_attempts=Math.max(i.max_attempts,xD(t.attempts)),Qv(i.event_type_counts,n.eventType),Jv(i.event_schema_versions,n.eventSchemaVersion),Jv(i.client_schema_versions,n.clientSchemaVersion),n.eventType==="command_finish"&&CD(i,t.event.payload),e.set(n.command,i)},OD=(e,t)=>{let n=t.ok_count+t.error_count,i=[...t.finish_durations_ms].sort((s,a)=>s-a),r=Object.entries(t.resolution_counts).sort((s,a)=>s[0].localeCompare(a[0]));return{command:e,count:t.count,event_type_counts:Object.fromEntries(Object.entries(t.event_type_counts).sort((s,a)=>s[0].localeCompare(a[0]))),max_attempts:t.max_attempts,event_schema_versions:[...t.event_schema_versions].sort((s,a)=>s-a),client_schema_versions:[...t.client_schema_versions].sort((s,a)=>s-a),...i.length>0?{duration_p50_ms:Vv(i,.5),duration_p95_ms:Vv(i,.95),duration_max_ms:i[i.length-1]}:{},...n>0?{ok_count:t.ok_count,error_count:t.error_count,error_rate:t.error_count/n}:{},...r.length>0?{command_resolution_counts:Object.fromEntries(r)}:{}}},LD=e=>{let t=(e??"status").trim().toLowerCase();if(Hv.includes(t))return t;throw cr({command_path:"telemetry",token:e?.trim()||"<empty>",allowed:Hv,examples:["pm telemetry status","pm telemetry flush","pm telemetry stats --limit 10","pm telemetry clear"]})},gd=()=>{throw new _("--limit must be a positive integer",m.USAGE)},Zv=e=>[!Number.isFinite(e),!Number.isInteger(e),e<=0].includes(!0)?gd():e,DD=e=>{let t=e.trim();return[t.length===0,!/^\d+$/.test(t)].includes(!0)?gd():Zv(Number.parseInt(t,10))},ND=e=>e===void 0?ED:typeof e=="number"?Zv(e):typeof e=="string"?DD(e):gd(),MD=e=>{if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.attempts=="number"&&typeof t.event=="object"&&t.event!==null},PD=e=>{try{let t=JSON.parse(e);return MD(t)?t:void 0}catch{return}},FD=e=>e===null?[]:e.split(`
|
|
18
|
+
`).map(t=>t.trim()).filter(t=>t.length>0),ew=e=>{let t=FD(e),n=[],i=0;for(let r of t){let s=PD(r);s===void 0?i+=1:n.push(s)}return{rows_total:t.length,valid_entries:n.length,invalid_rows:i,entries:n}},$D=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),UD=e=>{try{let t=JSON.parse(e);return $D(t)?t:{}}catch{return{}}},la=async e=>{let t=await Q(e);return t===null||t.trim().length===0?{}:UD(t)};function tw(e){let t=new Date;return new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()-Math.max(1,Math.trunc(e))+1)).toISOString().slice(0,10)}function jD(e,t,n){let i=Object.create(null);for(let[r,s]of Object.entries(e)){if(!/^\d{4}-\d{2}-\d{2}$/u.test(r)||r<t||r>n||typeof s!="object"||s===null||Array.isArray(s))continue;let a=s;!Number.isSafeInteger(a.count)||a.count<1||typeof a.last_seen!="string"||!a.last_seen.startsWith(r)||(i[r]={count:a.count,last_seen:a.last_seen})}return i}function _d(e,t){let n=Object.create(null);if(typeof e!="object"||e===null||Array.isArray(e))return n;let i=e,r=new Date().toISOString().slice(0,10);for(let s of fd){let a=i[s.alias];if(typeof a!="object"||a===null||Array.isArray(a))continue;let o=a;if(o.canonical!==s.canonical||typeof o.days!="object"||o.days===null||Array.isArray(o.days))continue;let c=jD(o.days,t,r);Object.keys(c).length>0&&(n[s.alias]={canonical:s.canonical,days:c})}return n}async function GD(e,t,n){let i=tw(n),r=await la(t),s=_d(r.alias_usage,i);if(JSON.stringify(r.alias_usage??{})===JSON.stringify(s))return s;try{await kr(async()=>{let a=await la(t);if(a.alias_usage===void 0)return;let o=_d(a.alias_usage,i);JSON.stringify(a.alias_usage)!==JSON.stringify(o)&&await Oe(t,`${JSON.stringify({...a,alias_usage:o},null,2)}
|
|
19
|
+
`)},e,250)}catch{}return s}async function tV(e){let t=fd.find(i=>i.alias===e);if(!t||$t().telemetry_disabled)return!1;let n=qe(process.cwd());try{return await kr(async()=>{let i=await I(n);if(!i.telemetry.enabled||$t().telemetry_disabled)return!1;let r=gt.join(n,pd),s=await la(r),a=_d(s.alias_usage,tw(i.telemetry.retention_days)),o=new Date().toISOString().slice(0,10),c=a[e]?.days[o];return a[e]={canonical:t.canonical,days:{...a[e]?.days,[o]:{count:Math.min(Number.MAX_SAFE_INTEGER,(c?.count??0)+1),last_seen:O()}}},await Oe(r,`${JSON.stringify({...s,alias_usage:a},null,2)}
|
|
20
|
+
`),!0},n,250)}catch{return!1}}var da=e=>e??null,ua=async e=>{let t=await I(e),n=gt.join(e,Xv),i=gt.join(e,pd),r=await Q(n),s=ew(r),a=await la(i),o=$t();return{enabled:t.telemetry.enabled&&!o.telemetry_disabled,configured_enabled:t.telemetry.enabled,env_overrides:o,endpoint:t.telemetry.endpoint,queue_path:n,state_path:i,queue_rows_total:s.rows_total,queue_entries:s.valid_entries,queue_invalid_rows:s.invalid_rows,queue_size_bytes:Buffer.byteLength(r??"","utf8"),last_attempted_flush_at:da(a.last_attempted_flush_at),last_successful_flush_at:da(a.last_successful_flush_at),last_failed_flush_at:da(a.last_failed_flush_at),last_failed_flush_error:da(a.last_failed_flush_error)}},qD=e=>{let t=new Map;for(let n of e)RD(t,n);return[...t.entries()].map(([n,i])=>OD(n,i)).sort((n,i)=>i.count-n.count||n.command.localeCompare(i.command))},KD=async(e,t)=>({action:"telemetry",subcommand:"status",status:await ua(t.globalPmRoot),generated_at:O()}),zD=async(e,t)=>{let n=await ua(t.globalPmRoot);await I_(t.globalPmRoot);let i=await ua(t.globalPmRoot),r=Math.max(0,n.queue_entries-i.queue_entries),s=i.queue_entries===0;return{action:"telemetry",subcommand:"flush",queue_entries_before:n.queue_entries,queue_entries_after:i.queue_entries,queue_entries_drained:r,queue_progressed:r>0,queue_empty:s,queue_drained:s,status:i,generated_at:O()}},WD=async(e,t)=>{let n=ND(e.limit),i=await Q(t.queuePath),r=ew(i),s=qD(r.entries),a=s.slice(0,n),o=await I(t.globalPmRoot),c=await GD(t.globalPmRoot,t.statePath,o.telemetry.retention_days),d=Object.entries(c).map(([l,u])=>{let p=Object.values(u.days);return{alias:l,canonical:u.canonical,count:p.reduce((g,f)=>Math.min(Number.MAX_SAFE_INTEGER,g+f.count),0),last_seen:p.map(g=>g.last_seen).sort().at(-1)}}).sort((l,u)=>u.count-l.count||l.alias.localeCompare(u.alias));return{action:"telemetry",subcommand:"stats",limit:n,total_commands:s.length,queue_entries:r.valid_entries,queue_invalid_rows:r.invalid_rows,queue_rows_total:r.rows_total,truncated:s.length>a.length,stats:a,alias_usage:d,zero_use_aliases:fd.map(l=>l.alias).filter(l=>c[l]===void 0),alias_usage_retention_days:o.telemetry.retention_days,generated_at:O()}},BD=async(e,t)=>kr(async()=>{let n=await I(t.globalPmRoot),i=[n.telemetry.enabled!==!1,n.telemetry.installation_id!=="",n.telemetry.first_run_prompt_completed!==!0].includes(!0);n.telemetry.enabled=!1,n.telemetry.first_run_prompt_completed=!0,n.telemetry.installation_id="",i&&await hu(t.globalPmRoot,n,"telemetry:clear");let r=gt.join(t.globalPmRoot,kD),s=await te(r);return await bD.rm(r,{recursive:!0,force:!0}),{action:"telemetry",subcommand:"clear",settings_changed:i,runtime_dir_removed:s&&!await te(r),queue_exists_after:await te(t.queuePath),state_exists_after:await te(t.statePath),status:await ua(t.globalPmRoot),generated_at:O()}},t.globalPmRoot),HD={status:KD,flush:zD,stats:WD,clear:BD};async function nV(e,t){let n=LD(e.subcommand),i=qe(process.cwd());return HD[n](e,{globalPmRoot:i,queuePath:gt.join(i,Xv),statePath:gt.join(i,pd)})}(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]="2661c74e-3e73-50f5-80a2-f103ff0cf2d4")}catch{}})();var nw=100;function xn(e,t="--only-index"){let n=typeof e=="number"?e:Number(String(e).trim());if(!Number.isInteger(n)||n<1)throw new _(`${t} requires a 1-based integer index into the linked-test list (got "${e}"). Use pm test <id> --list to inspect positions.`,m.USAGE);return n}function VD(e){let t=(e.command??e.path??"<no command>").replaceAll(/\s+/g," ").trim()||"<no command>";return t.length<=nw?t:`${t.slice(0,nw-3)}...`}function iw(e){return e.map((t,n)=>`${n+1}. ${VD(t)}`).join("; ")}function YD(e){let t=[];return e.match!==void 0&&t.push("match"),e.onlyIndex!==void 0&&t.push("only-index"),e.onlyLast===!0&&t.push("only-last"),t}function JD(e,t){let n=e.command?.toLowerCase()??"",i=e.path?.toLowerCase()??"";return n.includes(t)||i.includes(t)}function rw(e,t){let n=YD(t);if(n.length===0)return{selector:null,requested:null,selected:e,selected_indexes:e.map((r,s)=>s+1),selected_count:e.length,skipped_count:0};if(n.length>1)throw new _(`Combine at most one linked-test selector per run: ${n.map(r=>`--${r}`).join(" and ")} were provided. Pick one of --match, --only-index, --only-last.`,m.USAGE);let i=n[0];if(e.length===0)throw new _(`--${i} matched no linked tests because this item has none. Add one first with --add, --command, or --add-json.`,m.USAGE);if(i==="match"){let r=t.match.trim().toLowerCase();if(r.length===0)throw new _("--match requires a non-empty substring to match against linked-test command/path values",m.USAGE);let s=[],a=[];for(let o=0;o<e.length;o+=1)JD(e[o],r)&&(a.push(e[o]),s.push(o+1));if(a.length===0)throw new _(`--match "${t.match}" matched none of the ${e.length} linked test(s). Available entries: ${iw(e)}`,m.USAGE);return{selector:"match",requested:t.match,selected:a,selected_indexes:s,selected_count:a.length,skipped_count:e.length-a.length}}if(i==="only-index"){let r=xn(t.onlyIndex);if(r>e.length)throw new _(`--only-index ${r} is out of range: this item has ${e.length} linked test(s). Available entries: ${iw(e)}`,m.USAGE);return{selector:"only-index",requested:String(r),selected:[e[r-1]],selected_indexes:[r],selected_count:1,skipped_count:e.length-1}}return{selector:"only-last",requested:"last",selected:[e[e.length-1]],selected_indexes:[e.length],selected_count:1,skipped_count:e.length-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]="cfcc5f4f-caf0-5a2e-8a9d-219c3afb5d2d")}catch{}})();function sw(e){if(e.update===void 0&&e.updateIndex===void 0&&e.setJson===void 0)return;if(e.update===void 0==(e.updateIndex===void 0)||e.setJson===void 0)throw new _("Use exactly one --update or --update-index with --set-json",m.USAGE);let t;try{t=JSON.parse(e.setJson)}catch{throw new _("--set-json must contain a JSON object with explicit linked-test metadata fields",m.USAGE)}if(e.updateIndex!==void 0)return{selector:{index:xn(e.updateIndex,"--update-index")},patch:t};let n=e.update,i=/^(command|path)=/u.exec(n);return{selector:i?.[1]==="path"?{path:n.slice(i[0].length)}:{command:i?n.slice(i[0].length):n},patch:t}}function aw(e){if([e.list,e.run,e.progress,e.timeout!==void 0,e.acknowledgeLinkedTests,e.metricBelow!==void 0,e.metricDiff!==void 0,(e.add?.length??0)>0,(e.addJson?.length??0)>0,(e.remove?.length??0)>0,(e.removeIndex?.length??0)>0].some(Boolean))throw new _("Edit linked-test metadata separately from listing, additions, removals, execution options, metric filters and trust acknowledgement",m.USAGE)}function XD(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new _("Select one linked test by index, command, or path",m.USAGE);let n=Object.keys(t);if(n.length!==1||!["index","command","path"].includes(n[0]))throw new _("Select one linked test by index, command, or path",m.USAGE);if("index"in t){let i=xn(t.index,"--update-index");if(i<=e.length)return i-1}else{let i="command"in t?"command":"path",r="command"in t?t.command:t.path;if(typeof r!="string"||r.trim().length===0)throw new _("Linked-test selector must be a non-empty command or path",m.USAGE);let s=e.flatMap((a,o)=>a[i]===r?[o]:[]);if(s.length===1)return s[0];if(s.length>1)throw new _(`Linked-test selector is ambiguous; matching indexes: ${s.map(a=>a+1).join(", ")}`,m.USAGE,{code:"linked_test_update_ambiguous",required:"List linked tests and select one current --update-index."})}throw new _("No linked test matched the update selector",m.NOT_FOUND,{code:"linked_test_update_no_match",required:"List linked tests and select a current command, path, or --update-index."})}function QD(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new _("Linked-test metadata patch must be a JSON object",m.USAGE);let n=Object.keys(t);if(n.length===0||n.some(o=>!Ge.includes(o)||["command","cmd","timeout"].includes(o)))throw new _("Patch explicit linked-test metadata fields; command, aliases and provenance cannot be edited",m.USAGE);if(t.scope===null)throw new _("scope is required and cannot be cleared",m.USAGE);let i=Object.fromEntries(Object.entries(e).filter(([o])=>Ge.includes(o))),r=au(Ms(JSON.stringify({...i,command:e.command??"legacy-path-only",...Object.fromEntries(Object.entries(t).map(([o,c])=>[o,c===null?void 0:c]))}),"--set-json")[0]);ls(r);let s=n.filter(o=>!Fe(e[o],r[o])),a={...e};for(let o of s){let c=r[o];Object.assign(a,{[o]:c}),c===void 0&&delete a[o]}if(!a.command?.trim()&&!a.path?.trim())throw new _("Linked-test entry must retain a command or path",m.USAGE);return{test:a,fields:s}}async function ow(e,t,n={}){let i=x(process.cwd(),n.path);await $(i);let r=await I(i),s=U(t.author,r.author_default),a=F(r,P()),o=0,c=[],d=await or({pmRoot:i,settings:r,id:e,author:s,op:"tests_update",message:t.message,force:t.force,skipNoop:!0,typeToFolder:a.type_to_folder,resolveHistoryContext:()=>({linked_test_update:{index:o,fields:c}}),mutate(u){let p=u.metadata.tests??[],g=XD(p,t.selector),f=QD(p[g],t.patch);return o=g+1,c=f.fields,f.fields.length===0?{changedFields:[]}:(u.metadata.tests=p.map((h,y)=>y===g?{...f.test,updated_by:s,updated_at:O()}:h),{changedFields:["tests"]})}}),l=d.item.tests;return{ok:!0,id:d.item.id,tests:l,count:l.length,changed:d.changedFields.length>0,updated_index:o,updated_fields:c}}(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]="8316bbdc-b0f7-59b2-8875-1e0ad77eb8c0")}catch{}})();var ZD=[{code:"no_projects_matched_filters",regex:/\bNo projects matched the filters\b/i},{code:"no_test_files_found",regex:/\bNo test files found\b/i},{code:"no_tests_found",regex:/\bNo tests found\b/i},{code:"no_matching_tests",regex:/\bNo matching tests?\b/i},{code:"collected_zero_items",regex:/\bcollected 0 items?\b/i},{code:"reported_zero_tests",regex:/^\s*Ran 0 tests? across \d+ files?\./imu},{code:"reported_zero_passes",regex:/(?:^\s*(?:#|ℹ)?\s*tests\s+0\s*$[\s\S]*^\s*(?:#|ℹ)?\s*pass\s+0\s*$|^\s*(?:#|ℹ)?\s*pass\s+0\s*$[\s\S]*^\s*(?:#|ℹ)?\s*tests\s+0\s*$)/imu},{code:"reported_zero_tests",regex:/^\s*(?:#|ℹ)?\s*tests\s+0\s*$/imu}],eN=[{receiptCode:"reported_tests",regex:/^\s*(?:#|ℹ)?\s*tests\s+[1-9]\d*\s*$/imu},{receiptCode:"reported_passes",regex:/^\s*(?:#|ℹ)?\s*pass\s+[1-9]\d*\s*$/imu},{receiptCode:"tests_passed",regex:/\bTests?\s+[1-9]\d*\s+passed\b/iu},{receiptCode:"passed_count",regex:/\b[1-9]\d*\s+passed\b/iu},{receiptCode:"tests_summary",regex:/\bTests:\s+(?:.*\b)?[1-9]\d*\s+passed\b/iu},{receiptCode:"bun_pass_count",regex:/^\s*[1-9]\d* pass\s*$/imu},{receiptCode:"bun_executed_tests",regex:/^\s*Ran [1-9]\d* tests? across \d+ files?\./imu}];function ma(e,t){let n=`${e}
|
|
21
|
+
${t}`;for(let i of ZD)if(i.regex.test(n))return{code:i.code};return null}function cw(e,t){for(let[n,i]of[["stdout",e],["stderr",t]]){let r=eN.find(s=>s.regex.test(i));if(r)return{code:r.receiptCode,stream: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]="5aa7e990-08d9-56e4-860c-3fc52cebe728")}catch{}})();function dw(e,t,n,i,r){if((t.measure?.length??0)===0||r.some(a=>typeof a.stdout=="string"&&a.failure_category!=="spawn_error"&&a.failure_category!=="empty_run"&&ma(a.stdout,a.stderr??"")===null))return;let s=["--pm-path",i,...n.noExtensions?["--no-extensions"]:[],...n.author?["--author",n.author]:[],"test",e,"--list","--json"];throw new _("--measure requires an executed linked test",m.USAGE,{code:"test_measure_requires_execution",required:"Execute at least one linked command before recording measurement evidence.",why:"Empty, skipped and pre-execution refused runs cannot support measured evidence.",nextSteps:["Inspect the linked commands, adjust empty selections or missing commands, and resolve any trust refusal before retrying the measurement."],recovery:{suggested_retry:fe(s),suggested_retry_args:s}})}function hd(e,t,n,i,r=!1){if((t.measure?.length??0)===0||t.run===!0)return;let s=["--pm-path",i,...n.noExtensions?["--no-extensions"]:[],...n.author?["--author",n.author]:[]],a=[...s,...sp(e,t),...t.list?["--list"]:[],...r?["--background"]:[]],o=t.acknowledgeLinkedTests?[...s,"test",e,"--help"]:a,c=[...s,"test",e,"--acknowledge-linked-tests",...t.author?["--author",t.author]:[]];throw new _("--measure requires --run",m.USAGE,{code:"test_measure_requires_run",flag:"--measure",required:"Run the linked tests with --run to record measurement evidence.",why:"Measurements describe an executed linked-test run; recording them without execution would fabricate evidence.",...t.acknowledgeLinkedTests?{nextSteps:[`Review the linked commands and apply any requested link updates separately before acknowledging trust: ${fe([...s,"test",e,"--list"])}`,`After review, acknowledge trust as a separate non-executing operation: ${fe(c)}`,`Then run the measurement without --acknowledge-linked-tests: ${fe(a)}`]}:{},recovery:{missing:["--run"],suggested_retry:fe(o),suggested_retry_args:o}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="92f73d30-eac7-5c84-a7be-133323d1f549")}catch{}})();function lw(e){if(!/^(?:[^.[\]]+|\[\d+\])(?:\.[^.[\]]+|\[\d+\])*$/u.test(e))return[];let t=[],n=e.matchAll(/[^.[\]]+|\[\d+\]/g);for(let[i]of n){if(i.startsWith("[")&&i.endsWith("]")){let r=Number.parseInt(i.slice(1,-1),10);if(!Number.isSafeInteger(r))return[];t.push(r);continue}t.push(i)}return t}function yd(e,t){let n=t.trim();if(n.length===0)return{found:!1,value:void 0};let i=lw(n);if(i.length===0)return{found:!1,value:void 0};let r=e;for(let s of i){if(typeof r!="object"||r===null)return{found:!1,value:void 0};if(typeof s=="number"&&(!Array.isArray(r)||s>=r.length))return{found:!1,value:void 0};let a=Object.getOwnPropertyDescriptor(r,s);if(!a||!Object.hasOwn(a,"value"))return{found:!1,value:void 0};r=a.value}return{found:!0,value:r}}import{cp as tN,lstat as nN,mkdir as iN,readlink as rN,realpath as wd,stat as sN,symlink as uw}from"node:fs/promises";import{execFile as aN}from"node:child_process";import B from"node:path";import{promisify as oN}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]="26cfff37-1b7e-556f-8656-2e5c7c9d616f")}catch{}})();var cN=new Set([".agents",".git",".nyc_output",".turbo","coverage"]),mw=oN(aN);async function dN(e,t){let n=await _a(B.join(e,".git"));if(!n||n.isDirectory()&&!await _a(B.join(e,".git/HEAD")))return;let i=Object.fromEntries(Object.entries(process.env).filter(([r])=>!r.toUpperCase().startsWith("GIT_")));await mw("git",["clone","--no-local","--no-checkout","--template=","--origin=origin","--",e,t],{env:i,timeout:12e4,maxBuffer:1024*1024,windowsHide:!0}),await mw("git",["-C",t,"remote","remove","origin"],{env:i,timeout:1e4,windowsHide:!0})}function vd(e){return e.split(B.sep).some(t=>cN.has(t.toLowerCase()))}function Oi(e){return e===".."||e.startsWith(`..${B.sep}`)||B.isAbsolute(e)}async function _a(e){try{return await sN(e)}catch(t){if(!q(t))throw t;return}}async function pa(e){let t=[],n=e;for(;B.dirname(n)!==n;)try{return B.join(await wd(n),...t)}catch(i){if(!q(i))throw i;t.unshift(B.basename(n)),n=B.dirname(n)}return B.join(await wd(n),...t)}async function lN(e,t,n){let i=B.relative(t,await pa(e));if(!Oi(i))return i;let r=[],s=e;for(;B.dirname(s)!==s;){let a=await pa(s),o=n.find(([,c])=>c===a);if(o)return B.join(o[0],...r);r.unshift(B.basename(s)),s=B.dirname(s)}return i}async function _w(e,t){let n=[],i=[],r=await wd(e),s=await pa(B.resolve(t));if(![B.relative(r,s),B.relative(s,r)].every(Oi))throw new Error("Snapshot destination must be disjoint from the source workspace; choose a temporary root outside the checkout.");await iN(B.dirname(t),{recursive:!0}),await dN(r,t),await tN(r,t,{recursive:!0,force:!0,async filter(a){let o=B.relative(r,a);if(!o)return!0;if(vd(o))return!1;if(B.basename(a).toLowerCase()==="node_modules"){if((await _a(a))?.isDirectory()){let c=await pa(a),d=B.relative(r,c);if(!Oi(B.relative(c,r))||!Oi(d)&&(vd(d)||!d.split(B.sep).some(l=>l.toLowerCase()==="node_modules")))throw new Error(`Dependency symlink must target an included dependency directory or external installation: ${o}`);n.push([o,c])}return!1}return(await nN(a)).isSymbolicLink()?(i.push([o,B.resolve(B.dirname(a),await rN(a)),(await _a(a))?.isDirectory()?"junction":"file"]),!1):!0}});for(let[a]of n)await uw(B.resolve(r,a),B.join(t,a),"junction");for(let[a,o,c]of i){let d=await lN(o,r,n);if(Oi(d)||vd(d))throw new Error(`Source symlink must target included workspace source: ${a}`);await uw(B.resolve(t,d),B.join(t,a),c)}}import{spawn as Ow}from"node:child_process";import{cp as fw,mkdir as Ad,mkdtemp as Lw,open as Ed,readdir as Sd,rm as Di,symlink as mN}from"node:fs/promises";import{tmpdir as Dw}from"node:os";import oe 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]="b74444c7-c283-52b2-b65f-b0a086ff2b53")}catch{}})();var pw=20;function uN(){let e=process.env.PM_TRACKED_TEST_RUN_HISTORY_LIMIT;if(!e||e.trim().length===0)return pw;let t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?pw:t}function bd(e){let t=[...e].filter(i=>i.run_id.trim().length>0&&i.started_at.trim().length>0&&i.finished_at.trim().length>0&&i.recorded_at.trim().length>0).sort((i,r)=>{let s=Ji(i.recorded_at,r.recorded_at);if(s!==0)return s;let a=i.run_id.localeCompare(r.run_id);return a!==0?a:i.kind.localeCompare(r.kind)}),n=uN();return t.length>n?t.slice(t.length-n):t}async function fa(e){await se({pmRoot:e.pmRoot,settings:e.settings,id:e.itemId,op:"test_run_track",author:e.author,message:e.message,force:!1,mutate(t){let n=t.metadata.test_runs??[];return t.metadata.test_runs=bd([...n,e.entry]),{changedFields:["test_runs"]}}})}(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]="54338522-5725-5511-be94-b047d2c82fdc")}catch{}})();var ya=20*1024*1024,_N=3e3,pN=1e4,fN=5e3,gw=120,gN=new Set(["locks","extensions","runtime"]),hN=new Set(["history","index","search","extensions","locks","runtime"]),yN=[/eaddrinuse/i,/address already in use/i,/port\s+\d+\s+is already in use/i,/web server[^.\n]*already running/i,/failed to listen on/i],vN=/\b(?:could not|failed to|unable to)\s+acquire\b[^\n.]*\block\b/i,wN=/\b(?:already running|timed?\s*out|timeout|held by another|lock\s+is\s+held)\b/i,bN=new Set(["activity","calendar","context","ctx","deps","get","health","history","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","search","stats","test-all","validate"]);function Id(e,t){let n=process.env[e];if(typeof n!="string"||n.trim().length===0)return t;let i=Number.parseInt(n,10);return!Number.isFinite(i)||i<=0?t:i}function kN(){return Id("PM_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS",_N)}function EN(){return Id("PM_LINKED_TEST_HEARTBEAT_INTERVAL_MS",pN)}function SN(){return Id("PM_LINKED_TEST_PIPE_CLOSE_GRACE_MS",fN)}function TN(e){let t=process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();return t&&t.length>0?t:`${e}-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function AN(e){let t=0,n=0,i=0;for(let r of e){if(r.status==="passed"){t+=1;continue}if(r.status==="failed"||r.status==="refused"){n+=1;continue}i+=1}return{passed:t,failed:n,skipped:i}}function Cd(e){let t=0,n=0,i=0,r=0;for(let s of e){let a=s.execution_context;!a||a.is_pm_command!==!0||(t+=1,a.is_pm_tracker_read_command===!0&&(n+=1),a.mismatch_detected===!0&&(i+=1),a.auto_pm_context_applied===!0&&(r+=1))}return{checked_pm_commands:t,tracker_read_commands:n,mismatches:i,auto_remediated:r}}function IN(e){let t=e??"project";if(!Pe.includes(t))throw new _(`Invalid scope "${e}"`,m.USAGE);return t}function wa(e){if(!e)return"schema";let t=e.trim().toLowerCase();if(Wt.includes(t))return t;throw new _(`Invalid --pm-context value "${e}". Expected one of: ${Wt.join(", ")}`,m.USAGE)}function CN(e){return Ht(e??"source","--workspace-context")}function Nw(e,t,n){return n?t:Ht(e.workspace_context_mode,"linked test")??t}function Mw(e,t,n){return n||typeof e.pm_context_mode!="string"||e.pm_context_mode.trim().length===0?t:wa(e.pm_context_mode)}function Pw(e,t){return e==="auto"?t?"tracker":"schema":e}function xN(e){return Object.entries(e).filter(([t])=>t.startsWith("assert_")).some(([,t])=>t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:typeof t=="string"?t.trim().length>0:!0)}function RN(e){let{executionContext:t,runLevelPmContextMode:n,linkedOverridePmContextMode:i}=e;return!t.is_pm_tracker_read_command||!t.mismatch_detected?"":n==="tracker"&&i==="schema"?" Linked test metadata pm_context_mode=schema overrides run-level --pm-context tracker. Set pm_context_mode=tracker (or auto) on the linked test, or remove the override, to run against seeded tracker data.":t.pm_context_mode==="schema"?" Use --auto-pm-context to route PM tracker-read linked commands through seeded tracker data automatically. Alternatively, use --pm-context tracker for the whole run.":""}function ON(e,t){let n={};if(!e)return n;for(let i of e){let r=ki(i,t);if(r)for(let[s,a]of Object.entries(r))n[s]=a}return n}function LN(e,t){if(!e)return[];let n=[];for(let i of e){let r=Ei(i,t);r&&n.push(...r)}return[...new Set(n)]}function DN(e){let t=Mi(e);return Gt(t).some(n=>ss(n)!==null)}function Fw(e){let t=Mi(e);return Gt(t).some(n=>{let i=ss(n);if(!i)return!1;let r=_c(i);return r?bN.has(r.subcommand):!1})}function ga(e){if(e)return eh.has(e.subcommand)?It(e.args,th)?.subcommand:e.subcommand}function hw(e,t){if(e==="npx"||e==="bunx")return qt(t)?.command;if(e==="pnpm")return ga(It(t,dc));if(e==="npm")return ga(It(t,lc));if(e==="yarn")return ga(It(t,Qg));if(e==="bun")return ga(It(t,Zg))}function ha(e){return e?e==="vitest"||e==="test"||e.startsWith("test:"):!1}function kd(e){return!e||!_i(e.command)&&!mc(e.command)?!1:os(e.args)==="test-all"}var $w=new Map([...["sh","bash","dash","zsh"].map(e=>[e,/^(?:-c|-[a-z]*c[a-z]*)$/u]),...["cmd","cmd.exe"].map(e=>[e,/^\/[ck]$/u]),...["powershell","powershell.exe","pwsh","pwsh.exe"].map(e=>[e,/^-(?:c|command)$/u])]),NN=new Set(["npx","bunx"]);function Uw(e){let t=e.split(" ").filter(a=>a.length>0),n=as(t);if(n.length===0)return!1;let[i,...r]=n,s=$w.get(i);if(s){let a=r.findIndex(o=>s.test(o));return a>=0?Uw(r.slice(a+1).join(" ")):!1}return _i(i)||pi(i)?os(r)==="test-all":i==="node"&&r.length>0&&pi(r[0])?os(r.slice(1))==="test-all":NN.has(i)?kd(qt(r)):i==="pnpm"?kd(cs(r)):i==="npm"?kd(ds(r)):!1}function jw(e){let t=Mi(e);return Gt(t).some(n=>Uw(n))}function Gw(e){if(jw(e))throw new _('Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.',m.USAGE)}function Mi(e){return e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase()}function yw(e){return e.includes("node scripts/run-tests.mjs ")||e.endsWith("node scripts/run-tests.mjs")||e.includes("node ./scripts/run-tests.mjs ")||e.endsWith("node ./scripts/run-tests.mjs")}function xd(e){let t=e.split(" ").filter(a=>a.length>0),n=as(t);if(n.length===0)return!1;let[i,...r]=n,s=$w.get(i);if(s){let a=r.findIndex(o=>s.test(o));return a>=0&&xd(r.slice(a+1).join(" "))}return i==="vitest"||i.endsWith("/vitest")||i.endsWith("/vitest.mjs")?!0:i==="node"?MN(r):PN(i,r)}function MN(e){return e.includes("--test")||e.some(t=>t==="vitest"||t==="vitest.mjs"||t.endsWith("/vitest")||t.endsWith("/vitest.mjs"))}function PN(e,t){return e==="npx"||e==="bunx"?ha(qt(t)?.command):e==="pnpm"||e==="npm"?ha((e==="pnpm"?cs(t):ds(t))?.command)||ha(hw(e,t)):(e==="yarn"||e==="bun")&&ha(hw(e,t))}function b5(e){let t=Mi(e),n=Gt(t),i=n.some(s=>!yw(s)&&xd(s)),r=n.some(yw);return{accepted:!0,command_kind:i?"direct_runner":r?"sandbox_runner":"other",tracker_isolation:"runtime_injected",trust_boundary:"provenance",advisory:i?"Accepted with runtime-injected tracker isolation. Prefer the repository sandbox runner when available for reproducible build and coverage setup.":"Accepted with runtime-injected tracker isolation and provenance checks before execution."}}function FN(e){if(jw(e))return'Linked test command skipped: Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.'}function $N(e){return e?e.map(UN):[]}function UN(e){let t=e.trim(),n=nh(t)?us(Z(e,"--add"),"--add"):{command:t},i=ve(n.command);if(!i)throw new _("--add requires command=<value> or a bare command (path=<value> is optional metadata)",m.USAGE);return Gw(i),{command:i,path:ve(n.path),scope:IN(n.scope),timeout_seconds:jN(ve(n.timeout_seconds),ve(n.timeout)),pm_context_mode:Rs(ve(n.pm_context_mode),"--add"),workspace_context_mode:Ht(ve(n.workspace_context_mode),"--add"),env_set:ki(ve(n.env_set),"--add"),env_clear:Ei(ve(n.env_clear),"--add"),shared_host_safe:xs(ve(n.shared_host_safe),"--add","shared_host_safe"),assert_stdout_contains:Vt(ve(n.assert_stdout_contains)),assert_stdout_regex:An(ve(n.assert_stdout_regex),"--add","assert_stdout_regex"),assert_stderr_contains:Vt(ve(n.assert_stderr_contains)),assert_stderr_regex:An(ve(n.assert_stderr_regex),"--add","assert_stderr_regex"),assert_stdout_min_lines:Os(ve(n.assert_stdout_min_lines),"--add"),assert_json_field_equals:Ls(ve(n.assert_json_field_equals),"--add"),assert_json_field_gte:Ds(ve(n.assert_json_field_gte),"--add"),note:ve(n.note)}}function ve(e){let t=e?.trim();return t&&t.length>0?t:void 0}function jN(e,t){if(e&&t&&e!==t)throw new _("--add timeout and timeout_seconds must match when both are provided",m.USAGE);let n=e??t;if(n===void 0)return;let i=Math.floor(ye(n,"timeout_seconds"));if(i<=0)throw new _("--add timeout_seconds must be a positive integer",m.USAGE);return i}function GN(e){return e?e.flatMap(t=>{let n=Ms(t,"--add-json");for(let i of n){let r=i.command;if(!r)throw new _("--add-json requires a non-empty command string",m.USAGE);Gw(r)}return n}):[]}function qN(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new _("--remove requires command or path value",m.USAGE);let i=/^(command|path)\s*=/i.exec(n);if(i){let r=n.slice(i[0].length).trim();if(!r)throw new _("--remove requires a non-empty command=<value> or path=<value>",m.USAGE);return{kind:i[1].toLowerCase(),value:r}}if(/^[A-Za-z_][\w-]*=\S+$/u.test(n))throw new _("--remove structured selectors require command=<value> or path=<value>",m.USAGE);if(/^(?:[-*+]\s+)?(?:path|command)\s*:/i.test(n)||n.startsWith("```")){let r=Z(n,"--remove"),s=r.path!==void 0?"path":"command",a=r.path??r.command;if(!a?.trim())throw new _("--remove requires command=<value> and/or path=<value>",m.USAGE);return{kind:s,value:a.trim()}}return{kind:"either",value:n}}):[]}function KN(e){return e?[...new Set(e.map(t=>{let n=typeof t=="number"?t:Number.parseInt(t,10);if(!Number.isInteger(n)||n<1||String(n)!==String(t).trim())throw new _("--remove-index must be a positive integer",m.USAGE);return n}))]:[]}function zN(e){try{e.stdin?.end()}catch{}}function qw(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length<=gw?t:`${t.slice(0,gw-3)}...`}function Kw(e){return e==="off"?!1:e==="always"?!0:process.stderr.isTTY===!0}function Td(e){try{process.stderr.write(`${e}
|
|
22
|
+
`)}catch{}}function WN(e,t){if(!Kw(t))return null;let n=qw(e.command),i=Date.now();Td(`[pm test] linked-test ${e.index}/${e.total} start timeout_ms=${e.timeoutMs} command="${n}"`);let r=setInterval(()=>{let s=Date.now()-i;Td(`[pm test] linked-test ${e.index}/${e.total} running elapsed_ms=${s} command="${n}"`)},EN());return r.unref?.(),r}function BN(e,t,n,i){if(!Kw(i))return;let r=qw(e.command),s=Date.now()-n,a=t.timedOut||t.maxBufferExceeded||t.exitCode!==0?"failed":"passed",o=[];t.timedOut&&o.push("reason=timeout"),t.maxBufferExceeded&&o.push("reason=max_buffer"),t.outputTruncated&&o.push("output=truncated"),t.signal&&o.push(`signal=${t.signal}`);let c=t.exitCode===null?"null":String(t.exitCode),d=o.length>0?` ${o.join(" ")}`:"";Td(`[pm test] linked-test ${e.index}/${e.total} end status=${a} exit_code=${c} elapsed_ms=${s}${d} command="${r}"`)}async function vw(e){if(!(!Number.isInteger(e)||e<=0)){if(process.platform==="win32"){await new Promise(t=>{let n=Ow("taskkill",["/pid",String(e),"/T","/F"],{stdio:"ignore",windowsHide:!0});n.on("error",()=>t()),n.on("close",()=>t())});return}try{process.kill(-e,"SIGKILL");return}catch{}try{process.kill(e,"SIGKILL")}catch{}}}function HN(e){e.heartbeat&&clearInterval(e.heartbeat),e.timedOutTimer&&(clearTimeout(e.timedOutTimer),e.timedOutTimer=null),e.forceKillTimer&&(clearTimeout(e.forceKillTimer),e.forceKillTimer=null)}function VN(e,t){let n=!1;return async()=>{if(n)return;n=!0;let i=e.pid;if(!i||i<=0){try{e.kill("SIGTERM")}catch{}return}if(process.platform==="win32"){await vw(i);return}try{process.kill(-i,"SIGTERM")}catch{try{e.kill("SIGTERM")}catch{}}t.forceKillTimer=setTimeout(()=>{vw(i)},kN()),t.forceKillTimer.unref?.()}}function YN(e){return new Promise(t=>{let n=!1,i=null,r=(s,a=!1)=>{n||(n=!0,i&&(clearTimeout(i),i=null),a&&(e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy()),t(s))};e.on("exit",(s,a)=>{n||(i=setTimeout(()=>{r({code:s,signal:a},!0)},SN()),i.unref?.())}),e.on("close",(s,a)=>{r({code:s,signal:a})})})}function JN(e,t,n,i,r){return Ow(e,{cwd:r,env:t,shell:!0,windowsHide:!0,detached:process.platform!=="win32",stdio:["pipe",n,i]})}async function ww(e){let t=await Ed(e,"r");try{let n=(await t.stat()).size,i=Math.min(n,ya),r=Buffer.alloc(i);return i>0&&await t.read(r,0,i,0),{text:r.toString("utf8"),truncated:n>ya}}finally{await t.close()}}async function XN(e,t,n,i,r,s=process.cwd()){let a=Date.now(),o=await Lw(oe.join(Dw(),"pm-linked-test-output-"));try{let c=oe.join(o,"stdout.log"),d=oe.join(o,"stderr.log"),[l,u]=await Promise.all([Ed(c,"w"),Ed(d,"w")]),p;try{p=JN(e,n,l.fd,u.fd,s)}catch(N){throw await Promise.all([l.close(),u.close()]),N}let g=YN(p),f;p.on("error",N=>{f=N.message}),await Promise.all([l.close(),u.close()]),zN(p);let h={heartbeat:WN(i,r),forceKillTimer:null,timedOutTimer:null},y=VN(p,h),v=!1;h.timedOutTimer=setTimeout(()=>{v=!0,y()},t),h.timedOutTimer.unref?.();let{code:w,signal:k}=await g;HN(h);let[S,T]=await Promise.all([ww(c),ww(d)]),C=S.truncated||T.truncated,b=C?`
|
|
23
|
+
[pm linked-test output truncated at ${ya} bytes per stream; the child process continued to completion]
|
|
24
|
+
`:"",E={stdout:`${S.text}${b}`,stderr:T.text,exitCode:w,signal:k,timedOut:v,maxBufferExceeded:!1,outputTruncated:C,spawnError:f};return BN(i,E,a,r),E}finally{await Di(o,{recursive:!0,force:!0})}}function QN(e,t){let n=[];e.maxBufferExceeded&&n.push(`Linked test output exceeded maxBuffer=${ya} bytes. Reduce output volume or split the command.`),e.timedOut&&t>0&&n.push(`Linked test timed out after ${t}ms.`);let i=e.signal?`Linked test command terminated by signal ${e.signal}.`:void 0,r=e.spawnError?.trim()||i||"Linked test command failed.";return n.length===0?r:`${r} ${n.join(" ")}`}function ZN(e){let t=[e.spawnError??"",e.stderr,e.stdout].join(`
|
|
25
|
+
`);return yN.some(n=>n.test(t))||t.split(/\r?\n/u).some(n=>vN.test(n)&&wN.test(n))}function eM(e){return ZN(e)?"infra_collision":e.timedOut?"timeout":e.maxBufferExceeded?"max_buffer":e.spawnError?"spawn_error":e.signal?"signal":"assertion_failure"}function tM(){return{infra_collision:0,trust_refusal:0,config_refusal:0,assertion_failure:0,empty_run:0,timeout:0,max_buffer:0,spawn_error:0,signal:0}}function Ni(e){let t=tM();for(let n of e)n.status!=="failed"&&n.status!=="refused"||!n.failure_category||(t[n.failure_category]+=1);return t}function bw(e,t){for(let[n,i]of Object.entries(t.env_set))Bt.has(n.toUpperCase())||(e[n]=i);for(let n of t.env_clear)Bt.has(n.toUpperCase())||delete e[n]}function nM(e){e.PORT===void 0&&(e.PORT="0"),e.HOST===void 0&&(e.HOST="127.0.0.1"),e.PM_SHARED_HOST_SAFE===void 0&&(e.PM_SHARED_HOST_SAFE="1"),e.PLAYWRIGHT_HTML_OPEN===void 0&&(e.PLAYWRIGHT_HTML_OPEN="never"),e.PW_TEST_HTML_REPORT_OPEN===void 0&&(e.PW_TEST_HTML_REPORT_OPEN="never")}function iM(e,t){let n={...e.env_set,...t.env_set},i=[...new Set([...e.env_clear,...t.env_clear??[]])],r=t.shared_host_safe??e.shared_host_safe;return{env_set:n,env_clear:i,shared_host_safe:r}}function rM(e,t,n){return{env_set:ON(e,"--env-set"),env_clear:LN(t,"--env-clear"),shared_host_safe:n===!0}}async function Li(e,t,n=!1,i=Ad){if(await te(e))try{await Fn("seed_linked_test",async()=>{if(await i(oe.dirname(t),{recursive:!0}),n){await fw(e,t,{recursive:!0,force:!0});return}await fw(e,t,{force:!0})},{why:"Linked tests need an isolated PM context without mutating the source tracker.",nextSteps:["Reclaim capacity on the filesystem that hosts the linked-test temporary directory."]})}catch(r){if(typeof r=="object"&&r!==null&&"code"in r&&q(r))return;throw r}}async function kw(e,t,n,i=!1){for(let[r,s]of[[n.projectPmRoot,e],[n.globalPmRoot,t]])if(i){let a=await Q(Ae(r));if(a!==null){let o=await I(s);await za({pmRoot:s,filePath:Ae(s),raw:a,op:"settings:write",author:U(void 0,o.author_default),lockTtlSeconds:o.locks.ttl_seconds,lockWaitMs:o.locks.wait_ms,recordCreation:!0,message:"Seed linked-test schema settings history"})}}else await Li(Ae(r),Ae(s));await Li(oe.join(n.projectPmRoot,"extensions"),oe.join(e,"extensions"),!0),await Li(oe.join(n.globalPmRoot,"extensions"),oe.join(t,"extensions"),!0)}async function Ew(e,t){if(!await te(e))return;let n=await Sd(e,{withFileTypes:!0});for(let i of n){if(gN.has(i.name))continue;let r=oe.join(e,i.name),s=oe.join(t,i.name);if(i.isDirectory()){await Li(r,s,!0);continue}i.isFile()&&await Li(r,s)}}async function Sw(e,t){let n=await Q(Ae(e));if(n===null||await te(Gn(e)))return;let i=await I(t);await Di(Gn(t),{force:!0}),await Di(Ae(t),{force:!0}),await za({pmRoot:t,filePath:Ae(t),raw:n,op:"settings:write",author:U(void 0,i.author_default),lockTtlSeconds:i.locks.ttl_seconds,lockWaitMs:i.locks.wait_ms,recordCreation:!0,message:"Seed linked-test tracker settings history"})}async function Rn(e){if(!await te(e))return 0;let t=0,n=await Sd(e,{withFileTypes:!0});for(let i of n){if(!i.isDirectory()||hN.has(i.name))continue;let r=oe.join(e,i.name),s;try{s=await Sd(r,{withFileTypes:!0})}catch{continue}for(let a of s)a.isFile()&&Dt.some(o=>a.name.toLowerCase().endsWith(o))&&(t+=1)}return t}function sM(e){let t=typeof e.exitCode=="number"?e.exitCode:1;return(e.timedOut||e.maxBufferExceeded)&&t===0?1:t}function aM(e){let t=e.trim();if(t==="true")return!0;if(t==="false")return!1;if(t==="null")return null;let n=Number(t);if(t.length>0&&Number.isFinite(n))return n;if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch{}return t}function oM(e,t){return typeof e=="object"&&e!==null&&typeof t=="object"&&t!==null?Fe(e,t):Object.is(e,t)}function cM(e,t,n){let i=[];i.push(...Tw("stdout",t,e.assert_stdout_contains)),i.push(...Aw("stdout",t,e.assert_stdout_regex)),i.push(...Tw("stderr",n,e.assert_stderr_contains)),i.push(...Aw("stderr",n,e.assert_stderr_regex)),i.push(...dM(t,e.assert_stdout_min_lines));let r=e.assert_json_field_equals??{},s=e.assert_json_field_gte??{};if(!(Object.keys(r).length>0||Object.keys(s).length>0))return i;let a;try{a=JSON.parse(t)}catch(o){return i.push(`stdout is not valid JSON for assert_json_field_* checks: ${o instanceof Error?o.message:String(o)}`),i}for(let[o,c]of Object.entries(r)){let d=yd(a,o);if(!d.found){i.push(`assert_json_field_equals missing path "${o}"`);continue}let l=aM(c);oM(d.value,l)||i.push(`assert_json_field_equals mismatch at "${o}" (expected=${JSON.stringify(l)} actual=${JSON.stringify(d.value)})`)}for(let[o,c]of Object.entries(s)){let d=yd(a,o);if(!d.found){i.push(`assert_json_field_gte missing path "${o}"`);continue}if(typeof d.value!="number"||!Number.isFinite(d.value)){i.push(`assert_json_field_gte path "${o}" resolved to non-numeric value`);continue}d.value<c&&i.push(`assert_json_field_gte failed at "${o}" (expected >= ${c}, actual ${d.value})`)}return i}function Tw(e,t,n){let i=[];for(let r of n??[])t.includes(r)||i.push(`${e} missing required text: "${r}"`);return i}function Aw(e,t,n){let i=[];for(let r of n??[])try{new RegExp(r,"m").test(t)||i.push(`${e} failed regex assertion: /${r}/m`)}catch(s){i.push(`${e} regex assertion is invalid: /${r}/ (${s instanceof Error?s.message:String(s)})`)}return i}function dM(e,t){if(typeof t!="number")return[];let n=e.split(/\r?\n/).map(i=>i.trim()).filter(i=>i.length>0).length;return n<t?[`stdout line count ${n} is below required minimum ${t}`]:[]}function Iw(e){let t=Mi(e);return/(?:^|\s)(?:--test-name-pattern|--testnamepattern)(?:=|\s)/u.test(t)?!0:Gt(t).some(n=>/(?:^|\s)-t(?:=|\s)/u.test(n)&&xd(n))}function lM(e){return{root:e,schemaProjectPmPath:oe.join(e,"schema","project",".agents","pm"),schemaGlobalPmPath:oe.join(e,"schema","global"),trackerProjectPmPath:oe.join(e,"tracker","project",".agents","pm"),trackerGlobalPmPath:oe.join(e,"tracker","global"),workspaceSnapshotRoot:oe.join(e,"workspace","project"),workspaceIsolatedRoot:oe.join(e,"workspace","isolated")}}function uM(e,t,n){return e.some(i=>Nw(i,t,n)==="snapshot")}async function mM(e,t){let n=oe.join(e,".agents"),i=oe.join(n,"pm");await Ad(n,{recursive:!0}),await Di(i,{recursive:!0,force:!0}),await mN(t,i,process.platform==="win32"?"junction":"dir")}async function _M(e,t=po,n=!0){let i={defaults:!0,agentGuidance:"skip"};await t(void 0,{path:e.schemaProjectPmPath},i),await t(void 0,{path:e.schemaGlobalPmPath},i),n&&(await t(void 0,{path:e.trackerProjectPmPath},i),await t(void 0,{path:e.trackerGlobalPmPath},i))}async function pM(e,t,n){t&&(await kw(e.schemaProjectPmPath,e.schemaGlobalPmPath,t,!0),n&&(await kw(e.trackerProjectPmPath,e.trackerGlobalPmPath,t),await Ew(t.projectPmRoot,e.trackerProjectPmPath),await Ew(t.globalPmRoot,e.trackerGlobalPmPath),await Sw(t.projectPmRoot,e.trackerProjectPmPath),await Sw(t.globalPmRoot,e.trackerGlobalPmPath)))}function fM(e,t,n){return e.some(i=>{let r=i.command??"",s=r.length>0&&Fw(r),a=n?.autoPmContext===!0&&s?"auto":Mw(i,t,n?.overrideLinkedPmContext===!0);return Pw(a,s)==="tracker"})}async function gM(e,t){return{sourceProjectItemCount:t?await Rn(t.projectPmRoot):0,sourceGlobalItemCount:t?await Rn(t.globalPmRoot):0,schemaProjectItemCount:await Rn(e.schemaProjectPmPath),schemaGlobalItemCount:await Rn(e.schemaGlobalPmPath),trackerProjectItemCount:await Rn(e.trackerProjectPmPath),trackerGlobalItemCount:await Rn(e.trackerGlobalPmPath)}}function hM(e){let t=e.effectivePmContextMode==="tracker",n=t?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath,i=t?e.layout.trackerGlobalPmPath:e.layout.schemaGlobalPmPath,r=t?e.counts.trackerProjectItemCount:e.counts.schemaProjectItemCount,s=t?e.counts.trackerGlobalItemCount:e.counts.schemaGlobalItemCount,a=e.workspaceContextMode==="snapshot"?e.layout.workspaceSnapshotRoot:e.workspaceContextMode==="isolated"?e.layout.workspaceIsolatedRoot:e.sourceWorkspaceRoot,o=e.workspaceContextMode==="isolated"?"":a;return{requested_pm_context_mode:e.requestedPmContextMode,pm_context_mode:e.effectivePmContextMode,auto_pm_context_applied:e.autoPmContextApplied,is_pm_command:e.isPmCommand,is_pm_tracker_read_command:e.isPmTrackerReadCommand,source_project_pm_path:e.sourceRoots?.projectPmRoot??"",sandbox_project_pm_path:n,source_global_pm_path:e.sourceRoots?.globalPmRoot??"",sandbox_global_pm_path:i,source_project_item_count:e.counts.sourceProjectItemCount,sandbox_project_item_count:r,source_global_item_count:e.counts.sourceGlobalItemCount,sandbox_global_item_count:s,mismatch_detected:e.isPmCommand&&(e.counts.sourceProjectItemCount!==r||e.counts.sourceGlobalItemCount!==s),project_extensions_seeded:!!e.sourceRoots,global_extensions_seeded:!!e.sourceRoots,requested_workspace_context_mode:e.requestedWorkspaceContextMode,workspace_context_mode:e.workspaceContextMode,working_directory:a,source_workspace_root:o,trust:e.trust}}async function yM(e){let t=typeof e.linkedTest.pm_context_mode=="string"&&e.linkedTest.pm_context_mode.trim().length>0?wa(e.linkedTest.pm_context_mode):void 0,n=typeof e.linkedTest.command=="string"&&e.linkedTest.command.length>0?e.linkedTest.command:void 0,i=n?DN(n):!1,r=i&&n?Fw(n):!1,s=e.options?.autoPmContext===!0&&r,a=s?"auto":Mw(e.linkedTest,e.runLevelPmContextMode,e.options?.overrideLinkedPmContext===!0),o=Pw(a,r),c=o==="tracker"?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath;e.workspaceContextMode==="snapshot"&&await mM(e.layout.workspaceSnapshotRoot,c);let d=e.options?.pmRoot?await hc(e.options.pmRoot,e.linkedTest,e.currentSourceRef):await hc(e.layout.root,e.linkedTest,e.currentSourceRef);return{linkedOverridePmContextMode:t,executionContext:hM({layout:e.layout,counts:e.counts,sourceRoots:e.sourceRoots,isPmCommand:i,isPmTrackerReadCommand:r,requestedPmContextMode:a,effectivePmContextMode:o,autoPmContextApplied:s,requestedWorkspaceContextMode:e.requestedWorkspaceContextMode,workspaceContextMode:e.workspaceContextMode,sourceWorkspaceRoot:e.sourceWorkspaceRoot,trust:d})}}function Cw(e,t,n){return{command:e.command,path:e.path,status:"skipped",execution_context:t,error:n}}function vM(e,t,n,i){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"assertion_failure",execution_context:t,...i?{stdout:i.stdout,stderr:i.stderr}:{},error:n}}function wM(e,t,n){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"trust_refusal",execution_context:t,error:n}}function bM(e){if(e.executionContext.trust.trusted)return null;let t=e.options?.allowUntrustedLinkedTests===!0,n=e.options?.untrustedLinkedTestsPolicyEnabled===!0;if(t&&n)return null;let i=n?"Retry with --allow-untrusted-linked-tests for this invocation, or acknowledge the current commands with --acknowledge-linked-tests.":"Set testing.allow_untrusted_linked_tests=true, then retry with --allow-untrusted-linked-tests; alternatively acknowledge the current commands with --acknowledge-linked-tests.";return wM(e.linkedTest,e.executionContext,`Linked test command is not trusted by this clone (source_ref=${e.executionContext.trust.source_ref??"unknown"}, current_ref=${e.executionContext.trust.current_source_ref??"unknown"}). ${i}`)}function kM(e){if(!e.linkedTest.command)return Cw(e.linkedTest,e.executionContext,"No command configured for this linked test.");let t=FN(e.linkedTest.command);return t?Cw(e.linkedTest,e.executionContext,t):null}function EM(e){return e.executionContext.pm_context_mode!=="none"?null:e.executionContext.workspace_context_mode==="source"?va(e.linkedTest,e.executionContext,"pm_context_mode=none requires workspace_context_mode=isolated or snapshot so implicit tracker discovery cannot reach the source workspace."):e.executionContext.is_pm_command?va(e.linkedTest,e.executionContext,"pm_context_mode=none is for self-isolating SDK tests; direct PM commands require schema, tracker, or auto context."):null}function va(e,t,n){return{command:e.command,path:e.path,status:"refused",exit_code:null,failure_category:"config_refusal",execution_context:t,error:n}}function SM(e){let t=e.executionContext.pm_context_mode==="schema"&&e.executionContext.is_pm_tracker_read_command&&e.executionContext.mismatch_detected,n=e.options?.failOnContextMismatch===!0&&e.executionContext.is_pm_command&&e.executionContext.mismatch_detected;if(!t&&!n)return null;let i=RN({executionContext:e.executionContext,runLevelPmContextMode:e.runLevelPmContextMode,linkedOverridePmContextMode:e.linkedOverridePmContextMode}),r=e.options?.checkContext===!0?"Linked test preflight PM context mismatch detected":"Linked test PM context mismatch detected";return va(e.linkedTest,e.executionContext,`${r} (source_project_items=${e.executionContext.source_project_item_count}, sandbox_project_items=${e.executionContext.sandbox_project_item_count}).${i}`)}function TM(e){return kM(e)||bM(e)||EM(e)||SM(e)||(e.options?.requireAssertionsForPm===!0&&e.executionContext.is_pm_command&&!xN(e.linkedTest)?va(e.linkedTest,e.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled."):null)}function AM(e){let t=iM(e.runtimeDirectives,e.linkedTest),n={...process.env,SENTRY_ENVIRONMENT:"test"};return bw(n,e.runtimeDirectives),bw(n,{env_set:e.linkedTest.env_set??{},env_clear:e.linkedTest.env_clear??[]}),t.shared_host_safe&&nM(n),n.FORCE_COLOR="0",e.executionContext.pm_context_mode==="none"?delete n.PM_PATH:n.PM_PATH=e.executionContext.sandbox_project_pm_path,n.PM_GLOBAL_PATH=e.executionContext.sandbox_global_pm_path,e.executionContext.workspace_context_mode!=="source"&&(delete n.PM_BUILD_CONSUMER_LEASE,delete n.PM_BUILD_CONSUMER_LEASE_ROOT),e.executionContext.workspace_context_mode==="isolated"?(delete n.PM_SOURCE_WORKSPACE_ROOT,delete n.PM_SOURCE_PM_PATH,delete n[Vn]):(n.PM_SOURCE_WORKSPACE_ROOT=e.executionContext.source_workspace_root,n.PM_SOURCE_PM_PATH=e.executionContext.workspace_context_mode==="snapshot"?e.executionContext.sandbox_project_pm_path:e.executionContext.source_project_pm_path,n[Vn]="read_only"),n}function IM(e,t,n,i){return{command:e.command,path:e.path,status:"passed",exit_code:0,execution_context:t,stdout:n.stdout,stderr:n.stderr,...i?{execution_receipt:i}:{}}}function xw(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:1,failure_category:"empty_run",execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:`Linked test reported an empty test run (${e.emptyRunSignal.code}). Update the test selection so at least one test executes; unfiltered commands may opt out by omitting --fail-on-empty-test-run.`}}function CM(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:sM(e.execution),failure_category:eM(e.execution),execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:QN(e.execution,e.timeoutMs)}}function xM(e){let t=cw(e.execution.stdout,e.execution.stderr);if(e.options?.failOnEmptyTestRun===!0||Iw(e.linkedTest.command??"")){let i=ma(e.execution.stdout,e.execution.stderr);if(i)return xw({...e,emptyRunSignal:i});if(Iw(e.linkedTest.command??"")&&!t)return xw({...e,emptyRunSignal:{code:"missing_positive_execution_receipt"}})}let n=cM(e.linkedTest,e.execution.stdout,e.execution.stderr);return n.length>0?vM(e.linkedTest,e.executionContext,`Linked test assertion(s) failed: ${n.join("; ")}`,e.execution):IM(e.linkedTest,e.executionContext,e.execution,t)}async function RM(e){let t=e.linkedTest.command??"",n=(e.linkedTest.timeout_seconds??e.defaultTimeoutSeconds??120)*1e3,i=await XN(t,n,AM(e),{index:e.index+1,total:e.total,timeoutMs:n,command:t},e.progressMode,e.executionContext.working_directory);return i.exitCode===0&&!i.timedOut&&!i.maxBufferExceeded?xM({...e,execution:i}):CM({...e,execution:i,timeoutMs:n})}async function Rd(e,t,n){let i=[],r=await Lw(oe.join(Dw(),"pm-linked-test-")),s=lM(r),a=wa(n?.pmContext),o=CN(n?.workspaceContext),c=n?.progress===!0?"always":"auto",d=rM(n?.envSet,n?.envClear,n?.sharedHostSafe),l=n?.sourceRoots,u=hi(),p=fM(e,a,n),g=uM(e,o,n?.overrideLinkedWorkspaceContext===!0),f=await gi(u);try{await _M(s,po,p),await Ad(s.workspaceIsolatedRoot,{recursive:!0}),await pM(s,l,p),g&&await _w(u,s.workspaceSnapshotRoot);let h=await gM(s,l);for(let y=0;y<e.length;y+=1){let v=e[y],w=Nw(v,o,n?.overrideLinkedWorkspaceContext===!0),k=await yM({linkedTest:v,layout:s,counts:h,sourceRoots:l,runLevelPmContextMode:a,options:n,requestedWorkspaceContextMode:o,workspaceContextMode:w,currentSourceRef:f,sourceWorkspaceRoot:u}),S=TM({linkedTest:v,executionContext:k.executionContext,runLevelPmContextMode:a,linkedOverridePmContextMode:k.linkedOverridePmContextMode,options:n});if(S){i.push(S);continue}i.push(await RM({linkedTest:v,index:y,total:e.length,defaultTimeoutSeconds:t,runtimeDirectives:d,progressMode:c,executionContext:k.executionContext,options:n}))}}finally{await Di(s.root,{recursive:!0,force:!0,maxRetries:3,retryDelay:100})}return i}async function OM(e){let{id:t,pmRoot:n,settings:i,typeToFolder:r}=e,s=await Y(n,t,i.id_prefix,i.item_format,r);if(!s)throw new _(`Item ${t} not found`,m.NOT_FOUND);let a=await he(s,{schema:i.schema});return{itemId:s.id,tests:a.document.metadata.tests??[],testRuns:a.document.metadata.test_runs??[],changed:!1,removed:0}}function LM(e,t){return e.command===t.command&&e.path===t.path&&e.scope===t.scope&&e.pm_context_mode===t.pm_context_mode&&e.workspace_context_mode===t.workspace_context_mode}function DM(e,t){let n=[...e];for(let i of t)n.some(r=>LM(r,i))||n.push(i);return n}function NM(e,t,n){if(t.length===0&&n.length===0)return{tests:e,removed:0};let i=new Set(n),r=e.filter((s,a)=>i.has(a+1)?!1:!t.some(o=>o.kind==="command"?s.command===o.value:o.kind==="path"?s.path===o.value:s.command===o.value||s.path===o.value));return{tests:r,removed:e.length-r.length}}function MM(e,t,n,i){return NM(DM(e,t),n,i)}function PM(e){return[(e.envSet?.length??0)>0,(e.envClear?.length??0)>0,e.sharedHostSafe===!0,e.pmContext!==void 0,e.overrideLinkedPmContext===!0,e.failOnContextMismatch===!0,e.failOnSkipped===!0,e.failOnEmptyTestRun===!0,e.requireAssertionsForPm===!0,e.checkContext===!0,e.autoPmContext===!0,e.workspaceContext!==void 0,e.overrideLinkedWorkspaceContext===!0,e.allowUntrustedLinkedTests===!0].some(Boolean)}function zw(e){if(PM(e)&&e.run!==!0)throw new _("--env-set, --env-clear, --shared-host-safe, --pm-context, --override-linked-pm-context, --workspace-context, --override-linked-workspace-context, --allow-untrusted-linked-tests, --fail-on-context-mismatch, --fail-on-skipped, --fail-on-empty-test-run, --require-assertions-for-pm, --check-context, and --auto-pm-context require --run",m.USAGE);if(e.acknowledgeLinkedTests===!0&&e.run===!0)throw new _("--acknowledge-linked-tests records trust without executing commands; run it separately before --run",m.USAGE);if((e.match!==void 0||e.onlyIndex!==void 0||e.onlyLast===!0)&&e.run!==!0)throw new _("--match, --only-index, and --only-last require --run",m.USAGE)}async function FM(e){let{id:t,options:n,pmRoot:i,settings:r,typeToFolder:s,adds:a,removes:o,removeIndexes:c}=e;if(a.length===0&&o.length===0&&c.length===0)return OM({id:t,pmRoot:i,settings:r,typeToFolder:s});let d=0,l=await se({pmRoot:i,settings:r,id:t,op:a.length>0?"tests_add":"tests_remove",author:U(n.author,r.author_default),message:n.message,force:n.force,skipNoop:!0,mutate(u){let p=u.metadata.tests??[],g=MM(p,a,o,c);if(d=g.removed,(o.length>0||c.length>0)&&d===0)throw new _("No linked tests matched the requested removal selector",m.NOT_FOUND,{code:"linked_test_remove_no_match",unmatched:[...o.map(f=>`${f.kind}=${f.value}`),...c.map(f=>`index=${f}`)],required:"List linked tests and retry with an exact command/path or a current 1-based --remove-index.",examples:[`pm test ${t} --list`,`pm test ${t} --remove-index 1`]});return u.metadata.tests=g.tests,{changedFields:Fe(p,g.tests)?[]:["tests"]}}});return{itemId:l.item.id,tests:l.item.tests??[],testRuns:l.item.test_runs??[],changed:l.changedFields.length>0,removed:d}}function $M(e,t){zw(e);let n={match:e.match,onlyIndex:e.onlyIndex===void 0?void 0:xn(e.onlyIndex),onlyLast:e.onlyLast},i=e.run===!0?rw(t,n):void 0,r=e.timeout===void 0?void 0:ye(e.timeout,"timeout");if(r!==void 0&&r<=0)throw new _("Test timeout must be a positive number",m.USAGE);return{defaultTimeoutSeconds:r,pmContextMode:wa(e.pmContext),runSelection:i,testsToRun:i?.selected??t}}async function UM(e){let{options:t,runOptions:n,pmRoot:i}=e;return t.run!==!0?[]:await Rd(n.testsToRun,n.defaultTimeoutSeconds,{progress:t.progress,envSet:t.envSet,envClear:t.envClear,sharedHostSafe:t.sharedHostSafe,pmContext:n.pmContextMode,overrideLinkedPmContext:t.overrideLinkedPmContext,failOnContextMismatch:t.failOnContextMismatch,failOnEmptyTestRun:t.failOnEmptyTestRun===!0||(t.measure?.length??0)>0,requireAssertionsForPm:t.requireAssertionsForPm,checkContext:t.checkContext,autoPmContext:t.autoPmContext,workspaceContext:t.workspaceContext,overrideLinkedWorkspaceContext:t.overrideLinkedWorkspaceContext,pmRoot:i,allowUntrustedLinkedTests:t.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:e.untrustedLinkedTestsPolicyEnabled,sourceRoots:{projectPmRoot:i,globalPmRoot:qe(process.cwd())}})}function jM(e,t,n){let i=[];if(t&&t.selector!==null&&i.push(`linked_test_selection:${t.selector}=${t.requested};selected=${t.selected_count};skipped=${t.skipped_count};indexes=${t.selected_indexes.join(",")}`),e.run===!0&&e.checkContext===!0){let r=Cd(n);i.push(`context_preflight:checked_pm_commands=${r.checked_pm_commands};tracker_read_commands=${r.tracker_read_commands};mismatches=${r.mismatches};auto_remediated=${r.auto_remediated}`)}return i}function GM(e){let t=AN(e.runResults),n=Number.parseInt(process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim()??"",10),i=process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM?.trim(),r=O(),s=Ri(e.options.measure,r);return{run_id:TN("test"),kind:"test",status:t.failed>0||e.failOnSkippedTriggered?"failed":"passed",started_at:e.runStartedAt,finished_at:r,recorded_at:r,attempt:Number.isFinite(n)&&n>=1?n:void 0,resumed_from:i&&i.length>0?i:void 0,passed:t.passed,failed:t.failed,skipped:t.skipped,fail_on_skipped_triggered:e.failOnSkippedTriggered?!0:void 0,measurements:s.length>0?s:void 0,executions:e.runResults.filter(a=>a.command?.trim()).slice(0,32).map(a=>({command:a.command.trim(),requested_pm_context_mode:a.execution_context?.requested_pm_context_mode,pm_context_mode:a.execution_context?.pm_context_mode,workspace_context_mode:a.execution_context?.workspace_context_mode,trust_reason:a.execution_context?.trust.reason}))}}async function qM(e){let{options:t,pmRoot:n,settings:i,itemId:r,runStartedAt:s,runResults:a,failOnSkippedTriggered:o,warnings:c}=e;if(t.run!==!0||!s)return;let d=GM({options:t,runStartedAt:s,runResults:a,failOnSkippedTriggered:o});if(i.testing.record_results_to_items!==!0)return{entry:d,receipt:{recorded:!1,reason:"tracking_disabled",run_id:d.run_id,recovery_command:"pm config project set test-result-tracking --policy enabled"}};try{return await fa({pmRoot:n,settings:i,itemId:r,author:U(t.author,i.author_default),message:`Track test run summary (${d.run_id})`,entry:d}),{entry:d,receipt:{recorded:!0,reason:"recorded",run_id:d.run_id}}}catch(l){return c.push(`test_result_tracking_failed:${r}:${l instanceof Error?l.message:String(l)}`),{entry:d,receipt:{recorded:!1,reason:"write_failed",run_id:d.run_id}}}}function Rw(e,t,n){let i;if(e.metricBelow!==void 0){let r=e.metricBelow.indexOf("="),s=e.metricBelow.slice(0,r).trim(),a=e.metricBelow.slice(r+1).trim(),o=Number(a);if(r<=0||s.length===0||a.length===0||!Number.isFinite(o))throw new _("--metric-below must use name=value",m.USAGE);i=Kv(t,s,o)}return{measurements:n?.measurements,metric_below:i,metric_diff:e.metricDiff===void 0?void 0:zv(t,e.metricDiff)}}async function KM(e,t,n){if(e.acknowledgeLinkedTests===!0)return ch(t,n,O())}function zM(e){let{item:t,runResults:n,failureCategories:i,runSelection:r,failOnSkippedTriggered:s,warnings:a,recording:o,measurementProjection:c}=e;return{ok:n.every(d=>d.status!=="failed"&&d.status!=="refused")&&s!==!0,id:t.itemId,tests:t.tests,run_results:n,failure_categories:i,selection:r?{selector:r.selector,requested:r.requested,selected_indexes:r.selected_indexes,selected_count:r.selected_count,skipped_count:r.skipped_count}:void 0,fail_on_skipped_triggered:s?!0:void 0,warnings:a.length>0?a:void 0,changed:t.changed||o?.receipt.recorded===!0,...o?{evidence_recording:o.receipt}:{},count:t.tests.length,...t.removed>0?{removed:t.removed}:{},...c}}async function Ww(e,t,n){let i=sw(t);if(i)return aw(t),zw(t),hd(e,t,n,x(process.cwd(),n.path)),{...await ow(e,{...i,author:t.author,message:t.message,force:t.force},n),run_results:[],failure_categories:Ni([])};let r=cn(),s=x(process.cwd(),n.path);await $(s);let a=await I(s);hd(e,t,n,s),Ri(t.measure,"validation"),Rw(t,[],void 0);let o=F(a,P()),c=await r.resolveList(t.add,"--add"),d=await r.resolveList(t.addJson,"--add-json"),l=await r.resolveList(t.remove,"--remove"),u=[...$N(c),...GN(d)],p=await En(u,U(t.author,a.author_default),O())??[],g=qN(l),f=KN(t.removeIndex),h=await FM({id:e,options:t,pmRoot:s,settings:a,typeToFolder:o.type_to_folder,adds:p,removes:g,removeIndexes:f}),y=$M(t,h.tests),v=await KM(t,s,h.tests),w=t.run===!0?O():void 0,k=await UM({options:t,runOptions:y,pmRoot:s,untrustedLinkedTestsPolicyEnabled:a.testing.allow_untrusted_linked_tests});dw(e,t,n,s,k);let S=Ni(k),T=t.run===!0&&t.failOnSkipped===!0&&k.some(A=>A.status==="skipped"),C=jM(t,y.runSelection,k);v&&C.push(`linked_test_trust_acknowledged:${v.acknowledged}`);let b=await qM({options:t,pmRoot:s,settings:a,itemId:h.itemId,runStartedAt:w,runResults:k,failOnSkippedTriggered:T,warnings:C}),E=b?.receipt.recorded?bd([...h.testRuns,b.entry]):h.testRuns,N=Rw(t,E,b?.entry);return zM({item:h,runResults:k,failureCategories:S,runSelection:y.runSelection,failOnSkippedTriggered:T,warnings:C,recording:b,measurementProjection: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]="61f797d4-1c7c-52f2-83a9-818c2faca5ff")}catch{}})();var WM=(e,t)=>{if(e===void 0)return;let n=me(e,t);if(!n){let i=t.definitions.map(r=>r.id);throw new _(`Invalid --status value "${e}". Allowed: ${i.join(", ")}`,m.USAGE)}return n},BM=e=>{if(e===void 0)return;let t=ye(e,"timeout");if(t<=0)throw new _("timeout must be a positive number",m.USAGE);return t},Bw=(e,t)=>{if(e===void 0)return;let n=Number(e);if(!Number.isInteger(n)||n<0)throw new _(`${t} must be a non-negative integer`,m.USAGE);return n},HM=e=>e instanceof Error?e.message:String(e),VM=()=>{let e=process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();return e&&e.length>0?e:`test-all-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`},YM=e=>e.trim().replaceAll(/\s+/g," "),JM=e=>!e||Object.keys(e).length===0?"{}":JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))),XM=e=>!e||e.length===0?"[]":JSON.stringify([...e].sort((t,n)=>t.localeCompare(n))),QM=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"none"},ZM=e=>{let t=e?.trim().toLowerCase();return t&&t.length>0?t:"source"},ba=e=>[...new Set(e??[])].sort((t,n)=>t.localeCompare(n)),Hw=e=>Object.fromEntries(Object.entries(e??{}).sort(([t],[n])=>t.localeCompare(n))),eP=e=>typeof e=="number"?e:void 0,tP=e=>{let t={assert_stdout_contains:ba(e.assert_stdout_contains),assert_stdout_regex:ba(e.assert_stdout_regex),assert_stderr_contains:ba(e.assert_stderr_contains),assert_stderr_regex:ba(e.assert_stderr_regex),assert_stdout_min_lines:eP(e.assert_stdout_min_lines),assert_json_field_equals:Hw(e.assert_json_field_equals),assert_json_field_gte:Hw(e.assert_json_field_gte)};return JSON.stringify(t)},nP=e=>{let t=Od(e.command);return t!==void 0?`command:${e.scope}:${YM(t)}`:`path:${e.scope}:${Od(e.path)??""}`},Vw=e=>{let t=JM(e.env_set),n=XM(e.env_clear),i=QM(e.pm_context_mode),r=ZM(e.workspace_context_mode),s=e.shared_host_safe===!0?"true":"false",a=tP(e);return`${nP(e)}:${t}:${n}:${i}:${r}:${s}:${a}`},iP=(e,t)=>t===void 0?e:e===void 0||t>e?t:e,rP=e=>{let t=0,n=0,i=0;for(let r of e){if(r.status==="passed"){t+=1;continue}if(r.status==="failed"||r.status==="refused"){n+=1;continue}i+=1}return{passed:t,failed:n,skipped:i}},sP=(e,t)=>{for(let[n,i]of Object.entries(t))e[n]+=i},ka=(e,t)=>{if(e.progress===!0)try{process.stderr.write(`[pm test-all] ${t}
|
|
26
|
+
`)}catch{}},aP=async(e,t,n)=>{let i=[],r=0;for(let s of e){let a=await Ww(s.id,{run:!1},{...t,path:n});r+=a.tests.length,i.push({item:s,tests:a.tests})}return{itemTests:i,linkedTests:r}},oP=async e=>{let t=K(e.settings.schema),n=F(e.settings,P()),i=WM(e.options.status,t),r=Bw(e.options.limit,"--limit"),s=Bw(e.options.offset,"--offset")??0,a=(await Se(e.pmRoot,e.settings.item_format,n.type_to_folder,void 0,e.settings.schema)).filter(o=>i?o.status===i:!0).sort((o,c)=>o.id.localeCompare(c.id));return{filteredItems:r===void 0?a.slice(s):a.slice(s,s+r),statusFilter:i,limitFilter:r,offsetFilter:s}},cP=e=>{let t=new Map;for(let{tests:n}of e)for(let i of n){let r=Vw(i);if(!t.has(r)){t.set(r,i.timeout_seconds);continue}t.set(r,iP(t.get(r),i.timeout_seconds))}return t},dP=async(e,t)=>{let n=[],i=e.tests.map(l=>{let u=Vw(l),p=t.seenTestKeys.has(u);if(!p){t.seenTestKeys.add(u);let g=t.effectiveTimeoutByKey.get(u);n.push(g===void 0?l:{...l,timeout_seconds:g})}return{test:l,key:u,duplicate:p}}),r=n.length>0?await Rd(n,t.defaultTimeoutSeconds,{progress:t.options.progress,sourceRoots:t.sourceRoots,envSet:t.options.envSet,envClear:t.options.envClear,sharedHostSafe:t.options.sharedHostSafe,pmContext:t.options.pmContext,overrideLinkedPmContext:t.options.overrideLinkedPmContext,failOnContextMismatch:t.options.failOnContextMismatch,failOnEmptyTestRun:t.options.failOnEmptyTestRun,requireAssertionsForPm:t.options.requireAssertionsForPm,checkContext:t.options.checkContext,autoPmContext:t.options.autoPmContext,workspaceContext:t.options.workspaceContext,overrideLinkedWorkspaceContext:t.options.overrideLinkedWorkspaceContext,pmRoot:t.pmRoot,allowUntrustedLinkedTests:t.options.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:t.settings.testing.allow_untrusted_linked_tests}):[],s=0,a=i.map(({test:l,key:u,duplicate:p})=>{if(!p){let g=r[s];return s+=1,g}return{command:l.command,path:l.path,status:"skipped",error:`Duplicate linked test skipped (key=${u}).`}}),o=rP(a),c=Ni(a),d=await mP(e,o,a,t);return{passed:o.passed,failed:o.failed,skipped:o.skipped,trackingWarnings:d,failureCategories:c,result:{ok:o.failed===0&&!(t.options.failOnSkipped===!0&&o.skipped>0),id:e.item.id,status:e.item.status,test_count:e.tests.length,passed:o.passed,failed:o.failed,skipped:o.skipped,run_results:a,failure_categories:c}}},lP=(e,t)=>[e.failed>0,t.failOnSkipped===!0&&e.skipped>0].includes(!0),uP=e=>e?!0:void 0,mP=async(e,t,n,i)=>{if(!i.trackingEnabled)return[];try{let r=lP(t,i.options);await fa({pmRoot:i.pmRoot,settings:i.settings,itemId:e.item.id,author:i.trackingAuthor,message:`Track test-all run summary (${i.trackingRunId})`,entry:{run_id:i.trackingRunId,kind:"test-all",status:r?"failed":"passed",started_at:i.runStartedAt,finished_at:O(),recorded_at:O(),attempt:i.trackingAttempt,resumed_from:i.trackingResumedFrom,passed:t.passed,failed:t.failed,skipped:t.skipped,items:1,linked_tests:e.tests.length,fail_on_skipped_triggered:uP(i.options.failOnSkipped===!0&&t.skipped>0),executions:n.filter(s=>s.command?.trim()).slice(0,32).map(s=>({command:s.command.trim(),requested_pm_context_mode:s.execution_context?.requested_pm_context_mode,pm_context_mode:s.execution_context?.pm_context_mode,workspace_context_mode:s.execution_context?.workspace_context_mode,trust_reason:s.execution_context?.trust.reason}))}})}catch(r){return[`test_result_tracking_failed:${e.item.id}:${HM(r)}`]}return[]},_P=()=>{let e=process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim(),t=e?Number.parseInt(e,10):Number.NaN;return Number.isFinite(t)&&t>=1?t:void 0},Od=e=>{let t=e?.trim();return t&&t.length>0?t:void 0},pP=e=>({pmRoot:e.pmRoot,settings:e.settings,options:e.options,defaultTimeoutSeconds:e.defaultTimeoutSeconds,sourceRoots:{projectPmRoot:e.pmRoot,globalPmRoot:qe(process.cwd())},seenTestKeys:new Set,effectiveTimeoutByKey:cP(e.itemTests),trackingEnabled:e.settings.testing.record_results_to_items===!0,trackingAuthor:U(e.options.author,e.settings.author_default),trackingRunId:VM(),trackingAttempt:_P(),trackingResumedFrom:Od(process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM),runStartedAt:e.runStartedAt}),fP=(e,t,n)=>{let i={results:[],passed:0,failed:0,skipped:0,failureCategories:Ni([]),trackingWarnings:[]},r=e.failOnEmptyTestRun===!0&&t===0;return r&&(i.failed+=1,i.failureCategories.empty_run+=1,i.trackingWarnings.push(`empty_linked_test_selection:items=${n.length};linked_tests=0;fail_on_empty_test_run=true`)),{accumulation:i,failOnEmptyTestRunTriggered:r}},gP=async(e,t,n)=>{for(let[i,r]of e.entries()){ka(t.options,`item ${i+1}/${e.length} start id=${r.item.id} linked_tests=${r.tests.length}`);let s=await dP(r,t);sP(n.failureCategories,s.failureCategories),n.passed+=s.passed,n.failed+=s.failed,n.skipped+=s.skipped,n.trackingWarnings.push(...s.trackingWarnings),n.results.push(s.result),ka(t.options,`item ${i+1}/${e.length} end id=${r.item.id} status=${s.failed===0?"passed":"failed"} passed=${s.passed} failed=${s.failed} skipped=${s.skipped}`)}},hP=(e,t)=>{if(e.checkContext!==!0)return;let n=t.results.flatMap(r=>r.run_results),i=Cd(n);t.trackingWarnings.push(`context_preflight:checked_pm_commands=${i.checked_pm_commands};tracker_read_commands=${i.tracker_read_commands};mismatches=${i.mismatches};auto_remediated=${i.auto_remediated}`)},yP=e=>({ok:e.ok,totals:{items:e.filteredItems.length,linked_tests:e.linkedTests,passed:e.accumulation.passed,failed:e.accumulation.failed,skipped:e.accumulation.skipped,failure_categories:e.accumulation.failureCategories},failed:e.accumulation.failed,passed:e.accumulation.passed,skipped:e.accumulation.skipped,fail_on_skipped_triggered:e.failOnSkippedTriggered?!0:void 0,fail_on_empty_test_run_triggered:e.failOnEmptyTestRunTriggered?!0:void 0,warnings:e.accumulation.trackingWarnings.length>0?e.accumulation.trackingWarnings:void 0,results:e.accumulation.results}),vP=e=>[`selection items=${e.filteredItems.length}`,`linked_tests=${e.linkedTests}`,e.statusFilter===void 0?"":`status=${e.statusFilter}`,e.limitFilter===void 0?"":`limit=${e.limitFilter}`,e.offsetFilter>0?`offset=${e.offsetFilter}`:""].filter(t=>t.length>0).join(" "),wP=async(e,t)=>{let n=x(process.cwd(),t.path);await $(n);let i=await I(n),r=await oP({pmRoot:n,settings:i,options:e}),s=BM(e.timeout),a=O(),o=await aP(r.filteredItems,t,n);return ka(e,vP({...r,linkedTests:o.linkedTests})),{pmRoot:n,settings:i,filteredItems:r.filteredItems,itemTests:o.itemTests,linkedTests:o.linkedTests,defaultTimeoutSeconds:s,runStartedAt:a}},bP=e=>{let t=e.options.failOnSkipped===!0&&e.accumulation.skipped>0,n=![e.accumulation.failed>0,t,e.failOnEmptyTestRunTriggered].includes(!0);return{failOnSkippedTriggered:t,ok:n}},$5=async(e,t)=>{let n=await wP(e,t),{accumulation:i,failOnEmptyTestRunTriggered:r}=fP(e,n.linkedTests,n.filteredItems),s=pP({pmRoot:n.pmRoot,settings:n.settings,options:e,itemTests:n.itemTests,defaultTimeoutSeconds:n.defaultTimeoutSeconds,runStartedAt:n.runStartedAt});await gP(n.itemTests,s,i),hP(e,i);let a=bP({options:e,accumulation:i,failOnEmptyTestRunTriggered:r});return ka(e,`end status=${a.ok?"passed":"failed"} items=${n.filteredItems.length} linked_tests=${n.linkedTests} passed=${i.passed} failed=${i.failed} skipped=${i.skipped}`),yP({ok:a.ok,filteredItems:n.filteredItems,linkedTests:n.linkedTests,accumulation:i,failOnSkippedTriggered:a.failOnSkippedTriggered,failOnEmptyTestRunTriggered:r})};import XP from"node:os";import On from"node:fs/promises";import{spawn as Zw}from"node:child_process";import{createHash as kP,randomBytes as EP}from"node:crypto";import Pi 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]="7c89b3de-0b7c-529b-a655-87d3e83bd46c")}catch{}})();var eb=new Set(["queued","running"]),Md=new Set(["passed","failed","stopped","canceled"]),SP=3e3,TP=3e3,AP=3e4,tb=100,Yw=100;function nb(){return Date.now()}function ib(e){return e.map(t=>t.trim()).filter(t=>t.length>0)}function IP(e){let t=e.join(" ").replaceAll(/\s+/g," ").trim();return t.length<=180?t:`${t.slice(0,177)}...`}function CP(){let e=Date.now().toString(36),t=EP(3).toString("hex");return`tr-${e}-${t}`}function xP(e,t,n){let i={kind:e,command:ib(t),pm_root:Pi.resolve(n)};return kP("sha256").update(JSON.stringify(i)).digest("hex")}function Ln(e){if(!Number.isInteger(e)||!e||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return(typeof t=="object"&&t!==null&&"code"in t?t.code:void 0)==="EPERM"}}async function RP(e){await wt(wl(e)),await wt(Fa(e)),await wt(bl(e)),await wt(kl(e)),await wt(Tl(e))}async function rb(e,t){try{let n=JSON.parse(e);if(!n||typeof n!="object"||typeof n.id!="string")throw new Error("invalid run record payload");return n}catch(n){throw new _(`Failed to parse background test run record at ${t}: ${n instanceof Error?n.message:String(n)}`,m.GENERIC_FAILURE)}}async function nt(e,t){let n={...t,updated_at:O()};await Oe($a(e,t.id),`${JSON.stringify(n,null,2)}
|
|
27
|
+
`)}async function Dn(e,t){let n=$a(e,t),i=await Q(n);return i?rb(i,n):null}async function OP(e){let t=Fa(e);return await te(t)?(await On.readdir(t,{withFileTypes:!0})).filter(n=>n.isFile()&&n.name.endsWith(".json")).map(n=>Pi.join(t,n.name)).sort((n,i)=>i.localeCompare(n)):[]}function LP(e){let t=e.match(/^VmRSS:\s+(\d+)\s+kB$/m);if(t)return Number.parseInt(t[1],10)*1024}async function DP(e){if(process.platform==="linux")try{let t=await On.readFile(`/proc/${e}/status`,"utf8");return LP(t)}catch{return}}function NP(e){let t=e.lastIndexOf(")");if(t<0)return{};let n=e.slice(t+2).trim().split(/\s+/),i=Number.parseInt(n[11],10),r=Number.parseInt(n[12],10);return!Number.isFinite(i)||!Number.isFinite(r)?{}:{cpu_user_seconds:i/Yw,cpu_system_seconds:r/Yw}}async function MP(e){if(process.platform!=="linux")return{};try{let t=await On.readFile(`/proc/${e}/stat`,"utf8");return NP(t)}catch{return{}}}async function Dd(e){let t=e.child_pid??e.worker_pid;if(!Ln(t))return;let n=await DP(t),i=await MP(t),r=e.started_at?Date.parse(e.started_at):Number.NaN,s=Number.isFinite(r)?Math.max(0,(nb()-r)/1e3):void 0;return{recorded_at:O(),rss_bytes:n,cpu_user_seconds:i.cpu_user_seconds,cpu_system_seconds:i.cpu_system_seconds,uptime_seconds:s}}function Ld(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function PP(e,t){if(!t||typeof t!="object")return{summary:{passed:0,failed:1,skipped:0},parsedResult:null};let n=t;if(e==="test-all"){let o=n.totals??{};return{summary:{items:typeof o.items=="number"?o.items:void 0,linked_tests:typeof o.linked_tests=="number"?o.linked_tests:void 0,passed:Ld(o.passed),failed:Ld(o.failed),skipped:Ld(o.skipped),fail_on_skipped_triggered:n.fail_on_skipped_triggered===!0?!0:void 0},parsedResult:t}}let i=Array.isArray(n.run_results)?n.run_results:[],r=0,s=0,a=0;for(let o of i){if(!o||typeof o!="object")continue;let c=o.status;if(c==="passed"){r+=1;continue}if(c==="failed"||c==="refused"){s+=1;continue}a+=1}return{summary:{passed:r,failed:s,skipped:a,fail_on_skipped_triggered:n.fail_on_skipped_triggered===!0?!0:void 0},parsedResult:t}}function FP(e){let t=e.trim();if(t.length===0)return null;let n=t.match(/\[pm test-all\]\s+item\s+(\d+)\/(\d+)\s+(start|end)\s+id=([^\s]+)/i);if(n){let d=Number.parseInt(n[1],10),l=Number.parseInt(n[2],10);return{item_index:d,item_total:l,item_id:n[4],linked_test_index:void 0,linked_test_total:void 0,current_command:void 0,elapsed_ms:void 0,heartbeat_at:O(),phase:n[3]?.toLowerCase()==="end"?"finished":"running"}}let i=t.match(/\[pm test\]\s+linked-test\s+(\d+)\/(\d+)\s+(start|running|end)(?:.*elapsed_ms=(\d+))?/i);if(!i)return null;let r=Number.parseInt(i[1],10),s=Number.parseInt(i[2],10),a=i[4]?Number.parseInt(i[4],10):void 0,o=t.match(/\scommand="((?:\\.|[^"\\])*)"/),c=o?o[1].replaceAll('\\"','"').replaceAll("\\\\","\\"):void 0;return{linked_test_index:r,linked_test_total:s,current_command:c,elapsed_ms:Number.isFinite(a)?a:void 0,heartbeat_at:O(),phase:i[3]?.toLowerCase()==="end"?"finished":"running"}}function $P(e){return e.split(/\r?\n/).map(t=>t.trimEnd()).filter(t=>t.length>0)}function Nd(e,t){if(t<=0)return[];let n=$P(e);return n.length<=t?n:n.slice(n.length-t)}async function sb(e){let t=process.env.PM_BACKGROUND_CLI_ENTRY?.trim();if(t&&t.length>0){let r=Pi.resolve(e,t);if(await te(r))return r}let n=Pi.resolve(e,"dist","cli.js");if(await te(n))return n;let i=process.argv[1]?.trim();if(i&&i.length>0){let r=Pi.resolve(e,i);if(await te(r))return r}throw new _("Unable to resolve a CLI entrypoint for background test runs. Build the project or set PM_BACKGROUND_CLI_ENTRY.",m.GENERIC_FAILURE)}async function Fi(e,t){if(!eb.has(t.status)||Ln(t.worker_pid)||t.finished_at)return t;let n={...t,status:"failed",finished_at:O(),error:t.error??"Background test run worker exited before writing terminal status."};return await nt(e,n),n}async function Pd(e){await RP(e.pmRoot);let t=ib(e.commandArgs);if(t.length===0)throw new _("Background test run requires command arguments.",m.USAGE);let n=xP(e.kind,t,e.pmRoot),i=await $d(e.pmRoot,{});for(let l of i){let u=await Fi(e.pmRoot,l);if(u.fingerprint===n&&!(!eb.has(u.status)||!Ln(u.worker_pid)))return{started:!1,run:{...u,duplicate_of:u.id},duplicate_of:u.id}}let r=CP(),s=O(),a=El(e.pmRoot,r),o=Sl(e.pmRoot,r),c=Al(e.pmRoot,r);await On.writeFile(a,"","utf8"),await On.writeFile(o,"","utf8");let d={id:r,kind:e.kind,status:"queued",created_at:s,updated_at:s,requested_by:e.requestedBy,fingerprint:n,command_args:t,command_label:IP(t),pm_root:e.pmRoot,global_pm_root:e.globalPmRoot,target_id:e.targetId,status_filter:e.statusFilter,attempt:typeof e.attempt=="number"&&Number.isFinite(e.attempt)&&e.attempt>=1?Math.floor(e.attempt):1,resumed_from:e.resumedFrom,resumed_by:e.resumedBy,stdout_path:a,stderr_path:o,result_path:c,progress:{phase:"queued",message:"Queued for background execution.",heartbeat_at:s}};return await nt(e.pmRoot,d),{started:!0,run:d}}async function Fd(e){let t=await Dn(e.pmRoot,e.runId);if(!t)throw new _(`Background test run ${e.runId} not found`,m.NOT_FOUND);if(Md.has(t.status))throw new _(`Background test run ${t.id} is already terminal (${t.status}).`,m.CONFLICT);let n=await sb(process.cwd()),i=[];e.noExtensions===!0&&i.push("--no-extensions"),i.push("--path",t.pm_root,"test-runs-worker",t.id);let r={...process.env,PM_PATH:t.pm_root,PM_GLOBAL_PATH:t.global_pm_root,PM_BACKGROUND_TEST_RUN_ID:t.id,PM_BACKGROUND_TEST_RUN_ATTEMPT:String(t.attempt),PM_BACKGROUND_TEST_RUN_RESUMED_FROM:t.resumed_from??"",FORCE_COLOR:"0"},s=Zw(process.execPath,[n,...i],{cwd:process.cwd(),env:r,detached:!0,stdio:"ignore",windowsHide:!0});s.unref();let a={...t,status:"queued",worker_pid:s.pid,progress:{phase:"queued",message:"Worker process started.",heartbeat_at:O()}};return await nt(e.pmRoot,a),a}async function Jw(e,t,n){await e,await On.appendFile(t,n,"utf8")}function ab(e,t){let n=Number.parseInt(process.env[e]??"",10);return Number.isFinite(n)&&n>0?n:t}function UP(e){return{...process.env,PM_PATH:e.pm_root,PM_GLOBAL_PATH:e.global_pm_root,FORCE_COLOR:"0"}}function jP(e,t){return t?["--no-extensions",...e.command_args]:[...e.command_args]}function GP(e,t){let n=Promise.resolve();return{schedule(){n=n.then(async()=>{try{await nt(e,t)}catch{}})},async flush(){await n}}}function Xw(e,t){try{e.kill(t)}catch{}}async function qP(e,t,n,i){n.stopRequested||(n.stopRequested=!0,e.stop_requested_at=O(),e.progress={...e.progress,phase:"stopping",message:"Stop requested for background run.",heartbeat_at:O()},i(),Xw(t,"SIGTERM"),setTimeout(()=>Xw(t,"SIGKILL"),ab("PM_BACKGROUND_RUN_FORCE_KILL_DELAY_MS",TP)).unref?.())}function KP(e,t,n){return{phase:n,message:e,heartbeat_at:O(),item_index:t.item_index,item_total:t.item_total,item_id:t.item_id,linked_test_index:void 0,linked_test_total:void 0,current_command:void 0,elapsed_ms:void 0}}function zP(e,t,n,i){return{phase:i,message:e,heartbeat_at:O(),item_index:n.item_index??t.progress?.item_index,item_total:n.item_total??t.progress?.item_total,item_id:n.item_id??t.progress?.item_id,linked_test_index:n.linked_test_index,linked_test_total:n.linked_test_total,current_command:n.current_command,elapsed_ms:n.elapsed_ms}}function Qw(e,t,n){let i=FP(t);if(!i)return!1;let r=e.progress?.phase==="stopping"?"stopping":"running";return e.progress=i.item_id?KP(t,i,r):zP(t,e,i,r),i.phase==="finished"&&!n&&(e.progress.phase="running"),!0}function WP(e){if(e.trim().length===0)return null;try{return JSON.parse(e)}catch{return null}}function BP(e,t){return t?"stopped":e.exit_code===0&&(e.summary?.failed??0)===0&&e.summary?.fail_on_skipped_triggered!==!0?"passed":"failed"}function HP(e,t){return{phase:"finished",message:t?"Background run stopped.":`Background run finished with status=${e.status}.`,heartbeat_at:O(),item_index:e.progress?.item_index,item_total:e.progress?.item_total,item_id:e.progress?.item_id,linked_test_index:e.progress?.linked_test_index,linked_test_total:e.progress?.linked_test_total,current_command:e.progress?.current_command,elapsed_ms:e.progress?.elapsed_ms}}async function VP(e,t,n){if(t!==null){await Oe(e.result_path,`${JSON.stringify(t,null,2)}
|
|
28
|
+
`);return}await Oe(e.result_path,`${JSON.stringify({parse_error:"Background run output was not valid JSON.",stdout_excerpt:Nd(n,tb)},null,2)}
|
|
29
|
+
`)}async function ob(e,t,n=!1){let i=await Dn(e,t);if(!i)throw new _(`Background test run ${t} not found`,m.NOT_FOUND);let r={...i,status:"running",started_at:i.started_at??O(),worker_pid:process.pid,progress:{phase:"running",message:"Worker started.",heartbeat_at:O()}},s=await sb(process.cwd()),a=UP(r);await nt(e,r);let o=jP(r,n),c=Zw(process.execPath,[s,...o],{cwd:process.cwd(),env:a,detached:!1,stdio:["ignore","pipe","pipe"],windowsHide:!0});r.child_pid=c.pid;let d=GP(e,r),l=d.schedule,u=Promise.resolve(),p=Promise.resolve(),g="",f="",h={stopRequested:!1},y=()=>{qP(r,c,h,l)};process.on("SIGTERM",y),process.on("SIGINT",y);let v=setInterval(()=>{(async()=>(r.resource=await Dd(r),r.progress.heartbeat_at=O(),l()))()},ab("PM_BACKGROUND_RUN_RESOURCE_INTERVAL_MS",SP));v.unref?.(),c.stdout?.on("data",b=>{let E=b.toString("utf8");g+=E,u=Jw(u,r.stdout_path,E)}),c.stderr?.on("data",b=>{let E=b.toString("utf8");p=Jw(p,r.stderr_path,E),f+=E;let N=f.split(/\r?\n/);f=N.pop();let A=!1;for(let R of N){let G=R.trimEnd();G.length>0&&Qw(r,G,h.stopRequested)&&(A=!0)}A&&l()});let w=null,k=null;try{({code:w,signal:k}=await new Promise(b=>{c.on("close",(E,N)=>{b({code:E,signal:N})})}))}finally{clearInterval(v),process.off("SIGTERM",y),process.off("SIGINT",y)}await u,await p;let S=f.trimEnd();S.length>0&&Qw(r,S,h.stopRequested)&&l(),f="";let T=WP(g),C=PP(r.kind,T);return r.summary=C.summary,r.exit_code=typeof w=="number"?w:void 0,r.signal=k??void 0,r.finished_at=O(),r.status=BP(r,h.stopRequested),r.progress=HP(r,h.stopRequested),r.resource=await Dd(r),await VP(r,T,g),await nt(e,r),await d.flush(),r}async function $d(e,t){let n=await OP(e),i=[];for(let o of n){let c=await Q(o);if(!c)continue;let d=await rb(c,o);i.push(d)}let r=[];for(let o of i)r.push(await Fi(e,o));let s=(t.status?r.filter(o=>o.status===t.status):r).sort((o,c)=>{let d=Date.parse(c.updated_at)-Date.parse(o.updated_at);return Number.isFinite(d)&&d!==0?d:c.id.localeCompare(o.id)}),a=typeof t.limit=="number"&&t.limit>=0?t.limit:void 0;return a===void 0?s:s.slice(0,a)}async function cb(e,t){let n=await Dn(e,t);if(!n)throw new _(`Background test run ${t} not found`,m.NOT_FOUND);let i=await Fi(e,n),r=Ln(i.worker_pid),s=Ln(i.child_pid);i.status==="running"&&!s&&!i.finished_at&&!r&&(i.status="failed",i.finished_at=O(),i.error=i.error??"Background run process exited unexpectedly.",await nt(e,i)),i.status==="running"&&(i.resource=await Dd(i),await nt(e,i));let a=i.progress?.heartbeat_at,o=a?Date.parse(a):Number.NaN,c=Number.isFinite(o)?Math.max(0,nb()-o):void 0,d=Number.parseInt(process.env.PM_BACKGROUND_RUN_HEARTBEAT_STALE_MS??"",10),l=Number.isFinite(d)&&d>0?d:AP,u=i.status==="running"?c!==void 0&&c>l?"stale":"healthy":"inactive";return{run:i,health:{state:u,last_heartbeat_at:a,heartbeat_lag_ms:c,worker_alive:r,child_alive:s}}}function YP(e,t){let n=t?"SIGKILL":"SIGTERM";if(!Ln(e.worker_pid)||!e.worker_pid)return"none";try{return process.kill(e.worker_pid,n),n}catch{return"none"}}function JP(e,t){return{phase:"stopping",message:t==="none"?"Run marked stopped.":`Stop requested via ${t}.`,heartbeat_at:O(),item_index:e.progress?.item_index,item_total:e.progress?.item_total,item_id:e.progress?.item_id,linked_test_index:e.progress?.linked_test_index,linked_test_total:e.progress?.linked_test_total,current_command:e.progress?.current_command,elapsed_ms:e.progress?.elapsed_ms}}async function db(e,t,n=!1){let i=await Dn(e,t);if(!i)throw new _(`Background test run ${t} not found`,m.NOT_FOUND);let r=await Fi(e,i);if(Md.has(r.status))return{run:r,signal_sent:"none"};let s=YP(r,n);return s==="none"&&(r.status="stopped",r.finished_at=r.finished_at??O()),r.stop_requested_at=O(),r.progress=JP(r,s),await nt(e,r),{run:r,signal_sent:s}}async function lb(e,t,n,i=!1){let r=await Dn(e,t);if(!r)throw new _(`Background test run ${t} not found`,m.NOT_FOUND);let s=await Fi(e,r);if(!Md.has(s.status))throw new _(`Background test run ${t} is not terminal and cannot be resumed.`,m.CONFLICT);let a=await Pd({pmRoot:s.pm_root,globalPmRoot:s.global_pm_root,kind:s.kind,commandArgs:s.command_args,requestedBy:n,targetId:s.target_id,statusFilter:s.status_filter,resumedFrom:s.id,resumedBy:n,attempt:s.attempt+1});if(!a.started)return a.run;let o=await Fd({pmRoot:e,runId:a.run.id,noExtensions:i}),c={...s,resumed_by:o.id};return await nt(e,c),o}async function ub(e,t,n,i){let r=await Dn(e,t);if(!r)throw new _(`Background test run ${t} not found`,m.NOT_FOUND);let s=typeof i=="number"&&Number.isFinite(i)&&i>=0?Math.floor(i):tb,a=n==="stdout"||n==="both"?await Q(r.stdout_path)??"":"",o=n==="stderr"||n==="both"?await Q(r.stderr_path)??"":"";return{run:r,stream:n,tail:s,stdout:n==="stdout"||n==="both"?Nd(a,s):[],stderr:n==="stderr"||n==="both"?Nd(o,s):[]}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8e9a2374-d190-52e1-8afd-14e1954863f0")}catch{}})();var QP=["queued","running","passed","failed","stopped","canceled"],ZP=["stdout","stderr","both"];function eF(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(QP.includes(t))return t;throw new _(`Invalid --status value "${e}"`,m.USAGE)}function tF(e){if(e===void 0||e.trim().length===0)return"stderr";let t=e.trim().toLowerCase();if(ZP.includes(t))return t;throw new _(`Invalid --stream value "${e}"`,m.USAGE)}function nF(){try{let e=XP.userInfo().username.trim();if(e.length>0)return e}catch{}}function mb(e,t){let n=[e,uu(),t,process.env.USER,process.env.LOGNAME,process.env.USERNAME,nF()];for(let i of n){if(typeof i!="string")continue;let r=i.trim();if(r.length>0)return r}return"unknown"}async function Zt(e){await $(e)}async function s3(e,t){let n=x(process.cwd(),t.path),i=qe(process.cwd());await Zt(n);let r=await I(n),s=mb(e.author,r.author_default),a=await Pd({pmRoot:n,globalPmRoot:i,kind:e.kind,commandArgs:e.commandArgs,requestedBy:s,targetId:e.targetId,statusFilter:e.statusFilter});return a.started?{started:!0,run:await Fd({pmRoot:n,runId:a.run.id,noExtensions:e.noExtensions===!0})}:{started:!1,duplicate_of:a.duplicate_of,run:a.run}}async function a3(e,t){let n=x(process.cwd(),t.path);await Zt(n);let i=eF(e.status),r=zn(e.limit,"limit"),s=await $d(n,{status:i,limit:r});return{runs:s,count:s.length,filters:{status:i,limit:r}}}async function o3(e,t){let n=x(process.cwd(),t.path);await Zt(n);let i=await cb(n,e);return{run:i.run,health:i.health}}async function c3(e,t,n){let i=x(process.cwd(),n.path);await Zt(i);let r=tF(t.stream),s=zn(t.tail,"tail"),a=await ub(i,e,r,s);return{run:a.run,stream:a.stream,tail:a.tail,stdout:a.stdout,stderr:a.stderr}}async function d3(e,t,n){let i=x(process.cwd(),n.path);await Zt(i);let r=await db(i,e,t.force===!0);return{run:r.run,signal_sent:r.signal_sent}}async function l3(e,t,n){let i=x(process.cwd(),n.path);await Zt(i);let r=await I(i),s=mb(t.author,r.author_default),a=await lb(i,e,s,t.noExtensions===!0);return{resumed_from:e,run:a}}async function u3(e,t){let n=x(process.cwd(),t.path);await Zt(n);let i=await ob(n,e,t.noExtensions===!0);return{id:i.id,status:i.status,exit_code:i.exit_code}}export{dk as a,yp as b,rF as c,pk as d,pn as e,fk as f,cF as g,dF as h,go as i,lF as j,uF as k,mF as l,yk as m,_F as n,pF as o,fF as p,gF as q,bk as r,Tp as s,yF as t,Sp as u,Cp as v,Ik as w,Xn as x,Lk as y,Rp as z,Mk as A,CF as B,ho as C,Dp as D,Fk as E,LF as F,DF as G,Np as H,NF as I,MF as J,M as K,Le as L,et as M,fn as N,Mp as O,Fp as P,lt as Q,Qn as R,Wk as S,wo as T,bo as U,Gp as V,hn as W,ei as X,Eo as Y,l0 as Z,Hp as _,ti as $,So as aa,Pr as ba,To as ca,Yp as da,Jp as ea,Xp as fa,v$ as ga,Gr as ha,Oo as ia,L as ja,re as ka,C$ as la,yn as ma,Lo as na,x$ as oa,R$ as pa,Af as qa,O$ as ra,L$ as sa,D$ as ta,UE as ua,N$ as va,M$ as wa,Do as xa,P$ as ya,F$ as za,Ro as Aa,$$ as Ba,U$ as Ca,Cf as Da,j$ as Ea,n1 as Fa,qE as Ga,jt as Ha,i1 as Ia,KE as Ja,Rf as Ka,r1 as La,ri as Ma,s1 as Na,Of as Oa,YE as Pa,Mf as Qa,f1 as Ra,oi as Sa,g1 as Ta,nS as Ua,iS as Va,h1 as Wa,rS as Xa,jf as Ya,fS as Za,gS as _a,hS as $a,yS as ab,di as bb,vS as cb,_t as db,wS as eb,bS as fb,kS as gb,Po as hb,Fo as ib,ES as jb,zr as kb,Wr as lb,Gf as mb,zf as nb,rU as ob,NS as pb,MS as qb,Vf as rb,jo as sb,cU as tb,_U as ub,Qf as vb,eg as wb,OU as xb,LU as yb,li as zb,Jr as Ab,rg as Bb,sg as Cb,ag as Db,og as Eb,ug as Fb,oT as Gb,dT as Hb,lT as Ib,uT as Jb,gg as Kb,hg as Lb,yg as Mb,Qr as Nb,Zr as Ob,qg as Pb,aG as Qb,Kg as Rb,Wg as Sb,Bg as Tb,Yg as Ub,Xg as Vb,uc as Wb,gi as Xb,hi as Yb,nI as Zb,En as _b,sh as $b,hc as ac,oh as bc,ch as cc,RI as dc,lK as ec,ry as fc,wi as gc,oy as hc,cy as ic,dy as jc,Nc as kc,$C as lc,BK as mc,py as nc,fz as oc,vz as pc,ZC as qc,gy as rc,$c as sc,hy as tc,px as uc,ks as vc,Es as wc,Ts as xc,Cy as yc,Bt as zc,Cs as Ac,Wt as Bc,Ay as Cc,ki as Dc,Ei as Ec,xs as Fc,Rs as Gc,Ht as Hc,Vt as Ic,An as Jc,Os as Kc,Ls as Lc,Ds as Mc,Ms as Nc,Vs as Oc,Dx as Pc,Uc as Qc,XW as Rc,Xy as Sc,lO as Tc,CO as Uc,RO as Vc,ra as Wc,C2 as Xc,_v as Yc,yL as Zc,ed as _c,B2 as $c,td as ad,sB as bd,aB as cd,oB as dd,wv as ed,EB as fd,CL as gd,cd as hd,xL as id,RL as jd,OL as kd,SB as ld,TB as md,$B as nd,UB as od,jB as pd,Pv as qd,Fv as rd,WL as sd,$v as td,cH as ud,Uv as vd,dH as wd,lH as xd,oa as yd,cD as zd,hH as Ad,ld as Bd,yH as Cd,ud as Dd,dD as Ed,Ri as Fd,Kv as Gd,zv as Hd,GH as Id,Hv as Jd,tV as Kd,nV as Ld,ow as Md,hd as Nd,Cd as Od,b5 as Pd,eM as Qd,Ni as Rd,sM as Sd,Rd as Td,Ww as Ud,$5 as Vd,s3 as Wd,a3 as Xd,o3 as Yd,c3 as Zd,d3 as _d,l3 as $d,u3 as ae};
|
|
30
|
+
//# sourceMappingURL=chunk-QBNEZII5.js.map
|