@unbrained/pm-cli 2026.10.30 → 2026.11.1
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/.agents/skills/pm-user/references/ECOSYSTEM_PLANNING.md +1 -1
- package/.claude-plugin/marketplace.json +1 -1
- package/AGENTS.md +3 -3
- package/CHANGELOG.md +41 -0
- package/README.md +1 -1
- package/dist/cli/commander-usage.js +2 -2
- package/dist/cli/error-guidance.d.ts +45 -5
- package/dist/cli/error-guidance.js +5 -3
- package/dist/cli/extension-command-help.d.ts +1 -0
- package/dist/cli/extension-command-help.js +2 -2
- package/dist/cli/main.d.ts +1 -5
- package/dist/cli/main.js +5 -5
- package/dist/cli/migration-gates.d.ts +1 -1
- package/dist/cli/migration-gates.js +1 -1
- package/dist/cli/preflight-warnings.d.ts +11 -0
- package/dist/cli/preflight-warnings.js +4 -0
- package/dist/cli/register-mutation.js +2 -2
- package/dist/cli/register-operations.d.ts +3 -3
- package/dist/cli/register-operations.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/chunk-2GK2IVU5.js +8 -0
- package/dist/cli-bundle/chunks/chunk-5KW4WUAK.js +6 -0
- package/dist/cli-bundle/chunks/chunk-5WVE7XBS.js +114 -0
- package/dist/cli-bundle/chunks/chunk-6PKWKVS6.js +8 -0
- package/dist/cli-bundle/chunks/chunk-E74BORFX.js +128 -0
- package/dist/cli-bundle/chunks/chunk-F3ECOBKA.js +2 -0
- package/dist/cli-bundle/chunks/chunk-ICT6E4IW.js +2 -0
- package/dist/cli-bundle/chunks/chunk-MP2DQJH2.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-LWW4F4G2.js → chunk-MRUA2Z43.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-UUQX3PFD.js → chunk-MTRIGD7M.js} +76 -76
- package/dist/cli-bundle/chunks/{chunk-S2U7ECUJ.js → chunk-N45IXPCA.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-MVL27TAH.js → chunk-NILQ2ZMV.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-GRABKNFL.js → chunk-O56O7NIE.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-O6TFUV6M.js +31 -0
- package/dist/cli-bundle/chunks/{chunk-TH5KPAN4.js → chunk-SBVX5CMV.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-Y6NC3X3E.js → chunk-TMPO4CTZ.js} +3 -3
- package/dist/cli-bundle/chunks/chunk-TYERATXH.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-EHBGHX55.js → chunk-UEEG47TU.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-UUN3WNMQ.js +20 -0
- package/dist/cli-bundle/chunks/chunk-WFBYKDB2.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-RZQNFHXO.js → chunk-WX25MU4N.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-4BQD5SW2.js → chunk-Y7CKVU56.js} +30 -30
- package/dist/cli-bundle/chunks/{indexed-receipt-blobs-LHLE7PSG.js → indexed-receipt-blobs-KGMJVFH2.js} +2 -2
- package/dist/cli-bundle/chunks/item-transaction-Q5S5YLEJ.js +2 -0
- package/dist/cli-bundle/chunks/{mutation-admission-TRGAVS7N.js → mutation-admission-BOOCJPCU.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-BH4F6M7Z.js → register-list-query-23OX36Q3.js} +3 -3
- package/dist/cli-bundle/chunks/register-mutation-JPJ5YNDX.js +20 -0
- package/dist/cli-bundle/chunks/register-operations-IGR7ERY5.js +2 -0
- package/dist/cli-bundle/chunks/{register-setup-QPWSVHFZ.js → register-setup-BMIFKZZP.js} +2 -2
- package/dist/cli-bundle/chunks/{settlement-hook-MN3Y7LVX.js → settlement-hook-YWSWFOZY.js} +2 -2
- package/dist/cli-bundle/chunks/{stage-RTB6RAAO.js → stage-ON7CYYPM.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-POJPJX64.js → chunk-2Y77HWIX.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-SAT7IAEB.js → chunk-3NYWMUX3.js} +3 -3
- package/dist/cli-bundle/focused-chunks/chunk-3Z53POXU.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-5TWS5KOM.js +26 -0
- package/dist/cli-bundle/focused-chunks/chunk-5WCQFH6D.js +12 -0
- package/dist/cli-bundle/focused-chunks/{chunk-S23ZUASN.js → chunk-6GMYW42K.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-YQUZL2CK.js → chunk-6OKPYCLU.js} +5 -5
- package/dist/cli-bundle/focused-chunks/chunk-7WJDRZOR.js +22 -0
- package/dist/cli-bundle/focused-chunks/{chunk-3SRX77ES.js → chunk-AL7SOFUL.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-CIQ6YWCW.js +26 -0
- package/dist/cli-bundle/focused-chunks/{chunk-RKPUQDWF.js → chunk-DFUTCKUF.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-RYEZSZJ7.js → chunk-GE755ODZ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-JCR32IAO.js +91 -0
- package/dist/cli-bundle/focused-chunks/{chunk-BPE6JTKL.js → chunk-JLXGRDTG.js} +3 -3
- package/dist/cli-bundle/focused-chunks/chunk-LVA76N27.js +6 -0
- package/dist/cli-bundle/focused-chunks/{chunk-YU7QOYYV.js → chunk-M22TI7LP.js} +3 -3
- package/dist/cli-bundle/focused-chunks/chunk-PAT6QF63.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-VFWCSQAG.js → chunk-RPUDOJVB.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-SXZM4PSS.js +44 -0
- package/dist/cli-bundle/focused-chunks/chunk-UQIBGLDR.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-RGQEJFXO.js → chunk-VFQAZLKO.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-BCIUAEWX.js → chunk-VS2ZFPXD.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-FRFNGMAK.js → chunk-WX2RVS2Y.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-Z7GIVH6B.js +3 -0
- package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-VK2363JB.js → indexed-receipt-blobs-KHWT44EK.js} +2 -2
- package/dist/cli-bundle/focused-chunks/item-transaction-7VLPA2SU.js +2 -0
- package/dist/cli-bundle/focused-chunks/{mutation-admission-7VUODEPJ.js → mutation-admission-2DH27R5Y.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{settlement-hook-OK6A7PG2.js → settlement-hook-SJV52ZTV.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{stage-S5RP5SZH.js → stage-FYOBWQA7.js} +2 -2
- package/dist/cli-bundle/main.js +26 -22
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +4 -4
- package/dist/cli-bundle/sdk-core.js +1 -1
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-graph.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +57 -57
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +11 -11
- package/dist/core/config/nested-settings.js +1 -1
- package/dist/core/extensions/extension-hook-runtime.js +1 -1
- package/dist/core/extensions/extension-types.d.ts +4 -0
- package/dist/core/extensions/extension-types.js +1 -1
- package/dist/core/extensions/loader.js +1 -1
- package/dist/core/lock/lock.js +4 -4
- package/dist/core/output/mutation-projection.js +1 -1
- package/dist/core/output/output.js +3 -3
- package/dist/core/schema/fields-file.js +1 -1
- package/dist/core/sentry/helpers.d.ts +6 -0
- package/dist/core/sentry/helpers.js +1 -1
- package/dist/core/sentry/instrument.d.ts +1 -1
- package/dist/core/sentry/instrument.js +1 -1
- package/dist/core/shared/constants.js +1 -1
- package/dist/core/shared/errors.d.ts +6 -0
- package/dist/core/shared/errors.js +1 -1
- package/dist/core/shared/output-unicode.d.ts +10 -0
- package/dist/core/shared/output-unicode.js +2 -0
- package/dist/core/store/settings-validator.d.ts +1 -0
- package/dist/core/store/settings-validator.js +1 -1
- package/dist/core/store/settings.js +1 -1
- package/dist/core/telemetry/policy.d.ts +8 -0
- package/dist/core/telemetry/policy.js +1 -1
- package/dist/core/telemetry/runtime.js +3 -3
- package/dist/sdk/agent/command-recovery.d.ts +15 -0
- package/dist/sdk/agent/command-recovery.js +1 -1
- package/dist/sdk/cli-bootstrap.js +1 -1
- package/dist/sdk/cli-contracts/agent-output-contracts.d.ts +28 -0
- package/dist/sdk/cli-contracts/agent-output-contracts.js +2 -2
- package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1
- package/dist/sdk/cli-contracts/flag-contracts.d.ts +2 -0
- package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
- package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
- package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
- package/dist/sdk/cli-contracts/tool-schema.js +1 -1
- package/dist/sdk/cli-contracts.d.ts +1 -1
- package/dist/sdk/cli-contracts.js +1 -1
- package/dist/sdk/completion/fish.js +4 -4
- package/dist/sdk/completion/zsh.js +3 -3
- package/dist/sdk/config.d.ts +1 -0
- package/dist/sdk/config.js +1 -1
- package/dist/sdk/context-intent-contracts.d.ts +17 -0
- package/dist/sdk/context-intent-contracts.js +1 -1
- package/dist/sdk/core.d.ts +2 -1
- package/dist/sdk/core.js +1 -1
- package/dist/sdk/error-runtime.d.ts +9 -0
- package/dist/sdk/error-runtime.js +1 -1
- package/dist/sdk/errors.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/index.d.ts +3 -3
- package/dist/sdk/index.js +1 -1
- package/dist/sdk/init-agent-guidance.js +2 -2
- package/dist/sdk/lifecycle/claim.d.ts +27 -0
- package/dist/sdk/lifecycle/claim.js +1 -1
- package/dist/sdk/lifecycle/close.js +1 -1
- package/dist/sdk/lifecycle/create.js +1 -1
- package/dist/sdk/lifecycle/mcp-actions.d.ts +1 -1
- package/dist/sdk/lifecycle/mcp-actions.js +1 -1
- package/dist/sdk/lifecycle/plan.d.ts +2 -3
- package/dist/sdk/lifecycle/plan.js +1 -1
- package/dist/sdk/lifecycle/repeated-terminal-state.d.ts +45 -0
- package/dist/sdk/lifecycle/repeated-terminal-state.js +2 -0
- package/dist/sdk/lifecycle/shared-unset-fields.d.ts +9 -0
- package/dist/sdk/lifecycle/shared-unset-fields.js +1 -1
- package/dist/sdk/lifecycle/task-composition.js +1 -1
- package/dist/sdk/lifecycle/update-many.d.ts +0 -1
- package/dist/sdk/lifecycle/update-many.js +1 -1
- package/dist/sdk/lifecycle/update.d.ts +29 -1
- package/dist/sdk/lifecycle/update.js +2 -2
- package/dist/sdk/output/list-envelope.d.ts +8 -0
- package/dist/sdk/output/list-envelope.js +1 -1
- package/dist/sdk/output/table-rows.d.ts +7 -1
- package/dist/sdk/output/table-rows.js +1 -1
- package/dist/sdk/output.d.ts +2 -1
- package/dist/sdk/output.js +2 -2
- package/dist/sdk/ownership-source.d.ts +18 -0
- package/dist/sdk/ownership-source.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/context.js +2 -2
- package/dist/sdk/query/get.d.ts +1 -1
- package/dist/sdk/query/get.js +1 -1
- package/dist/sdk/query/next-ranking-policy.d.ts +35 -0
- package/dist/sdk/query/next-ranking-policy.js +2 -0
- package/dist/sdk/query/next.d.ts +12 -2
- package/dist/sdk/query/next.js +2 -2
- package/dist/sdk/query/projection-contracts.d.ts +4 -0
- package/dist/sdk/query/projection-contracts.js +1 -1
- package/dist/sdk/read-output/surfaces.d.ts +27 -0
- package/dist/sdk/read-output/surfaces.js +2 -0
- package/dist/sdk/read-output-contracts.js +1 -1
- package/dist/sdk/runtime/actions.js +1 -1
- package/dist/sdk/runtime-input.js +1 -1
- package/dist/sdk/runtime-primitives.d.ts +1 -0
- package/dist/sdk/runtime-primitives.js +1 -1
- package/dist/sdk/runtime-public-contracts.d.ts +2 -0
- package/dist/sdk/runtime.d.ts +2 -2
- package/dist/sdk/runtime.js +1 -1
- package/dist/sdk/start-task-status.d.ts +1 -1
- package/dist/sdk/start-task-status.js +1 -1
- package/dist/sdk/test/execution-receipts.d.ts +25 -0
- package/dist/sdk/test/execution-receipts.js +2 -2
- package/dist/sdk/test/execution.d.ts +5 -0
- package/dist/sdk/test/execution.js +2 -2
- package/dist/types.d.ts +2 -0
- package/dist/types.js +1 -1
- package/docs/AGENT_GUIDE.md +4 -4
- package/docs/AGENT_OUTPUT_ENCODINGS.md +12 -0
- package/docs/AGENT_UX_CONTRACTS.md +2 -1
- package/docs/COMMANDS.md +59 -5
- package/docs/COMMAND_NAMESPACES.md +1 -1
- package/docs/CONFIGURATION.md +48 -1
- package/docs/DEVELOPMENT_DEPENDENCY_SECURITY.md +26 -0
- package/docs/LIFECYCLE_COMMANDS.md +19 -4
- package/docs/PACKED_FIRST_RUN.md +2 -1
- package/docs/READ_OUTPUT_CONTRACTS.md +24 -6
- package/docs/SDK.md +82 -3
- package/docs/SDK_ACTION_CONFORMANCE.md +21 -0
- package/docs/TESTING.md +38 -2
- package/docs/agent-task-token-baseline.json +1 -1
- package/docs/agent-task-transcripts.json +1 -1
- package/marketplace.json +1 -1
- package/package.json +1 -1
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/extensions/calendar/index.ts +1 -0
- 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-34MP7WKK.js +0 -6
- package/dist/cli-bundle/chunks/chunk-3KMYHYJV.js +0 -2
- package/dist/cli-bundle/chunks/chunk-42BHHNTL.js +0 -128
- package/dist/cli-bundle/chunks/chunk-I5O3XZOA.js +0 -2
- package/dist/cli-bundle/chunks/chunk-LEIVUGDH.js +0 -8
- package/dist/cli-bundle/chunks/chunk-OH7WPD42.js +0 -114
- package/dist/cli-bundle/chunks/chunk-OOD2A7AF.js +0 -20
- package/dist/cli-bundle/chunks/chunk-Q5V7P6NM.js +0 -2
- package/dist/cli-bundle/chunks/chunk-QLPFYBXN.js +0 -2
- package/dist/cli-bundle/chunks/chunk-SA5NYLPE.js +0 -8
- package/dist/cli-bundle/chunks/chunk-VHLAVTJN.js +0 -31
- package/dist/cli-bundle/chunks/chunk-XAOVJG52.js +0 -3
- package/dist/cli-bundle/chunks/chunk-XPQ4RTSF.js +0 -2
- package/dist/cli-bundle/chunks/item-transaction-WIOBZW4E.js +0 -2
- package/dist/cli-bundle/chunks/register-mutation-5V2NANIS.js +0 -20
- package/dist/cli-bundle/chunks/register-operations-XSFRMUFX.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-2V6NMNYN.js +0 -26
- package/dist/cli-bundle/focused-chunks/chunk-ASHGXMX4.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-CKBN2D42.js +0 -12
- package/dist/cli-bundle/focused-chunks/chunk-I642DXOT.js +0 -22
- package/dist/cli-bundle/focused-chunks/chunk-K7DKG5HM.js +0 -91
- package/dist/cli-bundle/focused-chunks/chunk-NMQBXU7N.js +0 -44
- package/dist/cli-bundle/focused-chunks/chunk-PGM3ENGZ.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-QFNV4JTA.js +0 -6
- package/dist/cli-bundle/focused-chunks/chunk-QVJCQMZY.js +0 -26
- package/dist/cli-bundle/focused-chunks/chunk-R2TPPPVU.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-VJVJ2ZX2.js +0 -2
- package/dist/cli-bundle/focused-chunks/item-transaction-ZFDKJIP7.js +0 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{c as St,d as dn,e as ln,f as un,g as Nl,j as jl}from"./chunk-SAT7IAEB.js";import{a as Ll}from"./chunk-RKPUQDWF.js";import{i as Q,m as Za,x as Cl}from"./chunk-FRFNGMAK.js";import{a as ja,c as zi,d as Wi,e as ed,g as td,h as Ua,i as nd,j as Kt,k as Yt,l as id,m as rd,n as Ha,o as sd,p as Xt,q as Zt,r as cd,s as dd,t as za}from"./chunk-QFNV4JTA.js";import{a as qa}from"./chunk-SVOOGGAK.js";import{B as bd,C as Vi,D as kd,E as Wa,G as Ed,H as Sd,J as xd,K as Id,L as Ki,U as Yi}from"./chunk-ASHGXMX4.js";import{K as Ml}from"./chunk-VFWCSQAG.js";import{A as Pl,I as eo,w as Dl,y as Qa,z as Ol}from"./chunk-RYEZSZJ7.js";import{Aa as cn,Ba as kl,Ca as El,Da as Sl,Ea as Xa,G as Td,K as $d,L as Dd,M as Od,P as dr,Ra as xl,Sa as Il,Wa as Rl,Xa as Al,da as ur,ea as tl,fa as Va,ga as Bn,ia as Ka,j as Xi,ma as pl,n as Hn,na as fl,o as Rd,oa as hl,p as Ad,pa as _l,q as zn,qa as fr,sa as gl,ta as yl,ua as wl,va as Mt,wa as vl,xa as sn,ya as bl,z as Cd,za as Ya}from"./chunk-I642DXOT.js";import{a as Yc,b as Vt,c as Fa,d as Xc,e as Zc,f as it,g as qi,h as Qc,i as wt}from"./chunk-S23ZUASN.js";import{m as Jn,o as hr,v as Tl,y as $l}from"./chunk-PGM3ENGZ.js";import{C as mr,E as ll,F as ge,G as ye,H as ul,I as pr,J as rt,K as at,O as ml,P as ot,a as Zi,c as Yd,j as nl,k as il,m as rl,n as al,o as Et,p as ol,q as sl,w as cl,x as dl}from"./chunk-K7DKG5HM.js";import{$a as T,Aa as tn,Ba as Vd,Da as or,Ea as sr,Fa as qn,Ga as kt,Ha as Gn,Ia as Kd,Ja as cr,Ka as Nt,La as te,Ma as nn,Na as Xd,Oa as Ja,Pa as rn,Qa as an,Ra as on,Ta as Zd,Ua as Qd,Xa as je,_a as el,a as Pd,ab as lr,ba as z,ca as Hd,d as Re,da as Me,e as Ga,ea as zd,eb as ne,f as Ld,k as Qi,ka as Wd,l as Wn,la as Ba,m as Nd,ma as ir,n as er,na as en,o as Md,pa as rr,q as tr,qa as qd,r as nr,ra as Gd,t as jd,ta as Bd,u as $e,va as Jd,x as bt,y as Fd,ya as ar,z as Ud}from"./chunk-YU7QOYYV.js";import{b as Gt}from"./chunk-3SRX77ES.js";import{a as se,c as Te,e as Ie,f as Ke,j as fe,k as ad,l as Gi,n as od}from"./chunk-RGQEJFXO.js";import{Ad as Qt,Ba as Mc,Bb as Bc,Bd as vt,Ca as Ot,Cb as Jc,Cc as _d,Cd as Lt,Dc as le,Ea as jc,Fa as A,Ga as Fc,Ha as xe,Hd as yd,Ja as Hi,Ka as Uc,Kb as Vc,Kd as wd,La as Pa,Lb as Pt,Ld as vd,Ma as La,Md as re,Na,Nb as Ma,O as $c,Ob as Kc,Pa as Hc,Pb as Jt,Qa as zc,R as Dc,Rb as Je,T as Oa,Ta as Wc,Tb as Ve,Wb as ld,Y as me,Yb as Bi,Z as Ge,Zb as ud,_ as Oc,_b as md,a as Ec,aa as Y,ac as pd,bb as qc,d as Sc,da as Pc,e as xc,ic as F,kb as Gc,mc as K,o as Da,oa as Lc,oc as Ne,pa as Nc,pc as fd,qa as H,qc as Ji,va as Un,wa as M,xa as Be,xc as hd,ya as Ui,yd as $,za as Bt,zd as gd}from"./chunk-2V6NMNYN.js";import{a as _r,b as Vn}from"./chunk-EGN2HFRU.js";import{A as g,B as Fn,C as D,D as yt,E as j,F as B,I as Z,a as Mi,d as ji,p as Ic,r as Rc,t as Ac,v as Cc,w as Fi,x as Tc,z as y}from"./chunk-BPE6JTKL.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]="081bf1eb-4b9a-5fa9-a272-34ae781d250c")}catch{}})();var L=class extends TypeError{constructor(t){super(t),this.name="AssuranceMutationRefusalError"}},we=class extends TypeError{context;constructor(t,n={}){super(t),this.name="AssuranceEvaluationRefusalError",this.context=n}},Ye=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 mn(e){try{return await e()}catch(t){throw t instanceof L?new g(t.message,y.USAGE,{code:"invalid_argument_value",reason:"assurance_mutation_refused"}):t}}async function to(e){try{return await e()}catch(t){throw t instanceof we?new g(t.message,y.USAGE,{code:"invalid_argument_value",reason:"assurance_evaluation_refused",...t.context}):t}}import{createHash as gg}from"node:crypto";import yg 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 pn=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]="eaede7d4-43ae-5551-915e-19befefc29d0")}catch{}})();var Ul=1,jt=["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"],no=["items","dependency_kind","prose_edge_gap","graph","validate","health","history","links","provider","derived"],wg=["ceiling","floor","equals","zero","monotone_nondecreasing","monotone_nonincreasing","subset_of"],vg=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,gr=30,yr=5e3,Hl=4,bg=50;function st(e,t){if(!vg.test(e))throw new L(`${t} must be a stable lowercase id`)}function kg(e,t){if(!Number.isFinite(e)||e<0)throw new L(`${t} must be a finite non-negative number`)}function Kn(e){let t=wg.filter(r=>e[r]!==void 0);if(t.length!==1)throw new L(`assertion ${e.id} must declare exactly one polarity`);let n=t[0],i=e[n];return{polarity:n,value:n==="zero"?0:i}}function ro(e,t){return A(e)===A(t)}function zl(e,t){if(t.polarity==="equals")return ro(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 Wl(e){let t=Kn(e),n=e.negative_control.cases;return n.some(i=>i.expected==="pass")&&n.some(i=>i.expected==="fail")&&n.every(i=>zl(i.observed,t)===(i.expected==="pass"))}function Eg(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!ro(e.value,t.value)}function Sg(e,t){if(e.measurement_id!==t.measurement_id||e.owner_item_id!==t.owner_item_id||A(e.scope)!==A(t.scope))return!0;let n={observe:0,warn:1,block:2},i=(e.lifetime??"hold")==="hold"&&(t.lifetime??"hold")==="retire";return Eg(Kn(e),Kn(t))||n[t.enforcement]<n[e.enforcement]||i}function xg(e){if(e.state!==void 0&&!(e.state==="present"||e.state==="missing"))throw new L("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 L("items source with field requires exactly one of equals or state");if(e.field===void 0&&i!==0)throw new L("items source equals/state requires field")}function Ig(e){if(typeof e.dependency_kind!="string"||e.dependency_kind.trim().length===0)throw new L("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 L("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 L("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 L("dependency_kind source source_kind_state must be present or missing")}function Rg(e){if(e.sample_limit!==void 0&&(!Number.isInteger(e.sample_limit)||e.sample_limit<1))throw new L("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 L("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 L("prose_edge_gap exemption selectors must not be empty")}}function ao(e){st(e.id,"measurement.id"),e.max_cost!==void 0&&kg(e.max_cost,"measurement.max_cost");let t=e.source;if(Object.prototype.toString.call(t)!=="[object Object]")throw new L(`measurement.source.kind must be one of ${no.join(", ")}`);let n=Reflect.get(t,"kind");if(!no.includes(n))throw new L(`measurement.source.kind must be one of ${no.join(", ")}`);let i=t;if(i.kind==="items"&&xg(i),i.kind==="dependency_kind"&&Ig(i),i.kind==="prose_edge_gap"&&Rg(i),(i.kind==="graph"||i.kind==="validate"||i.kind==="health")&&(typeof i.field!="string"||i.field.trim().length===0))throw new L(`${i.kind} source requires field`);return i.kind==="provider"&&(st(i.provider,"provider source provider"),st(i.key,"provider source key")),e}function oo(e){if(st(e.id,"assertion.id"),st(e.measurement_id,"assertion.measurement_id"),typeof e.owner_item_id!="string"||e.owner_item_id.trim().length===0)throw new L("assertion.owner_item_id is required");let t=Kn(e);if(typeof t.value=="number"&&!Number.isFinite(t.value))throw new L(`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 L("retired assertion requires retire_reason");e.scope.kind==="filter"&&st(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 L("assertion negative control requires pass and fail cases");if(!Wl(e))throw new L(`assertion ${e.id} negative control does not prove its bound`);return e}function Ag(e){if(!Array.isArray(e.allowed_providers))throw new L("gate provider_policy.allowed_providers must be an array");for(let t of e.allowed_providers)st(t,"gate.provider_policy.allowed_provider");if(typeof e.triggers!="object"||e.triggers===null||Array.isArray(e.triggers))throw new L("gate provider_policy.triggers must be an object");for(let[t,n]of Object.entries(e.triggers)){if(!jt.includes(t))throw new L(`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 L(`gate provider policy trigger ${t} is invalid`)}}function ql(e){if(st(e.id,"gate.id"),!Array.isArray(e.assertion_ids))throw new L("gate.assertion_ids is required and must be an array");if(e.assertion_ids.length===0)throw new L("gate requires at least one assertion");for(let t of e.assertion_ids)st(t,"gate.assertion_id");if(!Array.isArray(e.triggers))throw new L(`gate.triggers is required and must be an array of ${jt.join(", ")}`);if(e.triggers.length===0)throw new L("gate requires at least one trigger");for(let t of e.triggers)if(!jt.includes(t))throw new L(`gate trigger must be one of ${jt.join(", ")}`);return e.provider_policy&&Ag(e.provider_policy),e}function fn(e){if(e.version!==Ul)throw new L(`unsupported assurance document version ${String(e.version)}`);let t=new Set;for(let i of e.measurements){if(ao(i),t.has(`measurement:${i.id}`))throw new L(`duplicate measurement ${i.id}`);t.add(`measurement:${i.id}`)}for(let i of e.assertions){if(oo(i),t.has(`assertion:${i.id}`))throw new L(`duplicate assertion ${i.id}`);t.add(`assertion:${i.id}`)}for(let i of e.gates){ql(i);let r=i.assertion_ids.filter(a=>!e.assertions.some(o=>o.id===a));if(r.length>0)throw new L(`gate ${i.id} references missing assertions: ${r.join(", ")}`);if(t.has(`gate:${i.id}`))throw new L(`duplicate gate ${i.id}`);t.add(`gate:${i.id}`)}let n=new Set(e.measurements.map(i=>i.id));for(let[i,r]of Gl(e))if(!n.has(i))throw new L(`${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 Gl(e){let t=new Map,n=(i,r)=>{let a=t.get(i)??[];a.push(r),t.set(i,a)};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 a of r)n(a,`derived measurement ${i.id}`)}return t}function Cg(e,t){let n=e.assertion_ids.flatMap(a=>{let o=t.assertions.find(s=>s.id===a);return[o.measurement_id,...o.scope.kind==="filter"?[o.scope.measurement_id]:[]]}),i=new Set,r=new Set;for(;n.length>0;){let a=n.pop();if(i.has(a))continue;i.add(a);let o=t.measurements.find(s=>s.id===a);o.source.kind==="provider"?r.add(o.source.provider):o.source.kind==="derived"&&so(o.source.expression,n)}return r}function Yn(){return{version:Ul,measurements:[],assertions:[],gates:[]}}function Tg(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 a=r==null||r===""||Array.isArray(r)&&r.length===0;return e.state==="missing"?a:!a}return ro(r,e.equals)})()));return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(i=>i.id)}}function $g(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 Dg(e,t){let n=[],i=Oa(e.dependency_kind)??e.dependency_kind.trim().toLowerCase();for(let r of t.items)for(let a of r.dependencies??[]){let o=Oa(a.kind)??a.kind.trim().toLowerCase(),s=a.source_kind?.trim();o===i&&$g(e,s)&&n.push(`${r.id}->${a.id}${s?`@${s}`:""}`)}return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n}}function Og(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 a=Reflect.get(r,"text");typeof a=="string"&&t.push(a)}}}return t}function Pg(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 io(e,t){return[e.toLowerCase(),t.toLowerCase()].sort().join("\0")}function Lg(e){let t=new Map,n=new Set,i=[],r=/(?<![\w-])[a-z0-9]+(?:-+[a-z0-9]+)+(?![\w-])/giu,a=0;for(let o of e){t.set(o.id.toLowerCase(),o.id);for(let s of o.dependencies??[])n.add(io(o.id,s.id));for(let s of[o.parent,o.blocked_by])typeof s=="string"&&n.add(io(o.id,s));for(let s of Og(o)){let c=[...s.matchAll(r)].map(d=>d[0]);a+=c.length,i.push({holder_id:o.id,segment:s,mentioned_ids:c})}}return{canonical_ids:t,linked_pairs:n,prose_mentions:i,mention_count:a}}function Ng(e,t){let n=Lg(t.items),i=new Map;for(let o of n.prose_mentions){let s=o.mentioned_ids.map(d=>n.canonical_ids.get(d.toLowerCase())).filter(d=>d!==void 0&&d!==o.holder_id),c=[...new Set(s)];for(let d of c){let l=io(o.holder_id,d);if(n.linked_pairs.has(l)||Pg(e.exemptions??[],o.holder_id,d,o.segment))continue;let u=c.some(m=>m!==d);i.get(l)?.explicit===!0&&!u||i.set(l,{contributor:`${o.holder_id}->${d}|subject=${u?"explicit":"implicit"}`,explicit:u})}}let r=[...i.values()],a=r.map(o=>o.contributor).sort();return{value:a.length,population_size:n.canonical_ids.size,cost:t.items.length+n.linked_pairs.size+n.mention_count,contributors:a.slice(0,e.sample_limit??25),partitions:{explicit_subject:r.filter(o=>o.explicit).length,implicit_subject:r.filter(o=>!o.explicit).length}}}function Mg(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 jg(e,t){let n=t.items.filter(i=>{let r=i[e.link],a=Array.isArray(r)&&r.length>0;return e.state==="present"?a:!a});return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(i=>i.id)}}function Fg(e,t){let n=e.source;return n.kind==="items"?Tg(n,t):n.kind==="dependency_kind"?Dg(n,t):n.kind==="prose_edge_gap"?Ng(n,t):n.kind==="history"?Mg(n,t):n.kind==="links"?jg(n,t):null}function Bl(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 Ug(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 Jl(e,t,n){let i=new Array(e.length),r=0,a=Array.from({length:Math.min(t,e.length)},async()=>{for(;r<e.length;){let o=r;r+=1,i[o]=await n(e[o],o)}});return await Promise.all(a),i}async function Vl(e,t,n,i,r){if("literal"in e)return{value:e.literal,costs:[],population_size:0,contributors:[]};if("measurement"in e){let o=n.find(d=>d.id===e.measurement);if(!o)throw new TypeError(`derived measurement references missing ${e.measurement}`);let s=await Kl(o,t,n,i,r);if(typeof s.value!="number")throw new TypeError(`derived measurement ${o.id} is not numeric`);let c=r.charged.has(o.id)?[]:[s.cost];return r.charged.add(o.id),{value:s.value,costs:c,population_size:s.population_size,contributors:s.contributors}}let a=await Jl(e.operands,Hl,o=>Vl(o,t,n,i,r));return{value:Ug(e.operator,a.map(o=>o.value)),costs:a.flatMap(o=>o.costs),population_size:Math.max(0,...a.map(o=>o.population_size)),contributors:[...new Set(a.flatMap(o=>o.contributors))]}}async function Hg(e,t,n,i,r){ao(e);let a=Date.now(),o,s=[],c=0;if(e.source.kind==="derived"){let u=await Vl(e.source.expression,t,n,[...i,e.id],r);o={value:u.value,population_size:u.population_size,cost:0,contributors:u.contributors},s=u.costs}else{let u=Fg(e,t);u!==null?o=u:(o=await t.external(e.source),c=1)}let d={units:o.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()-a},l=Bl([...s,d],Date.now()-a);if(e.max_cost!==void 0&&l.units>e.max_cost)throw new we(`measurement ${e.id} exceeded cost ceiling ${e.max_cost} with ${l.units}`);return{id:e.id,definition_fingerprint:`sha256:${gg("sha256").update(A(e)).digest("hex")}`,value:o.value,population_size:o.population_size,cost:l,contributors:o.contributors??[],...o.partitions?{partitions:o.partitions}:{}}}function Kl(e,t,n,i,r){if(i.includes(e.id))throw new TypeError(`derived measurement cycle: ${[...i,e.id].join(" -> ")}`);let a=r.cache.get(e.id);if(a)return a;let o=Hg(e,t,n,i,r).catch(s=>{if(s instanceof Ye&&s.measurement_id===void 0){let c={measurement_id:e.id,source_kind:s.source_kind,field:s.field,...s.check?{check:s.check}:{}},d=new Ye(s.message,c);throw d.cause=s,d}throw s});return r.cache.set(e.id,o),o}async function co(e,t,n=[e]){return Kl(e,t,n,[],{cache:new Map,charged:new Set})}function zg(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 Wg(e,t,n={}){oo(e);let i=Kn(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:zg(t.value,i),verdict:r?"retired":zl(t.value,i)?"pass":"fail",enforcement:e.enforcement,negative_control_proven:Wl(e),cost:t.cost,contributors:t.contributors,...t.partitions?{partitions:t.partitions}:{}}}function qg(e,t,n,i){let r=Cg(e,t);if(r.size===0)return;let a=e.provider_policy,o=a?.triggers[i];if(!a||!o)throw new we(`assurance gate ${e.id} refuses provider execution at trigger ${i} without an explicit provider policy`);let s=new Set(a.allowed_providers),c={low:0,medium:1,high:2};for(let d of r){if(!s.has(d))throw new we(`assurance gate ${e.id} refuses provider ${d}`);let l=n.provider_capabilities?.[d];if(!l)throw new we(`assurance provider ${d} has no declared capabilities`);if(c[l.cost_class]>c[o.max_cost_class])throw new we(`assurance gate ${e.id} refuses ${l.cost_class}-cost provider ${d} at trigger ${i}`);if(l.network&&!o.allow_network)throw new we(`assurance gate ${e.id} refuses network provider ${d} at trigger ${i}`)}}async function Fl(e,t,n,i,r){try{return await co(n,i,r)}catch(a){if(a instanceof Ye){let o=a.check?` check ${a.check}`:"",s=a.measurement_id??n.id,c=new we(`assurance gate ${e} assertion ${t} measurement ${s} source ${a.source_kind}${o} field ${a.field} could not resolve: ${a.message}`,{gate_id:e,assertion_id:t,measurement_id:s,source_kind:a.source_kind,field:a.field,...a.check?{check:a.check}:{}});throw c.cause=a,c}throw a}}async function Yl(e,t,n,i){fn(t);let r=t.gates.find(c=>c.id===e);if(!r)throw new we(`assurance gate ${e} not found`);if(!r.triggers.includes(i.trigger))throw new we(`assurance gate ${e} does not declare trigger ${i.trigger}`);qg(r,t,n,i.trigger);let a=await Jl(r.assertion_ids,Hl,async c=>{let d=t.assertions.find(p=>p.id===c),l=t.measurements.find(p=>p.id===d.measurement_id),u=n;if(d.scope.kind==="active"){let p=new Set(n.terminal_statuses??["closed","canceled"]);u={...n,items:n.items.filter(h=>!p.has(h.status))}}else if(d.scope.kind==="filter"){let p=d.scope.measurement_id,h=t.measurements.find(v=>v.id===p),_=await Fl(r.id,d.id,h,n,t.measurements),w=new Set(_.contributors);u={...n,items:n.items.filter(v=>w.has(v.id))}}let m=n.items.find(p=>p.id===d.owner_item_id),f=m!==void 0&&new Set(n.terminal_statuses??["closed","canceled"]).has(m.status);return Wg(d,await Fl(r.id,d.id,l,u,t.measurements),{owner_terminal:f})}),o=a.some(c=>c.verdict==="fail"&&c.enforcement==="block"),s=a.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:o?"block":s?"warn":"pass",exit_code:o?1:0,assertions:a,assertions_total:a.length,row_contract:{row_keys:["assertions"],jq_selector:".assertions[]"},cost:Bl(a.map(c=>c.cost),Math.max(0,...a.map(c=>c.cost.duration_ms)))}}function wr(e){return yg.join(e,"assurance.json")}async function Xl(e){let t=await B(wr(e));return t===null?Yn():vr(t)}function vr(e){try{return fn(JSON.parse(e))}catch(t){throw new g("The assurance registry is invalid. Repair or restore .agents/pm/assurance.json and retry.",y.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 br(e,t){return t==="measurement"?e.measurements:t==="assertion"?e.assertions:e.gates}function Gg(e,t){e==="measurement"?ao(t):e==="assertion"?oo(t):ql(t)}async function Xn(e,t){let n=structuredClone(br(await Xl(e),t));return{items:n,count:n.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function Zl(e,t,n){let i=br(await Xl(e),t).find(r=>r.id===n);if(!i)throw new we(`assurance ${t} ${n} not found`);return structuredClone(i)}async function kr(e,t,n,i={}){Gg(t,n);let r=await T(e),a=z(i.author,r.author_default),o=await an({pmRoot:e,filePath:wr(e),op:`assurance:${t}:put`,author:a,message:i.message,lockTtlSeconds:gr,lockWaitMs:yr,mutate:s=>{let c=s===null?Yn():vr(s),d=br(c,t),l=d.findIndex(m=>m.id===n.id),u=l<0?"created":"updated";if(t==="assertion"&&l>=0&&Sg(d[l],n)){let m=n.authorization_decision;if(!m||!i.authorized_decision_ids?.includes(m))throw new L(`loosening assertion ${n.id} requires a verified authorization_decision`)}return l<0?d.push(structuredClone(n)):d[l]=structuredClone(n),fn(c),{raw:`${JSON.stringify(c,null,2)}
|
|
1
|
+
import{c as St,d as dn,e as ln,f as un,g as Nl,j as jl}from"./chunk-3NYWMUX3.js";import{a as Ll}from"./chunk-DFUTCKUF.js";import{i as Q,m as Za,x as Cl}from"./chunk-WX2RVS2Y.js";import{a as ja,c as zi,d as Wi,e as ed,g as td,h as Ua,i as nd,j as Kt,k as Yt,l as id,m as rd,n as Ha,o as sd,p as Xt,q as Zt,r as cd,s as dd,t as za}from"./chunk-LVA76N27.js";import{a as qa}from"./chunk-SVOOGGAK.js";import{B as bd,C as Vi,D as kd,E as Wa,G as Ed,H as Sd,J as xd,K as Id,L as Ki,U as Yi}from"./chunk-Z7GIVH6B.js";import{K as Ml}from"./chunk-RPUDOJVB.js";import{A as Pl,I as eo,w as Dl,y as Qa,z as Ol}from"./chunk-GE755ODZ.js";import{A as Cd,Aa as Ya,Ba as cn,Ca as kl,Da as El,Ea as Sl,Fa as Xa,H as Td,L as $d,M as Dd,N as Od,Q as dr,Sa as xl,Ta as Il,Xa as Rl,Ya as Al,ea as ur,fa as tl,ga as Va,ha as Bn,ja as Ka,k as Xi,na as pl,o as Hn,oa as fl,p as Rd,pa as hl,q as Ad,qa as _l,r as zn,ra as fr,ta as gl,ua as yl,va as wl,wa as Mt,xa as vl,ya as sn,za as bl}from"./chunk-7WJDRZOR.js";import{a as Yc,b as Vt,c as Fa,d as Xc,e as Zc,f as it,g as qi,h as Qc,i as wt}from"./chunk-6GMYW42K.js";import{m as Jn,o as hr,v as Tl,y as $l}from"./chunk-PAT6QF63.js";import{C as mr,E as ll,F as ge,G as ye,H as ul,I as pr,J as rt,K as at,O as ml,P as ot,a as Zi,c as Yd,j as nl,k as il,m as rl,n as al,o as Et,p as ol,q as sl,w as cl,x as dl}from"./chunk-JCR32IAO.js";import{$a as T,Aa as tn,Ba as Vd,Da as or,Ea as sr,Fa as qn,Ga as kt,Ha as Gn,Ia as Kd,Ja as cr,Ka as Nt,La as te,Ma as nn,Na as Xd,Oa as Ja,Pa as rn,Qa as an,Ra as on,Ta as Zd,Ua as Qd,Xa as je,_a as el,a as Pd,ab as lr,ba as z,ca as Hd,d as Re,da as Me,e as Ga,ea as zd,eb as ne,f as Ld,k as Qi,ka as Wd,l as Wn,la as Ba,m as Nd,ma as ir,n as er,na as en,o as Md,pa as rr,q as tr,qa as qd,r as nr,ra as Gd,t as jd,ta as Bd,u as $e,va as Jd,x as bt,y as Fd,ya as ar,z as Ud}from"./chunk-M22TI7LP.js";import{b as Gt}from"./chunk-AL7SOFUL.js";import{a as se,c as Te,e as Ie,f as Ke,j as fe,k as ad,l as Gi,n as od}from"./chunk-VFQAZLKO.js";import{$d as vd,Ac as Ji,Ba as Mc,Bb as Bc,Ca as Ot,Cb as Jc,Ea as jc,Fa as A,Ga as Fc,Ha as xe,Hc as hd,Ja as Hi,Ka as Uc,Kb as Vc,La as Pa,Lb as Pt,Ma as La,Mc as _d,Na,Nb as Ma,Nc as le,O as $c,Ob as Kc,Od as $,Pa as Hc,Pb as Jt,Pd as gd,Qa as zc,Qd as Qt,R as Dc,Rb as Je,Rd as vt,Sd as Lt,T as Oa,Ta as Wc,Tb as Ve,Xd as yd,Y as me,Z as Ge,_ as Oc,_d as wd,a as Ec,aa as Y,ae as re,bb as qc,d as Sc,da as Pc,e as xc,ec as ld,gc as Bi,hc as ud,ic as md,kb as Gc,kc as pd,o as Da,oa as Lc,pa as Nc,qa as H,sc as F,va as Un,wa as M,wc as K,xa as Be,ya as Ui,yc as Ne,za as Bt,zc as fd}from"./chunk-CIQ6YWCW.js";import{a as _r,b as Vn}from"./chunk-EGN2HFRU.js";import{A as g,B as Fn,C as D,D as yt,E as j,F as B,I as Z,a as Mi,d as ji,p as Ic,r as Rc,t as Ac,v as Cc,w as Fi,x as Tc,z as y}from"./chunk-JLXGRDTG.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]="081bf1eb-4b9a-5fa9-a272-34ae781d250c")}catch{}})();var L=class extends TypeError{constructor(t){super(t),this.name="AssuranceMutationRefusalError"}},we=class extends TypeError{context;constructor(t,n={}){super(t),this.name="AssuranceEvaluationRefusalError",this.context=n}},Ye=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 mn(e){try{return await e()}catch(t){throw t instanceof L?new g(t.message,y.USAGE,{code:"invalid_argument_value",reason:"assurance_mutation_refused"}):t}}async function to(e){try{return await e()}catch(t){throw t instanceof we?new g(t.message,y.USAGE,{code:"invalid_argument_value",reason:"assurance_evaluation_refused",...t.context}):t}}import{createHash as gg}from"node:crypto";import yg 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 pn=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]="eaede7d4-43ae-5551-915e-19befefc29d0")}catch{}})();var Ul=1,jt=["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"],no=["items","dependency_kind","prose_edge_gap","graph","validate","health","history","links","provider","derived"],wg=["ceiling","floor","equals","zero","monotone_nondecreasing","monotone_nonincreasing","subset_of"],vg=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,gr=30,yr=5e3,Hl=4,bg=50;function st(e,t){if(!vg.test(e))throw new L(`${t} must be a stable lowercase id`)}function kg(e,t){if(!Number.isFinite(e)||e<0)throw new L(`${t} must be a finite non-negative number`)}function Kn(e){let t=wg.filter(r=>e[r]!==void 0);if(t.length!==1)throw new L(`assertion ${e.id} must declare exactly one polarity`);let n=t[0],i=e[n];return{polarity:n,value:n==="zero"?0:i}}function ro(e,t){return A(e)===A(t)}function zl(e,t){if(t.polarity==="equals")return ro(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 Wl(e){let t=Kn(e),n=e.negative_control.cases;return n.some(i=>i.expected==="pass")&&n.some(i=>i.expected==="fail")&&n.every(i=>zl(i.observed,t)===(i.expected==="pass"))}function Eg(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!ro(e.value,t.value)}function Sg(e,t){if(e.measurement_id!==t.measurement_id||e.owner_item_id!==t.owner_item_id||A(e.scope)!==A(t.scope))return!0;let n={observe:0,warn:1,block:2},i=(e.lifetime??"hold")==="hold"&&(t.lifetime??"hold")==="retire";return Eg(Kn(e),Kn(t))||n[t.enforcement]<n[e.enforcement]||i}function xg(e){if(e.state!==void 0&&!(e.state==="present"||e.state==="missing"))throw new L("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 L("items source with field requires exactly one of equals or state");if(e.field===void 0&&i!==0)throw new L("items source equals/state requires field")}function Ig(e){if(typeof e.dependency_kind!="string"||e.dependency_kind.trim().length===0)throw new L("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 L("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 L("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 L("dependency_kind source source_kind_state must be present or missing")}function Rg(e){if(e.sample_limit!==void 0&&(!Number.isInteger(e.sample_limit)||e.sample_limit<1))throw new L("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 L("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 L("prose_edge_gap exemption selectors must not be empty")}}function ao(e){st(e.id,"measurement.id"),e.max_cost!==void 0&&kg(e.max_cost,"measurement.max_cost");let t=e.source;if(Object.prototype.toString.call(t)!=="[object Object]")throw new L(`measurement.source.kind must be one of ${no.join(", ")}`);let n=Reflect.get(t,"kind");if(!no.includes(n))throw new L(`measurement.source.kind must be one of ${no.join(", ")}`);let i=t;if(i.kind==="items"&&xg(i),i.kind==="dependency_kind"&&Ig(i),i.kind==="prose_edge_gap"&&Rg(i),(i.kind==="graph"||i.kind==="validate"||i.kind==="health")&&(typeof i.field!="string"||i.field.trim().length===0))throw new L(`${i.kind} source requires field`);return i.kind==="provider"&&(st(i.provider,"provider source provider"),st(i.key,"provider source key")),e}function oo(e){if(st(e.id,"assertion.id"),st(e.measurement_id,"assertion.measurement_id"),typeof e.owner_item_id!="string"||e.owner_item_id.trim().length===0)throw new L("assertion.owner_item_id is required");let t=Kn(e);if(typeof t.value=="number"&&!Number.isFinite(t.value))throw new L(`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 L("retired assertion requires retire_reason");e.scope.kind==="filter"&&st(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 L("assertion negative control requires pass and fail cases");if(!Wl(e))throw new L(`assertion ${e.id} negative control does not prove its bound`);return e}function Ag(e){if(!Array.isArray(e.allowed_providers))throw new L("gate provider_policy.allowed_providers must be an array");for(let t of e.allowed_providers)st(t,"gate.provider_policy.allowed_provider");if(typeof e.triggers!="object"||e.triggers===null||Array.isArray(e.triggers))throw new L("gate provider_policy.triggers must be an object");for(let[t,n]of Object.entries(e.triggers)){if(!jt.includes(t))throw new L(`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 L(`gate provider policy trigger ${t} is invalid`)}}function ql(e){if(st(e.id,"gate.id"),!Array.isArray(e.assertion_ids))throw new L("gate.assertion_ids is required and must be an array");if(e.assertion_ids.length===0)throw new L("gate requires at least one assertion");for(let t of e.assertion_ids)st(t,"gate.assertion_id");if(!Array.isArray(e.triggers))throw new L(`gate.triggers is required and must be an array of ${jt.join(", ")}`);if(e.triggers.length===0)throw new L("gate requires at least one trigger");for(let t of e.triggers)if(!jt.includes(t))throw new L(`gate trigger must be one of ${jt.join(", ")}`);return e.provider_policy&&Ag(e.provider_policy),e}function fn(e){if(e.version!==Ul)throw new L(`unsupported assurance document version ${String(e.version)}`);let t=new Set;for(let i of e.measurements){if(ao(i),t.has(`measurement:${i.id}`))throw new L(`duplicate measurement ${i.id}`);t.add(`measurement:${i.id}`)}for(let i of e.assertions){if(oo(i),t.has(`assertion:${i.id}`))throw new L(`duplicate assertion ${i.id}`);t.add(`assertion:${i.id}`)}for(let i of e.gates){ql(i);let r=i.assertion_ids.filter(a=>!e.assertions.some(o=>o.id===a));if(r.length>0)throw new L(`gate ${i.id} references missing assertions: ${r.join(", ")}`);if(t.has(`gate:${i.id}`))throw new L(`duplicate gate ${i.id}`);t.add(`gate:${i.id}`)}let n=new Set(e.measurements.map(i=>i.id));for(let[i,r]of Gl(e))if(!n.has(i))throw new L(`${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 Gl(e){let t=new Map,n=(i,r)=>{let a=t.get(i)??[];a.push(r),t.set(i,a)};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 a of r)n(a,`derived measurement ${i.id}`)}return t}function Cg(e,t){let n=e.assertion_ids.flatMap(a=>{let o=t.assertions.find(s=>s.id===a);return[o.measurement_id,...o.scope.kind==="filter"?[o.scope.measurement_id]:[]]}),i=new Set,r=new Set;for(;n.length>0;){let a=n.pop();if(i.has(a))continue;i.add(a);let o=t.measurements.find(s=>s.id===a);o.source.kind==="provider"?r.add(o.source.provider):o.source.kind==="derived"&&so(o.source.expression,n)}return r}function Yn(){return{version:Ul,measurements:[],assertions:[],gates:[]}}function Tg(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 a=r==null||r===""||Array.isArray(r)&&r.length===0;return e.state==="missing"?a:!a}return ro(r,e.equals)})()));return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(i=>i.id)}}function $g(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 Dg(e,t){let n=[],i=Oa(e.dependency_kind)??e.dependency_kind.trim().toLowerCase();for(let r of t.items)for(let a of r.dependencies??[]){let o=Oa(a.kind)??a.kind.trim().toLowerCase(),s=a.source_kind?.trim();o===i&&$g(e,s)&&n.push(`${r.id}->${a.id}${s?`@${s}`:""}`)}return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n}}function Og(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 a=Reflect.get(r,"text");typeof a=="string"&&t.push(a)}}}return t}function Pg(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 io(e,t){return[e.toLowerCase(),t.toLowerCase()].sort().join("\0")}function Lg(e){let t=new Map,n=new Set,i=[],r=/(?<![\w-])[a-z0-9]+(?:-+[a-z0-9]+)+(?![\w-])/giu,a=0;for(let o of e){t.set(o.id.toLowerCase(),o.id);for(let s of o.dependencies??[])n.add(io(o.id,s.id));for(let s of[o.parent,o.blocked_by])typeof s=="string"&&n.add(io(o.id,s));for(let s of Og(o)){let c=[...s.matchAll(r)].map(d=>d[0]);a+=c.length,i.push({holder_id:o.id,segment:s,mentioned_ids:c})}}return{canonical_ids:t,linked_pairs:n,prose_mentions:i,mention_count:a}}function Ng(e,t){let n=Lg(t.items),i=new Map;for(let o of n.prose_mentions){let s=o.mentioned_ids.map(d=>n.canonical_ids.get(d.toLowerCase())).filter(d=>d!==void 0&&d!==o.holder_id),c=[...new Set(s)];for(let d of c){let l=io(o.holder_id,d);if(n.linked_pairs.has(l)||Pg(e.exemptions??[],o.holder_id,d,o.segment))continue;let u=c.some(m=>m!==d);i.get(l)?.explicit===!0&&!u||i.set(l,{contributor:`${o.holder_id}->${d}|subject=${u?"explicit":"implicit"}`,explicit:u})}}let r=[...i.values()],a=r.map(o=>o.contributor).sort();return{value:a.length,population_size:n.canonical_ids.size,cost:t.items.length+n.linked_pairs.size+n.mention_count,contributors:a.slice(0,e.sample_limit??25),partitions:{explicit_subject:r.filter(o=>o.explicit).length,implicit_subject:r.filter(o=>!o.explicit).length}}}function Mg(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 jg(e,t){let n=t.items.filter(i=>{let r=i[e.link],a=Array.isArray(r)&&r.length>0;return e.state==="present"?a:!a});return{value:n.length,population_size:t.items.length,cost:t.items.length,contributors:n.map(i=>i.id)}}function Fg(e,t){let n=e.source;return n.kind==="items"?Tg(n,t):n.kind==="dependency_kind"?Dg(n,t):n.kind==="prose_edge_gap"?Ng(n,t):n.kind==="history"?Mg(n,t):n.kind==="links"?jg(n,t):null}function Bl(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 Ug(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 Jl(e,t,n){let i=new Array(e.length),r=0,a=Array.from({length:Math.min(t,e.length)},async()=>{for(;r<e.length;){let o=r;r+=1,i[o]=await n(e[o],o)}});return await Promise.all(a),i}async function Vl(e,t,n,i,r){if("literal"in e)return{value:e.literal,costs:[],population_size:0,contributors:[]};if("measurement"in e){let o=n.find(d=>d.id===e.measurement);if(!o)throw new TypeError(`derived measurement references missing ${e.measurement}`);let s=await Kl(o,t,n,i,r);if(typeof s.value!="number")throw new TypeError(`derived measurement ${o.id} is not numeric`);let c=r.charged.has(o.id)?[]:[s.cost];return r.charged.add(o.id),{value:s.value,costs:c,population_size:s.population_size,contributors:s.contributors}}let a=await Jl(e.operands,Hl,o=>Vl(o,t,n,i,r));return{value:Ug(e.operator,a.map(o=>o.value)),costs:a.flatMap(o=>o.costs),population_size:Math.max(0,...a.map(o=>o.population_size)),contributors:[...new Set(a.flatMap(o=>o.contributors))]}}async function Hg(e,t,n,i,r){ao(e);let a=Date.now(),o,s=[],c=0;if(e.source.kind==="derived"){let u=await Vl(e.source.expression,t,n,[...i,e.id],r);o={value:u.value,population_size:u.population_size,cost:0,contributors:u.contributors},s=u.costs}else{let u=Fg(e,t);u!==null?o=u:(o=await t.external(e.source),c=1)}let d={units:o.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()-a},l=Bl([...s,d],Date.now()-a);if(e.max_cost!==void 0&&l.units>e.max_cost)throw new we(`measurement ${e.id} exceeded cost ceiling ${e.max_cost} with ${l.units}`);return{id:e.id,definition_fingerprint:`sha256:${gg("sha256").update(A(e)).digest("hex")}`,value:o.value,population_size:o.population_size,cost:l,contributors:o.contributors??[],...o.partitions?{partitions:o.partitions}:{}}}function Kl(e,t,n,i,r){if(i.includes(e.id))throw new TypeError(`derived measurement cycle: ${[...i,e.id].join(" -> ")}`);let a=r.cache.get(e.id);if(a)return a;let o=Hg(e,t,n,i,r).catch(s=>{if(s instanceof Ye&&s.measurement_id===void 0){let c={measurement_id:e.id,source_kind:s.source_kind,field:s.field,...s.check?{check:s.check}:{}},d=new Ye(s.message,c);throw d.cause=s,d}throw s});return r.cache.set(e.id,o),o}async function co(e,t,n=[e]){return Kl(e,t,n,[],{cache:new Map,charged:new Set})}function zg(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 Wg(e,t,n={}){oo(e);let i=Kn(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:zg(t.value,i),verdict:r?"retired":zl(t.value,i)?"pass":"fail",enforcement:e.enforcement,negative_control_proven:Wl(e),cost:t.cost,contributors:t.contributors,...t.partitions?{partitions:t.partitions}:{}}}function qg(e,t,n,i){let r=Cg(e,t);if(r.size===0)return;let a=e.provider_policy,o=a?.triggers[i];if(!a||!o)throw new we(`assurance gate ${e.id} refuses provider execution at trigger ${i} without an explicit provider policy`);let s=new Set(a.allowed_providers),c={low:0,medium:1,high:2};for(let d of r){if(!s.has(d))throw new we(`assurance gate ${e.id} refuses provider ${d}`);let l=n.provider_capabilities?.[d];if(!l)throw new we(`assurance provider ${d} has no declared capabilities`);if(c[l.cost_class]>c[o.max_cost_class])throw new we(`assurance gate ${e.id} refuses ${l.cost_class}-cost provider ${d} at trigger ${i}`);if(l.network&&!o.allow_network)throw new we(`assurance gate ${e.id} refuses network provider ${d} at trigger ${i}`)}}async function Fl(e,t,n,i,r){try{return await co(n,i,r)}catch(a){if(a instanceof Ye){let o=a.check?` check ${a.check}`:"",s=a.measurement_id??n.id,c=new we(`assurance gate ${e} assertion ${t} measurement ${s} source ${a.source_kind}${o} field ${a.field} could not resolve: ${a.message}`,{gate_id:e,assertion_id:t,measurement_id:s,source_kind:a.source_kind,field:a.field,...a.check?{check:a.check}:{}});throw c.cause=a,c}throw a}}async function Yl(e,t,n,i){fn(t);let r=t.gates.find(c=>c.id===e);if(!r)throw new we(`assurance gate ${e} not found`);if(!r.triggers.includes(i.trigger))throw new we(`assurance gate ${e} does not declare trigger ${i.trigger}`);qg(r,t,n,i.trigger);let a=await Jl(r.assertion_ids,Hl,async c=>{let d=t.assertions.find(p=>p.id===c),l=t.measurements.find(p=>p.id===d.measurement_id),u=n;if(d.scope.kind==="active"){let p=new Set(n.terminal_statuses??["closed","canceled"]);u={...n,items:n.items.filter(h=>!p.has(h.status))}}else if(d.scope.kind==="filter"){let p=d.scope.measurement_id,h=t.measurements.find(v=>v.id===p),_=await Fl(r.id,d.id,h,n,t.measurements),w=new Set(_.contributors);u={...n,items:n.items.filter(v=>w.has(v.id))}}let m=n.items.find(p=>p.id===d.owner_item_id),f=m!==void 0&&new Set(n.terminal_statuses??["closed","canceled"]).has(m.status);return Wg(d,await Fl(r.id,d.id,l,u,t.measurements),{owner_terminal:f})}),o=a.some(c=>c.verdict==="fail"&&c.enforcement==="block"),s=a.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:o?"block":s?"warn":"pass",exit_code:o?1:0,assertions:a,assertions_total:a.length,row_contract:{row_keys:["assertions"],jq_selector:".assertions[]"},cost:Bl(a.map(c=>c.cost),Math.max(0,...a.map(c=>c.cost.duration_ms)))}}function wr(e){return yg.join(e,"assurance.json")}async function Xl(e){let t=await B(wr(e));return t===null?Yn():vr(t)}function vr(e){try{return fn(JSON.parse(e))}catch(t){throw new g("The assurance registry is invalid. Repair or restore .agents/pm/assurance.json and retry.",y.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 br(e,t){return t==="measurement"?e.measurements:t==="assertion"?e.assertions:e.gates}function Gg(e,t){e==="measurement"?ao(t):e==="assertion"?oo(t):ql(t)}async function Xn(e,t){let n=structuredClone(br(await Xl(e),t));return{items:n,count:n.length,row_contract:{row_keys:["items"],jq_selector:".items[]"}}}async function Zl(e,t,n){let i=br(await Xl(e),t).find(r=>r.id===n);if(!i)throw new we(`assurance ${t} ${n} not found`);return structuredClone(i)}async function kr(e,t,n,i={}){Gg(t,n);let r=await T(e),a=z(i.author,r.author_default),o=await an({pmRoot:e,filePath:wr(e),op:`assurance:${t}:put`,author:a,message:i.message,lockTtlSeconds:gr,lockWaitMs:yr,mutate:s=>{let c=s===null?Yn():vr(s),d=br(c,t),l=d.findIndex(m=>m.id===n.id),u=l<0?"created":"updated";if(t==="assertion"&&l>=0&&Sg(d[l],n)){let m=n.authorization_decision;if(!m||!i.authorized_decision_ids?.includes(m))throw new L(`loosening assertion ${n.id} requires a verified authorization_decision`)}return l<0?d.push(structuredClone(n)):d[l]=structuredClone(n),fn(c),{raw:`${JSON.stringify(c,null,2)}
|
|
2
2
|
`,result:{changed:!0,action:u,kind:t,id:n.id}}}});return{...o.result,changed:o.changed}}async function lo(e,t,n={}){let i=Yn();i.measurements=structuredClone(t.measurements),i.assertions=structuredClone(t.assertions),i.gates=structuredClone(t.gates),fn(i);let r=await T(e),a=z(n.author,r.author_default),o=await an({pmRoot:e,filePath:wr(e),op:"assurance:bundle:apply",author:a,message:n.message,lockTtlSeconds:gr,lockWaitMs:yr,mutate:s=>{let c=s===null?Yn():vr(s),d=[],l=[],u=(m,f,p)=>{for(let h of f){let _=m.find(w=>w.id===h.id);if(!_){m.push(structuredClone(h)),d.push(`${p}:${h.id}`);continue}if(A(_)!==A(h))throw new L(`assurance bundle refuses to replace divergent ${p} ${h.id}`);l.push(`${p}:${h.id}`)}};return u(c.measurements,i.measurements,"measurement"),u(c.assertions,i.assertions,"assertion"),u(c.gates,i.gates,"gate"),fn(c),{raw:`${JSON.stringify(c,null,2)}
|
|
3
3
|
`,result:{changed:d.length>0,created_ids:d,unchanged_ids:l}}}});return{...o.result,changed:o.changed}}async function Ql(e,t,n,i={}){let r=await T(e),a=z(i.author,r.author_default),o=await an({pmRoot:e,filePath:wr(e),op:`assurance:${t}:remove`,author:a,message:i.message,lockTtlSeconds:gr,lockWaitMs:yr,mutate:s=>{let c=s===null?Yn():vr(s);if(t==="measurement"){let u=Gl(c).get(n);if(u&&u.length>0)throw new L(`assurance measurement ${n} is referenced by ${u.join(", ")}`)}if(t==="assertion"&&c.gates.some(u=>u.assertion_ids.includes(n)))throw new L(`assurance assertion ${n} is referenced by gate`);let d=br(c,t),l=d.findIndex(u=>u.id===n);if(l<0)throw new L(`assurance ${t} ${n} not found`);return d.splice(l,1),fn(c),{raw:`${JSON.stringify(c,null,2)}
|
|
4
4
|
`,result:{changed:!0,action:"removed",kind:t,id:n}}}});return{...o.result,changed:o.changed}}async function eu(e,t,n={}){if(t.dry_run)throw new TypeError("dry-run assurance verdicts are not persisted");let i=await T(e);await rn({pmRoot:e,op:"assurance:gate:verdict",author:z(n.author,i.author_default),context:{assurance_verdict:t},message:n.message??`Assurance gate ${t.gate_id} returned ${t.verdict}`,lockTtlSeconds:gr,lockWaitMs:yr})}async function tu(e,t={}){let n=t.limit??bg;if(!Number.isInteger(n)||n<1||n>pn)throw new TypeError(`assurance verdict limit must be an integer from 1 through ${pn}`);return(await Me(nn(e),te)).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)}import{mkdir as Bg,readFile as Jg}from"node:fs/promises";import iu from"node:path";import{createHash as Vg}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]="a8daf042-f74c-5f51-b7e8-f8ff4fb8fe8e")}catch{}})();var uo=class extends Error{constructor(t="Workspace transaction interrupted"){super(t),this.name="WorkspaceTransactionInterruptedError"}},ru="sdk-workspace-transaction",au=/^[a-zA-Z0-9._-]+$/,ou=30,su=3e3;function _o(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n||!au.test(n))throw new TypeError(`${t} must match [a-zA-Z0-9._-]+`);return n}function mo(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n)throw new TypeError(`${t} must be non-empty`);return n}function go(e){return{pmRoot:mo(e.pmRoot,"Transaction pmRoot"),transactionId:_o(e.transactionId,"Transaction id"),author:mo(e.author,"Transaction author")}}function Sr(e,t,n){let i=e??t;if(!Number.isInteger(i)||i<=0)throw new TypeError(`${n} must be a positive integer`);return i}function cu(e,t){return iu.join(e,"transactions","sdk",`${t}.json`)}async function Xe(e,t){t.updatedAt=$();let n=cu(e,t.transactionId);await Bg(iu.dirname(n),{recursive:!0}),await Z(n,`${JSON.stringify(t,null,2)}
|
|
@@ -8,12 +8,12 @@ import{c as St,d as dn,e as ln,f as un,g as Nl,j as jl}from"./chunk-SAT7IAEB.js"
|
|
|
8
8
|
`)){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 Sy(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 a=[...new Set(t[i+1]?.match(/\bpm-[a-z0-9][a-z0-9-]{2,63}\b/gu)??[])].sort((o,s)=>o.localeCompare(s));n.set(r,a)}return n}async function xy(e){let t=xu.relative(e.workspaceRoot,xu.resolve(e.workspaceRoot,e.sourcePath)),n=await Iu(e.workspaceRoot,["blame","--line-porcelain","-L",`${e.lineRange.start},${e.lineRange.end}`,"--",t]),i=await Iu(e.workspaceRoot,["log","-n","256","--format=%H%x00%B%x00","--",t]);return{commitLines:Ey(n),commitItems:Sy(i),available:!0}}function Iy(e){let t=e.current.nodes.at(-1),n=e.current.kinds.length+1,i;for(let r of e.graph.incidentEdges(t)){let a=r.source===t,o=a?r.target:r.source;if((e.visitedDepth.get(o)??Number.POSITIVE_INFINITY)<n)continue;e.visitedDepth.set(o,n);let s=e.graph.registry().require(r.kind),c={nodes:[...e.current.nodes,o],kinds:[...e.current.kinds,a?r.kind:s.inverse??r.kind]};e.details.get(o)?.type?.toLowerCase()==="decision"?(i=n,e.found.push(c)):e.queue.push(c)}return i}function Ry(e){let t=[{nodes:[e.itemId],kinds:[]}],n=new Map([[e.itemId,0]]),i=[],r;for(;t.length>0;){let a=t.shift(),o=a.kinds.length;r!==void 0&&o>=r||o>=e.maxDepth||(r=Iy({current:a,graph:e.graph,details:e.details,visitedDepth:n,queue:t,found:i})??r)}return i.sort((a,o)=>a.nodes.join("\0").localeCompare(o.nodes.join("\0"))),i}function Ay(e,t,n){let i=$l(t);if(!i.graph.hasNode(e))return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let r=Ry({itemId:e,maxDepth:n,graph:i.graph,details:new Map(i.details.map(s=>[s.id,s]))}),a=r[0];if(!a)return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let o=[...new Set(r.map(s=>s.nodes.at(-1)))];return{status:o.length===1?"found":"ambiguous",nodes:a.nodes,kinds:a.kinds,alternative_decision_ids:o.slice(1)}}async function Cy(e){if(!e.lineRange)return{commitLines:new Map,commitItems:new Map,available:!0};try{return await xy({workspaceRoot:e.workspaceRoot,sourcePath:e.paths[0],lineRange:e.lineRange})}catch{return{commitLines:new Map,commitItems:new Map,available:!1}}}function Ty(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 $y(e){return[...e.commitLines.keys()].filter(t=>(e.commitItems.get(t)?.length??0)>0)}async function Au(e){Ru(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 Cy(e),i=$y(n),r=new Map;for(let a of e.candidates){let o=[...n.commitLines.entries()].filter(([l])=>n.commitItems.get(l)?.includes(a.item.id)),s=o.reduce((l,[,u])=>l+u,0),c=Ay(a.item.id,e.corpus,t),d=Ty({hasLineRange:e.lineRange!==void 0,attributionAvailable:n.available,contributionLines:s,decisionStatus:c.status});r.set(a.item.id,{score:s*100+a.files.length*10+Math.max(0,9-Math.floor((Date.now()-Date.parse(a.item.updated_at))/(720*60*60*1e3))),contribution_lines:s,evidence:[...a.files.map(l=>({kind:"linked_file",reference:l.path})),...o.map(([l,u])=>({kind:"git_commit",reference:l.slice(0,12),contribution_lines:u}))],rationale:{value:a.item.value?.trim()||null,why_now:a.item.why_now?.trim()||null,outcome:a.item.outcome?.trim()||null,objective:a.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}}}(function(){try{var e=typeof window<"u"?window:typeof 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 ni=["software-delivery","research","agent-evaluation","operations"];function Cu(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 Rr(e,t,n,i,r){let a=`preset-${e}`,o=r.map(c=>({id:`${a}-missing-${c}`,description:`Active items missing ${c} evidence.`,source:{kind:"links",link:c,state:"missing"}})),s=o.map(c=>Cu(`${c.id}-zero`,c.id,i,0,"warn"));return{id:e,title:t,description:n,declarations:{measurements:o,assertions:s,gates:[{id:`${a}-readiness`,description:n,assertion_ids:s.map(c=>c.id),triggers:["ci","scheduled"]}]}}}function Ar(e,t){return e==="software-delivery"?Rr(e,"Software delivery","Warn when active delivery work lacks executable tests or documentation.",t,["tests","docs"]):e==="research"?Rr(e,"Research","Warn when active research work lacks reproducibility files or documentation.",t,["files","docs"]):e==="agent-evaluation"?Rr(e,"Agent evaluation","Warn when active evaluation work lacks executable scenarios or recorded artifacts.",t,["tests","files"]):Rr(e,"Operations","Warn when active operational work lacks runbook documentation or repair evidence.",t,["docs","files"])}function Tu(e,t,n,i={}){return lo(e,Ar(t,n).declarations,i)}async function $u(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 a={id:`derived-active-missing-${r}`,description:`Observed active items missing ${r} evidence.`,source:{kind:"links",link:r,state:"missing"}},o=(await co(a,i)).value,s=Cu(`${a.id}-ceiling`,a.id,t,o,"observe"),c=`active-missing-${r}`;return{id:c,population_size:i.items.length,scope:{kind:"active"},observed:o,declarations:{measurements:[a],assertions:[s],gates:[{id:`derived-${c}`,description:`Observe the accepted ${r} evidence baseline.`,assertion_ids:[s.id],triggers:["ci","scheduled"]}]}}}))}function Du(e,t,n={}){return lo(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 Ou(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 kr(e,"assertion",{...t,enforcement:n},{...i,message:i.message??`Promote assurance assertion ${t.id} from ${t.enforcement} to ${n}`})}import Nu from"node:fs/promises";import{createRequire as Dy}from"node:module";import Ae 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 Pu(e,t){let n=Ae.relative(t,e);if(n.length>0&&n!==".."&&!n.startsWith(`..${Ae.sep}`)&&!Ae.isAbsolute(n))return n.split(Ae.sep).join("/");let i=Ae.resolve(e),r=0xcbf29ce484222325n;for(let a=0;a<i.length;a+=1)r^=BigInt(i.charCodeAt(a)),r=BigInt.asUintN(64,r*0x100000001b3n);return`<external>/${r.toString(16).padStart(16,"0")}/${Ae.basename(Ae.dirname(e))}/package.json`}function Oy(e){return e.includes(`${Ae.sep}.pnpm${Ae.sep}`)?"pnpm":e.includes(`${Ae.sep}node_modules${Ae.sep}`)?"npm":"other"}async function Lu(e){try{let t=JSON.parse(await Nu.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 wo(e){try{return await Nu.realpath(e)}catch{return Ae.resolve(e)}}async function Mu(e,t,n=Ge(import.meta.url,["../../.."])){let i=await wo(t),r=await wo(Ae.join(n,"package.json")),a=await Lu(r),o=new Map;a!==void 0&&o.set(r,{version:a,path:Pu(r,i),layout:"host",consumers:["pm-cli-host"]});for(let d of e)try{let l=Dy(d.entry_path).resolve("@unbrained/pm-cli/package.json"),u=await wo(l),m=await Lu(u);if(m===void 0)continue;let f=u,p=o.get(f);if(p){p.consumers.includes(d.name)||(p.consumers.push(d.name),p.consumers.sort((h,_)=>h.localeCompare(_)));continue}o.set(f,{version:m,path:Pu(u,i),layout:Oy(u),consumers:[d.name]})}catch{}let s=[...o.values()].sort((d,l)=>d.path.localeCompare(l.path)),c=a===void 0?[]:s.filter(d=>d.version!==a);return{host_version:a??null,copies:s,mismatches:c,warnings:c.map(d=>`extension_host_pm_cli_version_skew:${a}:${d.version}:${d.consumers.join("+")}`)}}import vo from"node:fs/promises";import bo from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="069e2e60-11d9-5a37-a966-9073944d32a2")}catch{}})();var ju=8388608,Py=new Set(["resolved","failed"]),Ly=[{kind:"boolean",matches:e=>typeof e=="boolean"||typeof e=="string"&&/^(?:true|false)$/iu.test(e.trim())},{kind:"single_digit",matches:e=>typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=9||typeof e=="string"&&/^\d$/u.test(e.trim())}];function Ze(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ko(e){return Ly.find(t=>t.matches(e))?.kind}function Fu(e){let t=new Map,n=0,i=0;return{entries:e.map(r=>{let a=Ze(r.agent_provenance)?r.agent_provenance:void 0;if(a===void 0||!qd(r).ok)return r;let o={},s=!1;for(let[d,l]of Object.entries(a)){let u=Ze(l)?ko(l.value):void 0;if(u===void 0){o[d]=l;continue}s=!0,i+=1;let m=r.agent_harness??"unknown",f=`${m}\0${d}\0${u}`,p=t.get(f)??{harness:m,dimension:d,kind:u,count:0};p.count+=1,t.set(f,p)}if(!s)return r;n+=1;let c={...r};return Object.keys(o).length===0?delete c.agent_provenance:c.agent_provenance=o,Gd(r,c,{retainPriorRecord:!0,retainPriorRecordHash:!1})}),receipt:{changed:n>0,events_changed:n,observations_removed:i,invalid_values:[...t.values()].sort((r,a)=>r.harness.localeCompare(a.harness)||r.dimension.localeCompare(a.dimension)||r.kind.localeCompare(a.kind))}}}async function Uu(e){let t=[];for(let n of await Hu(e)??[])try{let i=await vo.readFile(bo.join(e,"history",n),"utf8");for(let r of i.split(`
|
|
9
9
|
`)){if(r.trim().length===0)continue;let a=zu(r);if(!(a===null||!Ze(a.agent_provenance))&&Object.values(a.agent_provenance).some(o=>Ze(o)&&ko(o.value)!==void 0)){t.push(n.slice(0,-6));break}}}catch{}return t}async function Hu(e){try{return(await vo.readdir(bo.join(e,"history"))).filter(t=>t.endsWith(".jsonl")).sort()}catch{return null}}async function Ny(e,t,n){let i;try{i=await vo.open(bo.join(e,"history",t),"r");let r=(await i.stat()).size,a=Math.min(r,Math.max(0,n)),o=Buffer.alloc(a),{bytesRead:s}=await i.read(o,0,a,0),c=o.subarray(0,s).toString("utf8"),d=s>=r,l=c.lastIndexOf(`
|
|
10
10
|
`),u=c;return d||(u=l===-1?"":c.slice(0,l+1)),{content:u,bytesRead:s,complete:d}}catch{return null}finally{await i?.close()}}function zu(e){try{let t=JSON.parse(e);return Ze(t)?t:null}catch{return null}}function My(e,t,n){let i=typeof e.agent_harness=="string"?e.agent_harness:void 0;if(i===void 0)return;let r=Ze(e.agent_provenance)?e.agent_provenance:{};if(Object.entries(r).forEach(([o,s])=>{if(!Ze(s))return;let c=ko(s.value);if(!c)return;let d=`${i}\0${o}\0${c}`,l=n.get(d)??{harness:i,dimension:o,kind:c,count:0};l.count+=1,n.set(d,l)}),!Ze(e.context))return;let a=e.context.agent_provenance_outcomes;Ze(a)&&Object.entries(a).forEach(([o,s])=>{if(!Ze(s)||typeof s.resolver!="string"||!Py.has(String(s.status)))return;let c=`${i}\0${o}\0${s.resolver}`,d=t.get(c)??{harness:i,dimension:o,resolver:s.resolver,attempts:0,successes:0};d.attempts+=1,s.status==="resolved"&&(d.successes+=1),t.set(c,d)})}function jy(e,t,n,i,r,a){let o=r;for(let s of e.split(`
|
|
11
|
-
`)){if(s.trim().length===0)continue;if(o>=i)return{eventsRead:o,truncated:!0};o+=1;let c=zu(s);if(c===null){a.malformed_events+=1;continue}if(typeof c.ts=="string"&&vt(c.ts)){let d=new Date(c.ts).toISOString();(a.earliest_event_at===null||d<a.earliest_event_at)&&(a.earliest_event_at=d),(a.latest_event_at===null||d>a.latest_event_at)&&(a.latest_event_at=d)}My(c,t,n)}return{eventsRead:o,truncated:!1}}function Fy(e,t,n){return n?[...e.filter(i=>i.attempts>0&&i.successes===0).map(i=>`provenance_resolver_zero_success:${i.harness}:${i.dimension}:${i.resolver}:${String(i.attempts)}`),...t.map(i=>`provenance_value_domain_invalid:${i.harness}:${i.dimension}:${i.kind}:${String(i.count)}`)]:[]}async function Wu(e,t=1e4){if(!Number.isSafeInteger(t)||t<0)throw new RangeError("Provenance event limit must be a non-negative safe integer.");let n={scope:"history_prefix",event_limit:t,byte_limit:ju,bytes_read:0,events_read:0,truncated:!1,unreadable_sources:0,malformed_events:0,earliest_event_at:null,latest_event_at:null,complete:!1},i=new Map,r=new Map,a=0,o=0,s=!1,c=await Hu(e);c===null&&(n.unreadable_sources+=1);for(let u of c??[]){let m=await Ny(e,u,Math.max(0,ju-o));if(m===null){n.unreadable_sources+=1;continue}o+=m.bytesRead;let f=jy(m.content,i,r,t,a,n);if(a=f.eventsRead,f.truncated){s=!0;break}if(!m.complete){s=!0;break}}let d=[...i.values()].sort((u,m)=>u.harness.localeCompare(m.harness)||u.dimension.localeCompare(m.dimension)||u.resolver.localeCompare(m.resolver)),l=[...r.values()].sort((u,m)=>u.harness.localeCompare(m.harness)||u.dimension.localeCompare(m.dimension)||u.kind.localeCompare(m.kind));return n.bytes_read=o,n.events_read=a,n.truncated=s,n.complete=!s&&n.unreadable_sources===0&&n.malformed_events===0,{outcomes:d,sample:n,invalid_values:l,warnings:Fy(d,l,n.complete),events_read:a,truncated:s}}import Uy from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="eeaf2318-5964-5d98-ad90-9faa7fc69975")}catch{}})();function Eo(e){if(!e.itemDocument)return[];let t=e.itemDocument.metadata?.assignee?.trim();if(!t||t===e.author||e.force)return[];let n=je(e.settings);if(n.ownership_enforcement==="strict")throw new g(`Item ${e.subjectId} is assigned to ${t}. Use --force to override.`,y.CONFLICT);return n.ownership_enforcement==="warn"?[`ownership_warning:assignee_conflict:${e.subjectId}:${t}`]:[]}async function Hy(e){let t=await B(e.subject.historyPath);if(t!==e.historyRawBeforeLock)throw new g(`History for ${e.subject.id} changed while waiting for lock; retry ${e.operation}.`,y.CONFLICT);let n=await ge(e.pmRoot,e.subject.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder),i=n?e.readItem?await e.readItem(n):await ye(n,{schema:e.settings.schema}):null;if((i?.raw??null)!==(e.currentItemRawBeforeLock??null))throw new g(`Item ${e.subject.id} changed while waiting for lock; retry ${e.operation}.`,y.CONFLICT);return{historyRawUnderLock:t,locatedUnderLock:n,loadedItemUnderLock:i}}async function Cr(e){let t=e.writeHistoryRaw??Z;try{await t(e.historyPath,e.nextHistoryRaw),await Ba(e.historyPath)}catch(n){try{e.historyRawUnderLock===null?await Uy.rm(e.historyPath,{force:!0}):await t(e.historyPath,e.historyRawUnderLock),await Ba(e.historyPath)}catch(i){throw new AggregateError([n,i],`History rewrite failed and rollback also failed: ${String(n)}`)}throw n}}async function qu(e){let t=[...Eo({itemDocument:e.itemDocument,subjectId:e.subject.id,author:e.author,force:e.force,settings:e.settings})],n=await re(e.pmRoot,e.subject.id,e.settings.locks.ttl_seconds,e.author,!!e.force,e.settings.governance.force_required_for_stale_lock,e.settings.locks.wait_ms);try{let i=await Hy({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:e.operation});return await e.applyRewrite(i),e.applyPostRewrite&&t.push(...await e.applyPostRewrite(i)),t}finally{await n()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6283ef18-f75e-5e8c-a65f-0ba05858bc2b")}catch{}})();async function Gu(e){let{subject:t,settings:n,operation:i,options:r}=e,a=await Hd(t.historyPath,t.id);if(a.raw===null)throw new g(`No history stream exists for ${t.id}.`,y.NOT_FOUND);if(a.entries.length===0)throw new g(`No history entries exist for ${t.id}; nothing to ${i.slice(8)}.`,y.USAGE);let o=t.located?await ye(t.located,{schema:n.schema}):null,s=z(r.author,n.author_default),c=await e.transform({raw:a.raw,entries:a.entries,verification:Gn(a.entries),loadedItem:o,author:s}),d=Gn(c.rewrittenEntries);if(!d.ok)throw new g(`${i} produced an invalid rewritten chain (${d.errors.join(", ")}).`,y.GENERIC_FAILURE);let l=c.changed&&!r.dryRun?await qu({pmRoot:e.pmRoot,subject:t,settings:n,typeRegistry:e.typeRegistry,historyRawBeforeLock:a.raw,currentItemRawBeforeLock:o?.raw??null,operation:i,author:s,force:r.force,itemDocument:o?.document??null,applyRewrite:async u=>{await c.beforeWrite?.(),c.applyRewrite?await c.applyRewrite(u):await Cr({historyPath:t.historyPath,nextHistoryRaw:Nt(c.rewrittenEntries),historyRawUnderLock:u.historyRawUnderLock})},applyPostRewrite:c.afterWrite??(async()=>K({path:t.historyPath,scope:"project",op:`${i.replace("-","_")}:history`}))}):[];return c.report({verification:d,warnings:l})}(function(){try{var e=typeof window<"u"?window:typeof 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 Tr(e,t,n=25){let i=e.definitions.filter(o=>o.roles.length===0).map(o=>o.id).sort((o,s)=>o.localeCompare(s)),r=new Set(i),a=t.filter(o=>{let s=ad(o.status,e);return s!==void 0&&r.has(s)}).map(o=>o.id).sort((o,s)=>o.localeCompare(s));return{roleless_status_count:i.length,roleless_statuses:i.slice(0,n),roleless_statuses_truncated:i.length>n,affected_item_count:a.length,affected_item_ids:a.slice(0,n),affected_item_ids_truncated:a.length>n}}function $r(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 Ju=8,So=100;function Vu(e,t){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function Fe(e,t){return Array.isArray(e)?{count:e.length,sample:e.slice(0,t),truncated:e.length>t}:{count:0,sample:[],truncated:!1}}function zy(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 ii(e,t){let n=Fe(e,t);return{...n,sample:n.sample.map(i=>zy(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 Wy(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 qy={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:ii(e.discovered,t),effective:ii(e.effective,t),loaded:ii(e.loaded,t),failed:Fe(e.failed,t),warnings:W(e.warnings,t),activation:{failed:Fe(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:Wy(n.migration_status)},author_manifest:e.author_manifest,triage:e.triage,capability_contract:e.capability_contract,capability_guidance:Fe(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:Fe(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:Fe(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:Fe(e.history_conflict_markers,t),history_invalid_json:Fe(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 xo(e,t){let n=qy[e.name];return n?n(e.details,t):e.details}function Ku(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 Gy(e){if(e.name==="extensions"&&e.status==="ok")return Ku(e);let t=xo(e,8);return Buffer.byteLength(JSON.stringify(t))<Buffer.byteLength(JSON.stringify(e.details))?t:e.details}function Io(e,t){let n=new Set([...t,...e.failed_because]);return(e.findings??[]).filter(i=>n.has(i.warning))}function By(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:Gy(n)})),warnings:t.sample,findings:Io(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 Bu(e){return e.details.skipped===!0}function Jy(e){let t=W(e.warnings,8),n=e.checks.filter(Bu).map(i=>i.name);return{ok:e.ok,...e.verdict?{verdict:e.verdict}:{},checks:e.checks.filter(i=>!Bu(i)).map(i=>({name:i.name,status:i.status,ok:i.ok,details:{}})),warning_count:t.count,warnings:t.sample,findings:Io(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 Vy(e,t,n){return t.full===!0?e:n?Jy(e):t.brief===!0?By(e):{...e,checks:e.checks.map(i=>i.name==="extensions"&&i.status==="ok"?{...i,details:Ku(i)}:i),projection:{mode:"standard",warning_count:e.warning_count,warnings_truncated:e.warnings_truncated===!0,detail_limit:8}}}function Ro(e,t,n){let i=e.warning_count??e.warnings.length,r=e.warnings.slice(0,100),a={...e,warning_count:i,warning_limit:100,warnings_truncated:i>100,warnings:r,findings:Io(e,r)},o=Vy(a,t,n);return{...o,warning_count:i,warning_limit:100,warnings_truncated:i>o.warnings.length,...o.projection?{projection:{...o.projection,warning_count:i,warnings_truncated:i>o.warnings.length}}:{}}}import Co from"node:fs/promises";import ce from"node:path";import Ky from"node:readline/promises";import{stdin as Yy,stdout as Dr}from"node:process";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f3a0706e-7162-5cde-9f48-c5de9b2fbd8e")}catch{}})();var I$=["ask","add","skip","status"],Xy=["AGENTS.md","CLAUDE.md"],Zy=["pm init","pm context","pm search","pm create","pm claim","pm files","pm docs","pm test --run","pm close","pm release","pm_author"],Qy=8,To=1,ew="<!-- pm-cli:agent-guidance:start:",tw=`<!-- pm-cli:agent-guidance:start:v${To} -->`,Ao="<!-- pm-cli:agent-guidance:end -->",ai="Add workflow guidance later: pm init --agent-guidance add";var nw=()=>Ky.createInterface({input:Yy,output:Dr});function hn(e,t){let n=ce.relative(e,t);return n.length===0?ce.basename(t):n.split(ce.sep).join("/")}function Yu(e){return e.endsWith(`
|
|
11
|
+
`)){if(s.trim().length===0)continue;if(o>=i)return{eventsRead:o,truncated:!0};o+=1;let c=zu(s);if(c===null){a.malformed_events+=1;continue}if(typeof c.ts=="string"&&vt(c.ts)){let d=new Date(c.ts).toISOString();(a.earliest_event_at===null||d<a.earliest_event_at)&&(a.earliest_event_at=d),(a.latest_event_at===null||d>a.latest_event_at)&&(a.latest_event_at=d)}My(c,t,n)}return{eventsRead:o,truncated:!1}}function Fy(e,t,n){return n?[...e.filter(i=>i.attempts>0&&i.successes===0).map(i=>`provenance_resolver_zero_success:${i.harness}:${i.dimension}:${i.resolver}:${String(i.attempts)}`),...t.map(i=>`provenance_value_domain_invalid:${i.harness}:${i.dimension}:${i.kind}:${String(i.count)}`)]:[]}async function Wu(e,t=1e4){if(!Number.isSafeInteger(t)||t<0)throw new RangeError("Provenance event limit must be a non-negative safe integer.");let n={scope:"history_prefix",event_limit:t,byte_limit:ju,bytes_read:0,events_read:0,truncated:!1,unreadable_sources:0,malformed_events:0,earliest_event_at:null,latest_event_at:null,complete:!1},i=new Map,r=new Map,a=0,o=0,s=!1,c=await Hu(e);c===null&&(n.unreadable_sources+=1);for(let u of c??[]){let m=await Ny(e,u,Math.max(0,ju-o));if(m===null){n.unreadable_sources+=1;continue}o+=m.bytesRead;let f=jy(m.content,i,r,t,a,n);if(a=f.eventsRead,f.truncated){s=!0;break}if(!m.complete){s=!0;break}}let d=[...i.values()].sort((u,m)=>u.harness.localeCompare(m.harness)||u.dimension.localeCompare(m.dimension)||u.resolver.localeCompare(m.resolver)),l=[...r.values()].sort((u,m)=>u.harness.localeCompare(m.harness)||u.dimension.localeCompare(m.dimension)||u.kind.localeCompare(m.kind));return n.bytes_read=o,n.events_read=a,n.truncated=s,n.complete=!s&&n.unreadable_sources===0&&n.malformed_events===0,{outcomes:d,sample:n,invalid_values:l,warnings:Fy(d,l,n.complete),events_read:a,truncated:s}}import Uy from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="eeaf2318-5964-5d98-ad90-9faa7fc69975")}catch{}})();function Eo(e){if(!e.itemDocument)return[];let t=e.itemDocument.metadata?.assignee?.trim();if(!t||t===e.author||e.force)return[];let n=je(e.settings);if(n.ownership_enforcement==="strict")throw new g(`Item ${e.subjectId} is assigned to ${t}. Use --force to override.`,y.CONFLICT);return n.ownership_enforcement==="warn"?[`ownership_warning:assignee_conflict:${e.subjectId}:${t}`]:[]}async function Hy(e){let t=await B(e.subject.historyPath);if(t!==e.historyRawBeforeLock)throw new g(`History for ${e.subject.id} changed while waiting for lock; retry ${e.operation}.`,y.CONFLICT);let n=await ge(e.pmRoot,e.subject.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder),i=n?e.readItem?await e.readItem(n):await ye(n,{schema:e.settings.schema}):null;if((i?.raw??null)!==(e.currentItemRawBeforeLock??null))throw new g(`Item ${e.subject.id} changed while waiting for lock; retry ${e.operation}.`,y.CONFLICT);return{historyRawUnderLock:t,locatedUnderLock:n,loadedItemUnderLock:i}}async function Cr(e){let t=e.writeHistoryRaw??Z;try{await t(e.historyPath,e.nextHistoryRaw),await Ba(e.historyPath)}catch(n){try{e.historyRawUnderLock===null?await Uy.rm(e.historyPath,{force:!0}):await t(e.historyPath,e.historyRawUnderLock),await Ba(e.historyPath)}catch(i){throw new AggregateError([n,i],`History rewrite failed and rollback also failed: ${String(n)}`)}throw n}}async function qu(e){let t=[...Eo({itemDocument:e.itemDocument,subjectId:e.subject.id,author:e.author,force:e.force,settings:e.settings})],n=await re(e.pmRoot,e.subject.id,e.settings.locks.ttl_seconds,e.author,!!e.force,e.settings.governance.force_required_for_stale_lock,e.settings.locks.wait_ms);try{let i=await Hy({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:e.operation});return await e.applyRewrite(i),e.applyPostRewrite&&t.push(...await e.applyPostRewrite(i)),t}finally{await n()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6283ef18-f75e-5e8c-a65f-0ba05858bc2b")}catch{}})();async function Gu(e){let{subject:t,settings:n,operation:i,options:r}=e,a=await Hd(t.historyPath,t.id);if(a.raw===null)throw new g(`No history stream exists for ${t.id}.`,y.NOT_FOUND);if(a.entries.length===0)throw new g(`No history entries exist for ${t.id}; nothing to ${i.slice(8)}.`,y.USAGE);let o=t.located?await ye(t.located,{schema:n.schema}):null,s=z(r.author,n.author_default),c=await e.transform({raw:a.raw,entries:a.entries,verification:Gn(a.entries),loadedItem:o,author:s}),d=Gn(c.rewrittenEntries);if(!d.ok)throw new g(`${i} produced an invalid rewritten chain (${d.errors.join(", ")}).`,y.GENERIC_FAILURE);let l=c.changed&&!r.dryRun?await qu({pmRoot:e.pmRoot,subject:t,settings:n,typeRegistry:e.typeRegistry,historyRawBeforeLock:a.raw,currentItemRawBeforeLock:o?.raw??null,operation:i,author:s,force:r.force,itemDocument:o?.document??null,applyRewrite:async u=>{await c.beforeWrite?.(),c.applyRewrite?await c.applyRewrite(u):await Cr({historyPath:t.historyPath,nextHistoryRaw:Nt(c.rewrittenEntries),historyRawUnderLock:u.historyRawUnderLock})},applyPostRewrite:c.afterWrite??(async()=>K({path:t.historyPath,scope:"project",op:`${i.replace("-","_")}:history`}))}):[];return c.report({verification:d,warnings:l})}(function(){try{var e=typeof window<"u"?window:typeof 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 Tr(e,t,n=25){let i=e.definitions.filter(o=>o.roles.length===0).map(o=>o.id).sort((o,s)=>o.localeCompare(s)),r=new Set(i),a=t.filter(o=>{let s=ad(o.status,e);return s!==void 0&&r.has(s)}).map(o=>o.id).sort((o,s)=>o.localeCompare(s));return{roleless_status_count:i.length,roleless_statuses:i.slice(0,n),roleless_statuses_truncated:i.length>n,affected_item_count:a.length,affected_item_ids:a.slice(0,n),affected_item_ids_truncated:a.length>n}}function $r(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 Ju=8,So=100;function Vu(e,t){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function Fe(e,t){return Array.isArray(e)?{count:e.length,sample:e.slice(0,t),truncated:e.length>t}:{count:0,sample:[],truncated:!1}}function zy(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 ii(e,t){let n=Fe(e,t);return{...n,sample:n.sample.map(i=>zy(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 Wy(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 qy={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:ii(e.discovered,t),effective:ii(e.effective,t),loaded:ii(e.loaded,t),failed:Fe(e.failed,t),warnings:W(e.warnings,t),activation:{failed:Fe(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:Wy(n.migration_status)},author_manifest:e.author_manifest,triage:e.triage,capability_contract:e.capability_contract,capability_guidance:Fe(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:Fe(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:Fe(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:Fe(e.history_conflict_markers,t),history_invalid_json:Fe(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 xo(e,t){let n=qy[e.name];return n?n(e.details,t):e.details}function Ku(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 Gy(e){if(e.name==="extensions"&&e.status==="ok")return Ku(e);let t=xo(e,8);return Buffer.byteLength(JSON.stringify(t))<Buffer.byteLength(JSON.stringify(e.details))?t:e.details}function Io(e,t){let n=new Set([...t,...e.failed_because]);return(e.findings??[]).filter(i=>n.has(i.warning))}function By(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:Gy(n)})),warnings:t.sample,findings:Io(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 Bu(e){return e.details.skipped===!0}function Jy(e){let t=W(e.warnings,8),n=e.checks.filter(Bu).map(i=>i.name);return{ok:e.ok,...e.verdict?{verdict:e.verdict}:{},checks:e.checks.filter(i=>!Bu(i)).map(i=>({name:i.name,status:i.status,ok:i.ok,details:{}})),warning_count:t.count,warnings:t.sample,findings:Io(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 Vy(e,t,n){return t.full===!0?e:n?Jy(e):t.brief===!0?By(e):{...e,checks:e.checks.map(i=>i.name==="extensions"&&i.status==="ok"?{...i,details:Ku(i)}:i),projection:{mode:"standard",warning_count:e.warning_count,warnings_truncated:e.warnings_truncated===!0,detail_limit:8}}}function Ro(e,t,n){let i=e.warning_count??e.warnings.length,r=e.warnings.slice(0,100),a={...e,warning_count:i,warning_limit:100,warnings_truncated:i>100,warnings:r,findings:Io(e,r)},o=Vy(a,t,n);return{...o,warning_count:i,warning_limit:100,warnings_truncated:i>o.warnings.length,...o.projection?{projection:{...o.projection,warning_count:i,warnings_truncated:i>o.warnings.length}}:{}}}import Co from"node:fs/promises";import ce from"node:path";import Ky from"node:readline/promises";import{stdin as Yy,stdout as Dr}from"node:process";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bb8a4985-8bc0-5290-a6f9-310d940cf4d7")}catch{}})();var I$=["ask","add","skip","status"],Xy=["AGENTS.md","CLAUDE.md"],Zy=["pm init","pm context","pm search","pm create","pm claim","pm files","pm docs","pm test --run","pm close","pm release","pm_author"],Qy=8,To=1,ew="<!-- pm-cli:agent-guidance:start:",tw=`<!-- pm-cli:agent-guidance:start:v${To} -->`,Ao="<!-- pm-cli:agent-guidance:end -->",ai="Add workflow guidance later: pm init --agent-guidance add";var nw=()=>Ky.createInterface({input:Yy,output:Dr});function hn(e,t){let n=ce.relative(e,t);return n.length===0?ce.basename(t):n.split(ce.sep).join("/")}function Yu(e){return e.endsWith(`
|
|
12
12
|
`)?e:`${e}
|
|
13
13
|
`}function iw(e){return e.includes(`\r
|
|
14
14
|
`)?`\r
|
|
15
15
|
`:`
|
|
16
|
-
`}function Xu(e){let t=e.indexOf(ew);if(t===-1)return null;let n=e.indexOf(Ao,t);return n===-1?null:{start_index:t,end_index:n+Ao.length}}function rw(e){return Xu(e)!==null}function aw(e,t="<your project test command>"){return[tw,"## pm Workflow (Agent Quickstart)","",'- Cold start with the measured canonical orientation: `pm context --
|
|
16
|
+
`}function Xu(e){let t=e.indexOf(ew);if(t===-1)return null;let n=e.indexOf(Ao,t);return n===-1?null:{start_index:t,end_index:n+Ao.length}}function rw(e){return Xu(e)!==null}function aw(e,t="<your project test command>"){return[tw,"## pm Workflow (Agent Quickstart)","",'- Cold start with the measured canonical orientation: `pm context --for orient`; before item mutation, also run `pm search "<keywords>" --limit 10`, `pm list --status open --limit 20`, and `pm list --status in_progress --limit 20`.',"- Claim and start: `pm claim <id> --start`, or `pm claim --next --start` to take the next available item in one write.",`- Link evidence while coding: \`pm files <id> --add ...\`, \`pm docs <id> --add ...\`, \`pm test <id> --add command="${t}"\`.`,'- Verify and close: `pm test <id> --run --progress`, then atomically record closure evidence with `pm close <id> "<reason>" --resolution "<what changed>" --expected "<expected outcome>" --actual "<observed outcome>" --validate-close warn`, then `pm release <id>`.',"- Author identity is automatic for supported agent harnesses; use `--author` only for an explicit override.","",Ao,""].join(e)}function Zu(e,t="<your project test command>"){let n=iw(e),i=aw(n,t),r=Xu(e);if(r){let s=e.slice(r.end_index),c=s.startsWith(`\r
|
|
17
17
|
`)?s.slice(2):s.startsWith(`
|
|
18
18
|
`)?s.slice(1):s,d=Yu(`${e.slice(0,r.start_index)}${i}${c}`);return{next_content:d,changed:d!==e}}let a=e.length===0?"":e.endsWith(`
|
|
19
19
|
`)?`
|
|
@@ -49,7 +49,7 @@ ${d}`,y.GENERIC_FAILURE)}}function Ym(e){let t=e.trim(),n=t.includes("@file:")?t
|
|
|
49
49
|
`,conflict_paths:c,paths_from_theirs:d,preferred:r}}import ea from"node:path";import{execFile as bS}from"node:child_process";import{createHash as Of}from"node:crypto";import{readdir as kS}from"node:fs/promises";import ES from"node:path";import{promisify as SS}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="af5442e7-c8af-5d81-8c89-7f1a98159cec")}catch{}})();var mt=SS(bS),Qr=/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u;async function hM(e,t,n){let i=t.trim(),r=/^(['"])(.*)\1$/su.exec(i)?.[2]??i;for(let a of["rebase-merge","rebase-apply"])try{let{stdout:o}=await mt("git",["rev-parse","--path-format=absolute","--git-path",`${a}/orig-head`],{cwd:e,timeout:1e4}),s=(await Vn(o.trim(),128))?.trim();if(s===void 0||!Qr.test(s))continue;let{stdout:c}=await mt("git",["rev-parse","--verify",`${s}:${r}`],{cwd:e,timeout:1e4}),d=c.trim();return{kind:"rebase",original_head:s,original_blob:d}}catch{}if(n!==void 0&&Object.keys(process.env).some(a=>/^GITHEAD_[a-f0-9]{40}(?:[a-f0-9]{24})?$/u.test(a)))try{let{stdout:a}=await mt("git",["rev-parse","HEAD","ORIG_HEAD"],{cwd:e,timeout:1e4}),[o,s]=a.trim().split(/\r?\n/u);if(o!==s||!Qr.test(o))return;let{stdout:c}=await mt("git",["rev-parse","--verify",`${o}:${r}`],{cwd:e,timeout:1e4}),d=c.trim(),l=Of(d.length===40?"sha1":"sha256").update(`blob ${Buffer.byteLength(n)}\0`).update(n).digest("hex");return d!==l?void 0:{kind:"merge",original_head:o,original_blob:d}}catch{}}function Pf(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;return Object.keys(t).length===3&&(t.kind==="rebase"||t.kind==="merge")&&typeof t.original_head=="string"&&Qr.test(t.original_head)&&typeof t.original_blob=="string"&&Qr.test(t.original_blob)}async function Lf(e,t,n,i){if(i!==void 0&&Of(n.original_blob.length===40?"sha1":"sha256").update(`blob ${Buffer.byteLength(i)}\0`).update(i).digest("hex")!==n.original_blob)return!1;try{let{stdout:r}=await mt("git",["rev-parse","--absolute-git-dir"],{cwd:e,timeout:1e4}),a=new Set(["rebase-merge","rebase-apply","MERGE_HEAD","CHERRY_PICK_HEAD","REVERT_HEAD"]);if((await kS(r.trim())).some(d=>a.has(d)))return!1;let{stdout:o}=await mt("git",["rev-parse","HEAD"],{cwd:e,timeout:1e4});if(o.trim()!==n.original_head)return!1;let{stdout:s}=await mt("git",["rev-parse","--verify",`HEAD:${t}`],{cwd:e,timeout:1e4});if(s.trim()!==n.original_blob)return!1;let{stdout:c}=await mt("git",["hash-object","--",ES.resolve(e,t)],{cwd:e,timeout:1e4});return c.trim()!==n.original_blob?!1:(await mt("git",["diff","--cached","--quiet","HEAD","--",t],{cwd:e,timeout:1e4}),!0)}catch{return!1}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="35c5d9a8-5ae0-5e97-9ea3-f8a70a5fd7d0")}catch{}})();var xS=/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/u,IS=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u,na=2048,RS=64,AS=1e5,CS=new Set(["version","id","item_path","item_id","requested_preference","requested_preference_applied","preferred","conflict_resolution","fields_from_theirs","union_fields","merged_field_hashes","decisions","state","created_at","reconciled_at","value_availability","value_policy","evidence_source","operation","settlement"]);function pt(e){return xS.test(e)}var TS=new Set(["field","base","ours","theirs","retained","discarded","retained_side","resolution_basis"]),ia="bounded_non_sensitive_scalars_v1",$S=new Set(["open","in_progress","blocked","closed","canceled"]),DS=new Set(["risk","confidence","severity"]),OS=new Set(["low","medium","high","critical"]),Mf=new Map([["priority",new Set([0,1,2,3,4].map(A))],["status",new Set([...$S].map(A))],...[...DS].map(e=>[e,new Set([...OS].map(A))])]);function tt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function jf(e,t){return Object.keys(e).every(n=>t.has(n))}function ta(e){return Array.isArray(e)&&e.length<=na&&e.every(t=>typeof t=="string"&&t.length>0&&t.length<=256)}function ki(e){let t=[{value:e,depth:0}],n=0;for(;t.length>0;){let i=t.pop();if(n+=1,n>AS||i.depth>RS)return!1;if(Array.isArray(i.value))for(let r of i.value)t.push({value:r,depth:i.depth+1});else if(tt(i.value))for(let r of Object.values(i.value))t.push({value:r,depth:i.depth+1})}return!0}function Ff(e){if(!tt(e))return!1;let t=[void 0,"ours","theirs"],n=[void 0,"requested_preference","document_updated_at","stable_value_tiebreak"];return[jf(e,TS),typeof e.field=="string",typeof e.field=="string"&&e.field.length>0,typeof e.field=="string"&&e.field.length<=256,Object.hasOwn(e,"base"),Object.hasOwn(e,"ours"),Object.hasOwn(e,"theirs"),Object.hasOwn(e,"retained"),Object.hasOwn(e,"discarded"),ki(e.base),ki(e.ours),ki(e.theirs),ki(e.retained),ki(e.discarded),t.includes(e.retained_side),n.includes(e.resolution_basis)].every(Boolean)}function PS(e){if(!tt(e))return!1;let t=Object.entries(e);return t.length<=na&&t.every(([n,i])=>n.length>0&&n.length<=256&&typeof i=="string"&&/^[a-f0-9]{64}$/u.test(i))}function LS(e,t){if(typeof e!="string"||e.length===0||e.length>4096||e.includes("\0")||e.includes("\\")||ea.posix.isAbsolute(e))return!1;let n=ea.posix.normalize(e);return n!==".."&&!n.startsWith("../")&&ea.posix.basename(n,ea.posix.extname(n))===t}function NS(e){return!ta(e.fields_from_theirs)||!ta(e.union_fields)||!Array.isArray(e.decisions)||e.decisions.length>na||!e.decisions.every(Ff)?!1:e.merged_field_hashes===void 0||PS(e.merged_field_hashes)}function MS(e){let t=[void 0,"ours","theirs"],n=[void 0,"preferred_side","stable_value_order","latest_document_update"],i=[void 0,"clone_local","hash_only","bounded_inline","mixed"],r=[void 0,"clone_local","durable"];return t.includes(e.requested_preference)&&t.includes(e.preferred)&&(e.requested_preference_applied===void 0||typeof e.requested_preference_applied=="boolean")&&n.includes(e.conflict_resolution)&&(e.state==="pending"||e.state==="reconciled")&&i.includes(e.value_availability)&&(e.value_policy===void 0||e.value_policy===ia)&&r.includes(e.evidence_source)}function jS(e){return typeof e.created_at=="string"&&Qt(e.created_at)&&(e.reconciled_at===void 0||typeof e.reconciled_at=="string"&&Qt(e.reconciled_at))}function Nf(e,t){if(!tt(t)||oa(t)===void 0)return!1;let n=Object.keys(t);if(!n.every(r=>r==="pm_value_hash"||r==="pm_value"))return!1;if(!Object.hasOwn(t,"pm_value"))return n.length===1;let i=t.pm_value;return(i===null||Mf.get(e)?.has(A(i))===!0)&&At(i)===t.pm_value_hash}function FS(e){if(!e.decisions.every(i=>i.base===null&&i.ours===null&&i.theirs===null&&Nf(i.field,i.retained)&&Nf(i.field,i.discarded)))return!1;let t=e.decisions.reduce((i,r)=>i+(tt(r.retained)&&Object.hasOwn(r.retained,"pm_value")?1:0)+(tt(r.discarded)&&Object.hasOwn(r.discarded,"pm_value")?1:0),0),n=t===0?"hash_only":t===e.decisions.length*2?"bounded_inline":"mixed";return e.value_availability===n&&(t===0||e.value_policy===ia)}function US(e){return e.operation!==void 0&&!Pf(e.operation)?!1:e.settlement===void 0||e.settlement==="original_git_state_restored"&&e.state==="reconciled"&&e.operation!==void 0}function HS(e){for(let t of["version","id","item_path","item_id","fields_from_theirs","union_fields","decisions","state","created_at"])if(!Object.hasOwn(e,t))return"required_fields";return e.version!==1||!jf(e,CS)?"required_fields":typeof e.id!="string"||!pt(e.id)?"receipt_id":typeof e.item_id!="string"||!IS.test(e.item_id)?"item_id":LS(e.item_path,e.item_id)?null:"item_path"}function ra(e,t){if(!tt(e))return"required_fields";let n=HS(e);return n!==null?n:US(e)?NS(e)?MS(e)?jS(e)?t==="durable"&&!FS(e)?"durable_decisions":null:"timestamps":"enums":"collections":"operation"}function aa(e){if(!tt(e)||e.version!==1||e.value_policy!==void 0||!Array.isArray(e.decisions))return e;let t=(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0,n=(e.requested_preference==="ours"||e.requested_preference==="theirs")&&e.value_availability==="clone_local";return!t&&!n?e:{...e,decisions:e.decisions.map(i=>!tt(i)||!Object.hasOwn(i,"retained")||!Object.hasOwn(i,"discarded")?i:{base:V(void 0),ours:V(void 0),theirs:V(void 0),...i})}}function Uf(e){if(!tt(e))return;if(!ta(e.fields_from_theirs))return"fields_from_theirs";if(!ta(e.union_fields))return"union_fields";if(!Array.isArray(e.decisions)||e.decisions.length>na)return"decisions";let t=e.decisions.findIndex(n=>!Ff(n));return t>=0?`decisions[${t}]`:"merged_field_hashes"}function ws(e,t){return ra(e,t)===null}function oa(e){if(typeof e!="object"||e===null||Array.isArray(e)||!("pm_value_hash"in e))return;let t=e.pm_value_hash;return typeof t=="string"&&/^[a-f0-9]{64}$/u.test(t)?t:void 0}function vs(e,t){let n=Rn(t),i=At(n?void 0:t);return!n&&(t===null||Mf.get(e)?.has(A(t))===!0)?{pm_value_hash:i,pm_value:t}:{pm_value_hash: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]="7bab0a8e-842c-5588-a0b2-22ef261ddb06")}catch{}})();var JS=BS(zS),sa=100;async function bs(e){try{let{stdout:t}=await JS("git",["rev-parse","--path-format=absolute","--git-path","pm-merge-receipts"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return t.trim()}catch{return null}}async function Wf(e,t){let n=ae.dirname(ae.resolve(e,t));for(let i=0;i<12;i+=1){if(await D(ae.join(n,"settings.json")))return n;let r=ae.dirname(n);if(r===n)break;n=r}return null}function An(e){return ae.join(e,"merge-receipts")}function Tt(e){return`${e}.json`}async function Hf(e){let t;try{t=e.readReceipt?await e.readReceipt(e.receiptPath):await Vn(e.receiptPath,_r)}catch(a){if(yt(a))return null;throw a}if(t===null)throw new Error(`Receipt ${e.receiptId} settlement source is not a bounded regular file.`);let n;try{n=aa(JSON.parse(t))}catch{throw new Error(`Receipt ${e.receiptId} settlement source is not valid JSON.`)}if(!ws(n,e.evidenceSource)||n.id!==e.receiptId||e.settlement!==void 0&&n.operation===void 0||ae.basename(e.receiptPath)!==Tt(n.id))throw new Error(`Receipt ${e.receiptId} settlement source failed schema or identity validation.`);let{evidence_source:i,...r}=n;return{path:e.receiptPath,fingerprints:Si(n),modern:n.value_policy!==void 0,content:`${JSON.stringify({...r,state:"reconciled",reconciled_at:e.reconciledAt,...e.settlement?{settlement:e.settlement}:{}},null,2)}
|
|
50
50
|
`}}function Ei(e,t=!1){return xe(A({id:e.id,item_id:e.item_id,item_path:e.item_path,created_at:e.created_at,requested_preference:e.requested_preference??e.preferred??"ours",requested_preference_applied:e.requested_preference_applied??(e.conflict_resolution??"preferred_side")==="preferred_side",conflict_resolution:e.conflict_resolution??"preferred_side",fields_from_theirs:e.fields_from_theirs,union_fields:e.union_fields,merged_field_hashes:e.merged_field_hashes??null,operation:e.operation??null,decisions:t?e.decisions.map(n=>({field:n.field,retained_hash:xe(A(V(n.retained))),discarded_hash:xe(A(V(n.discarded)))})):ca(e).decisions}))}function Si(e){let t=[Ei(e)];return e.value_policy===void 0&&(e.value_availability===void 0||e.value_availability==="clone_local")&&t.push(Ei(e,!0)),t}function VS(e,t){let{reconciled_at:n,settlement:i,...r}=e;return t.state==="reconciled"?{...r,state:"reconciled",reconciled_at:t.reconciled_at,...t.settlement===void 0?{}:{settlement:t.settlement}}:{...r,state:"pending"}}async function KS(e,t,n){let i=new Map;for(let r of t){let a=e.get(r.id);if(r.state!=="reconciled"||a===void 0)continue;let o=i.get(a.item_id);if(o===void 0){try{o=await Me(ae.join(n,"history",`${a.item_id}.jsonl`),a.item_id),kt(o).ok||(o=[])}catch{o=[]}i.set(a.item_id,o)}let s=a.settlement==="original_git_state_restored",c=A({...ca(a),...s?{reason:a.settlement,operation:a.operation}:{}});if(!o.some(d=>{if(d.op!=="merge_reconcile"||d.record_hash_version===void 0)return!1;let l=d.context?.merge;if(typeof l!="object"||l===null||Array.isArray(l))return!1;let u=l[s?"abandoned_receipts":"receipts"];return Array.isArray(u)&&u.some(m=>A(m)===c)})){let{reconciled_at:d,settlement:l,...u}=a;e.set(a.id,{...u,state:"pending"})}}}function ca(e){return{receipt_id:e.id,item_id:e.item_id,item_path:e.item_path,conflict_fields:e.decisions.map(t=>t.field),fields_from_theirs:e.fields_from_theirs,union_fields:e.union_fields,requested_preference:e.requested_preference??e.preferred??"ours",requested_preference_applied:e.requested_preference_applied??(e.conflict_resolution??"preferred_side")==="preferred_side",conflict_resolution:e.conflict_resolution,decisions:e.decisions.map(t=>({field:t.field,retained_hash:oa(t.retained)??At(Rn(t.retained)?void 0:t.retained),discarded_hash:oa(t.discarded)??At(Rn(t.discarded)?void 0:t.discarded)}))}}async function FM(e){let t=await bs(e.cwd);if(t===null)return null;let n=e.itemPath.trim(),i=/^(['"])(.*)\1$/su.exec(n)?.[2]??n,r=ae.basename(i,ae.extname(i)),a={version:1,id:WS(),item_path:i.replaceAll("\\","/"),item_id:r,requested_preference:e.preferred,requested_preference_applied:(e.conflictResolution??"preferred_side")==="preferred_side",conflict_resolution:e.conflictResolution??"preferred_side",fields_from_theirs:[...e.fieldsFromTheirs],union_fields:[...e.unionFields],...e.mergedFieldHashes?{merged_field_hashes:{...e.mergedFieldHashes}}:{},decisions:structuredClone(e.decisions).map(s=>({...s,base:V(s.base),ours:V(s.ours),theirs:V(s.theirs),retained:V(s.retained),discarded:V(s.discarded)})),...e.operation?{operation:e.operation}:{},state:"pending",created_at:$(),value_availability:"clone_local"};await Fn(t),await Z(ae.join(t,Tt(a.id)),`${JSON.stringify(a,null,2)}
|
|
51
51
|
`);let o=await Wf(e.cwd,a.item_path);if(o!==null){let s=An(o),c=a.decisions.map(u=>({field:u.field,base:null,ours:null,theirs:null,retained:vs(u.field,u.retained),discarded:vs(u.field,u.discarded),retained_side:u.retained_side,resolution_basis:u.resolution_basis})),d=c.reduce((u,m)=>u+(Object.hasOwn(m.retained,"pm_value")?1:0)+(Object.hasOwn(m.discarded,"pm_value")?1:0),0),l={...a,decisions:c,value_availability:d===0?"hash_only":d===c.length*2?"bounded_inline":"mixed",value_policy:ia};await Fn(s),await Z(ae.join(s,Tt(a.id)),`${JSON.stringify(l,null,2)}
|
|
52
|
-
`)}return a}async function zf(e,t){let n;try{n=await qS(e)}catch(s){let c=await YS(e,s);return{receipts:[],invalid_evidence_count:c?0:1,invalid_evidence:c?[]:[{evidence_source:t,reason:"directory_unreadable"}],invalid_evidence_truncated:!1}}let i=[],r=0,a=[],o=(s,c)=>{if(r+=1,a.length>=sa)return;let d=s.slice(0,-5);a.push({evidence_source:t,reason:c.reason,...c.validation_path?{validation_path:c.validation_path}:{},...c.validation_error===void 0?{}:{validation_error:c.validation_error},...pt(d)?{receipt_id:d}:{candidate_name_hash:xe(s)}})};for(let s of n.sort((c,d)=>c.localeCompare(d))){if(!s.endsWith(".json"))continue;let c=await XS(e,s,t);c.receipt!==void 0?i.push(c.receipt):o(s,c)}return{receipts:i,invalid_evidence_count:r,invalid_evidence:a,invalid_evidence_truncated:r>a.length}}async function YS(e,t,n=GS){if(!j(t))return!1;let i=e;for(;;)try{return(await n(i)).isDirectory()}catch(r){if(!j(r))return!1;let a=ae.dirname(i);if(a===i)return!0;i=a}}async function XS(e,t,n){let i;try{i=await Vn(ae.join(e,t),_r)}catch{return{reason:"candidate_unreadable"}}if(i===null)return{reason:"candidate_not_bounded_regular_file"};let r;try{r=aa(JSON.parse(i))}catch{return{reason:"candidate_invalid_json"}}let a=ra(r,n);if(a!==null)return{reason:new Set(["receipt_id","item_id","item_path"]).has(a)?"identity_invalid":"schema_invalid",validation_error:a,...a==="collections"?{validation_path:Uf(r)}:{}};let o=r;if(t!==Tt(o.id))return{reason:"identity_invalid",validation_error:"filename"};let{preferred:s,evidence_source:c,...d}=o;return{receipt:{...d,requested_preference:o.requested_preference??s??"ours",requested_preference_applied:o.requested_preference_applied??(o.conflict_resolution??"preferred_side")==="preferred_side",conflict_resolution:o.conflict_resolution??"preferred_side",evidence_source:n}}}async function ZS(e,t,n){if(n.length===0)return[];let{readIndexedReceiptBlobs:i}=await import("./indexed-receipt-blobs-VK2363JB.js"),r=await QS(t),a=await i(r?.workspace??e,An(t),n.map(o=>Tt(o.id)),_r,r?.directory);return n.flatMap(o=>{try{let s=aa(JSON.parse(a.get(Tt(o.id))??""));if(ra(s,"durable")!==null)return[];let c=s,d=Si(o);return c.id===o.id&&Si(c).some(l=>d.includes(l))?[o.id]:[]}catch{return[]}})}async function QS(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT,n=process.env.PM_SOURCE_PM_PATH,i=process.env.PM_PATH;if(!(process.env.PM_SOURCE_CONTEXT_ACCESS!=="read_only"||!t||!n||!i))try{if(await Ct(e)!==await Ct(i))return;let r=ae.relative(await Ct(t),await Ct(n)),a=r===".."||r.startsWith(`..${ae.sep}`)||ae.isAbsolute(r),o=An(a?ae.join(await Ct(t),".agents","pm"):await Ct(n)),[s,c]=await Promise.all([Ct(o),Ct(An(n))]);return s!==c?void 0:{workspace:t,directory:o}}catch{return}}async function ft(e,t={}){let n=await bs(e),i=n===null?{receipts:[],invalid_evidence_count:0,invalid_evidence:[],invalid_evidence_truncated:!1}:await zf(n,"clone_local"),r=t.pmRoot??ae.join(e,".agents","pm"),a=await zf(An(r),"durable"),o=new Map(a.receipts.map(u=>[u.id,u])),s=0,c=[];for(let u of i.receipts){let m=o.get(u.id);if(m!==void 0&&!(m.value_policy===void 0?Si(u):[Ei(u)]).includes(Ei(m))){o.delete(u.id),s+=1,i.invalid_evidence.length+a.invalid_evidence.length+c.length<sa&&c.push({evidence_source:"clone_local_and_durable",reason:"copy_provenance_mismatch",receipt_id:u.id});continue}o.set(u.id,m===void 0?u:VS(u,m))}await KS(o,a.receipts,r);let d=a.receipts.filter(u=>o.has(u.id)),l=new Set(await ZS(e,r,d));return{durable_receipt_ids:[...l],unstaged_durable_receipt_ids:d.filter(u=>!l.has(u.id)).map(u=>u.id),receipts:[...o.values()].filter(u=>(t.includeReconciled||u.state==="pending")&&(t.includeLossless!==!1||u.decisions.length>0)).sort((u,m)=>u.created_at.localeCompare(m.created_at)),invalid_evidence_count:i.invalid_evidence_count+a.invalid_evidence_count+s,invalid_evidence:[...i.invalid_evidence,...a.invalid_evidence,...c].slice(0,sa),invalid_evidence_truncated:i.invalid_evidence_truncated||a.invalid_evidence_truncated||i.invalid_evidence_count+a.invalid_evidence_count+s>sa,clone_local_evidence_resolved:n!==null}}function qf(e,t,n){let i=new Set([...t?.durable_receipt_ids??[],...n?t?.unstaged_durable_receipt_ids??[]:[]]),r=[...e].filter(a=>!i.has(a));if(r.length!==0)throw new g(`Merge reconciliation refused ${r.length} receipt(s) without validated tracked evidence; no audit history was written.`,y.CONFLICT,{code:"merge_receipt_not_portable",required:"Every receipt cited by tracked history must have matching validated evidence in the Git index before any audit write.",recovery:{suggested_retry:"pm merge report --include-reconciled"},nextSteps:["Stage valid project sidecars after reviewing git diff, or use pm merge reconcile --stage for guarded lossless settlement. Restore missing original counterparts or preserve unrelated stale receipts outside the active store. Never copy private clone-local values into tracked evidence. Then rerun pm merge reconcile --dry-run."]})}function Cn(e){let t=[],n=[];for(let i of e)(Array.isArray(i.decisions)&&i.decisions.length>0?t:n).push(i);return{pendingDecisions:t,lossless:n}}async function UM(e,t,n={}){let i=await bs(e);if(i===null){if(n.requireExisting===!0)throw new Error(`Receipt ${t.id} disappeared before settlement.`);return}let r=t.evidence_source??"clone_local";if(!ws(t,r))throw new Error("Merge receipt trusted settlement input failed schema validation.");let a=$(),o=ae.join(i,Tt(t.id)),s=await Wf(e,t.item_path),c=s===null?null:ae.join(An(s),Tt(t.id)),d=(await Promise.all([Hf({receiptPath:o,receiptId:t.id,evidenceSource:"clone_local",reconciledAt:a,settlement:n.settlement}),...c===null?[]:[Hf({receiptPath:c,receiptId:t.id,evidenceSource:"durable",reconciledAt:a,settlement:n.settlement})]])).filter(l=>l!==null);if(d.length===0){if(n.requireExisting===!0)throw new Error(`Receipt ${t.id} disappeared before settlement.`);return}if(!(d.some(l=>l.modern)?[Ei(t)]:Si(t)).some(l=>d.every(u=>u.fingerprints.includes(l))))throw new Error(`Receipt ${t.id} settlement copies disagree on immutable merge provenance.`);for(let l of d)await Z(l.path,l.content)}async function HM(e){let t=await ft(e.cwd??process.cwd(),{...e,includeLossless:!0}),n=t.clone_local_evidence_resolved===!0&&t.invalid_evidence_count===0;return{ok:n,complete:n,count:t.receipts.length,invalid_evidence_count:t.invalid_evidence_count,invalid_evidence:t.invalid_evidence,invalid_evidence_truncated:t.invalid_evidence_truncated,clone_local_evidence_resolved:t.clone_local_evidence_resolved,receipts:t.receipts,generated_at:$()}}import{createHash as e0}from"node:crypto";import da 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 t0="2026-08-09T16:15:18.000Z",Bf=Symbol("pre-durable-disposition-eligible");function ht(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ks(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 Gf(e){return ht(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 Jf(e,t){if(typeof e!="string")return!1;let n=da.posix.normalize(e);return e.length<=4096&&!e.includes("\\")&&!e.includes("\0")&&!da.posix.isAbsolute(e)&&n===e&&!n.startsWith("../")&&(da.posix.basename(n)===`${t}.toon`||da.posix.basename(n)===`${t}.md`)}function n0(e,t){return typeof e.receipt_id=="string"&&pt(e.receipt_id)&&(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0&&e.conflict_resolution===void 0&&e.item_id===t&&Jf(e.item_path,t)}function Vf(e){let t=e.conflict_fields,n=e.fields_from_theirs,i=e.union_fields,r=e.decisions,a=Array.isArray(r)?new Set(r.flatMap(o=>Gf(o)?[o.field]:[])):new Set;return ks(t)&&ks(n)&&ks(i)&&Array.isArray(r)&&r.length>0&&r.length<=256&&Object.keys(r).length===r.length&&r.every(Gf)&&a.size===r.length&&t.length===a.size&&t.every(o=>a.has(o))}function i0(e,t){return n0(e,t)&&Vf(e)}function r0(e,t){return typeof e.receipt_id=="string"&&pt(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&&Jf(e.item_path,t)&&Vf(e)}function a0(e){return e[Bf]===!0}function Kf(e,t){if(!ht(e)||!ht(e.context))return[];let n=e.context.merge;return!ht(n)||!Array.isArray(n.receipts)?[]:n.receipts.flatMap(i=>!ht(i)||typeof i.receipt_id!="string"||i.receipt_id.trim().length===0?[]:[{receiptId:i.receipt_id,legacySummaryAccepted:i0(i,t),[Bf]:r0(i,t),...typeof e.ts=="string"&&Qt(e.ts)?{eventTimestamp:e.ts}:{}}])}function Yf(e,t,n){if(!ht(e)||e.op!=="merge_reconcile")return[];if(!ht(e.context)||!ht(e.context.merge))return[];let i=e.context.merge.missing_receipt_dispositions;return!Array.isArray(i)||i.length>256?[]:i.flatMap(r=>!ht(r)||typeof r.receipt_id!="string"||!pt(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"||!Qt(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 Xf(e,t,n=[]){let i=new Map;for(let a of n){let o=`${a.itemId}\0${a.originalHistoryLine}\0${a.receiptId}\0${a.originalEventTimestamp}`;i.set(o,Math.max(i.get(o)??0,a.auditHistoryLine))}let r=a=>a0(a)&&a.eventTimestamp!==void 0&&Lt(a.eventTimestamp,t0)<0&&(i.get(`${a.itemId}\0${a.line}\0${a.receiptId}\0${a.eventTimestamp}`)??0)>a.line;return{missing:e.filter(a=>!a.legacySummaryAccepted&&!t.has(a.receiptId)&&!r(a)).map(a=>({item_id:a.itemId,history_line:a.line,...pt(a.receiptId)?{receipt_id:a.receiptId}:{receipt_reference_hash:e0("sha256").update(a.receiptId).digest("hex")}})),acceptedLegacyCount:e.filter(a=>a.legacySummaryAccepted).length,acceptedDispositionCount:e.filter(r).length}}import{isUtf8 as o0}from"node:buffer";import{readFile as s0}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cca38e64-dd53-5086-8825-dc1c8f1cc587")}catch{}})();function c0(e){let t;try{t=JSON.parse(e)}catch{if(e.trimStart().startsWith("{")&&e.includes("}"))throw new g("History salvage cannot discard a potentially complete record with trailing corruption.",y.CONFLICT,{code:"history_salvage_refused"});return null}if(typeof t!="object"||t===null||Array.isArray(t))throw new g("History salvage would conceal interior corruption or a malformed record.",y.CONFLICT,{code:"history_salvage_refused"});let n=t;if(!Array.isArray(n.patch)||![n.ts,n.author,n.op,n.before_hash,n.after_hash].every(i=>typeof i=="string"))throw new g("History salvage requires complete history records before the invalid tail.",y.CONFLICT,{code:"history_salvage_refused"});return n}function d0(e){if($e(e))throw new g("Resolve history merge conflicts before salvage.",y.CONFLICT,{code:"history_salvage_refused"});let t=[],n=0,i,r=0;for(let[o,s]of e.split(`
|
|
52
|
+
`)}return a}async function zf(e,t){let n;try{n=await qS(e)}catch(s){let c=await YS(e,s);return{receipts:[],invalid_evidence_count:c?0:1,invalid_evidence:c?[]:[{evidence_source:t,reason:"directory_unreadable"}],invalid_evidence_truncated:!1}}let i=[],r=0,a=[],o=(s,c)=>{if(r+=1,a.length>=sa)return;let d=s.slice(0,-5);a.push({evidence_source:t,reason:c.reason,...c.validation_path?{validation_path:c.validation_path}:{},...c.validation_error===void 0?{}:{validation_error:c.validation_error},...pt(d)?{receipt_id:d}:{candidate_name_hash:xe(s)}})};for(let s of n.sort((c,d)=>c.localeCompare(d))){if(!s.endsWith(".json"))continue;let c=await XS(e,s,t);c.receipt!==void 0?i.push(c.receipt):o(s,c)}return{receipts:i,invalid_evidence_count:r,invalid_evidence:a,invalid_evidence_truncated:r>a.length}}async function YS(e,t,n=GS){if(!j(t))return!1;let i=e;for(;;)try{return(await n(i)).isDirectory()}catch(r){if(!j(r))return!1;let a=ae.dirname(i);if(a===i)return!0;i=a}}async function XS(e,t,n){let i;try{i=await Vn(ae.join(e,t),_r)}catch{return{reason:"candidate_unreadable"}}if(i===null)return{reason:"candidate_not_bounded_regular_file"};let r;try{r=aa(JSON.parse(i))}catch{return{reason:"candidate_invalid_json"}}let a=ra(r,n);if(a!==null)return{reason:new Set(["receipt_id","item_id","item_path"]).has(a)?"identity_invalid":"schema_invalid",validation_error:a,...a==="collections"?{validation_path:Uf(r)}:{}};let o=r;if(t!==Tt(o.id))return{reason:"identity_invalid",validation_error:"filename"};let{preferred:s,evidence_source:c,...d}=o;return{receipt:{...d,requested_preference:o.requested_preference??s??"ours",requested_preference_applied:o.requested_preference_applied??(o.conflict_resolution??"preferred_side")==="preferred_side",conflict_resolution:o.conflict_resolution??"preferred_side",evidence_source:n}}}async function ZS(e,t,n){if(n.length===0)return[];let{readIndexedReceiptBlobs:i}=await import("./indexed-receipt-blobs-KHWT44EK.js"),r=await QS(t),a=await i(r?.workspace??e,An(t),n.map(o=>Tt(o.id)),_r,r?.directory);return n.flatMap(o=>{try{let s=aa(JSON.parse(a.get(Tt(o.id))??""));if(ra(s,"durable")!==null)return[];let c=s,d=Si(o);return c.id===o.id&&Si(c).some(l=>d.includes(l))?[o.id]:[]}catch{return[]}})}async function QS(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT,n=process.env.PM_SOURCE_PM_PATH,i=process.env.PM_PATH;if(!(process.env.PM_SOURCE_CONTEXT_ACCESS!=="read_only"||!t||!n||!i))try{if(await Ct(e)!==await Ct(i))return;let r=ae.relative(await Ct(t),await Ct(n)),a=r===".."||r.startsWith(`..${ae.sep}`)||ae.isAbsolute(r),o=An(a?ae.join(await Ct(t),".agents","pm"):await Ct(n)),[s,c]=await Promise.all([Ct(o),Ct(An(n))]);return s!==c?void 0:{workspace:t,directory:o}}catch{return}}async function ft(e,t={}){let n=await bs(e),i=n===null?{receipts:[],invalid_evidence_count:0,invalid_evidence:[],invalid_evidence_truncated:!1}:await zf(n,"clone_local"),r=t.pmRoot??ae.join(e,".agents","pm"),a=await zf(An(r),"durable"),o=new Map(a.receipts.map(u=>[u.id,u])),s=0,c=[];for(let u of i.receipts){let m=o.get(u.id);if(m!==void 0&&!(m.value_policy===void 0?Si(u):[Ei(u)]).includes(Ei(m))){o.delete(u.id),s+=1,i.invalid_evidence.length+a.invalid_evidence.length+c.length<sa&&c.push({evidence_source:"clone_local_and_durable",reason:"copy_provenance_mismatch",receipt_id:u.id});continue}o.set(u.id,m===void 0?u:VS(u,m))}await KS(o,a.receipts,r);let d=a.receipts.filter(u=>o.has(u.id)),l=new Set(await ZS(e,r,d));return{durable_receipt_ids:[...l],unstaged_durable_receipt_ids:d.filter(u=>!l.has(u.id)).map(u=>u.id),receipts:[...o.values()].filter(u=>(t.includeReconciled||u.state==="pending")&&(t.includeLossless!==!1||u.decisions.length>0)).sort((u,m)=>u.created_at.localeCompare(m.created_at)),invalid_evidence_count:i.invalid_evidence_count+a.invalid_evidence_count+s,invalid_evidence:[...i.invalid_evidence,...a.invalid_evidence,...c].slice(0,sa),invalid_evidence_truncated:i.invalid_evidence_truncated||a.invalid_evidence_truncated||i.invalid_evidence_count+a.invalid_evidence_count+s>sa,clone_local_evidence_resolved:n!==null}}function qf(e,t,n){let i=new Set([...t?.durable_receipt_ids??[],...n?t?.unstaged_durable_receipt_ids??[]:[]]),r=[...e].filter(a=>!i.has(a));if(r.length!==0)throw new g(`Merge reconciliation refused ${r.length} receipt(s) without validated tracked evidence; no audit history was written.`,y.CONFLICT,{code:"merge_receipt_not_portable",required:"Every receipt cited by tracked history must have matching validated evidence in the Git index before any audit write.",recovery:{suggested_retry:"pm merge report --include-reconciled"},nextSteps:["Stage valid project sidecars after reviewing git diff, or use pm merge reconcile --stage for guarded lossless settlement. Restore missing original counterparts or preserve unrelated stale receipts outside the active store. Never copy private clone-local values into tracked evidence. Then rerun pm merge reconcile --dry-run."]})}function Cn(e){let t=[],n=[];for(let i of e)(Array.isArray(i.decisions)&&i.decisions.length>0?t:n).push(i);return{pendingDecisions:t,lossless:n}}async function UM(e,t,n={}){let i=await bs(e);if(i===null){if(n.requireExisting===!0)throw new Error(`Receipt ${t.id} disappeared before settlement.`);return}let r=t.evidence_source??"clone_local";if(!ws(t,r))throw new Error("Merge receipt trusted settlement input failed schema validation.");let a=$(),o=ae.join(i,Tt(t.id)),s=await Wf(e,t.item_path),c=s===null?null:ae.join(An(s),Tt(t.id)),d=(await Promise.all([Hf({receiptPath:o,receiptId:t.id,evidenceSource:"clone_local",reconciledAt:a,settlement:n.settlement}),...c===null?[]:[Hf({receiptPath:c,receiptId:t.id,evidenceSource:"durable",reconciledAt:a,settlement:n.settlement})]])).filter(l=>l!==null);if(d.length===0){if(n.requireExisting===!0)throw new Error(`Receipt ${t.id} disappeared before settlement.`);return}if(!(d.some(l=>l.modern)?[Ei(t)]:Si(t)).some(l=>d.every(u=>u.fingerprints.includes(l))))throw new Error(`Receipt ${t.id} settlement copies disagree on immutable merge provenance.`);for(let l of d)await Z(l.path,l.content)}async function HM(e){let t=await ft(e.cwd??process.cwd(),{...e,includeLossless:!0}),n=t.clone_local_evidence_resolved===!0&&t.invalid_evidence_count===0;return{ok:n,complete:n,count:t.receipts.length,invalid_evidence_count:t.invalid_evidence_count,invalid_evidence:t.invalid_evidence,invalid_evidence_truncated:t.invalid_evidence_truncated,clone_local_evidence_resolved:t.clone_local_evidence_resolved,receipts:t.receipts,generated_at:$()}}import{createHash as e0}from"node:crypto";import da 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 t0="2026-08-09T16:15:18.000Z",Bf=Symbol("pre-durable-disposition-eligible");function ht(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ks(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 Gf(e){return ht(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 Jf(e,t){if(typeof e!="string")return!1;let n=da.posix.normalize(e);return e.length<=4096&&!e.includes("\\")&&!e.includes("\0")&&!da.posix.isAbsolute(e)&&n===e&&!n.startsWith("../")&&(da.posix.basename(n)===`${t}.toon`||da.posix.basename(n)===`${t}.md`)}function n0(e,t){return typeof e.receipt_id=="string"&&pt(e.receipt_id)&&(e.preferred==="ours"||e.preferred==="theirs")&&e.requested_preference===void 0&&e.conflict_resolution===void 0&&e.item_id===t&&Jf(e.item_path,t)}function Vf(e){let t=e.conflict_fields,n=e.fields_from_theirs,i=e.union_fields,r=e.decisions,a=Array.isArray(r)?new Set(r.flatMap(o=>Gf(o)?[o.field]:[])):new Set;return ks(t)&&ks(n)&&ks(i)&&Array.isArray(r)&&r.length>0&&r.length<=256&&Object.keys(r).length===r.length&&r.every(Gf)&&a.size===r.length&&t.length===a.size&&t.every(o=>a.has(o))}function i0(e,t){return n0(e,t)&&Vf(e)}function r0(e,t){return typeof e.receipt_id=="string"&&pt(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&&Jf(e.item_path,t)&&Vf(e)}function a0(e){return e[Bf]===!0}function Kf(e,t){if(!ht(e)||!ht(e.context))return[];let n=e.context.merge;return!ht(n)||!Array.isArray(n.receipts)?[]:n.receipts.flatMap(i=>!ht(i)||typeof i.receipt_id!="string"||i.receipt_id.trim().length===0?[]:[{receiptId:i.receipt_id,legacySummaryAccepted:i0(i,t),[Bf]:r0(i,t),...typeof e.ts=="string"&&Qt(e.ts)?{eventTimestamp:e.ts}:{}}])}function Yf(e,t,n){if(!ht(e)||e.op!=="merge_reconcile")return[];if(!ht(e.context)||!ht(e.context.merge))return[];let i=e.context.merge.missing_receipt_dispositions;return!Array.isArray(i)||i.length>256?[]:i.flatMap(r=>!ht(r)||typeof r.receipt_id!="string"||!pt(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"||!Qt(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 Xf(e,t,n=[]){let i=new Map;for(let a of n){let o=`${a.itemId}\0${a.originalHistoryLine}\0${a.receiptId}\0${a.originalEventTimestamp}`;i.set(o,Math.max(i.get(o)??0,a.auditHistoryLine))}let r=a=>a0(a)&&a.eventTimestamp!==void 0&&Lt(a.eventTimestamp,t0)<0&&(i.get(`${a.itemId}\0${a.line}\0${a.receiptId}\0${a.eventTimestamp}`)??0)>a.line;return{missing:e.filter(a=>!a.legacySummaryAccepted&&!t.has(a.receiptId)&&!r(a)).map(a=>({item_id:a.itemId,history_line:a.line,...pt(a.receiptId)?{receipt_id:a.receiptId}:{receipt_reference_hash:e0("sha256").update(a.receiptId).digest("hex")}})),acceptedLegacyCount:e.filter(a=>a.legacySummaryAccepted).length,acceptedDispositionCount:e.filter(r).length}}import{isUtf8 as o0}from"node:buffer";import{readFile as s0}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cca38e64-dd53-5086-8825-dc1c8f1cc587")}catch{}})();function c0(e){let t;try{t=JSON.parse(e)}catch{if(e.trimStart().startsWith("{")&&e.includes("}"))throw new g("History salvage cannot discard a potentially complete record with trailing corruption.",y.CONFLICT,{code:"history_salvage_refused"});return null}if(typeof t!="object"||t===null||Array.isArray(t))throw new g("History salvage would conceal interior corruption or a malformed record.",y.CONFLICT,{code:"history_salvage_refused"});let n=t;if(!Array.isArray(n.patch)||![n.ts,n.author,n.op,n.before_hash,n.after_hash].every(i=>typeof i=="string"))throw new g("History salvage requires complete history records before the invalid tail.",y.CONFLICT,{code:"history_salvage_refused"});return n}function d0(e){if($e(e))throw new g("Resolve history merge conflicts before salvage.",y.CONFLICT,{code:"history_salvage_refused"});let t=[],n=0,i,r=0;for(let[o,s]of e.split(`
|
|
53
53
|
`).entries()){if(!s.trim()){n+=s.length+1;continue}let c=c0(s);if(c===null){i===void 0&&(i=n,r=o+1),n+=s.length+1;continue}if(i!==void 0)throw new g("History salvage would discard a record or conceal interior corruption.",y.CONFLICT,{code:"history_salvage_refused",required:"Recover the damaged record from version control or a backup; no bytes were changed."});t.push(c),n+=s.length+1}let a=kt(t);if(!a.ok||a.item_hash_version===void 0)throw new g("History salvage requires a nonempty verified prefix.",y.CONFLICT,{code:"history_salvage_refused",verification_errors:a.errors,required:"Recover an intact history prefix from version control or a backup."});return{entries:t,itemHashVersion:a.item_hash_version,prefix:i===void 0?e:e.slice(0,i),receipt:i===void 0?null:{first_invalid_line:r,discarded_bytes:Buffer.byteLength(e.slice(i)),discarded_sha256:xe(e.slice(i)),retained_entries:t.length}}}async function l0(e,t,n){if(!e.located)return{itemRaw:null,document:n};let i=await ul(e.located,{schema:t.schema});return{itemRaw:i.raw,document:i.document??n}}async function Zf(e){let t;try{t=await s0(e)}catch(n){if(j(n))return null;throw n}if(!o0(t))throw new g("History salvage requires UTF-8 input; recover binary corruption from a byte-preserving backup.",y.CONFLICT,{code:"history_salvage_refused"});return t.toString("utf8")}async function Qf(e){let{subject:t,settings:n,options:i,author:r}=e;if([i.normalizeProvenance,i.auditOperation,i.auditContext,i.auditContextById,i.forceAuditEntry,i.mergeReceiptProof,i.mergeReceiptProofById].some(Boolean))throw new g("Tail salvage cannot be combined with other repair modes.",y.USAGE);let a=await Zf(t.historyPath);if(a===null)throw new g(`No history stream exists for ${t.id}.`,y.NOT_FOUND);await Ne({path:t.historyPath,scope:"project"});let o=d0(a),s=il(o.entries,o.entries.length-1),c=Vd(s);if(typeof s.metadata.id=="string"&&s.metadata.id!==t.id)throw new g("History belongs to another item; salvage refused.",y.CONFLICT,{code:"history_salvage_refused"});let d=await l0(t,n,c),l=Eo({itemDocument:d.document,subjectId:t.id,author:r,force:i.force,settings:n}),u=o.itemHashVersion,m=i.dryRun===!0,f=o.receipt!==null;if(f&&!m){let p=await re(e.pmRoot,t.id,n.locks.ttl_seconds,r,!!i.force,n.governance.force_required_for_stale_lock,n.locks.wait_ms);try{let h=await Zf(t.historyPath),_=await ge(e.pmRoot,t.id,n.id_prefix,n.item_format,e.typeRegistry.type_to_folder),w=_?await B(_.itemPath):null;if(h!==a||w!==d.itemRaw)throw new g("History or item changed while waiting for salvage lock; retry.",y.CONFLICT);let v=rr({...Jd({hashAlgorithm:Re(o.entries.at(-1).hash_algorithm),nowIso:$(),author:r,op:"history_salvage",before:c,after:c,message:i.message,context:{history_salvage:o.receipt}}),before_hash:o.entries.at(-1).after_hash,after_hash:o.entries.at(-1).after_hash,item_hash_version:u});await Cr({historyPath:t.historyPath,historyRawUnderLock:a,nextHistoryRaw:`${o.prefix}${JSON.stringify(v)}
|
|
54
54
|
`}),l.push(...await K({path:t.historyPath,scope:"project",op:"history_salvage:history"}))}finally{await p()}}return{id:t.id,dry_run:m,changed:f,history:{path:t.historyPath,entries_scanned:o.entries.length,chain_drift_before:!1,entries_rehashed:0,entries_patch_repaired:0,converted_replace_to_add:0,skipped_ops:0,reconciled_with_item:!1,audit_entry_added:f&&!m,verify_ok:!0,verify_errors:[],item_hash_version_before:u,item_hash_version_after:u,version_disposition:"preserved"},item:{exists:t.located!==null,path:t.located?.itemPath??null,matched_chain_before:null},provenance_normalization:{requested:!1,changed:!1,events_changed:0,observations_removed:0,invalid_values:[]},...o.receipt?{salvage:o.receipt}:{},warnings:l,generated_at:$()}}import{realpath as rh}from"node:fs/promises";import Es from"node:path";import ah from"fast-json-patch";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a6d2870f-ebba-580a-85e9-3eb44e533d08")}catch{}})();function eh(e,t){return t==="body"?e.body:e.metadata[t]}function u0(e,t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;let n=t;return e==="comments"?typeof n.created_at=="string"&&typeof n.author=="string"&&typeof n.text=="string":typeof n.path=="string"||e==="tests"&&typeof n.command=="string"}function m0(e){let t={...e};if(t.source_kind==="merge_union"&&(t.source_kind="local_mutation"),t.provenance!==null&&typeof t.provenance=="object"&&!Array.isArray(t.provenance)){let n={...t.provenance};n.source_kind==="merge_union"&&(n.source_kind="local_mutation"),t.provenance=n}return t}function th(e,t){if(!Array.isArray(t)||!["comments","docs","tests"].includes(e)||!t.every(i=>u0(e,i)))return t;let n=t.map(i=>e==="comments"?i:m0(i));return[...new Map(n.map(i=>[A(i),i])).values()]}function Ss(e,t){if(e===void 0||Object.is(e,t))return!0;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let i=new Set;return e.every(r=>{let a=t.findIndex((o,s)=>!i.has(s)&&Ss(r,o));return a<0?!1:(i.add(a),!0)})}if(e===null||t===null||typeof e!="object"||typeof t!="object"||Array.isArray(t))return!1;let n=t;return Object.entries(e).every(([i,r])=>Object.hasOwn(n,i)&&Ss(r,n[i]))}function nh(e,t){let n=new Set(t),i=[];for(let r=e.length-1;r>=0&&n.size>0;r-=1){let a=e[r],o=new Set;for(let c of sr(a.patch))o.add(dr(c.path)),c.from&&o.add(dr(c.from));let s=[...n].filter(c=>o.has(c));if(s.length!==0){for(let c of s)n.delete(c);i.push({index:r+1,ts:a.ts,author:a.author,op:a.op,fields:s.sort((c,d)=>c.localeCompare(d))})}}return i.reverse()}function p0(e,t,n){let i=ah.compare(t,n);if(i.length===0)return;let r=new Set;for(let p of i)r.add(dr(p.path));let a=new Set([...r].filter(p=>Ss(th(p,eh(t,p)),th(p,eh(n,p))))),o=new Set([...r].filter(p=>!a.has(p))),s=nh(e,o),c=nh(e,a),d=[...r].sort((p,h)=>p.localeCompare(h)),l=[...o].sort((p,h)=>p.localeCompare(h)),u=[...a].sort((p,h)=>p.localeCompare(h)),m=[...new Set(s.map(p=>p.author))].sort((p,h)=>p.localeCompare(h)),f=[...new Set(c.map(p=>p.author))].sort((p,h)=>p.localeCompare(h));return{reconciled_field_count:r.size,reconciled_fields:d,reverted_field_count:o.size,reverted_fields:l,discarded_events:s,discarded_authors:m,preserved_field_count:a.size,preserved_fields:u,preserved_events:c,preserved_authors:f,recovery_hint:s.length>0?"Reconciliation keeps the on-disk item and overwrites these replayed mutations. To recover one, inspect it with pm history <id> --diff --field <field>, then re-apply the lost value with pm update.":null}}async function f0(e){try{return await rh(e)}catch{return null}}async function h0(e){if(await f0(Es.resolve(e.gitWorkspaceRoot,e.receipt.item_path))!==e.currentPath)return null;let t=[...new Set([...e.receipt.fields_from_theirs,...e.receipt.union_fields,...e.receipt.decisions.map(a=>a.field)])].sort(),n=e.receipt.merged_field_hashes;if(!n||t.length===0)return null;let i=Object.keys(n).sort();if(t.length!==i.length||t.some((a,o)=>a!==i[o]))return null;let r=e.currentItemReplay.metadata;return t.every(a=>{let o=a==="body"?e.currentItemReplay.body:r[a];return[At(o),xe(A(V(o)))].includes(n[a])})?{receipt:e.receipt,declaredFields:t}:null}async function _0(e){if(e.proof.gitWorkspaceRoot===null)return{trusted:!1,reason:"git_workspace_unavailable",receipt_ids:[]};if(e.itemPath===null||e.currentItemReplay===null)return{trusted:!1,reason:"item_path_unavailable",receipt_ids:[]};let t=e.proof.receipts.filter(o=>o.item_id===e.id);if(t.length===0)return{trusted:!1,reason:"no_item_receipts",receipt_ids:[]};let n=await rh(e.itemPath),i=[];for(let o of t){let s=await h0({receipt:o,gitWorkspaceRoot:e.proof.gitWorkspaceRoot,currentPath:n,currentItemReplay:e.currentItemReplay});s&&i.push(s)}let r=new Set(i.flatMap(({declaredFields:o})=>o)),a=e.reconciliation?.reconciled_fields;return i.length>0&&(a===void 0||a.length>0&&a.every(o=>r.has(o)))?{trusted:!0,reason:"trusted_merge_driver_hash_evidence",receipt_ids:i.map(({receipt:o})=>o.id)}:{trusted:!1,reason:"no_receipt_set_proves_snapshot",receipt_ids:[]}}async function ih(e,t,n,i){if(e===void 0)return;let{receipt:r,gitWorkspaceRoot:a}=e,o=t.currentItemPath===null?null:Es.relative(a,t.currentItemPath).split(Es.sep).join("/");if(!n||i.entriesRehashed!==0||i.entriesPatchRepaired!==0||t.matchedChainBefore!==!0||t.currentItemRawBeforeLock===null||o!==r.item_path||r.operation===void 0||!await Lf(a,r.item_path,r.operation,t.currentItemRawBeforeLock))throw new g("Restored-origin receipt evidence no longer proves the exact clean item snapshot.",y.CONFLICT,{code:"merge_reconcile_receipt_evidence_untrusted",recovery:{suggested_retry:"pm merge reconcile --dry-run"}})}async function g0(e){let t=new Set(e.options.mergeReceiptProof?.receipts.filter(o=>o.item_id===e.subjectId).map(o=>o.id)??[]),n=e.options.mergeReceiptProof?await ft(e.options.mergeReceiptProof.gitWorkspaceRoot??process.cwd(),{includeReconciled:!0,includeLossless:!0,pmRoot:e.pmRoot}):void 0,i=n?.receipts.filter(o=>o.item_id===e.subjectId&&t.has(o.id))??[];qf(t,n,e.options.dryRun===!0);let r=e.options.mergeReceiptProof?await _0({proof:{...e.options.mergeReceiptProof,receipts:i},id:e.subjectId,itemPath:e.itemReplayContext.currentItemPath,currentItemReplay:e.itemReplayContext.currentItemReplay,reconciliation:e.reconciliation}):void 0;if(r&&!r.trusted&&e.options.force!==!0)throw new g(`Merge receipt evidence for ${e.subjectId} does not prove the exact item snapshot (${r.reason}).`,y.CONFLICT,{code:"merge_reconcile_receipt_evidence_untrusted",required:"Use authoritative clone-local or durable receipt evidence whose canonical path, declared fields, and merged-value hashes match the current item, or review the mismatch and rerun with --force.",recovery:{suggested_retry:"pm merge reconcile --dry-run"}});let a=r?.trusted?i.filter(o=>r.receipt_ids.includes(o.id)):[];return{mergeReceiptProof:r,effectiveAuditContext:a.length>0&&e.options.force!==!0?{...e.options.auditContext,merge:{receipts:a.map(ca)}}:e.options.auditContext}}function y0(e,t,n){let i=e.located?.itemPath??null,r=t.loadedItem,a=t.entries;if(!r)return{currentItemReplay:null,currentItemPath:i,matchedChainBefore:null,currentItemRawBeforeLock:null,loadedItem:null};let o=or(r.document),s=a[a.length-1].after_hash;return{currentItemReplay:o,currentItemPath:i,matchedChainBefore:tn(o,n,Re(a.at(-1)?.hash_algorithm)).includes(s),currentItemRawBeforeLock:r.raw,loadedItem:r}}function w0(e){return typeof e.message=="string"&&e.message.trim().length>0?e.message:`history-repair re-anchored ${e.entriesRehashed} entr${e.entriesRehashed===1?"y":"ies"}${e.entriesPatchRepaired>0?`, repaired ${e.entriesPatchRepaired} patch(es)`:""}${e.reconcileNeeded?", reconciled chain with on-disk item":""}.`}function v0(e){let t=[...e.reanchorEntries];if(!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let n=e.reconcileNeeded&&e.currentItemReplay?e.currentItemReplay:e.finalReplay,i=Re(e.reanchorEntries.at(-1)?.hash_algorithm),r=tn(e.finalReplay,e.itemHashVersion,i),a=e.reanchorEntries[e.reanchorEntries.length-1].after_hash,o=r.indexOf(a),s=tn(n,e.itemHashVersion,i),c={hash_algorithm:i,ts:$(),author:e.author,op:e.auditOperation,patch:e.reconcileNeeded&&e.currentItemReplay?ah.compare(e.finalReplay,e.currentItemReplay):[],before_hash:r[o],after_hash:s[o],message:e.message,...e.explicitItemHashVersion?{item_hash_version:e.itemHashVersion}:{},...e.auditContext===void 0?{}:{context:e.auditContext}};return t.push(rr({...c,event_class:zd(c)})),{rewrittenEntries:t,auditEntryAdded:!0}}function b0(e,t,n){let i=[];return e||i.push("history_repair_no_changes"),t>0&&i.push(`history_repair_skipped_unresolvable_ops:${t}`),n&&n.discarded_events.length>0&&i.push(`history_repair_reconcile_discards_events:${n.discarded_events.length}`,`history_repair_discarded_authors:${n.discarded_authors.join(",")}`),i}async function xs(e,t,n){let{pmRoot:i,settings:r,typeRegistry:a}=await Qa(n.path),o=await Ol(i,e,r,a.type_to_folder);return t.salvageTail===!0?Qf({pmRoot:i,subject:o,settings:r,typeRegistry:a,options:t,author:z(t.author,r.author_default)}):Gu({pmRoot:i,subject:o,settings:r,typeRegistry:a,operation:"history-repair",options:t,transform:s=>E0({pmRoot:i,subject:o,options:t},s)})}function k0(e,t,n){let i=(e.mergeAbandonmentProof!==void 0||e.mergeReceiptProof!==void 0&&e.force!==!0)&&n!==void 0&&t.some(r=>r.record_hash_version!==void 0&&r.op==="merge_reconcile"&&A(r.context)===A(n));return e.forceAuditEntry===!0&&!i}async function E0(e,t){let{pmRoot:n,subject:i,options:r}=e,a=t.entries,o=t.verification,s=kt(a),c=r.normalizeProvenance?Fu(a):{entries:a,receipt:{changed:!1,events_changed:0,observations_removed:0,invalid_values:[]}},d=Kd(c.entries),l=new Set(c.entries.map(P=>P.item_hash_version).filter(P=>P!==void 0)),u=cr(c.entries,d),m=y0(i,t,d);await ih(r.mergeAbandonmentProof,m,o.ok,u);let f=u.finalDocument,p=tn(f,d),h=!1;if(m.currentItemReplay!==null){let P=tn(m.currentItemReplay,d);h=!p.some((x,q)=>x===P[q])}let _=h&&m.currentItemReplay?p0(u.entries,f,m.currentItemReplay):void 0,{mergeReceiptProof:w,effectiveAuditContext:v}=await g0({options:r,pmRoot:n,subjectId:i.id,itemReplayContext:m,reconciliation:_}),E=[u.entriesRehashed>0,u.entriesPatchRepaired>0,h,k0(r,u.entries,v),c.receipt.changed].some(Boolean),k=t.author,I=!!r.dryRun,C=w0({message:r.message,entriesRehashed:u.entriesRehashed,entriesPatchRepaired:u.entriesPatchRepaired,reconcileNeeded:h}),{rewrittenEntries:S,auditEntryAdded:b}=v0({reanchorEntries:u.entries,changed:E,reconcileNeeded:h,currentItemReplay:m.currentItemReplay,finalReplay:f,author:k,message:C,auditOperation:r.auditOperation??"history_repair",auditContext:c.receipt.changed?{...v,provenance_normalization:c.receipt}:v,itemHashVersion:d,explicitItemHashVersion:u.explicitItemHashVersion}),O=b0(E,u.skippedOps,_);return{changed:E,rewrittenEntries:S,beforeWrite:async()=>ih(r.mergeAbandonmentProof,m,o.ok,u),report:({verification:P,warnings:x})=>({id:i.id,dry_run:I,changed:E,history:{path:i.historyPath,entries_scanned:a.length,chain_drift_before:!o.ok,entries_rehashed:u.entriesRehashed,entries_patch_repaired:u.entriesPatchRepaired,converted_replace_to_add:u.convertedReplaceToAdd,skipped_ops:u.skippedOps,reconciled_with_item:h,audit_entry_added:b,verify_ok:P.ok,verify_errors:P.errors,item_hash_version_before:s.item_hash_version??null,item_hash_version_after:d,version_disposition:l.size>1?"selected_for_ambiguous_stream":"preserved"},item:{exists:m.currentItemPath!==null,path:m.currentItemPath,matched_chain_before:m.matchedChainBefore},provenance_normalization:{requested:r.normalizeProvenance===!0,...c.receipt},..._?{reconciliation:_}:{},...w?{merge_receipt_proof:w}:{},warnings:[...new Set([...O,...x])].sort((q,Se)=>q.localeCompare(Se)),generated_at:$()})}}function P1(e,t){if(t&&e!==void 0)throw new g("history-repair: <id> and --all are mutually exclusive; pass an item id to repair one stream or --all to repair every drifted stream.",y.USAGE);if(!t&&e===void 0)throw new g("history-repair: provide an item <id> or pass --all to repair every drifted stream.",y.USAGE)}async function L1(e,t){if(e.salvageTail===!0)throw new g("Tail salvage requires one explicit item ID; --all is not supported.",y.USAGE);let{pmRoot:n,settings:i,typeRegistry:r}=await Qa(t.path),a=[],o=await at(n,i.item_format,r.type_to_folder,a,i.schema,{forceSourceScan:!0}),s=await Ht(n,o),c=e.normalizeProvenance?await Uu(n):[],d=[...new Set([...s.driftedItems,...c])].sort((f,p)=>f.localeCompare(p)),l=[],u=[],m={repaired:0,skipped_clean:0,failed:0};for(let f of d)try{let p=await xs(f,{...e,auditContext:e.auditContextById?.[f],auditContextById:void 0,mergeReceiptProof:e.mergeReceiptProofById?.[f]??e.mergeReceiptProof,mergeReceiptProofById:void 0},t),h=p.changed?"repaired":"skipped_clean";m[h]+=1,u.push(...p.warnings.map(_=>`${f}:${_}`)),l.push({id:f,outcome:h,entries_rehashed:p.history.entries_rehashed,entries_patch_repaired:p.history.entries_patch_repaired,reconciled_with_item:p.history.reconciled_with_item,...p.reconciliation?{reconciliation:p.reconciliation}:{},...p.merge_receipt_proof?{merge_receipt_proof:p.merge_receipt_proof}:{},warnings:p.warnings})}catch(p){m.failed+=1,l.push({id:f,outcome:"failed",error:p instanceof Error?p.message:String(p)})}return e.dryRun||await Wd(n),{all:!0,dry_run:!!e.dryRun,scanned_streams:o.length,drifted_streams:s.driftedItems.length,provenance_invalid_streams:c.length,streams:l,totals:m,warnings:[...new Set([...a,...u])].sort((f,p)=>f.localeCompare(p)),generated_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]="11486e17-e6da-5770-8621-f59a17bb4922")}catch{}})();var S0=new Set(Sl),oh=25,x0=be.join("runtime","telemetry","events.jsonl"),I0=be.join("runtime","telemetry","state.json"),R0=2500,A0=500,sh=Al-3,C0=["x-pm-telemetry-max-schema-version","x-pm-telemetry-max-version"];function $s(e,t=!1){return e.startsWith("agent_guidance_")||e.startsWith("telemetry_")||e.startsWith("extension_disabled_pm_")||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 Ds(e){let t=e.trim(),n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function Tn(e){return e.trim().toLowerCase()}function As(e,t){let n=Tn(e),i=Tn(t);return n.startsWith("builtin-")?!0:i==="beads"||i==="todos"}async function Os(e){try{return(await _t.stat(e)).isDirectory()}catch{return!1}}async function T0(e){let t=(await _t.readdir(e,{withFileTypes:!0})).filter(i=>i.isDirectory()),n=await Promise.all(t.map(i=>_t.readdir(be.join(e,i.name),{withFileTypes:!0})));return new Set(n.flatMap(i=>i.filter(r=>r.isFile()).filter(r=>Un.some(a=>r.name.endsWith(a))).map(r=>be.parse(r.name).name)))}async function $0(e,t,n,i){let r=await Ne({path:e,scope:"project"}),a=t!=="_workspace"&&!i.has(t);if(!n.enabled&&!a)return{warnings:r,overThreshold:!1,classification:"live"};let o;try{o=await _t.readFile(e,"utf8")}catch{return{warnings:r,overThreshold:!1,classification:"unreadable"}}let s="live";if(a){let d=o.split(/\r?\n/).map(l=>l.trim()).filter(Boolean).at(-1);try{s=JSON.parse(d??"{}").op==="delete"?"tombstone":"orphaned"}catch{s="orphaned"}}let c=n.enabled?o.split(/\r?\n/).filter(d=>d.trim().length>0).length:0;return{warnings:r,overThreshold:n.enabled&&c>n.max_entries,classification:s}}async function D0(e,t,n){let i=be.join(e,"history");if(!await Os(i))return{count:0,warnings:[],over_threshold:[],max_entries:null,tombstones:[],orphaned:[]};let r=(await _t.readdir(i)).filter(l=>l.endsWith(".jsonl")).sort((l,u)=>l.localeCompare(u)),a=t.enabled?t.max_entries:null,o=[],s=[],c=[],d=[];for(let l of r){let u=be.join(i,l),m=l.slice(0,-6),f=await $0(u,m,t,n);o.push(...f.warnings),f.classification==="tombstone"&&c.push(m),f.classification==="orphaned"&&d.push(m),f.overThreshold&&s.push(m)}return{count:r.length,warnings:[...o,...s.map(l=>`history_stream_over_compact_threshold:${l}`),...d.map(l=>`history_orphaned_stream:${l}`)],over_threshold:s,max_entries:a,tombstones:c,orphaned:d}}function Cs(e,t){return be.relative(e,t).replaceAll("\\","/")}async function ch(e,t){let n=[...new Set(Object.values(t))].sort((r,a)=>r.localeCompare(a)),i=[];for(let r of n){let a=be.join(e,r),o=[];try{o=await _t.readdir(a)}catch(s){if(typeof s=="object"&&s!==null&&"code"in s&&j(s))continue;continue}for(let s of o)Un.some(c=>s.toLowerCase().endsWith(c))&&i.push(be.join(a,s))}return i.sort((r,a)=>Cs(e,r).localeCompare(Cs(e,a))),i}function O0(e){return!(typeof e=="object"&&e!==null&&"code"in e&&j(e))}async function P0(e,t,n){let i=await ch(e,t),r=[],a=[],o=[],s=[],c=Gt(F());for(let d of i){let l=Cs(e,d),u;try{u=await _t.readFile(d,"utf8")}catch{r.push(l);continue}let m=$e(u);if(m){a.push({path:l,...m});continue}try{let f=bt(u,{format:Mc(d),schema:n,extensionFieldNames:c});s.push({ref:l,version:er(f.metadata)})}catch{o.push(l)}}return{paths:i,unreadable:r,conflictMarkers:a,parseFailures:o,formatVersions:s}}async function L0(e){let t=be.join(e,"history"),n=[],i=[],r=[],a=[],o=[],s=[];try{s=(await _t.readdir(t)).filter(c=>c.endsWith(".jsonl")).sort((c,d)=>c.localeCompare(d))}catch(c){O0(c)&&n.push("history")}for(let c of s){let d=c.slice(0,-6),l;try{l=await _t.readFile(be.join(t,c),"utf8")}catch{n.push(d);continue}let u=$e(l);if(u){i.push({id:d,...u});continue}l.split(/\r?\n/).forEach((m,f)=>{if(m.trim())try{let p=JSON.parse(m);a.push(...Kf(p,d).map(h=>({itemId:d,line:f+1,...h}))),o.push(...Yf(p,d,f+1))}catch{r.push({id:d,line:f+1})}})}return{files:s,unreadable:n,conflictMarkers:i,invalidJson:r,mergeReceiptReferences:a,mergeReceiptDispositions:o}}function dh(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 N0(e,t,n,i,r,a){let o=await P0(e,t,n),s=await L0(e),c=tr(o.formatVersions,Wn,Qi),d=fe(n),l=hr(a,x=>jd(x,d),Jn()),u=await Xr(e),m=await St(e),f=await vf(e,m),p=await bf(e,m,i,r),h=m===null?null:await un(m),_=await ft(m??e,{includeReconciled:!0,includeLossless:!0,pmRoot:e}),w=new Set(_.durable_receipt_ids),v=Xf(s.mergeReceiptReferences,w,s.mergeReceiptDispositions),E=v.missing,k=_.receipts.filter(x=>x.state==="pending"),{pendingDecisions:I,lossless:C}=Cn(k),S=h?.status==="missing"&&h.missing_keys.length===5&&h.drifted_keys.length===0,b=[...o.unreadable.map(x=>`integrity_item_unreadable:${x}`),...o.conflictMarkers.map(x=>`integrity_item_conflict_marker:${x.path}:L${x.line}`),...o.parseFailures.map(x=>`integrity_item_parse_failed:${x}`),...s.unreadable.map(x=>`integrity_history_unreadable:${x}`),...s.conflictMarkers.map(x=>`integrity_history_conflict_marker:${x.id}:L${x.line}`),...s.invalidJson.map(x=>`integrity_history_invalid_json:${x.id}:L${x.line}`),...c.outdated.map(x=>`integrity_item_outdated_format_version:${x}`),...c.ahead.map(x=>`integrity_item_ahead_format_version:${x}`),...dh(l),...u.tracked_path_count>0?[`tracked_runtime_cache_files:${u.tracked_path_count}`]:[],...h!==null&&h.status!=="ok"?[`merge_driver_configuration_${S?"missing":"drift"}:${h.missing_keys.length+h.drifted_keys.length}`]:[],...p.warnings,...f.warnings,...I.length>0?[`merge_decisions_unreviewed:${I.length}`]:[],...C.length>0?[`merge_receipts_pending:${C.length}`]:[],...kf({invalidEvidenceCount:_.invalid_evidence_count,missingHistoryReferenceCount:E.length})],O=[...new Set(b)].sort((x,q)=>x.localeCompare(q)),P=O.filter(x=>!x.startsWith("integrity_legacy_hierarchy_"));return{check:{name:"integrity",status:P.length===0?"ok":"warn",ok:P.length===0,details:{checked_item_files:o.paths.length,checked_history_streams:s.files.length,counts:{item_unreadable:o.unreadable.length,item_conflict_markers:o.conflictMarkers.length,item_parse_failures:o.parseFailures.length,history_unreadable:s.unreadable.length,history_conflict_markers:s.conflictMarkers.length,history_invalid_json:s.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:h===null||h.status==="ok"?0:h.missing_keys.length+h.drifted_keys.length,merge_fence:p.count,ignored_merge_artifacts:f.rules.length,pending_merge_decisions:I.length,lossless_merge_receipts:C.length,invalid_merge_receipt_evidence:_.invalid_evidence_count,missing_merge_receipt_history_references:E.length,accepted_legacy_merge_receipt_references:v.acceptedLegacyCount,accepted_missing_merge_receipt_dispositions:v.acceptedDispositionCount},item_unreadable:o.unreadable,item_conflict_markers:o.conflictMarkers,item_parse_failures:o.parseFailures,item_outdated_format_version:c.outdated,item_ahead_format_version:c.ahead,hierarchy_integrity:{...l,relations:Fe(l.relations,Ju)},history_unreadable:s.unreadable,history_conflict_markers:s.conflictMarkers,history_invalid_json:s.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:h===null?null:{...h,required:r},merge_fence:p.audit,ignored_merge_artifacts:f.rules,pending_merge_decision_items:[...new Set(I.map(x=>x.item_id))].sort((x,q)=>x.localeCompare(q)),lossless_merge_receipt_items:[...new Set(C.map(x=>x.item_id))].sort((x,q)=>x.localeCompare(q)),invalid_merge_receipt_evidence_details:_.invalid_evidence,invalid_merge_receipt_evidence_details_truncated:_.invalid_evidence_truncated,missing_merge_receipt_history_reference_details:E.slice(0,So),missing_merge_receipt_history_reference_details_truncated:E.length>So}},warnings:O,gitWorkspaceRoot:m,pendingMergeReceipts:k}}function M0(e){if(typeof e.activate=="function")return!0;let t=e.default;return typeof t!="object"||t===null?!1:typeof t.activate=="function"}function j0(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:M0(e.module)};return Array.isArray(e.capabilities)&&(t.capabilities=[...e.capabilities]),t}function F0(e,t){return Y(e.id)||`migration-${String(t+1).padStart(3,"0")}`}function U0(e){let t=Y(e.status)?.toLowerCase();return t==="failed"?"failed":t==="applied"?"applied":"pending"}function H0(e){return Y(e.reason)??Y(e.error)??Y(e.message)}function Is(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 z0(e){let t=[],n=[],i=[];e.forEach((a,o)=>{let s=F0(a.definition,o),c=U0(a.definition);if(c==="applied"){t.push({layer:a.layer,name:a.name,id:s,status:c});return}if(c==="failed"){i.push({layer:a.layer,name:a.name,id:s,status:c,reason:H0(a.definition)});return}n.push({layer:a.layer,name:a.name,id:s,status:c})}),t.sort(Is),n.sort(Is),i.sort(Is);let r=[...i.map(a=>`extension_migration_failed:${a.layer}:${a.name}:${a.id}`),...n.map(a=>`extension_migration_pending:${a.layer}:${a.name}:${a.id}`)];return{summary:{applied:t,pending:n,failed:i,applied_count:t.length,pending_count:n.length,failed_count:i.length},warnings:r}}function lh(e,t,n,i,r,a,o,s,c){let d=[...new Set(e)].sort((_,w)=>_.localeCompare(w)),l=[...new Set(d.map(_=>Ds(_)))].sort((_,w)=>_.localeCompare(w)),u=d.filter(_=>_.startsWith("extension_capability_unknown:")).length,m=c.length>0,f=m?"partial":"full",p=d.map(oi).filter(_=>_!==void 0),h=Qo(d,{deactivate:"pm extension --deactivate <name> --project/--global",doctor:"pm extension --doctor --project/--global --detail deep --trace"});return h&&p.push(h),t>0&&p.push("Run pm extension --explore --project and pm extension --explore --global to inspect load failures."),n>0&&p.push("Review checks[name=extensions].details.activation.failed in pm health --json for activation error details."),(i.failed_count>0||i.pending_count>0)&&p.push("Resolve pending/failed extension migrations before write commands; use --force only when policy allows."),r>0&&p.push("Run pm extension --manage --project and pm extension --manage --global to refresh managed-state diagnostics."),u>0&&p.push(`Unknown extension capabilities detected. Allowed capabilities: ${Mi.join(", ")}. Review extension_capability_unknown warning details for suggested replacements.`),d.some(_=>_.startsWith("extension_capability_legacy_alias:"))&&p.push("Legacy extension capability aliases were auto-remapped to canonical capabilities. Update manifests to canonical names (migration/validation -> schema)."),d.some(_=>_.startsWith("extension_command_definition_legacy_handler_alias:"))&&p.push("Extension command definitions using legacy handler were auto-remapped. Update command definitions to use run: (context) => ... for forward compatibility."),m?p.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>."):o.length>0&&p.push("Loaded unmanaged extensions are currently treated as informational. Use pm extension --manage --project/--global --fix-managed-state to adopt them for update checks."),p.length===0&&p.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:a,unmanaged_loaded_extension_count:o.length,unmanaged_loaded_extensions:o,unmanaged_expected_extension_count:s.length,unmanaged_expected_extensions:s,unmanaged_action_required_extension_count:c.length,unmanaged_action_required_extensions:c,update_health_coverage:f,update_health_partial:m,unknown_capability_count:u,top_warnings:d.slice(0,8),remediation:p}}async function W0(e,t,n){let i=await os(Be(e)),r=await Je({pmRoot:e,settings:t,cwd:process.cwd(),noExtensions:n}),a=r.loaded.map(S=>j0(S)),o=await Mu(r.loaded,Be(e)),s=await Ve({...r,loaded:r.loaded}),[c,d]=await Promise.all([he(r.roots.project),he(r.roots.global)]);await as(e,s.registrations.migrations);let l=z0(s.registrations.migrations),u={failed:s.failed,warnings:s.warnings,hook_counts:s.hook_counts,command_override_count:s.command_override_count,command_handler_count:s.command_handler_count,parser_override_count:s.parser_override_count,preflight_override_count:s.preflight_override_count,service_override_count:s.service_override_count,renderer_override_count:s.renderer_override_count,registration_counts:s.registration_counts,registrations:s.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}}},m=new Set(c.state.entries.map(S=>Tn(S.name))),f=new Set(d.state.entries.map(S=>Tn(S.name))),p=[...new Map(r.loaded.filter(S=>!(S.layer==="project"?m:f).has(Tn(S.name))).map(S=>[`${S.layer}:${S.name}`,{layer:S.layer,name:S.name,directory:S.directory}])).values()].sort((S,b)=>{let O=`${S.layer}:${S.name}`,P=`${b.layer}:${b.name}`;return O.localeCompare(P)}),h=p.map(S=>`${S.layer}:${S.name}`).sort((S,b)=>S.localeCompare(b)),_=p.filter(S=>As(S.name,S.directory)).map(S=>`${S.layer}:${S.name}`).sort((S,b)=>S.localeCompare(b)),w=p.filter(S=>!As(S.name,S.directory)).map(S=>`${S.layer}:${S.name}`).sort((S,b)=>S.localeCompare(b)),v=w.length>0?[`extension_update_health_partial_coverage:skipped_unmanaged:${w.length}`]:[],E=[...i.warnings,...r.warnings,...u.warnings,...l.warnings,...c.warnings,...d.warnings,...v,...o.warnings],k=gi(E),I=yi(),C=lh(E,r.failed.length,s.failed.length,l.summary,c.warnings.length+d.warnings.length,c.state.entries.length+d.state.entries.length,h,_,w);return{check:{name:"extensions",status:E.length===0?"ok":"warn",ok:E.length===0,details:{...r,loaded:a,warnings:E,activation:u,author_manifest:i,triage:C,...l.summary.pending_count>0?{remediation_map:{extension_migration_pending:"pm extension migrate --project"}}:{},capability_contract:I,capability_guidance:k,host_version_census:o}},warnings:E}}function Ts(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=Vu(e,oh);return{values:n.values,truncated:n.truncated,total:e.length}}function la(e){let t=(process.env[e]??"").trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function q0(){let e=(process.env.PM_TELEMETRY_SOURCE_CONTEXT??"").trim().toLowerCase();return S0.has(e)?e:null}function ua(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 uh(e){let t=0,n=0,i=0,r=0,a=0;for(let o of e.split(`
|
|
55
55
|
`)){let s=o.trim();if(s.length!==0){i+=1;try{let c=JSON.parse(s);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,a=Math.max(a,d),d>=sh&&(r+=1)}else n+=1}catch{n+=1}}}return{validEntries:t,invalidRows:n,totalRows:i,highRetryEntries:r,maxAttempts:a}}function G0(){return{validEntries:0,invalidRows:0,totalRows:0,highRetryEntries:0,maxAttempts:0}}function B0(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 J0(e,t){let n=e.telemetry.endpoint.trim();return!t||!e.telemetry.enabled||n.length===0||Xa().telemetry_disabled?void 0:{attempted:!0,...await mh(n)}}function V0(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,a=n.last_failed_flush_at,o=a&&(!r||a>r),s=!r,c=t.validEntries>=A0;return(o||s||c)&&i.push(`telemetry_queue_pending:${t.validEntries}`),t.highRetryEntries>0&&i.push(`telemetry_queue_high_retries:${t.highRetryEntries}`),i}function K0(e){return!e||e.ok!==!1?[]:typeof e.status=="number"?[`telemetry_endpoint_probe_http_status:${e.status}`]:["telemetry_endpoint_probe_failed"]}function Y0(e){let t=Number.parseInt(e?.max_schema_version??"",10);return e?.ok===!0&&Number.isInteger(t)&&t>Rl?[`telemetry_schema_version_behind:${t}`]:[]}function X0(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 Z0(){return{...Xa(),pm_no_telemetry:la("PM_NO_TELEMETRY"),telemetry_otel_disabled:la("PM_TELEMETRY_OTEL_DISABLED"),telemetry_inline_flush:la("PM_TELEMETRY_INLINE_FLUSH"),telemetry_source_context:q0()}}function Q0(e,t){return e.telemetry.enabled&&t.validEntries>0}function ex(e,t){return e&&t.every(n=>!n.startsWith("telemetry_queue_pending:")&&!n.startsWith("telemetry_queue_high_retries:"))}async function mh(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(R0)});return{probe_url:ua(t),ok:n.ok,status:n.status,max_schema_version:(()=>{for(let i of C0){let r=n.headers.get(i)?.trim();if(r&&r.length>0)return r}})()}}catch(n){return{probe_url:ua(t),ok:!1,error:n instanceof Error?n.message:"probe_failed"}}}async function tx(e,t){let n=Ui(process.cwd()),i=be.join(n,x0),r=be.join(n,I0),a=await B(i),o=a!==null,s=a?Buffer.byteLength(a,"utf8"):0,c=a?uh(a):G0(),d=await B(r),{runtimeState:l,stateParseFailed:u}=B0(d),m=e.telemetry.endpoint.trim(),f=ua(m),p=await J0(e,t.checkTelemetry),h=[];u&&h.push("telemetry_state_invalid_json"),h.push(...V0(e,c,l),...K0(p),...Y0(p),...X0(e,l));let _=Q0(e,c),w=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:f,global_pm_root:n,queue_path:i,queue_exists:o,queue_entries:c.validEntries,queue_draining:ex(_,h),queue_invalid_rows:c.invalidRows,queue_rows_total:c.totalRows,queue_size_bytes:s,queue_high_retry_entries:c.highRetryEntries,queue_high_retry_threshold:sh,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:w,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:p??{attempted:!1},env_overrides:Z0()}},warnings:h}}async function nx(e){let t;try{t=await _m(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,...t.owner_dead_lock_samples?{owner_dead_lock_samples:t.owner_dead_lock_samples,recovery_command:"pm gc --scope locks"}:{},unreadable_lock_count:t.unreadable_lock_count,unparseable_lock_count:t.unparseable_lock_count}},warnings:n}}async function ix(e){let t="metadata",n=e.items,i=await Ht(e.pmRoot,n,{cacheHitVerification:t}),r=[...new Set([...i.hashMismatches,...i.chainMismatches,...i.versionSkews])].sort((w,v)=>w.localeCompare(v)),a=[],o=[];if(r.length>0){n=await at(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema,{forceSourceScan:!0}),i=await Ht(e.pmRoot,n),a=[...new Set([...i.hashMismatches,...i.chainMismatches,...i.versionSkews])].sort((v,E)=>v.localeCompare(E));let w=new Set(a);o=r.filter(v=>!w.has(v))}let{missingStreams:s,unreadableStreams:c,hashMismatches:d,chainMismatches:l,versionSkews:u,driftedItems:m,workspaceStateMismatches:f,workspaceStateMissing:p,workspaceStateUnreadable:h}=i,_=[...s.map(w=>`history_drift_missing_stream:${w}`),...c.map(w=>`history_drift_unreadable_stream:${w}`),...d.map(w=>`history_drift_hash_mismatch:${w}`),...l.map(w=>`history_drift_chain_mismatch:${w}`),...u.map(w=>`history_drift_version_skew:${w}`),...f.map(w=>`history_drift_workspace_state_mismatch:${w}`),...p.map(w=>`history_drift_workspace_state_missing:${w}`),...h.map(w=>`history_drift_workspace_state_unreadable:${w}`)];return{check:{name:"history_drift",status:_.length===0?"ok":"warn",ok:_.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:a,resolved_false_positive_items:o,authoritative_item_source:r.length>0},drifted_items:m,counts:{drifted:m.length,missing_streams:s.length,unreadable_streams:c.length,hash_mismatches:d.length,chain_mismatches:l.length,version_skews:u.length,workspace_state_mismatches:f.length,workspace_state_missing:p.length,workspace_state_unreadable:h.length},missing_streams:s,unreadable_streams:c,hash_mismatches:d,chain_mismatches:l,version_skews:u,workspace_state_mismatches:f,workspace_state_missing:p,workspace_state_unreadable:h}},warnings:_}}function rx(e,t){let n=ur(e),i=Bn(n.settings),r=fr(n.settings,t),a=i.active?Mt(i.active.name,i.active.model):null;return{runtimeDefaults:n,providerResolution:i,vectorStoreResolution:r,runtimeEmbeddingIdentity:a,semanticRuntimeAvailable:!!(i.active&&r.active)}}function ax(){return{refreshed:[],skipped:[],warnings:[]}}async function ox(e){return!e.refreshPolicy.enabled||!e.snapshot.semanticRuntimeAvailable||e.staleBefore.length===0?ax():El(e.pmRoot,e.staleBefore,{settings:e.snapshot.runtimeDefaults.settings,apply_runtime_defaults:!1})}function sx(e){return e.strictVectorizationWarnings&&e.semanticRuntimeAvailable&&!!(e.ledgerBefore.embedding&&e.runtimeEmbeddingIdentity&&sn(e.ledgerBefore.embedding,e.runtimeEmbeddingIdentity))}function cx(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 dx(e,t,n){return e.enabled&&t&&n.length>0?null:e.enabled?t?"no_stale_items":"semantic_runtime_unavailable":"refresh_disabled"}function ph(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:Va(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:Va(i,e.vector_store?.adapter??null)}}function lx(e){return{enabled:e.enabled,check_only:e.checkOnly,no_refresh:e.noRefresh,refresh_vectors:e.refreshVectors}}function ux(e,t,n){return e.enabled&&n.length>0&&t}async function mx(e,t,n,i,r){let a=rx(t,e),o=await cn(e),s=a.semanticRuntimeAvailable?eo(n,o.entries):[],c=await ox({pmRoot:e,snapshot:a,refreshPolicy:i,staleBefore:s}),d=await cn(e),l=a.semanticRuntimeAvailable?eo(n,d.entries):[],u=!a.runtimeDefaults.auto_ollama_defaults_applied,m=sx({strictVectorizationWarnings:u,semanticRuntimeAvailable:a.semanticRuntimeAvailable,ledgerBefore:o,runtimeEmbeddingIdentity:a.runtimeEmbeddingIdentity}),f=cx({ledgerBefore:o,ledgerAfter:d,refreshResult:c,strictVectorizationWarnings:u,semanticRuntimeAvailable:a.semanticRuntimeAvailable,embeddingIdentityChanged:m,staleAfter:l}),p=Ts(s,r),h=Ts(l,r),_=ux(i,a.semanticRuntimeAvailable,s);return{check:{name:"vectorization",status:f.length===0?"ok":"warn",ok:f.length===0,details:{semantic_runtime_available:a.semanticRuntimeAvailable,compatibility_mode_auto_defaults:a.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_applied:a.runtimeDefaults.auto_ollama_defaults_applied,auto_ollama_defaults_skipped_reason:a.runtimeDefaults.auto_ollama_defaults_skipped_reason??null,auto_ollama_defaults_remediation:a.runtimeDefaults.auto_ollama_defaults_remediation??null,refresh_policy:lx(i),...ph(t,a),embedding_identity_changed:m,embedding_identity_before:o.embedding??null,embedding_identity_runtime:a.runtimeEmbeddingIdentity??null,items:n.length,ledger_entries_before:Object.keys(o.entries).length,stale_items_detail_mode:r?"full":"summary",stale_items_summary_limit:oh,stale_items_before_total:p.total,stale_items_before:p.values,stale_items_before_truncated:p.truncated,refresh_attempted:_,refresh_skipped_reason:dx(i,a.semanticRuntimeAvailable,s),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:f}}function px(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 fh(e){let t=e.checkOnly===!0,n=e.refreshVectors===!0;if(n&&t)throw new g("--check-only cannot be combined with --refresh-vectors",y.USAGE);if(n&&e.noRefresh===!0)throw new g("--no-refresh cannot be combined with --refresh-vectors",y.USAGE);return{enabled:n,checkOnly:t,noRefresh:!n,refreshVectors:n}}var fx=new Set(["extensions","locks","search"]);function hx(e){let t=new Set(Rc.filter(r=>r.length>0)),n=new Set,i=new Set(Object.values(Ac));for(let r of e.folders)t.has(r)&&!i.has(r)||(t.delete(r),n.add(r));for(let r of fx)t.delete(r),n.add(r);return{requiredDirs:[...t].sort((r,a)=>r.localeCompare(a)),optionalDirs:[...n].sort((r,a)=>r.localeCompare(a)),optionalDirSet:n}}async function _x(e,t,n){let{requiredDirs:i,optionalDirs:r,optionalDirSet:a}=hx(t),o=[],s=[],c=[];for(let d of[...i,...r]){let l=be.join(e,d);c.push(...await Ne({path:l,scope:"project"})),!await Os(l)&&(a.has(d)?s.push(d):o.push(d))}return{requiredDirs:i,optionalDirs:r,missingRequiredDirs:o,missingOptionalDirs:s,missingDirs:n?[...o,...s]:[...o],hookWarnings:c}}function hh(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 gx(e){return e.skipPolicy.skipDrift&&e.skipPolicy.skipVectors?rt(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema):at(e.pmRoot,e.settings.item_format,e.typeRegistry.type_to_folder,e.itemReadWarnings,e.settings.schema)}function Rs(e){return{check:{name:e,status:"ok",ok:!0,details:{skipped:!0}},warnings:[]}}function yx(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 wx(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 vx(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 Ps=e=>e.unknown_event_count??0,Ls=e=>e.actionable_unknown_event_count??Ps(e);function bx(e,t,n,i,r,a){let o=Ps(i),s=Ls(i),c=o>0,d=s>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}:{},...a.outcomes.length>0?{provenance_resolver_outcomes:a.outcomes}:{},...a.invalid_values.length>0?{provenance_invalid_values:a.invalid_values}:{},provenance_sample:a.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 _h(e){let t=e.count===0?[]:[`stale_in_progress_items:${e.count}`];return{scan:e,warnings:t}}function kx(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 Ex(e){let t=e.check.details.counts;return typeof t?.drifted=="number"?t.drifted:0}function Sx(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 gh(e){let t=new Map;for(let[i,r]of Object.entries(e.remediationSources))for(let a of r)t.has(a)||t.set(a,i);let n=new Map(e.checks.map(i=>[i.name,i]));return e.warnings.map(i=>{let r=t.get(i)??"integrity",a=Do(i)?.code??Ds(i),o=n.get(r)?.details,s=typeof o?.remediation_map=="object"&&o.remediation_map!==null?o.remediation_map:{},c=oi(i)??(a==="agent_guidance_outdated"?"pm init --agent-guidance add":a==="agent_guidance_unreadable"?"Check AGENTS.md and CLAUDE.md read permissions and file types, then retry pm health.":s[a]),d=$s(i,e.requireMergeDrivers)?"advisory":"gate_failing";return{warning:i,code:a,check:r,severity:d,...typeof c=="string"?{remediation:c}:d==="gate_failing"?{disposition:"no_safe_automatic_remediation"}:{}}})}function xx(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 Ix(e){for(let t of e.checks){let n=Oo(e.remediationSources[t.name]);xx({check:t,remediationMap:n,historyDriftedCount:e.historyDriftedCount,overThresholdCount:e.overThresholdCount}),Object.keys(n).length>0&&(t.details={...t.details,remediation_map:n})}}async function Rx(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(o=>typeof o=="string"):[],i=new Set([t.missing_streams,t.unreadable_streams,t.chain_mismatches].flatMap(o=>Array.isArray(o)?o:[])),r=new Map;for(let o of e.pendingMergeReceipts){let s=r.get(o.item_id)??[];s.push(o),r.set(o.item_id,s)}let a=[];for(let o of n){if(i.has(o))continue;let s=r.get(o);if(!(!s||s.length===0))try{await xs(o,{dryRun:!0,mergeReceiptProof:{gitWorkspaceRoot:e.gitWorkspaceRoot,receipts:s}},e.global),a.push(o)}catch{}}return[...new Set(a)].sort((o,s)=>o.localeCompare(s))}function Ax(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 yh(e,t={}){let n=M(process.cwd(),e.path);await ne(n);let i=Bt(n),{settings:r,warnings:a}=await el(n),o=[...new Set(a)],s=H(r,F()),c=t.strictDirectories===!0,d=t.strictExit===!0||t.failOnWarn===!0,l=t.requireMergeDrivers===!0||d,u=fh(t),m=await _x(n,s,c),f=px(r),p=await tx(r,{checkTelemetry:t.checkTelemetry===!0}),h=await W0(n,r,!!e.noExtensions),_=hh(t),w=[],v=await gx({pmRoot:n,settings:r,typeRegistry:s,skipPolicy:_,itemReadWarnings:w}),E=v,k=Tr(fe(r.schema),v),I=[...(await rm({pm_root:n,cwd:process.cwd(),mode:"status",interactive:!1,settings:r}).catch(()=>({warnings:["agent_guidance_unreadable:AGENTS.md,CLAUDE.md"]}))).warnings.filter(ue=>ue.startsWith("agent_guidance_")),...f,...$r(k)],C=_.skipDrift?{warnings:[]}:await Yd({pmRoot:n,settings:r,itemIds:v.map(ue=>ue.id),commandLabel:"health"}),S=await D0(n,r.history.compact_policy,await T0(n)),b=await ti(n,20,t.verboseAuthorEvents===!0),O=Ls(b),P=O>0?[`history_unknown_author_events:${O}`]:[],x=_h(await xl(n,v,{in_progress_status:r.schema.workflow.in_progress_status,threshold_hours:r.mutation_guard.stale_in_progress_hours})),q=await Wu(n),Se=q.warnings,_e=await nx(n),pe=_.skipIntegrity&&!l?{...Rs("integrity"),gitWorkspaceRoot:null,pendingMergeReceipts:[]}:await N0(n,s.type_to_folder,r.schema,r,l,v),Le=_.skipDrift?Rs("history_drift"):await ix({pmRoot:n,items:E,settings:r,typeRegistry:s,itemReadWarnings:w}),Pi=[...new Set(w)],jn=await Rx({gitWorkspaceRoot:pe.gitWorkspaceRoot,pendingMergeReceipts:pe.pendingMergeReceipts,historyDriftCheck:Le,global:e});Ax(Le,jn);let U=_.skipVectors?Rs("vectorization"):await mx(n,r,E,u,t.verboseStaleItems===!0),G=[yx(i,r,o),wx(m,c),vx(I,k),p.check,h.check,bx(v,r,S,b,x.scan,q),_e.check,pe.check,Le.check,U.check],Li=kx({directoryState:m,normalizedSettingsReadWarnings:o,settingWarnings:I,normalizedItemReadWarnings:Pi,telemetryCheck:p,extensionCheck:h,historyPolicyWarnings:C.warnings,historySummary:S,authorAttributionWarnings:P,staleInProgressWarnings:x.warnings,provenanceWarnings:Se,locksCheck:_e,integrityCheck:pe,historyDriftCheck:Le,vectorizationCheck:U}),Ni=Sx({directoryState:m,normalizedSettingsReadWarnings:o,settingWarnings:I,normalizedItemReadWarnings:Pi,telemetryCheck:p,extensionCheck:h,historyPolicyWarnings:C.warnings,historySummary:S,authorAttributionWarnings:P,staleInProgressWarnings:x.warnings,provenanceWarnings:Se,locksCheck:_e,integrityCheck:pe,historyDriftCheck:Le,vectorizationCheck:U});Ix({checks:G,remediationSources:Ni,historyDriftedCount:Ex(Le),overThresholdCount:S.over_threshold.length});let Ta=Li.filter(ue=>!$s(ue,l)),$a=gh({warnings:Li,checks:G,remediationSources:Ni,requireMergeDrivers:l}),fg=new Set($a.filter(ue=>ue.severity==="gate_failing").map(ue=>ue.check)),hg=new Set($a.map(ue=>ue.check));for(let ue of G)ue.ok=!fg.has(ue.name),hg.has(ue.name)&&(ue.status="warn");let _g={ok:Ta.length===0,verdict:{authority:"ok",...d?{strict_exit:!0}:{},...l?{require_merge_drivers:!0}:{},exit_code:d&&Ta.length>0?y.GENERIC_FAILURE:0},checks:G,warnings:Li,findings:$a,failed_because:Ta,generated_at:$()};return Ro(_g,t,_.summaryMode)}var Lj={buildHierarchyIntegrityWarnings:dh,buildExtensionHealthTriageSummary:lh,buildHealthFindings:gh,buildCapabilityContractMetadata:yi,buildStaleInProgressHealthSummary:_h,buildVectorizationProviderDetails:ph,collectUnknownCapabilityGuidance:gi,isAdvisoryHealthWarning:$s,isDirectory:Os,isExpectedUnmanagedExtension:As,listItemDocumentPaths:ch,normalizeEndpointForDisplay:ua,normalizeExtensionNameForMatch:Tn,parseTelemetryQueue:uh,probeTelemetryEndpointHealth:mh,projectHealthResult:Ro,resolveActionableUnknownAuthorEventCount:Ls,resolveHealthSkipPolicy:hh,resolveUnknownAuthorEventCount:Ps,resolveVectorRefreshPolicy:fh,selectStaleItemDetail:Ts,summarizeHealthCheckDetails:xo,summarizeExtensionList:ii,summarizeRecordList:Fe,summarizeStringList:W,telemetryEnvFlagEnabled:la,warningCode:Ds};(function(){try{var e=typeof window<"u"?window:typeof 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 wh(e,t,n){if(!n.has(t.metadata.status))return{reason:"not_terminal"};if(e.length===0)return{reason:"missing_history"};if(!Pl(e,t).ok)return{reason:"unverified_history"};let i=ar(),r={reason:"no_proven_transition"};for(let[a,o]of e.entries()){let s=n.has(String(i.metadata.status));i=nl(i,o.patch,a+1,o.op),n.has(String(i.metadata.status))?s||(r=["create","close","cancel","update","update_audit"].includes(o.op)&&vt(o.ts)?{timestamp:o.ts,source_index:a+1}:{reason:"no_proven_transition"}):r={reason:"no_proven_transition"}}return r}function vh(e){return new Set([...e.terminal_statuses,...[...e.alias_to_id].filter(([,t])=>e.terminal_statuses.has(t)).map(([t])=>t)])}async function bh(e,t,n,i,r){let a=vh(n),o=t.filter(d=>a.has(d.status)&&!d.closed_at),s=[],c=[];for(let d of i?o:[]){let l;try{let u=await Me(Ot(e,d.id),d.id),{body:m,...f}=d;l=wh(u,{metadata:f,body:m},a)}catch{c.push({id:d.id,reason:"unreadable_history"});continue}if("reason"in l){c.push({id:d.id,reason:l.reason});continue}s.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:o.length,missing_closed_at_item_ids:o.slice(0,r).map(d=>d.id),missing_closed_at_item_ids_truncated:o.length>r,closure_history_inspected:i,closure_timestamp_derivable_count:s.length,closure_timestamp_residual_count:c.length,closure_timestamp_residual:c.slice(0,r),closure_timestamp_residual_truncated:c.length>r,...o.length>0?{closure_timestamp_fix_hint:"pm validate --check-metadata --auto-fix --fix-scope timestamps --dry-run"}:{}},fixes:s,warnings:o.length>0?[`validate_metadata_missing_closed_at:${o.length}`]:[]}}async function kh(e,t){let n=M(process.cwd(),t.path),i=await T(n),r=fe(i.schema);await ot({pmRoot:n,settings:i,id:e.item_id,op:"update",author:z(t.author,i.author_default),message:"Backfill closed_at from verified lifecycle history",skipNoop:!0,async mutate(a){if(a.metadata.closed_at)return{changedFields:[]};let o=await Me(Ot(n,a.metadata.id),a.metadata.id),s=vh(r),c=wh(o,a,s);if(!("timestamp"in c)||c.timestamp!==e.value)throw new g("Closure timestamp evidence changed or cannot be verified; rerun the timestamp repair preview.",y.GENERIC_FAILURE);return a.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 Cx(e,t){return e==="malformed"||t==="malformed"?"malformed":e==="moved"||t==="moved"?"moved":"deleted"}function Eh(e){return`${e.item_id} ${e.link_kind}`}function Sh(e,t){let n=new Map;for(let i of e){let r=n.get(i.path);r?(r.classification=Cx(r.classification,i.classification),r.owners.set(Eh(i),i)):n.set(i.path,{classification:i.classification,owners:new Map([[Eh(i),i]])})}return[...n.entries()].sort(([i],[r])=>i.localeCompare(r)).map(([i,r])=>({path:i,classification:r.classification,items:[...r.owners.values()].map(a=>{let o=t(a.item_id);return{id:a.item_id,type:o?.type??"Unknown",title:o?.title??"",status:o?.status??"",field:a.link_kind}}).sort((a,o)=>{let s=a.id.localeCompare(o.id);return s!==0?s:a.field.localeCompare(o.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 xh(e,t,n,i,r=40){let a=r===1/0?1/0:Number.isFinite(r)?Math.max(0,Math.floor(r)):40,o=new Map(t.map(d=>[d.path,d])),s={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=Sh(e,n).map(d=>{let l=[],u=[];for(let f of d.items){let p=nr(f.status,i)??f.status;i.terminal_statuses.has(p)?(u.push(f),p===i.close_status&&(s.legacy_closed_missing_linked_links_count+=1)):l.push(f)}s.missing_linked_links_count+=d.items.length,s.active_missing_linked_links_count+=l.length,s.legacy_terminal_missing_linked_links_count+=u.length,l.length>0&&(s.active_missing_linked_paths_count+=1);let m=o.get(d.path);return{...d,candidates:m?.candidates??[],candidates_truncated:m?.candidates_truncated??!1,link_count:d.items.length,active_link_count:l.length,items:[...l,...u].slice(0,a),items_truncated:d.items.length>a}});return c.sort((d,l)=>+(l.active_link_count>0)-+(d.active_link_count>0)||d.path.localeCompare(l.path)),s.missing_linked_path_rows_count=c.length,s.missing_linked_path_rows=c.slice(0,a),s.missing_linked_path_rows_truncated=c.length>a,s}import $n from"node:fs/promises";import Dn 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 Tx(e,t){let n=[...new Set(Object.values(t))],i=[];return await Promise.all(n.map(async r=>{let a;try{a=await $n.readdir(Dn.join(e,r))}catch{return}for(let o of a)for(let s of Un)if(o.toLowerCase().endsWith(s)){i.push({relativePath:`${r}/${o}`,id:o.slice(0,-s.length)});break}})),i.sort((r,a)=>r.relativePath.localeCompare(a.relativePath))}function $x(e,t){let{id:n,relativePath:i,liveItemIds:r,out:a}=e,o=$e(t);if(o){a.conflictMarkers.push({id:n,path:i,line:o.line,detail:`unresolved merge conflict marker ${o.marker}`});return}let s=Dx(e,t);s!==null&&(s.op==="delete"&&r.has(n)&&a.resurrected.push({id:n,deleted_at:typeof s.ts=="string"?s.ts:"",deleted_by:typeof s.author=="string"?s.author:""}),s.op==="history_repair"&&Array.isArray(s.patch)&&s.patch.length>0&&(a.repairReconciliations+=1))}function Dx(e,t){let{id:n,relativePath:i,out:r}=e,a=null,o=!1,s=t.split(/\r?\n/).map((c,d)=>({content:c.trim(),number:d+1})).filter(c=>c.content.length>0);for(let c of s){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");a=d}catch{return r.unparseable.push({id:n,path:i,line:c.number,detail:"history line is not a valid JSON object"}),null}if(a.op==="create"){if(o)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;o=!0}}return a}function Ns(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 Ox(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},i;try{i=await $n.readdir(Dn.join(e,"history"))}catch{return n}for(let r of i.sort((a,o)=>a.localeCompare(o))){if(!r.endsWith(".jsonl"))continue;n.scanned+=1;let a;try{a=await $n.readFile(Dn.join(e,"history",r),"utf8")}catch(o){n.unparseable.push({id:r.slice(0,-6),path:`history/${r}`,detail:Ns("history stream",o)});continue}$x({id:r.slice(0,-6),relativePath:`history/${r}`,liveItemIds:t,out:n},a)}return n}function Ih(e){let t=$e(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 Px(e){let t=[],n=0,i=null;try{i=await B(Bt(e))}catch(a){n+=1,t.push({path:"settings.json",detail:Ns("configuration file",a)})}if(i!==null){n+=1;let a=Ih(i);a!==null&&t.push({path:"settings.json",detail:a})}let r;try{r=await $n.readdir(Dn.join(e,"schema"))}catch{return{scanned:n,unparseable:t}}for(let a of r.sort((o,s)=>o.localeCompare(s))){if(!a.endsWith(".json"))continue;n+=1;let o;try{o=await $n.readFile(Dn.join(e,"schema",a),"utf8")}catch(c){t.push({path:`schema/${a}`,detail:Ns("configuration file",c)});continue}let s=Ih(o);s!==null&&t.push({path:`schema/${a}`,detail:s})}return{scanned:n,unparseable:t}}async function Rh(e,t,n,i={}){let r=await Tx(e,n),a=new Set(r.map(u=>u.id)),o=new Map;for(let u of r){let m=o.get(u.id);m===void 0?o.set(u.id,[u.relativePath]):m.push(u.relativePath)}let s=[...o.entries()].filter(([,u])=>u.length>1).map(([u,m])=>({id:u,paths:[...m].sort((f,p)=>f.localeCompare(p))})).sort((u,m)=>u.id.localeCompare(m.id)),c=(await Promise.all(r.map(async u=>{if(!t.has(u.id))return{path:u.relativePath,id:u.id};try{let m=Dn.join(e,u.relativePath);return bt(await $n.readFile(m,"utf8"),{format:m.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 Ox(e,a),l=await Px(e);return{item_files_on_disk:r.length,item_ids_on_disk:a.size,parsed_items:t.size,unreadable_item_files:c,duplicate_item_ids:s,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 cc from"node:fs/promises";import{realpathSync as JI}from"node:fs";import{execFile as VI}from"node:child_process";import Ee from"node:path";import{promisify as KI}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 Lx=["metadata","resolution"],Ms=["metadata","resolution","estimates","timestamps","lifecycle"],Nx="completed";function js(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function Ah(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function Ch(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let i=Ah(n.close_reason)??Nx;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:i,command:`pm update ${n.id} --resolution ${js(i)}`,gate:"resolution"})}return t}function Th(e){let t=[];for(let n of e){let i=Ah(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 ${js(i)}`,gate:"metadata"})}return t}function $h(e,t){return e.map(n=>{let i=Zd(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 Oh(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 ${js(n.path)}`})}return t}function Ph(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 g(`--fix-scope values must not be empty. Supported values: ${Ms.join(", ")}.`,y.USAGE);return new Set(Lx)}let n=new Set;for(let i of t){let r=i.toLowerCase().replaceAll("-","_");if(Ms.includes(r)){n.add(r);continue}throw new g(`Unknown --fix-scope value "${i}". Supported values: ${Ms.join(", ")}.`,y.USAGE)}return n}function Lh(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 xi(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 Mx=/^([A-Z][A-Z0-9]*-\d+)\b/iu;function jx(e,t={}){if(typeof e!="string")return null;let n=e.trim();if(n.length===0)return null;let i=Mx.exec(n);if(!i)return null;let r=i[1],a=r.toUpperCase(),o=r.slice(0,r.lastIndexOf("-")),s=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: ${a}`)||d.includes(`ISSUE CODE \`${a}\``)||d.includes(`\`${a}\``)||d.includes(`[${a}]`);return o===o.toUpperCase()||/^\s*(?::|—|–|\])/u.test(c)||s.has(o.toUpperCase())||l?a:null}function Nh(e){return typeof e=="string"&&e.trim().length>0}function Fx(e){let t=new Set(e.map(o=>o.id.toLowerCase())),n=new Map,i=new Map;for(let o of e){let s=o.id.toLowerCase(),c=new Set([...o.parent===null?[]:[o.parent.toLowerCase()],...o.derivations].filter(d=>d!==s&&t.has(d)));n.set(s,c);for(let d of c){let l=i.get(d)??[];l.push(s),i.set(d,l)}}let r=[...[...n].filter(([,o])=>o.size===0).map(([o])=>o)],a=new Set;for(let o=0;o<r.length;o+=1)for(let s of i.get(r[o])??[]){let c=n.get(s);c.delete(r[o]),c.size===0&&(a.add(s),r.push(s))}return e.filter(o=>!a.has(o.id.toLowerCase()))}function Mh(e,t={}){let n=new Map;for(let r of e){if(typeof r.title!="string"||Nh(r.duplicate_of))continue;let a=jx(r.title,{...t,evidenceText:r.body});if(a===null)continue;let o=n.get(a);o||(o=[],n.set(a,o)),o.some(s=>s.id===r.id)||o.push({id:r.id,title:r.title,parent:Nh(r.parent)?r.parent.trim():null,derivations:(r.dependencies??[]).filter(s=>["discovered_from","supersedes","incident_from"].includes(s.kind)).map(s=>s.id.trim().toLowerCase()).filter(s=>s!==r.id.toLowerCase())})}let i=[];for(let[r,a]of n){if(a.length<2)continue;let o=Fx(a);if(o.length<2)continue;let s=[...o].sort((c,d)=>c.id.localeCompare(d.id));i.push({code:r,count:s.length,ids:s.map(c=>c.id),titles:s.map(c=>c.title)})}return i.sort((r,a)=>r.code.localeCompare(a.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 jh(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,a)=>r.localeCompare(a))){let r=t.get(i),a={};for(let o of[...r.keys()].sort((s,c)=>s.localeCompare(c)))a[o]=r.get(o);n[i]=a}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 Fh(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function Uh(e,t,n=3){let i=Number.isFinite(n)&&n>=1?Math.floor(n):3,r=new Map;for(let a of t){let o=Fh(a);if(o.length===0)continue;let s=r.get(o);s?s.push(a):r.set(o,[a])}return e.map(a=>{if(a.includes(",")||a.replace(/^[a-z]:[\\/]/i,"").includes(":"))return{path:a,classification:"malformed",candidates:[],candidates_truncated:!1};let o=(r.get(Fh(a))??[]).filter(s=>s!==a).sort((s,c)=>s.localeCompare(c));return o.length===0?{path:a,classification:"deleted",candidates:[],candidates_truncated:!1}:{path:a,classification:"moved",candidates:o.slice(0,i),candidates_truncated:o.length>i}})}function Hh(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]="6f94fb3c-3d6c-5543-a2f0-e12680459e71")}catch{}})();var Ux=/^[a-z][a-z0-9+.-]+:\/\//i;function Ii(e){return Ux.test(e.trim())}import Hx from"node:fs/promises";import ke from"node:path";import{glob as zx}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]="12655e94-6304-56cf-9f5d-387a26572db0")}catch{}})();var Wx=["path","scope","note"],qx=["pattern","glob","path","scope","note"],Gx=["path"],Bx=["from","to"],Jx=new Set(["note","scope"]);function Wh(e){let t=e??"project";if(!Da.includes(t))throw new g(`Invalid scope "${e}". Valid scopes: ${Da.join(", ")} (default: project).`,y.USAGE);return t}function Fs(e){if(e.startsWith("```")||e.includes(`
|
|
@@ -62,4 +62,4 @@ ${a}`,y.GENERIC_FAILURE)}}function Ca(e){return typeof e.tag=="string"&&e.tag.tr
|
|
|
62
62
|
`);oe(e.progressEnabled,"writing keyword artifacts"),await Z(t,`${JSON.stringify(e.manifest,null,2)}
|
|
63
63
|
`),await Z(n,`${r}
|
|
64
64
|
`);let a=[];if(e.mode!=="keyword")try{oe(e.progressEnabled,"writing vectorization status ledger"),await kl(e.pmRoot,e.vectorizationLedgerEntries,e.vectorizationEmbeddingMetadata)}catch(o){a.push(`search_vectorization_status_ledger_write_failed:${o instanceof Error?o.message:String(o)}`)}return a}async function OW(e,t){let n=oC(e.mode),i=aC(e),r=e.full===!0;oe(i,`start mode=${n}`);let a=M(process.cwd(),t.path);await ne(a);let o=ur(await T(a)).settings,s=null;try{s=await re(a,tl,o.locks.ttl_seconds,z(void 0,"pm-reindex"),!1,o.governance.force_required_for_stale_lock,o.locks.wait_ms)}catch(c){throw c instanceof g&&c.exitCode===y.CONFLICT?new g("Another pm reindex run is already active for this project. Wait for it to finish before starting a new keyword, semantic, or hybrid reindex.",y.CONFLICT,{code:"reindex_already_running",type:"urn:pm-cli:error:reindex_already_running",why:"Semantic reindex can be expensive and duplicate runs compete for the same local embedding model and vector store.",nextSteps:["Check active pm reindex processes before starting another reindex.","Rerun with --progress when you need non-interactive visibility."]}):c}try{let c=dC(o),d=lC(o),l=_C({requestedMode:n,pmRoot:a,settings:o,extensionEmbedding:c,extensionVectorAdapter:d}),u=n;oe(i,"loading item corpus");let m=await gC({pmRoot:a,settings:o}),f=m.warnings,{documentCandidates:p,metadataDocuments:h}=m;oe(i,`loaded_items=${h.length}`);let _=$(),w=hC(u,_,h),v=Oi.join(a,wc),E=Oi.join(a,vc),k=u==="keyword"?await kc(a,p,o.schema,f):h,I=[],C={},S=null,b=fC(u);if(u==="keyword"&&await yC({pmRoot:a,settings:o,forceFullSemantic:r,extensionEmbedding:c,reindexWarnings:f}),u!=="keyword"){let x=await xC({pmRoot:a,settings:o,requestedMode:n,activeEmbeddingProvider:l.activeEmbeddingProvider,activeVectorStore:l.activeVectorStore,extensionEmbedding:c,extensionVectorAdapter:d,documentCandidates:p,metadataDocuments:h,documentsForKeywordArtifacts:k,forceFullSemantic:r,reindexWarnings:f,semanticWarnings:I,semanticSummary:b,progressEnabled:i});k=x.documentsForKeywordArtifacts,C=x.vectorizationLedgerEntries,S=x.vectorizationEmbeddingMetadata}let O=await IC({pmRoot:a,mode:u,manifest:w,documentsForKeywordArtifacts:k,settings:o,vectorizationLedgerEntries:C,vectorizationEmbeddingMetadata:S,progressEnabled:i}),P=[...await K({path:v,scope:"project",op:"reindex:manifest"}),...await K({path:E,scope:"project",op:"reindex:embeddings"}),...await Ji({mode:u,total_items:h.length})];return oe(i,"done"),{ok:!0,mode:u,total_items:h.length,semantic:b,artifacts:{manifest:wc,embeddings:vc},warnings:[...f,...I,...O,...P],generated_at:_}}finally{await s?.()}}export{L as a,we as b,Ye as c,mn as d,to as e,Ul as f,jt as g,no as h,Sg as i,ao as j,oo as k,ql as l,fn as m,Yn as n,co as o,Wg as p,Yl as q,Xn as r,Zl as s,kr as t,lo as u,Ql as v,eu as w,tu as x,go as y,uu as z,YC as A,iy as B,XC as C,ay as D,eT as E,hu as F,cy as G,vT as H,dv as I,BD as J,KD as K,YD as L,ci as M,XD as N,ZD as O,QD as P,eO as Q,tO as R,nO as S,iO as T,rO as U,aO as V,oO as W,sO as X,ns as Y,ls as Z,I$ as _,rm as $,my as aa,bu as ba,DT as ca,ti as da,OT as ea,wy as fa,vy as ga,PT as ha,by as ia,qh as ja,FT as ka,Au as la,Bh as ma,KF as na,YF as oa,ni as pa,Ar as qa,Tu as ra,$u as sa,Du as ta,Ou as ua,Mu as va,Fu as wa,Uu as xa,Wu as ya,At as za,rM as Aa,aM as Ba,oM as Ca,sM as Da,hM as Ea,Lf as Fa,ca as Ga,FM as Ha,ft as Ia,qf as Ja,UM as Ka,HM as La,t0 as Ma,a0 as Na,Kf as Oa,Hy as Pa,Gu as Qa,xs as Ra,P1 as Sa,L1 as Ta,Tr as Ua,$r as Va,yh as Wa,Lj as Xa,wh as Ya,bh as Za,kh as _a,xh as $a,Rh as ab,SI as bb,xI as cb,eU as db,tU as eb,nU as fb,iU as gb,RI as hb,AI as ib,CI as jb,rU as kb,Kh as lb,$I as mb,Yh as nb,Gs as ob,Zh as pb,DI as qb,OI as rb,PI as sb,Ks as tb,Ys as ub,hU as vb,_U as wb,gU as xb,uR as yb,AH as zb,F_ as Ab,Ti as Bb,z_ as Cb,W_ as Db,q_ as Eb,uc as Fb,wA as Gb,uz as Hb,Pz as Ib,zz as Jb,ig as Kb,rg as Lb,ag as Mb,mW as Nb,xW as Ob,IW as Pb,RW as Qb,OW as Rb};
|
|
65
|
-
//# sourceMappingURL=chunk-
|
|
65
|
+
//# sourceMappingURL=chunk-6OKPYCLU.js.map
|