@unbrained/pm-cli 2026.10.9 → 2026.10.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +2 -2
- package/CHANGELOG.md +19 -0
- package/dist/cli/register-mutation.js +2 -2
- package/dist/cli-bundle/bundle-manifest.json +115 -115
- package/dist/cli-bundle/chunks/{chunk-P5NS7EFC.js → chunk-2JYTSTQP.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-ZNXRGATT.js → chunk-BXSXT5Z6.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-QQHNXCO3.js → chunk-ESRACL6K.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-5MOFELIF.js → chunk-K2UTE75T.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-55MK3QQM.js → chunk-KNW3RSLS.js} +3 -3
- package/dist/cli-bundle/chunks/chunk-MEWBSWE3.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-KOGF6O6W.js → chunk-OBLO45UM.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-XW3BLWFF.js → chunk-RBPOO46D.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-E4XR5LKU.js → chunk-RUT3CCAG.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-CPZOW6L2.js → chunk-S445XEYT.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-5NR6TDYB.js → chunk-SSY4OSJR.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-5TCQ5J3V.js → chunk-YMLF6QT7.js} +75 -75
- package/dist/cli-bundle/chunks/{chunk-NIF7JOPW.js → chunk-ZWRLAOA4.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-2YOWMNWY.js → register-list-query-T6BOR67M.js} +2 -2
- package/dist/cli-bundle/chunks/register-mutation-6NXR7SAJ.js +20 -0
- package/dist/cli-bundle/chunks/{register-operations-BMK65YM3.js → register-operations-PDOBQZUJ.js} +2 -2
- package/dist/cli-bundle/chunks/{register-setup-24TFFK6N.js → register-setup-MAYFPKBX.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-362645PL.js → chunk-52UJEHEV.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-EZ4367G4.js → chunk-EIOQNLBQ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-SAN3KPX4.js → chunk-GVGFUD52.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-DSLNUL2Q.js → chunk-JGFSSR3G.js} +16 -16
- package/dist/cli-bundle/focused-chunks/{chunk-IARAEFMA.js → chunk-KNJR2WUO.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-MJQ253F3.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-MCVWZUGK.js → chunk-SIEGIPNT.js} +28 -28
- package/dist/cli-bundle/main.js +2 -2
- package/dist/cli-bundle/sdk-contracts.js +1 -1
- 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 +51 -51
- 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 +9 -9
- package/dist/core/item/item-format.d.ts +2 -0
- package/dist/core/item/item-format.js +3 -3
- package/dist/core/schema/runtime-field-values.d.ts +2 -2
- package/dist/core/schema/runtime-field-values.js +1 -1
- package/dist/core/store/item-format-migration.js +1 -1
- package/dist/core/store/item-store.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/governance/reliability.d.ts +74 -0
- package/dist/sdk/governance/reliability.js +2 -0
- package/dist/sdk/governance.d.ts +1 -0
- package/dist/sdk/governance.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/structured-mutations.d.ts +5 -1
- package/dist/sdk/structured-mutations.js +1 -1
- package/docs/QUALITY_EVIDENCE.md +52 -1
- package/docs/RELEASE_RELIABILITY.md +54 -3
- package/docs/SDK.md +16 -2
- package/docs/TESTING.md +36 -0
- package/docs/agent-task-token-baseline.json +15 -14
- package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +4 -3
- package/marketplace.json +2 -2
- package/package.json +1 -1
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-claude/package.json +2 -2
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/pm-codex/package.json +2 -2
- package/plugins/pm-codex/plugin.json +1 -1
- package/runtime-dependencies.json +2 -2
- package/dist/cli-bundle/chunks/chunk-N7GKWO4G.js +0 -2
- package/dist/cli-bundle/chunks/register-mutation-ILOWFMTV.js +0 -20
- package/dist/cli-bundle/focused-chunks/chunk-2ATAD56F.js +0 -2
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{A as Vn,Bb as si,Cb as Ke,D as Kn,Dc as mi,E as Qn,O as Yn,P as Xn,S as Jn,Sb as ai,Ub as ci,Wb as li,Xb as di,a as pe,b as K,c as En,ca as ze,cb as oi,d as Sn,da as vt,ea as Zn,fa as ei,ga as ti,ha as ri,k as bt,ka as ni,la as Et,ma as St,n as Gn,na as Ve,r as $n,ta as ii,v as ye,w as Bn,x as Wn,y as We,z as zn,zc as ui}from"./chunk-XW3BLWFF.js";import{$ as O,$i as fe,$l as Cn,Ag as Xr,Ai as fn,Cg as ce,Cm as Tn,Di as hn,Dl as kn,Dm as Mn,Ec as A,Eh as tn,El as xn,Fh as rn,Gg as Jr,Gh as nn,Hg as Me,Hh as on,Hm as Fn,Ig as Fe,Jc as qr,Kc as dt,Ki as pn,Kn as qn,Lm as Dn,M as Hr,Mm as Pn,Nc as Y,Nh as V,Ni as yn,Nm as Ue,Oc as Nr,Oh as sn,Om as Hn,Pc as ae,Pm as Ge,Qh as ht,Qi as He,Qm as $e,R as f,Rh as de,Rm as Be,Sh as ue,Sm as Ln,T as h,Tf as P,Th as pt,Ub as D,Uh as H,V as xe,Va as U,Vh as an,Wh as me,Wm as On,X as Lr,Xh as cn,Xi as Le,Xm as wt,Zh as yt,Zi as Oe,_i as gn,_l as Rn,ai as ln,aj as he,ba as lt,bb as k,bi as Pe,bj as _n,bm as _t,ci as dn,cj as wn,cm as An,db as jr,dd as X,dg as x,di as un,dj as je,eg as mt,el as In,en as jn,fb as z,fd as Ur,fj as bn,gf as I,gj as vn,hb as Ae,ia as se,ja as Re,jf as Te,kf as Vr,la as Ce,ld as Gr,lf as Kr,lh as De,ma as Or,mf as ut,mh as Zr,nf as Qr,ng as j,nh as le,nm as qe,no as Nn,oo as Un,pg as J,qd as $r,rd as Br,rm as Ne,ti as L,vd as Wr,vi as q,xd as zr,xf as Yr,xh as ft,xi as mn,yi as Z,yn as ee,zh as en,zi as gt}from"./chunk-5TCQ5J3V.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]="7dd9061f-1b49-5ecb-a306-74f09283fe57")}catch{}})();var jo="PmCliError";function jc(e){if(!No(e)||e.code!=="item_already_exists"||e.exitCode!==f.CONFLICT)return!1;let t=e.context;return typeof t=="object"&&t!==null&&t.code==="item_already_exists"&&typeof t.id=="string"&&t.id.trim().length>0&&typeof t.path=="string"&&t.path.trim().length>0}function qo(e){if(!Number.isFinite(e))throw new TypeError("createPmCliExpectedError options.exitCode must be a finite number");let t=Math.trunc(e);if(t<=f.SUCCESS)throw new TypeError("createPmCliExpectedError options.exitCode must be a positive exit code");return t}function fi(e,t={}){if(typeof e!="string"||e.trim().length===0)throw new TypeError("createPmCliExpectedError message must be a non-empty string");let r=new h(e,qo(t.exitCode??f.USAGE),t.context??{});return"cause"in t&&Object.defineProperty(r,"cause",{value:t.cause,enumerable:!1,configurable:!0,writable:!0}),r}function No(e){if(!(e instanceof Error)||e.name!==jo)return!1;let t=e;return typeof t.exitCode=="number"&&Number.isFinite(t.exitCode)}import pi from"node:fs/promises";import yi 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]="f3603dce-8aeb-5409-80f4-ad3367e35eb9")}catch{}})();function Uo(e,t,r){let n=new Set,i=[];for(let o of e){let s=o.trim();if(s.length===0||n.has(s))continue;n.add(s);let a=t.get(s);if(a===void 0){i.push({id:s,entries:0,selected:!1,skip_reason:"no_stream"});continue}if(a.entries<=r){i.push({id:s,entries:a.entries,selected:!1,skip_reason:"already_compact"});continue}i.push({id:s,entries:a.entries,selected:!0,skip_reason:null})}return i}function Go(e,t){let r=[...e].sort((i,o)=>o.entries-i.entries||i.id.localeCompare(o.id)),n=[];for(let i of r){if(t.scope==="closed"&&i.bucket!=="closed"){n.push({id:i.id,entries:i.entries,selected:!1,skip_reason:"scope_mismatch"});continue}if(i.entries<=t.minEntries){n.push({id:i.id,entries:i.entries,selected:!1,skip_reason:"already_compact"});continue}if(t.allOver!==void 0&&i.entries<=t.allOver){n.push({id:i.id,entries:i.entries,selected:!1,skip_reason:"below_threshold"});continue}n.push({id:i.id,entries:i.entries,selected:!0,skip_reason:null})}return n}function hi(e,t){if(t.ids!==void 0&&t.ids.length>0){let r=new Map(e.map(n=>[n.id,n]));return Uo(t.ids,r,t.minEntries)}return Go(e,t)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c6009e5f-840e-5e3a-b8b9-6e9d42d63410")}catch{}})();function $o(e,t){if(e===void 0)return{kind:"default",raw:null,compactCount:t.length,retainedCount:0};let r=e.trim();if(r.length===0)throw new h("history-compact --before requires a non-empty value.",f.USAGE);if(/^\d+$/.test(r)){let o=Number.parseInt(r,10),s=q(t);if(!Number.isSafeInteger(o)||o<s+1||o>s+t.length+1)throw new h(`history-compact --before version must be between ${s+1} and ${s+t.length+1}.`,f.USAGE);let a=o-s-1;return{kind:"version",raw:r,compactCount:a,retainedCount:t.length-a}}let n=Date.parse(r);if(!Number.isFinite(n))throw new h(`Invalid history-compact --before value "${e}". Use a version number or ISO timestamp.`,f.USAGE);let i=0;for(let[o,s]of t.entries()){let a=Date.parse(s.ts);if(!Number.isFinite(a))throw new h(`History for this item contains invalid timestamp at entry ${o+1}.`,f.GENERIC_FAILURE);if(a>=n)break;i+=1}return{kind:"timestamp",raw:r,compactCount:i,retainedCount:t.length-i}}function Bo(e,t){let r=de(),n=de();for(let i=0;i<e.length;i+=1){let o=e[i];r=Z(r,o.patch,i+1,o.op),i+1===t&&(n=structuredClone(r))}return{checkpoint:n,finalReplay:r}}function Wo(e,t){if(!e)return{loadedItem:null,currentItemRawBeforeLock:null,matchedChainBefore:null};let r=t[t.length-1];return{loadedItem:e,currentItemRawBeforeLock:e.raw,matchedChainBefore:en.some(n=>(r.item_hash_version===void 0||r.item_hash_version===n)&&pt(me(e.document),n,x(r.hash_algorithm)).includes(r.after_hash))}}function zo(e,t){return typeof e.message=="string"&&e.message.trim().length>0?e.message:t.raw===null?`history-compact compacted full stream (${t.compactCount} entr${t.compactCount===1?"y":"ies"}).`:`history-compact compacted ${t.compactCount} entr${t.compactCount===1?"y":"ies"} before ${t.raw}.`}function Vo(e){return e.raw===null?`history-compact baseline snapshot after compacting ${e.compactCount} entr${e.compactCount===1?"y":"ies"}.`:`history-compact baseline snapshot before ${e.raw}.`}function Ko(e){if(!e.changed)return{rewrittenEntries:e.historyEntries,baselineEntryAdded:!1,auditEntryAdded:!1};let{checkpoint:t,finalReplay:r}=Bo(e.historyEntries,e.boundary.compactCount),n=e.historyEntries.slice(e.boundary.compactCount),i=q(e.historyEntries,!0),o=e.historyEntries[e.boundary.compactCount-1],s=V({hashAlgorithm:x(o.hash_algorithm),nowIso:e.historyEntries[e.boundary.compactCount-1].ts,author:e.author,op:"history_compact_baseline",before:H(de()),after:H(t),message:Vo(e.boundary),context:{history_compaction:{contract_version:1,version_offset:i===null?null:i+e.boundary.compactCount-1,checkpoint_timestamp_semantics:"last_compacted_entry",pruned_entry_count:e.boundary.compactCount,pruned_stream_digest:tn(e.historyEntries.slice(0,e.boundary.compactCount)),retained_proof:"stream_digest_and_checkpoint",limitation:"individual_pruned_entries_require_pre_compaction_stream"}}}),a=[rn({...s,before_hash:pt(de(),o.item_hash_version??1,x(o.hash_algorithm))[0],after_hash:o.after_hash,item_hash_version:o.item_hash_version}),...n];return e.dryRun||a.push(V({nowIso:I(),author:e.author,op:"history_compact",before:H(r),after:H(r),message:zo(e.options,e.boundary)})),{rewrittenEntries:a,baselineEntryAdded:!0,auditEntryAdded:!e.dryRun}}async function Qo(e,t,r){let{pmRoot:n,settings:i,typeRegistry:o}=await pe(r.path),s=await K(n,e,i,o.type_to_folder);return Ke({pmRoot:n,subject:s,settings:i,typeRegistry:o,operation:"history-compact",options:t,transform:a=>Yo(s,t,a)})}function Yo(e,t,r){let n=e.historyPath,i=r.entries,o=r.verification;if(!o.ok)throw new h(`history-compact requires a valid history chain (${o.errors.join(", ")}). Run pm history-repair ${e.id} first.`,f.CONFLICT);let s=$o(t.before,i),a=s.compactCount>0,c=!!t.dryRun,d=r.author,l=[];a||l.push("history_compact_noop_before_boundary");let u=Wo(r.loadedItem,i);u.matchedChainBefore===!1&&l.push("history_compact_item_chain_mismatch");let{rewrittenEntries:m,baselineEntryAdded:p,auditEntryAdded:g}=Ko({historyEntries:i,boundary:s,changed:a,dryRun:c,author:d,options:t}),_=q(i,!0),y=s.retainedCount>0&&_!==null?_+s.compactCount+1:null;return{changed:a,rewrittenEntries:m,report:({verification:w,warnings:v})=>({id:e.id,dry_run:c,changed:a,compact_boundary:{kind:s.kind,before:s.raw,entries_compacted:s.compactCount,entries_retained:s.retainedCount,first_retained_entry:y},history:{path:n,entries_scanned:i.length,entries_after:m.length,baseline_entry_added:p,audit_entry_added:g,verify_ok:w.ok,verify_errors:w.errors},item:{exists:e.located!==null,path:e.located?.itemPath??null,matched_chain_before:u.matchedChainBefore},warnings:[...new Set([...l,...v])].sort((E,b)=>E.localeCompare(b)),generated_at:I()})}}var Xo=3;function Jo(e){for(let r of["allOver","minEntries"]){let n=e[r];if(n!==void 0&&(!Number.isSafeInteger(n)||n<0))throw new h(`history-compact ${r} must be a non-negative safe integer.`,f.USAGE)}let t=Cn(e.ids);if(e.ids!==void 0&&t==="")throw new h("history-compact ids requires at least one valid item ID.",f.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more string or finite numeric IDs; non-finite and unsupported selector values are rejected."});return{...e,ids:t===void 0?void 0:Rn(t)}}function sl(e,t){let r=t.ids!==void 0&&t.ids.length>0,n=t.allOver!==void 0||t.scope!==void 0;if((e!==void 0?1:0)+(r?1:0)+(n?1:0)==0)throw new h("history-compact: provide an item <id>, or a bulk selector (--ids, --all-over <N>, --closed, or --all-streams).",f.USAGE);if(e!==void 0&&(r||n))throw new h("history-compact: <id> and bulk selectors (--ids/--all-over/--closed/--all-streams) are mutually exclusive; pass one item id, or use bulk mode without a positional id.",f.USAGE);if(r&&n)throw new h("history-compact: --ids is mutually exclusive with --all-over/--closed/--all-streams; pass an explicit id list or a scan selector, not both.",f.USAGE)}function Zo(e){let t=0;for(let r of e.split(/\r?\n/))r.trim().length>0&&(t+=1);return t}async function es(e){let t=j(e.settings.schema),r=We(t),n=await je(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema),i=new Map(n.map(d=>[d.id,r.classify(d.status)])),o=yi.join(e.pmRoot,"history"),s=[],a=[];if(!await xe(o))return{candidates:s,preselectionErrors:a};let c=(await pi.readdir(o)).filter(d=>d.endsWith(".jsonl")).sort((d,l)=>d.localeCompare(l));for(let d of c){let l=yi.join(o,d),u=d.slice(0,-6);try{let m=await pi.readFile(l,"utf8");await ae({path:l,scope:"project"}),s.push({id:u,entries:Zo(m),bucket:i.get(u)??null})}catch(m){a.push({id:u,outcome:"errored",entries_before:0,entries_after:null,skip_reason:null,changed:!1,error:m instanceof Error?m.message:String(m)})}}return{candidates:s,preselectionErrors:a}}async function ts(e){if(!e.row.selected)return{selected:!1,compacted:!1,errored:!1,result:{id:e.row.id,outcome:"skipped",entries_before:e.row.entries,entries_after:null,skip_reason:e.row.skip_reason,changed:!1,error:null}};try{let t=await Qo(e.row.id,{dryRun:e.dryRun,author:e.options.author,message:e.options.message,force:e.options.force},e.global);return{selected:!0,compacted:!0,errored:!1,result:{id:e.row.id,outcome:"compacted",entries_before:e.row.entries,entries_after:t.history.entries_after,skip_reason:null,changed:t.changed,error:null}}}catch(t){return{selected:!0,compacted:!1,errored:!0,result:{id:e.row.id,outcome:"errored",entries_before:e.row.entries,entries_after:null,skip_reason:null,changed:!1,error:t instanceof Error?t.message:String(t)}}}}async function al(e,t){let r=Jo(e),{pmRoot:n,settings:i,typeRegistry:o}=await pe(t.path),{candidates:s,preselectionErrors:a}=await es({pmRoot:n,settings:i,typeToFolder:o.type_to_folder}),c=r.ids!==void 0&&r.ids.length>0?"ids":"scan",d=e.minEntries??Xo,l=i.history.compact_policy,u=c==="scan"&&e.allOver===void 0&&l.enabled,m=e.allOver??(u?l.max_entries:void 0),p=hi(s,{ids:r.ids,scope:e.scope,minEntries:d,allOver:m}),g=!!e.dryRun,_=[...a],y={streams_considered:s.length+a.length,selected:0,items_compacted:0,items_skipped:0,items_errored:a.length};for(let w of p){let v=await ts({row:w,options:r,dryRun:g,global:t});if(_.push(v.result),!v.selected){y.items_skipped+=1;continue}y.selected+=1,v.compacted&&(y.items_compacted+=1),v.errored&&(y.items_errored+=1)}return{bulk:!0,dry_run:g,mode:c,scope:e.scope??null,criteria:{min_entries:d,all_over:m??null,policy_threshold_applied:u},totals:y,results:_,generated_at:I()}}import It 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]="ebf3254f-1fed-5972-b91a-b8ff101675f4")}catch{}})();function kt(e){return Array.isArray(e)?e:typeof e=="string"?[e]:[]}function _i(e){let t=[];for(let r of e)t.includes(r)||t.push(r);return t.includes("g")||t.push("g"),t.join("")}function wi(e){let t=e.trim();if(t.length===0)throw new h("history-redact --regex requires a non-empty pattern.",f.USAGE);let r=t,n="g";if(t.startsWith("/")&&t.length>1){let i=t.lastIndexOf("/");i>0&&(r=t.slice(1,i),n=_i(t.slice(i+1)))}if(r.length===0)throw new h("history-redact --regex cannot use an empty pattern.",f.USAGE);try{new RegExp(r,n)}catch{throw new h("Invalid --regex value; provide a valid JavaScript regular expression.",f.USAGE)}return{kind:"regex",source:r,flags:n}}function bi(e,t){let r=[...new Set(kt(e).map(o=>o.trim()))].filter(o=>o.length>0).map(o=>({kind:"literal",value:o})),n=[...new Set(kt(t).map(o=>o.trim()))].filter(o=>o.length>0).map(wi),i=[...r,...n];if(i.length===0)throw new h("history-redact requires at least one matcher via --literal or --regex.",f.USAGE,{code:"missing_required_argument",required:"Provide --literal <value> and/or --regex <pattern>.",examples:['pm history-redact pm-a1b2 --literal "[redacted_path_prefix]/private"','pm history-redact pm-a1b2 --regex "/192\\\\.168\\\\.[0-9.]+/g" --replacement "[scrubbed_ip]"']});return i}function vi(e,t,r){if(t.length===0)return{value:e,replacements:0};let n=0,i=0;for(;n<=e.length;){let o=e.indexOf(t,n);if(o===-1)break;i+=1,n=o+Math.max(1,t.length)}return i===0?{value:e,replacements:0}:{value:e.split(t).join(r),replacements:i}}function Ei(e,t,r){let n=new RegExp(t.source,t.flags),i=[...e.matchAll(n)];return i.length===0?{value:e,replacements:0}:{value:e.replace(n,r),replacements:i.length}}function xt(e,t,r){let n=e,i=0;for(let o of t){let s=o.kind==="literal"?vi(n,o.value,r):Ei(n,o,r);n=s.value,i+=s.replacements}return{value:n,replacements:i}}function ge(e,t,r){if(typeof e=="string")return xt(e,t,r);if(Array.isArray(e)){let n=0;return{value:e.map(i=>{let o=ge(i,t,r);return n+=o.replacements,o.value}),replacements:n}}if(typeof e=="object"&&e!==null){let n=0,i={};for(let[o,s]of Object.entries(e)){let a=ge(s,t,r);n+=a.replacements,i[o]=a.value}return{value:i,replacements:n}}return{value:e,replacements:0}}function gi(e,t,r){let n=0;return{patch:e.map(i=>{if(!Object.prototype.hasOwnProperty.call(i,"value"))return i;let o=ge(i.value,t,r);return n+=o.replacements,o.replacements>0?{...i,value:o.value}:i}),replacements:n}}function rs(e){let t=structuredClone(ht),r=0,n=0;for(let i=0;i<e.length;i+=1){let o=e[i];ue(t,void 0,x(o.hash_algorithm))!==o.before_hash&&(r+=1),t=Z(t,o.patch,i+1,o.op),ue(t,void 0,x(o.hash_algorithm))!==o.after_hash&&(n+=1)}return{hashMismatchesBefore:r,hashMismatchesAfter:n,finalDocument:t}}function ns(e,t,r){let n=0,i=!1,o=!1,s=e.message;if(typeof e.message=="string"){let d=xt(e.message,t,r);s=d.value,n+=d.replacements,d.replacements>0&&(i=!0)}let a=gi(e.patch,t,r);n+=a.replacements,i||=a.replacements>0;let c=e.reanchor_evidence?.map(d=>{let l=d.patch?gi(d.patch,t,r):{patch:void 0,replacements:0},u=d.record?ge(d.record,t,r):{value:void 0,replacements:0};n+=l.replacements,n+=u.replacements;let m=l.replacements>0||u.replacements>0;if(i||=m,!m)return d;o=!0;let{patch:p,record:g,record_hash:_,record_hash_version:y,...w}=d;return l.replacements>0?w:{...w,patch:d.patch}});return{entry:{...e,message:s,patch:a.patch,...c?{reanchor_evidence:c}:{}},replacements:n,changed:i,reanchorEvidenceRedacted:o}}function is(e,t,r){let n=structuredClone(ht),i=0,o=0,s=[];for(let a=0;a<e.length;a+=1){let c=e[a],d=nn(c);if(!d.ok)throw new h(`history-redact refuses invalid immutable record ${a+1} (${d.error}).`,f.GENERIC_FAILURE);let l=ns(c,t,r);o+=l.replacements,l.changed&&(i+=1);let u=ue(n,void 0,x(c.hash_algorithm));n=Z(n,l.entry.patch,a+1,l.entry.op);let m=ue(n,void 0,x(c.hash_algorithm));s.push(on(c,{...l.entry,before_hash:u,after_hash:m},{retainPriorRecord:l.changed,retainPriorRecordHash:!l.changed}))}return{entries:s,finalDocument:n,entriesChanged:i,replacements:o}}function Si(e){return Object.keys(e.metadata).length>0}function os(e){if(!Si(e.finalDocument))return{raw:null,path:null,document:null};let t=Fe(H(e.finalDocument),{schema:e.settings.schema});if(t.metadata.id!==e.subject.id)throw new h("history-redact would change the item id; narrow your patterns.",f.USAGE);return{document:t,path:z(e.pmRoot,t.metadata.type,e.subject.id,"toon",e.typeToFolder),raw:Me(t,{format:"toon",schema:e.settings.schema})}}function ss(e,t){return typeof e.message=="string"&&e.message.trim().length>0?e.message:`history-redact replaced ${t.replacements} match(es) across ${t.entriesChanged} entr${t.entriesChanged===1?"y":"ies"}.`}function as(e){let t=[...e.rewritten.entries];if(e.dryRun||!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let r=e.nextItemDocument??H(e.rewritten.finalDocument);return t.push(V({nowIso:I(),author:e.author,op:"history_redact",before:r,after:r,message:e.message})),{rewrittenEntries:t,auditEntryAdded:!0}}function cs(e){let t=[];return{applyRewrite:async({historyRawUnderLock:r})=>{let n=await Le(e.pmRoot,e.author),i=new Set;e.currentItem.path&&i.add(e.currentItem.path),e.nextItem.path&&i.add(e.nextItem.path);let o=new Map;e.currentItem.path&&e.currentItem.raw!==null&&o.set(e.currentItem.path,e.currentItem.raw);let s=()=>{};try{try{e.nextItem.path&&e.nextItem.raw!==null&&e.nextItem.raw!==e.currentItem.raw&&await O(e.nextItem.path,e.nextItem.raw),e.currentItem.path&&(!e.nextItem.path||e.nextItem.path!==e.currentItem.path)&&await It.rm(e.currentItem.path,{force:!0}),await O(e.subject.historyPath,ln(e.rewrittenEntries))}catch(c){try{await ls(e.subject.historyPath,r,i,o)}finally{await ft(e.subject.historyPath)}throw c}await ft(e.subject.historyPath);let a=e.nextItem.path??e.currentItem.path;a&&(t=await Oe({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:e.typeRegistry.type_to_folder,schema:e.settings.schema,itemPath:a,...e.currentItem.path?{previousItemPath:e.currentItem.path}:{},document:e.nextItem.document}))}finally{await n().catch(a=>{s=()=>{throw a}})}s()},afterWrite:async()=>[...t,...await ds(e.subject.historyPath,[e.nextItem.path,e.currentItem.path])]}}async function ls(e,t,r,n){t===null?await It.rm(e,{force:!0}):await O(e,t);for(let i of r){let o=n.get(i);o===void 0?await It.rm(i,{force:!0}):await O(i,o)}}async function ds(e,t){let r=[],n=new Set(t.filter(i=>i!==null));for(let i of n)r.push(...await Y({path:i,scope:"project",op:"history_redact"}));return r.push(...await Y({path:e,scope:"project",op:"history_redact:history"})),r}async function xl(e,t,r){let{pmRoot:n,settings:i,typeRegistry:o}=await pe(r.path),s=t.replacement??"",a=s.length===0,c=a?"[redacted]":s,d=bi(t.literal,t.regex),l=await K(n,e,i,o.type_to_folder);return Ke({pmRoot:n,subject:l,settings:i,typeRegistry:o,operation:"history-redact",options:t,transform:u=>us({pmRoot:n,subject:l,settings:i,typeRegistry:o,options:t,rules:d,replacement:c,replacementIsDefault:a},u)})}function us(e,t){let{pmRoot:r,subject:n,settings:i,typeRegistry:o,options:s,rules:a,replacement:c,replacementIsDefault:d}=e,l=t.entries,u=rs(l),m=is(l,a,c),p=u.hashMismatchesBefore+u.hashMismatchesAfter,g=!!s.dryRun,_=m.replacements>0,y=[];p>0&&y.push(`history_redact_preexisting_hash_mismatches:${p}`),_||y.push("history_redact_no_matches");let w={raw:t.loadedItem?.raw??null,path:n.located?.itemPath??null,document:t.loadedItem?.document??null},v=os({pmRoot:r,subject:n,settings:i,typeToFolder:o.type_to_folder,finalDocument:m.finalDocument}),E=(w.path??null)!==(v.path??null)||(w.raw??null)!==(v.raw??null),b=t.author,R=ss(s,m),{rewrittenEntries:S,auditEntryAdded:C}=as({rewritten:m,dryRun:g,changed:_,nextItemDocument:v.document,author:b,message:R});return{changed:_,rewrittenEntries:S,...cs({pmRoot:r,subject:n,settings:i,typeRegistry:o,currentItem:w,nextItem:v,author:b,rewrittenEntries:S}),report:({verification:Ie,warnings:B})=>({id:n.id,dry_run:g,changed:_,patterns:{literal_count:a.filter(W=>W.kind==="literal").length,regex_count:a.filter(W=>W.kind==="regex").length,total_count:a.length,replacement_is_default:d},history:{path:n.historyPath,entries_scanned:l.length,entries_changed:m.entriesChanged,replacements:m.replacements,hash_mismatches_before:u.hashMismatchesBefore,hash_mismatches_after:u.hashMismatchesAfter,preexisting_hash_mismatches:p,audit_entry_added:C,verify_ok:Ie.ok,verify_errors:Ie.errors},item:{existed_before:w.path!==null,exists_after:v.path!==null,path_before:w.path,path_after:v.path,changed:E},warnings:[...new Set([...y,...B])].sort((W,ke)=>W.localeCompare(ke)),generated_at:I()})}}var Rl={applyLiteralRule:vi,applyRegexRule:Ei,buildRedactionRules:bi,hasItemMetadata:Si,normalizeRegexFlags:_i,normalizeStringArrayInput:kt,parseRegexRule:wi,redactStringValue:xt,redactUnknownValue:ge};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="63c96190-0df9-5803-aa61-b973493a7277")}catch{}})();var Rt={format:"pm-history-attestation",version:1,stream_hash:"exact_file_bytes",rollup_hash:"stable_json_without_workspace_digest",ordering:"stream_id_code_unit_ascending",consistency:"per_stream_snapshot_with_change_detection",trust:"independently_retained_bundle"};import{createHash as ms}from"node:crypto";import{isUtf8 as fs}from"node:buffer";import _e from"node:fs/promises";import Ct 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]="a049f799-3807-59b5-96de-51e900798779")}catch{}})();async function Ii(e){try{return(await _e.readdir(e)).filter(t=>t.endsWith(".jsonl")).sort()}catch(t){if(Lr(t))return[];throw t}}function hs(e,t,r,n){let i=t.at(-1),o;for(let c=t.length-1;c>=0;c-=1)if(["history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","merge_reconcile"].includes(t[c].op)){o=t[c];break}let s=t[0]?.context?.history_compaction,a=typeof s=="object"&&s!==null&&"pruned_stream_digest"in s&&typeof s.pruned_stream_digest=="string"?s.pruned_stream_digest:null;return{id:e,entries:t.length,bytes:r,stream_digest:n,latest_after_hash:i?.after_hash??null,latest_record_hash:i?.record_hash??null,latest_hash_algorithm:i?x(i.hash_algorithm):null,rewrite_count:t.reduce((c,d)=>c+(d.reanchor_evidence?.length??0),0),checkpoint_digest:a,last_maintenance:o?{op:o.op,ts:o.ts,record_hash:o.record_hash??null}:null}}function ps(e,t,r){try{if(!/^[A-Za-z0-9_-]+$/u.test(e)||!fs(t))return null;let n=[];for(let i of t.toString("utf8").split(/\r?\n/u)){if(!i.trim())continue;let o=JSON.parse(i);if(typeof o!="object"||o===null||Array.isArray(o))return null;let s=o;if(![s.op,s.author,s.ts,s.before_hash,s.after_hash].every(a=>typeof a=="string")||!Array.isArray(s.patch))return null;n.push(s)}return yt(n).ok?hs(e,n,t.length,r):null}catch{return null}}async function At(e,t){if(!(await _e.stat(e)).isDirectory())throw new TypeError("attestation tracker root must be a directory");let r=Ct.join(e,"history"),n=await Ii(r),i=new Map,o=[];for(let s of n){let a=s.slice(0,-6),c={id:a,digest:null,stream:null};o.push(c);let d=Ct.join(r,s);try{let l=await _e.lstat(d);if(i.set(s,D([l.ino,l.size,l.mtimeMs,l.ctimeMs])),!l.isFile())continue;let u=await _e.readFile(d);c.digest=ms(t).update(u).digest("hex"),c.stream=ps(a,u,c.digest)}catch{}}if(D(n)!==D(await Ii(r)))throw new TypeError("attestation history inventory changed during read; retry");for(let[s,a]of i){let c=await _e.lstat(Ct.join(r,s));if(a!==D([c.ino,c.size,c.mtimeMs,c.ctimeMs]))throw new TypeError("attestation history stream changed during read; retry")}return o}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="54d3c0f4-e663-5e31-aa4e-45ea2f6aaf75")}catch{}})();function Tt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Mt(e,t){return Object.keys(e).length===t.length&&t.every(r=>Object.hasOwn(e,r))}function te(e,t){return typeof e=="string"&&(t==="sha256"?/^[a-f0-9]{64}$/u:/^[a-f0-9]{128}$/u).test(e)}function ys(e){return e.entries===0?[e.latest_hash_algorithm,e.latest_after_hash,e.latest_record_hash,e.checkpoint_digest,e.last_maintenance].every(t=>t===null)&&e.rewrite_count===0:e.latest_hash_algorithm!=="sha256"&&e.latest_hash_algorithm!=="sha512"?!1:te(e.latest_after_hash,e.latest_hash_algorithm)&&(e.latest_record_hash===null||te(e.latest_record_hash,e.latest_hash_algorithm))}function gs(e){return e===null?!0:!Tt(e)||!Mt(e,["op","ts","record_hash"])?!1:typeof e.op=="string"&&["history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","merge_reconcile"].includes(e.op)&&typeof e.ts=="string"&&Te(e.ts)&&(e.record_hash===null||te(e.record_hash,"sha256")||te(e.record_hash,"sha512"))}function _s(e,t){return!Tt(e)||!Mt(e,["id","entries","bytes","stream_digest","latest_after_hash","latest_record_hash","latest_hash_algorithm","rewrite_count","checkpoint_digest","last_maintenance"])?!1:typeof e.id=="string"&&/^[A-Za-z0-9_-]+$/u.test(e.id)&&[e.entries,e.bytes,e.rewrite_count].every(r=>typeof r=="number"&&Number.isSafeInteger(r)&&r>=0)&&te(e.stream_digest,t)&&ys(e)&&(e.checkpoint_digest===null||te(e.checkpoint_digest,"sha256"))&&gs(e.last_maintenance)}function ki(e){if(!Tt(e)||!Mt(e,["format","version","hash_algorithm","generated_at","streams","workspace_digest"]))throw new TypeError("Invalid history attestation bundle");if(e.format!==Rt.format||e.version!==1||typeof e.generated_at!="string"||!Te(e.generated_at)||!Array.isArray(e.streams)||e.hash_algorithm!=="sha256"&&e.hash_algorithm!=="sha512")throw new TypeError("Invalid history attestation format");let t=e.hash_algorithm,r;for(let o of e.streams){if(!_s(o,t))throw new TypeError("Invalid history attestation stream");let s=o.id;if(r!==void 0&&s<=r)throw new TypeError("Invalid history attestation stream order");r=s}let{workspace_digest:n,...i}=e;if(mt(D(i),t)!==n)throw new TypeError("History attestation rollup mismatch");return e}async function xi(e={}){let t=x(e.hashAlgorithm),r=e.generatedAt??I();if(!Te(r))throw new TypeError("Invalid history attestation timestamp");let n=await At(k(e.cwd??process.cwd(),e.pmRoot),t),i=n.filter(s=>s.stream===null);if(i.length>0)throw new TypeError(`Cannot export history attestation: invalid streams ${i.map(s=>s.id).join(", ")}`);let o={format:Rt.format,version:1,hash_algorithm:t,generated_at:r,streams:n.map(s=>s.stream)};return ki({...o,workspace_digest:mt(D(o),t)})}async function Ri(e,t={}){let r=ki(e),n=await At(k(t.cwd??process.cwd(),t.pmRoot),r.hash_algorithm),i=new Map(n.map(l=>[l.id,l])),o=new Map(r.streams.map(l=>[l.id,l])),s=r.streams.filter(l=>!i.has(l.id)).map(l=>l.id),a=n.filter(l=>!o.has(l.id)).map(l=>l.id),c=n.filter(l=>l.stream===null).map(l=>l.id),d=[];for(let l of r.streams){let u=i.get(l.id);u&&(u.digest!==l.stream_digest||D(u.stream)!==D(l))&&d.push({id:l.id,before_digest:l.stream_digest,after_digest:u.digest,last_maintenance:u.stream?.last_maintenance??null})}return{ok:s.length+a.length+c.length+d.length===0,workspace_digest:r.workspace_digest,streams_checked:n.length,changed_streams:d.map(l=>l.id),missing_streams:s,added_streams:a,invalid_streams:c,transitions:d}}import Ci 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]="3bca4afb-f1cc-5627-a377-b30e8005a284")}catch{}})();async function Jl(e,t){for(let n of["verify","output","hashAlgorithm"]){let i=e[n];if(!(n==="verify"&&typeof i=="object"&&i!==null)&&i!==void 0&&(typeof i!="string"||i.trim().length===0))throw new h(`history attest ${n} requires a nonempty string.`,f.USAGE)}if(e.verify!==void 0){if(e.output!==void 0||e.hashAlgorithm!==void 0)throw new h("history attest --verify cannot be combined with --output or --hash-algorithm",f.USAGE);let n;try{n=typeof e.verify=="string"?JSON.parse(await Ci.readFile(e.verify,"utf8")):e.verify}catch{throw new h("Cannot read history attestation proof. Provide --verify with a readable JSON proof file.",f.USAGE)}return Ri(n,{pmRoot:t.path})}let r=await xi({pmRoot:t.path,hashAlgorithm:x(e.hashAlgorithm)});if(e.output===void 0)return r;try{await Ci.writeFile(e.output,`${JSON.stringify(r,null,2)}
|
|
1
|
+
import{A as Vn,Bb as si,Cb as Ke,D as Kn,Dc as mi,E as Qn,O as Yn,P as Xn,S as Jn,Sb as ai,Ub as ci,Wb as li,Xb as di,a as pe,b as K,c as En,ca as ze,cb as oi,d as Sn,da as vt,ea as Zn,fa as ei,ga as ti,ha as ri,k as bt,ka as ni,la as Et,ma as St,n as Gn,na as Ve,r as $n,ta as ii,v as ye,w as Bn,x as Wn,y as We,z as zn,zc as ui}from"./chunk-RBPOO46D.js";import{$ as O,$i as gn,$l as Rn,Ah as en,Ai as gt,Bg as Xr,Bi as fn,Dg as ce,Dm as Tn,Ec as A,Ei as hn,El as kn,Em as Mn,Fh as tn,Fl as xn,Gh as rn,Hg as Jr,Hh as nn,Ig as Me,Ih as on,Im as Fn,Jc as qr,Jg as Fe,Kc as dt,Li as pn,Ln as qn,M as Hr,Mm as Dn,Nc as Y,Nm as Pn,Oc as Nr,Oh as V,Oi as yn,Om as Ue,Pc as ae,Ph as sn,Pm as Hn,Qm as Ge,R as f,Rh as ht,Ri as He,Rm as $e,Sh as de,Sm as Be,T as h,Tf as P,Th as ue,Tm as Ln,Ub as D,Uh as pt,V as xe,Va as U,Vh as H,Wh as an,X as Lr,Xh as me,Xm as On,Yh as cn,Yi as Le,Ym as wt,_h as yt,_i as Oe,aj as fe,am as Cn,ba as lt,bb as k,bi as ln,bj as he,ci as Pe,cj as _n,cm as _t,db as jr,dd as X,dg as x,di as dn,dj as wn,dm as An,eg as mt,ei as un,ej as je,fb as z,fd as Ur,fl as In,fn as jn,gf as I,gj as bn,hb as Ae,hj as vn,ia as se,ja as Re,jf as Te,kf as Vr,la as Ce,ld as Gr,lf as Kr,ma as Or,mf as ut,mh as De,nf as Qr,ng as j,nh as Zr,oh as le,om as qe,oo as Nn,pg as J,po as Un,qd as $r,rd as Br,sm as Ne,ui as L,vd as Wr,wi as q,xd as zr,xf as Yr,yh as ft,yi as mn,zi as Z,zn as ee}from"./chunk-YMLF6QT7.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]="7dd9061f-1b49-5ecb-a306-74f09283fe57")}catch{}})();var jo="PmCliError";function jc(e){if(!No(e)||e.code!=="item_already_exists"||e.exitCode!==f.CONFLICT)return!1;let t=e.context;return typeof t=="object"&&t!==null&&t.code==="item_already_exists"&&typeof t.id=="string"&&t.id.trim().length>0&&typeof t.path=="string"&&t.path.trim().length>0}function qo(e){if(!Number.isFinite(e))throw new TypeError("createPmCliExpectedError options.exitCode must be a finite number");let t=Math.trunc(e);if(t<=f.SUCCESS)throw new TypeError("createPmCliExpectedError options.exitCode must be a positive exit code");return t}function fi(e,t={}){if(typeof e!="string"||e.trim().length===0)throw new TypeError("createPmCliExpectedError message must be a non-empty string");let r=new h(e,qo(t.exitCode??f.USAGE),t.context??{});return"cause"in t&&Object.defineProperty(r,"cause",{value:t.cause,enumerable:!1,configurable:!0,writable:!0}),r}function No(e){if(!(e instanceof Error)||e.name!==jo)return!1;let t=e;return typeof t.exitCode=="number"&&Number.isFinite(t.exitCode)}import pi from"node:fs/promises";import yi 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]="f3603dce-8aeb-5409-80f4-ad3367e35eb9")}catch{}})();function Uo(e,t,r){let n=new Set,i=[];for(let o of e){let s=o.trim();if(s.length===0||n.has(s))continue;n.add(s);let a=t.get(s);if(a===void 0){i.push({id:s,entries:0,selected:!1,skip_reason:"no_stream"});continue}if(a.entries<=r){i.push({id:s,entries:a.entries,selected:!1,skip_reason:"already_compact"});continue}i.push({id:s,entries:a.entries,selected:!0,skip_reason:null})}return i}function Go(e,t){let r=[...e].sort((i,o)=>o.entries-i.entries||i.id.localeCompare(o.id)),n=[];for(let i of r){if(t.scope==="closed"&&i.bucket!=="closed"){n.push({id:i.id,entries:i.entries,selected:!1,skip_reason:"scope_mismatch"});continue}if(i.entries<=t.minEntries){n.push({id:i.id,entries:i.entries,selected:!1,skip_reason:"already_compact"});continue}if(t.allOver!==void 0&&i.entries<=t.allOver){n.push({id:i.id,entries:i.entries,selected:!1,skip_reason:"below_threshold"});continue}n.push({id:i.id,entries:i.entries,selected:!0,skip_reason:null})}return n}function hi(e,t){if(t.ids!==void 0&&t.ids.length>0){let r=new Map(e.map(n=>[n.id,n]));return Uo(t.ids,r,t.minEntries)}return Go(e,t)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c6009e5f-840e-5e3a-b8b9-6e9d42d63410")}catch{}})();function $o(e,t){if(e===void 0)return{kind:"default",raw:null,compactCount:t.length,retainedCount:0};let r=e.trim();if(r.length===0)throw new h("history-compact --before requires a non-empty value.",f.USAGE);if(/^\d+$/.test(r)){let o=Number.parseInt(r,10),s=q(t);if(!Number.isSafeInteger(o)||o<s+1||o>s+t.length+1)throw new h(`history-compact --before version must be between ${s+1} and ${s+t.length+1}.`,f.USAGE);let a=o-s-1;return{kind:"version",raw:r,compactCount:a,retainedCount:t.length-a}}let n=Date.parse(r);if(!Number.isFinite(n))throw new h(`Invalid history-compact --before value "${e}". Use a version number or ISO timestamp.`,f.USAGE);let i=0;for(let[o,s]of t.entries()){let a=Date.parse(s.ts);if(!Number.isFinite(a))throw new h(`History for this item contains invalid timestamp at entry ${o+1}.`,f.GENERIC_FAILURE);if(a>=n)break;i+=1}return{kind:"timestamp",raw:r,compactCount:i,retainedCount:t.length-i}}function Bo(e,t){let r=de(),n=de();for(let i=0;i<e.length;i+=1){let o=e[i];r=Z(r,o.patch,i+1,o.op),i+1===t&&(n=structuredClone(r))}return{checkpoint:n,finalReplay:r}}function Wo(e,t){if(!e)return{loadedItem:null,currentItemRawBeforeLock:null,matchedChainBefore:null};let r=t[t.length-1];return{loadedItem:e,currentItemRawBeforeLock:e.raw,matchedChainBefore:en.some(n=>(r.item_hash_version===void 0||r.item_hash_version===n)&&pt(me(e.document),n,x(r.hash_algorithm)).includes(r.after_hash))}}function zo(e,t){return typeof e.message=="string"&&e.message.trim().length>0?e.message:t.raw===null?`history-compact compacted full stream (${t.compactCount} entr${t.compactCount===1?"y":"ies"}).`:`history-compact compacted ${t.compactCount} entr${t.compactCount===1?"y":"ies"} before ${t.raw}.`}function Vo(e){return e.raw===null?`history-compact baseline snapshot after compacting ${e.compactCount} entr${e.compactCount===1?"y":"ies"}.`:`history-compact baseline snapshot before ${e.raw}.`}function Ko(e){if(!e.changed)return{rewrittenEntries:e.historyEntries,baselineEntryAdded:!1,auditEntryAdded:!1};let{checkpoint:t,finalReplay:r}=Bo(e.historyEntries,e.boundary.compactCount),n=e.historyEntries.slice(e.boundary.compactCount),i=q(e.historyEntries,!0),o=e.historyEntries[e.boundary.compactCount-1],s=V({hashAlgorithm:x(o.hash_algorithm),nowIso:e.historyEntries[e.boundary.compactCount-1].ts,author:e.author,op:"history_compact_baseline",before:H(de()),after:H(t),message:Vo(e.boundary),context:{history_compaction:{contract_version:1,version_offset:i===null?null:i+e.boundary.compactCount-1,checkpoint_timestamp_semantics:"last_compacted_entry",pruned_entry_count:e.boundary.compactCount,pruned_stream_digest:tn(e.historyEntries.slice(0,e.boundary.compactCount)),retained_proof:"stream_digest_and_checkpoint",limitation:"individual_pruned_entries_require_pre_compaction_stream"}}}),a=[rn({...s,before_hash:pt(de(),o.item_hash_version??1,x(o.hash_algorithm))[0],after_hash:o.after_hash,item_hash_version:o.item_hash_version}),...n];return e.dryRun||a.push(V({nowIso:I(),author:e.author,op:"history_compact",before:H(r),after:H(r),message:zo(e.options,e.boundary)})),{rewrittenEntries:a,baselineEntryAdded:!0,auditEntryAdded:!e.dryRun}}async function Qo(e,t,r){let{pmRoot:n,settings:i,typeRegistry:o}=await pe(r.path),s=await K(n,e,i,o.type_to_folder);return Ke({pmRoot:n,subject:s,settings:i,typeRegistry:o,operation:"history-compact",options:t,transform:a=>Yo(s,t,a)})}function Yo(e,t,r){let n=e.historyPath,i=r.entries,o=r.verification;if(!o.ok)throw new h(`history-compact requires a valid history chain (${o.errors.join(", ")}). Run pm history-repair ${e.id} first.`,f.CONFLICT);let s=$o(t.before,i),a=s.compactCount>0,c=!!t.dryRun,d=r.author,l=[];a||l.push("history_compact_noop_before_boundary");let u=Wo(r.loadedItem,i);u.matchedChainBefore===!1&&l.push("history_compact_item_chain_mismatch");let{rewrittenEntries:m,baselineEntryAdded:p,auditEntryAdded:g}=Ko({historyEntries:i,boundary:s,changed:a,dryRun:c,author:d,options:t}),_=q(i,!0),y=s.retainedCount>0&&_!==null?_+s.compactCount+1:null;return{changed:a,rewrittenEntries:m,report:({verification:w,warnings:v})=>({id:e.id,dry_run:c,changed:a,compact_boundary:{kind:s.kind,before:s.raw,entries_compacted:s.compactCount,entries_retained:s.retainedCount,first_retained_entry:y},history:{path:n,entries_scanned:i.length,entries_after:m.length,baseline_entry_added:p,audit_entry_added:g,verify_ok:w.ok,verify_errors:w.errors},item:{exists:e.located!==null,path:e.located?.itemPath??null,matched_chain_before:u.matchedChainBefore},warnings:[...new Set([...l,...v])].sort((E,b)=>E.localeCompare(b)),generated_at:I()})}}var Xo=3;function Jo(e){for(let r of["allOver","minEntries"]){let n=e[r];if(n!==void 0&&(!Number.isSafeInteger(n)||n<0))throw new h(`history-compact ${r} must be a non-negative safe integer.`,f.USAGE)}let t=Cn(e.ids);if(e.ids!==void 0&&t==="")throw new h("history-compact ids requires at least one valid item ID.",f.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more string or finite numeric IDs; non-finite and unsupported selector values are rejected."});return{...e,ids:t===void 0?void 0:Rn(t)}}function sl(e,t){let r=t.ids!==void 0&&t.ids.length>0,n=t.allOver!==void 0||t.scope!==void 0;if((e!==void 0?1:0)+(r?1:0)+(n?1:0)==0)throw new h("history-compact: provide an item <id>, or a bulk selector (--ids, --all-over <N>, --closed, or --all-streams).",f.USAGE);if(e!==void 0&&(r||n))throw new h("history-compact: <id> and bulk selectors (--ids/--all-over/--closed/--all-streams) are mutually exclusive; pass one item id, or use bulk mode without a positional id.",f.USAGE);if(r&&n)throw new h("history-compact: --ids is mutually exclusive with --all-over/--closed/--all-streams; pass an explicit id list or a scan selector, not both.",f.USAGE)}function Zo(e){let t=0;for(let r of e.split(/\r?\n/))r.trim().length>0&&(t+=1);return t}async function es(e){let t=j(e.settings.schema),r=We(t),n=await je(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema),i=new Map(n.map(d=>[d.id,r.classify(d.status)])),o=yi.join(e.pmRoot,"history"),s=[],a=[];if(!await xe(o))return{candidates:s,preselectionErrors:a};let c=(await pi.readdir(o)).filter(d=>d.endsWith(".jsonl")).sort((d,l)=>d.localeCompare(l));for(let d of c){let l=yi.join(o,d),u=d.slice(0,-6);try{let m=await pi.readFile(l,"utf8");await ae({path:l,scope:"project"}),s.push({id:u,entries:Zo(m),bucket:i.get(u)??null})}catch(m){a.push({id:u,outcome:"errored",entries_before:0,entries_after:null,skip_reason:null,changed:!1,error:m instanceof Error?m.message:String(m)})}}return{candidates:s,preselectionErrors:a}}async function ts(e){if(!e.row.selected)return{selected:!1,compacted:!1,errored:!1,result:{id:e.row.id,outcome:"skipped",entries_before:e.row.entries,entries_after:null,skip_reason:e.row.skip_reason,changed:!1,error:null}};try{let t=await Qo(e.row.id,{dryRun:e.dryRun,author:e.options.author,message:e.options.message,force:e.options.force},e.global);return{selected:!0,compacted:!0,errored:!1,result:{id:e.row.id,outcome:"compacted",entries_before:e.row.entries,entries_after:t.history.entries_after,skip_reason:null,changed:t.changed,error:null}}}catch(t){return{selected:!0,compacted:!1,errored:!0,result:{id:e.row.id,outcome:"errored",entries_before:e.row.entries,entries_after:null,skip_reason:null,changed:!1,error:t instanceof Error?t.message:String(t)}}}}async function al(e,t){let r=Jo(e),{pmRoot:n,settings:i,typeRegistry:o}=await pe(t.path),{candidates:s,preselectionErrors:a}=await es({pmRoot:n,settings:i,typeToFolder:o.type_to_folder}),c=r.ids!==void 0&&r.ids.length>0?"ids":"scan",d=e.minEntries??Xo,l=i.history.compact_policy,u=c==="scan"&&e.allOver===void 0&&l.enabled,m=e.allOver??(u?l.max_entries:void 0),p=hi(s,{ids:r.ids,scope:e.scope,minEntries:d,allOver:m}),g=!!e.dryRun,_=[...a],y={streams_considered:s.length+a.length,selected:0,items_compacted:0,items_skipped:0,items_errored:a.length};for(let w of p){let v=await ts({row:w,options:r,dryRun:g,global:t});if(_.push(v.result),!v.selected){y.items_skipped+=1;continue}y.selected+=1,v.compacted&&(y.items_compacted+=1),v.errored&&(y.items_errored+=1)}return{bulk:!0,dry_run:g,mode:c,scope:e.scope??null,criteria:{min_entries:d,all_over:m??null,policy_threshold_applied:u},totals:y,results:_,generated_at:I()}}import It 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]="ebf3254f-1fed-5972-b91a-b8ff101675f4")}catch{}})();function kt(e){return Array.isArray(e)?e:typeof e=="string"?[e]:[]}function _i(e){let t=[];for(let r of e)t.includes(r)||t.push(r);return t.includes("g")||t.push("g"),t.join("")}function wi(e){let t=e.trim();if(t.length===0)throw new h("history-redact --regex requires a non-empty pattern.",f.USAGE);let r=t,n="g";if(t.startsWith("/")&&t.length>1){let i=t.lastIndexOf("/");i>0&&(r=t.slice(1,i),n=_i(t.slice(i+1)))}if(r.length===0)throw new h("history-redact --regex cannot use an empty pattern.",f.USAGE);try{new RegExp(r,n)}catch{throw new h("Invalid --regex value; provide a valid JavaScript regular expression.",f.USAGE)}return{kind:"regex",source:r,flags:n}}function bi(e,t){let r=[...new Set(kt(e).map(o=>o.trim()))].filter(o=>o.length>0).map(o=>({kind:"literal",value:o})),n=[...new Set(kt(t).map(o=>o.trim()))].filter(o=>o.length>0).map(wi),i=[...r,...n];if(i.length===0)throw new h("history-redact requires at least one matcher via --literal or --regex.",f.USAGE,{code:"missing_required_argument",required:"Provide --literal <value> and/or --regex <pattern>.",examples:['pm history-redact pm-a1b2 --literal "[redacted_path_prefix]/private"','pm history-redact pm-a1b2 --regex "/192\\\\.168\\\\.[0-9.]+/g" --replacement "[scrubbed_ip]"']});return i}function vi(e,t,r){if(t.length===0)return{value:e,replacements:0};let n=0,i=0;for(;n<=e.length;){let o=e.indexOf(t,n);if(o===-1)break;i+=1,n=o+Math.max(1,t.length)}return i===0?{value:e,replacements:0}:{value:e.split(t).join(r),replacements:i}}function Ei(e,t,r){let n=new RegExp(t.source,t.flags),i=[...e.matchAll(n)];return i.length===0?{value:e,replacements:0}:{value:e.replace(n,r),replacements:i.length}}function xt(e,t,r){let n=e,i=0;for(let o of t){let s=o.kind==="literal"?vi(n,o.value,r):Ei(n,o,r);n=s.value,i+=s.replacements}return{value:n,replacements:i}}function ge(e,t,r){if(typeof e=="string")return xt(e,t,r);if(Array.isArray(e)){let n=0;return{value:e.map(i=>{let o=ge(i,t,r);return n+=o.replacements,o.value}),replacements:n}}if(typeof e=="object"&&e!==null){let n=0,i={};for(let[o,s]of Object.entries(e)){let a=ge(s,t,r);n+=a.replacements,i[o]=a.value}return{value:i,replacements:n}}return{value:e,replacements:0}}function gi(e,t,r){let n=0;return{patch:e.map(i=>{if(!Object.prototype.hasOwnProperty.call(i,"value"))return i;let o=ge(i.value,t,r);return n+=o.replacements,o.replacements>0?{...i,value:o.value}:i}),replacements:n}}function rs(e){let t=structuredClone(ht),r=0,n=0;for(let i=0;i<e.length;i+=1){let o=e[i];ue(t,void 0,x(o.hash_algorithm))!==o.before_hash&&(r+=1),t=Z(t,o.patch,i+1,o.op),ue(t,void 0,x(o.hash_algorithm))!==o.after_hash&&(n+=1)}return{hashMismatchesBefore:r,hashMismatchesAfter:n,finalDocument:t}}function ns(e,t,r){let n=0,i=!1,o=!1,s=e.message;if(typeof e.message=="string"){let d=xt(e.message,t,r);s=d.value,n+=d.replacements,d.replacements>0&&(i=!0)}let a=gi(e.patch,t,r);n+=a.replacements,i||=a.replacements>0;let c=e.reanchor_evidence?.map(d=>{let l=d.patch?gi(d.patch,t,r):{patch:void 0,replacements:0},u=d.record?ge(d.record,t,r):{value:void 0,replacements:0};n+=l.replacements,n+=u.replacements;let m=l.replacements>0||u.replacements>0;if(i||=m,!m)return d;o=!0;let{patch:p,record:g,record_hash:_,record_hash_version:y,...w}=d;return l.replacements>0?w:{...w,patch:d.patch}});return{entry:{...e,message:s,patch:a.patch,...c?{reanchor_evidence:c}:{}},replacements:n,changed:i,reanchorEvidenceRedacted:o}}function is(e,t,r){let n=structuredClone(ht),i=0,o=0,s=[];for(let a=0;a<e.length;a+=1){let c=e[a],d=nn(c);if(!d.ok)throw new h(`history-redact refuses invalid immutable record ${a+1} (${d.error}).`,f.GENERIC_FAILURE);let l=ns(c,t,r);o+=l.replacements,l.changed&&(i+=1);let u=ue(n,void 0,x(c.hash_algorithm));n=Z(n,l.entry.patch,a+1,l.entry.op);let m=ue(n,void 0,x(c.hash_algorithm));s.push(on(c,{...l.entry,before_hash:u,after_hash:m},{retainPriorRecord:l.changed,retainPriorRecordHash:!l.changed}))}return{entries:s,finalDocument:n,entriesChanged:i,replacements:o}}function Si(e){return Object.keys(e.metadata).length>0}function os(e){if(!Si(e.finalDocument))return{raw:null,path:null,document:null};let t=Fe(H(e.finalDocument),{schema:e.settings.schema});if(t.metadata.id!==e.subject.id)throw new h("history-redact would change the item id; narrow your patterns.",f.USAGE);return{document:t,path:z(e.pmRoot,t.metadata.type,e.subject.id,"toon",e.typeToFolder),raw:Me(t,{format:"toon",schema:e.settings.schema})}}function ss(e,t){return typeof e.message=="string"&&e.message.trim().length>0?e.message:`history-redact replaced ${t.replacements} match(es) across ${t.entriesChanged} entr${t.entriesChanged===1?"y":"ies"}.`}function as(e){let t=[...e.rewritten.entries];if(e.dryRun||!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let r=e.nextItemDocument??H(e.rewritten.finalDocument);return t.push(V({nowIso:I(),author:e.author,op:"history_redact",before:r,after:r,message:e.message})),{rewrittenEntries:t,auditEntryAdded:!0}}function cs(e){let t=[];return{applyRewrite:async({historyRawUnderLock:r})=>{let n=await Le(e.pmRoot,e.author),i=new Set;e.currentItem.path&&i.add(e.currentItem.path),e.nextItem.path&&i.add(e.nextItem.path);let o=new Map;e.currentItem.path&&e.currentItem.raw!==null&&o.set(e.currentItem.path,e.currentItem.raw);let s=()=>{};try{try{e.nextItem.path&&e.nextItem.raw!==null&&e.nextItem.raw!==e.currentItem.raw&&await O(e.nextItem.path,e.nextItem.raw),e.currentItem.path&&(!e.nextItem.path||e.nextItem.path!==e.currentItem.path)&&await It.rm(e.currentItem.path,{force:!0}),await O(e.subject.historyPath,ln(e.rewrittenEntries))}catch(c){try{await ls(e.subject.historyPath,r,i,o)}finally{await ft(e.subject.historyPath)}throw c}await ft(e.subject.historyPath);let a=e.nextItem.path??e.currentItem.path;a&&(t=await Oe({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:e.typeRegistry.type_to_folder,schema:e.settings.schema,itemPath:a,...e.currentItem.path?{previousItemPath:e.currentItem.path}:{},document:e.nextItem.document}))}finally{await n().catch(a=>{s=()=>{throw a}})}s()},afterWrite:async()=>[...t,...await ds(e.subject.historyPath,[e.nextItem.path,e.currentItem.path])]}}async function ls(e,t,r,n){t===null?await It.rm(e,{force:!0}):await O(e,t);for(let i of r){let o=n.get(i);o===void 0?await It.rm(i,{force:!0}):await O(i,o)}}async function ds(e,t){let r=[],n=new Set(t.filter(i=>i!==null));for(let i of n)r.push(...await Y({path:i,scope:"project",op:"history_redact"}));return r.push(...await Y({path:e,scope:"project",op:"history_redact:history"})),r}async function xl(e,t,r){let{pmRoot:n,settings:i,typeRegistry:o}=await pe(r.path),s=t.replacement??"",a=s.length===0,c=a?"[redacted]":s,d=bi(t.literal,t.regex),l=await K(n,e,i,o.type_to_folder);return Ke({pmRoot:n,subject:l,settings:i,typeRegistry:o,operation:"history-redact",options:t,transform:u=>us({pmRoot:n,subject:l,settings:i,typeRegistry:o,options:t,rules:d,replacement:c,replacementIsDefault:a},u)})}function us(e,t){let{pmRoot:r,subject:n,settings:i,typeRegistry:o,options:s,rules:a,replacement:c,replacementIsDefault:d}=e,l=t.entries,u=rs(l),m=is(l,a,c),p=u.hashMismatchesBefore+u.hashMismatchesAfter,g=!!s.dryRun,_=m.replacements>0,y=[];p>0&&y.push(`history_redact_preexisting_hash_mismatches:${p}`),_||y.push("history_redact_no_matches");let w={raw:t.loadedItem?.raw??null,path:n.located?.itemPath??null,document:t.loadedItem?.document??null},v=os({pmRoot:r,subject:n,settings:i,typeToFolder:o.type_to_folder,finalDocument:m.finalDocument}),E=(w.path??null)!==(v.path??null)||(w.raw??null)!==(v.raw??null),b=t.author,R=ss(s,m),{rewrittenEntries:S,auditEntryAdded:C}=as({rewritten:m,dryRun:g,changed:_,nextItemDocument:v.document,author:b,message:R});return{changed:_,rewrittenEntries:S,...cs({pmRoot:r,subject:n,settings:i,typeRegistry:o,currentItem:w,nextItem:v,author:b,rewrittenEntries:S}),report:({verification:Ie,warnings:B})=>({id:n.id,dry_run:g,changed:_,patterns:{literal_count:a.filter(W=>W.kind==="literal").length,regex_count:a.filter(W=>W.kind==="regex").length,total_count:a.length,replacement_is_default:d},history:{path:n.historyPath,entries_scanned:l.length,entries_changed:m.entriesChanged,replacements:m.replacements,hash_mismatches_before:u.hashMismatchesBefore,hash_mismatches_after:u.hashMismatchesAfter,preexisting_hash_mismatches:p,audit_entry_added:C,verify_ok:Ie.ok,verify_errors:Ie.errors},item:{existed_before:w.path!==null,exists_after:v.path!==null,path_before:w.path,path_after:v.path,changed:E},warnings:[...new Set([...y,...B])].sort((W,ke)=>W.localeCompare(ke)),generated_at:I()})}}var Rl={applyLiteralRule:vi,applyRegexRule:Ei,buildRedactionRules:bi,hasItemMetadata:Si,normalizeRegexFlags:_i,normalizeStringArrayInput:kt,parseRegexRule:wi,redactStringValue:xt,redactUnknownValue:ge};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="63c96190-0df9-5803-aa61-b973493a7277")}catch{}})();var Rt={format:"pm-history-attestation",version:1,stream_hash:"exact_file_bytes",rollup_hash:"stable_json_without_workspace_digest",ordering:"stream_id_code_unit_ascending",consistency:"per_stream_snapshot_with_change_detection",trust:"independently_retained_bundle"};import{createHash as ms}from"node:crypto";import{isUtf8 as fs}from"node:buffer";import _e from"node:fs/promises";import Ct 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]="a049f799-3807-59b5-96de-51e900798779")}catch{}})();async function Ii(e){try{return(await _e.readdir(e)).filter(t=>t.endsWith(".jsonl")).sort()}catch(t){if(Lr(t))return[];throw t}}function hs(e,t,r,n){let i=t.at(-1),o;for(let c=t.length-1;c>=0;c-=1)if(["history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","merge_reconcile"].includes(t[c].op)){o=t[c];break}let s=t[0]?.context?.history_compaction,a=typeof s=="object"&&s!==null&&"pruned_stream_digest"in s&&typeof s.pruned_stream_digest=="string"?s.pruned_stream_digest:null;return{id:e,entries:t.length,bytes:r,stream_digest:n,latest_after_hash:i?.after_hash??null,latest_record_hash:i?.record_hash??null,latest_hash_algorithm:i?x(i.hash_algorithm):null,rewrite_count:t.reduce((c,d)=>c+(d.reanchor_evidence?.length??0),0),checkpoint_digest:a,last_maintenance:o?{op:o.op,ts:o.ts,record_hash:o.record_hash??null}:null}}function ps(e,t,r){try{if(!/^[A-Za-z0-9_-]+$/u.test(e)||!fs(t))return null;let n=[];for(let i of t.toString("utf8").split(/\r?\n/u)){if(!i.trim())continue;let o=JSON.parse(i);if(typeof o!="object"||o===null||Array.isArray(o))return null;let s=o;if(![s.op,s.author,s.ts,s.before_hash,s.after_hash].every(a=>typeof a=="string")||!Array.isArray(s.patch))return null;n.push(s)}return yt(n).ok?hs(e,n,t.length,r):null}catch{return null}}async function At(e,t){if(!(await _e.stat(e)).isDirectory())throw new TypeError("attestation tracker root must be a directory");let r=Ct.join(e,"history"),n=await Ii(r),i=new Map,o=[];for(let s of n){let a=s.slice(0,-6),c={id:a,digest:null,stream:null};o.push(c);let d=Ct.join(r,s);try{let l=await _e.lstat(d);if(i.set(s,D([l.ino,l.size,l.mtimeMs,l.ctimeMs])),!l.isFile())continue;let u=await _e.readFile(d);c.digest=ms(t).update(u).digest("hex"),c.stream=ps(a,u,c.digest)}catch{}}if(D(n)!==D(await Ii(r)))throw new TypeError("attestation history inventory changed during read; retry");for(let[s,a]of i){let c=await _e.lstat(Ct.join(r,s));if(a!==D([c.ino,c.size,c.mtimeMs,c.ctimeMs]))throw new TypeError("attestation history stream changed during read; retry")}return o}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="54d3c0f4-e663-5e31-aa4e-45ea2f6aaf75")}catch{}})();function Tt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Mt(e,t){return Object.keys(e).length===t.length&&t.every(r=>Object.hasOwn(e,r))}function te(e,t){return typeof e=="string"&&(t==="sha256"?/^[a-f0-9]{64}$/u:/^[a-f0-9]{128}$/u).test(e)}function ys(e){return e.entries===0?[e.latest_hash_algorithm,e.latest_after_hash,e.latest_record_hash,e.checkpoint_digest,e.last_maintenance].every(t=>t===null)&&e.rewrite_count===0:e.latest_hash_algorithm!=="sha256"&&e.latest_hash_algorithm!=="sha512"?!1:te(e.latest_after_hash,e.latest_hash_algorithm)&&(e.latest_record_hash===null||te(e.latest_record_hash,e.latest_hash_algorithm))}function gs(e){return e===null?!0:!Tt(e)||!Mt(e,["op","ts","record_hash"])?!1:typeof e.op=="string"&&["history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","merge_reconcile"].includes(e.op)&&typeof e.ts=="string"&&Te(e.ts)&&(e.record_hash===null||te(e.record_hash,"sha256")||te(e.record_hash,"sha512"))}function _s(e,t){return!Tt(e)||!Mt(e,["id","entries","bytes","stream_digest","latest_after_hash","latest_record_hash","latest_hash_algorithm","rewrite_count","checkpoint_digest","last_maintenance"])?!1:typeof e.id=="string"&&/^[A-Za-z0-9_-]+$/u.test(e.id)&&[e.entries,e.bytes,e.rewrite_count].every(r=>typeof r=="number"&&Number.isSafeInteger(r)&&r>=0)&&te(e.stream_digest,t)&&ys(e)&&(e.checkpoint_digest===null||te(e.checkpoint_digest,"sha256"))&&gs(e.last_maintenance)}function ki(e){if(!Tt(e)||!Mt(e,["format","version","hash_algorithm","generated_at","streams","workspace_digest"]))throw new TypeError("Invalid history attestation bundle");if(e.format!==Rt.format||e.version!==1||typeof e.generated_at!="string"||!Te(e.generated_at)||!Array.isArray(e.streams)||e.hash_algorithm!=="sha256"&&e.hash_algorithm!=="sha512")throw new TypeError("Invalid history attestation format");let t=e.hash_algorithm,r;for(let o of e.streams){if(!_s(o,t))throw new TypeError("Invalid history attestation stream");let s=o.id;if(r!==void 0&&s<=r)throw new TypeError("Invalid history attestation stream order");r=s}let{workspace_digest:n,...i}=e;if(mt(D(i),t)!==n)throw new TypeError("History attestation rollup mismatch");return e}async function xi(e={}){let t=x(e.hashAlgorithm),r=e.generatedAt??I();if(!Te(r))throw new TypeError("Invalid history attestation timestamp");let n=await At(k(e.cwd??process.cwd(),e.pmRoot),t),i=n.filter(s=>s.stream===null);if(i.length>0)throw new TypeError(`Cannot export history attestation: invalid streams ${i.map(s=>s.id).join(", ")}`);let o={format:Rt.format,version:1,hash_algorithm:t,generated_at:r,streams:n.map(s=>s.stream)};return ki({...o,workspace_digest:mt(D(o),t)})}async function Ri(e,t={}){let r=ki(e),n=await At(k(t.cwd??process.cwd(),t.pmRoot),r.hash_algorithm),i=new Map(n.map(l=>[l.id,l])),o=new Map(r.streams.map(l=>[l.id,l])),s=r.streams.filter(l=>!i.has(l.id)).map(l=>l.id),a=n.filter(l=>!o.has(l.id)).map(l=>l.id),c=n.filter(l=>l.stream===null).map(l=>l.id),d=[];for(let l of r.streams){let u=i.get(l.id);u&&(u.digest!==l.stream_digest||D(u.stream)!==D(l))&&d.push({id:l.id,before_digest:l.stream_digest,after_digest:u.digest,last_maintenance:u.stream?.last_maintenance??null})}return{ok:s.length+a.length+c.length+d.length===0,workspace_digest:r.workspace_digest,streams_checked:n.length,changed_streams:d.map(l=>l.id),missing_streams:s,added_streams:a,invalid_streams:c,transitions:d}}import Ci 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]="3bca4afb-f1cc-5627-a377-b30e8005a284")}catch{}})();async function Jl(e,t){for(let n of["verify","output","hashAlgorithm"]){let i=e[n];if(!(n==="verify"&&typeof i=="object"&&i!==null)&&i!==void 0&&(typeof i!="string"||i.trim().length===0))throw new h(`history attest ${n} requires a nonempty string.`,f.USAGE)}if(e.verify!==void 0){if(e.output!==void 0||e.hashAlgorithm!==void 0)throw new h("history attest --verify cannot be combined with --output or --hash-algorithm",f.USAGE);let n;try{n=typeof e.verify=="string"?JSON.parse(await Ci.readFile(e.verify,"utf8")):e.verify}catch{throw new h("Cannot read history attestation proof. Provide --verify with a readable JSON proof file.",f.USAGE)}return Ri(n,{pmRoot:t.path})}let r=await xi({pmRoot:t.path,hashAlgorithm:x(e.hashAlgorithm)});if(e.output===void 0)return r;try{await Ci.writeFile(e.output,`${JSON.stringify(r,null,2)}
|
|
2
2
|
`,{flag:"wx",mode:384})}catch{throw new h("Cannot create history attestation proof. Choose --output with a new filename in a writable directory; existing files are never overwritten.",f.USAGE)}return{output:e.output,workspace_digest:r.workspace_digest,streams:r.streams.length}}import ws from"fast-json-patch";import Ft 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]="ebfa0c5e-461b-5078-8272-69086e84b4dc")}catch{}})();async function Ai(e,t,r){let n=await _n(e,{schema:t.schema});return n.error===null?{raw:n.raw,document:n.document}:{raw:n.raw,document:Ti(r),recovered:!0}}function bs(e,t){return mn(e,t,{errorSubject:"restore",allowFutureTimestamp:!0})}function Ti(e){let t=gt(e,e.length-1);return Object.keys(t.metadata).length===0?{metadata:{},body:t.body}:Fe(H(t))}async function vs(e,t,r,n){let i=await K(e,t,r,n),o=i.located?await He({pmRoot:e,settings:r,itemId:i.id,commandLabel:"restore"}):{warnings:[]};return{...i,historyPolicyWarnings:o.warnings}}function Es(e,t){let r=me(e),n=me(t),i=ws.compare(r,n),o=new Set;for(let s of i){if(s.path==="/body"||s.path.startsWith("/body/")){o.add("body");continue}let a=s.path.replace(/^\/(?:metadata|front_matter)\/?/,"").split("/")[0];o.add(a.replaceAll("~1","/").replaceAll("~0","~"))}return Array.from(o).sort((s,a)=>s.localeCompare(a))}async function Ss(e){let t=await si({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:"restore",readItem:r=>Ai(r,e.settings,e.history)});return{loadedItemUnderLock:t.loadedItemUnderLock,existingItemPath:t.locatedUnderLock?.itemPath??null}}function Is(e,t){return e?{document:e.document,originalRaw:e.raw}:{document:Ti(t),originalRaw:null}}function ks(e){let t=e.document.metadata.assignee?.trim();if(!(t&&t!==e.author&&!e.force))return[];if(e.enforcement==="strict")throw new h(`Item ${e.resolvedId} is assigned to ${t}. Use --force to override.`,f.CONFLICT);return e.enforcement==="warn"?[`ownership_warning:assignee_conflict:${e.resolvedId}:${t}`]:[]}async function xs(e){if(e.existingItemPath&&e.resolvedOriginalRaw!==null&&e.restoredItemPath!==e.existingItemPath){await O(e.existingItemPath,e.resolvedOriginalRaw),await Ft.rm(e.restoredItemPath,{force:!0});return}if(e.existingItemPath&&e.resolvedOriginalRaw!==null){await O(e.existingItemPath,e.resolvedOriginalRaw);return}await Ft.rm(e.restoredItemPath,{force:!0})}async function Rs(e){return[...await Y({path:e.restoredItemPath,scope:"project",op:"restore",item_id:e.after.metadata.id,item_type:e.after.metadata.type,before:e.before,after:e.after,changed_fields:["restored"]}),...await Y({path:e.historyPath,scope:"project",op:"restore:history",item_id:e.after.metadata.id,item_type:e.after.metadata.type,before:e.before,after:e.after,changed_fields:["restored"]})]}async function fd(e,t,r,n){let i=k(process.cwd(),n.path);await P(i);let o=await L(i),s=U(o,A()),a=await vs(i,e,o,s.type_to_folder),c=a.id,{raw:d,entries:l}=await Zr(a.historyPath,c);if(l.length===0)throw new h(`No history exists for ${c}; restore is unavailable.`,f.NOT_FOUND);let u=bs(t,l),m=fn(gt(l,u.historyIndex),u),p=an(m,{schema:o.schema});if(p.metadata.id!==c)throw new h(`Restore target resolved to item ${p.metadata.id}, expected ${c}.`,f.GENERIC_FAILURE);let g=(a.located?await Ai(a.located,o,l):null)?.raw??null,_=De(r.author,o.author_default),y=await Qr(i,c,o.locks.ttl_seconds,_,!!r.force,o.governance.force_required_for_stale_lock,o.locks.wait_ms);try{let{loadedItemUnderLock:w,existingItemPath:v}=await Ss({pmRoot:i,subject:a,settings:o,typeRegistry:s,historyRawBeforeLock:d,currentItemRawBeforeLock:g,history:l}),E="toon",b=Is(w,l),R=ks({document:b.document,author:_,force:r.force,enforcement:o.governance.ownership_enforcement,resolvedId:c}),S=Es(b.document,p),C=await pn({pmRoot:i,settings:o,operation:"restore",author:_,before:b.document,after:p});await Nr({pm_root:i,operation:"restore",before:b.document,after:p,changed_fields:S,sdk:bn({pmRoot:i,settings:o,typeToFolder:s.type_to_folder})});let Ie=Me(p,{format:E,schema:o.schema}),B=z(i,p.metadata.type,c,E,s.type_to_folder),W=await Le(i,_),ke=[];try{await O(B,Ie),v&&B!==v&&await Ft.rm(v);let Lo=V({nowIso:I(),author:_,op:"restore",before:b.document,after:p,message:r.message,context:C.decisions.length===0?void 0:{workflow_policies:C.decisions}});try{await sn(a.historyPath,Lo)}catch(Oo){throw await xs({existingItemPath:v,resolvedOriginalRaw:b.originalRaw,restoredItemPath:B}),Oo}ke=await Oe({pmRoot:i,preferredFormat:o.item_format,typeToFolder:s.type_to_folder,schema:o.schema,itemPath:B,previousItemPath:v??void 0,document:p})}finally{await W()}let Ho=await Rs({restoredItemPath:B,historyPath:a.historyPath,before:b.document,after:p});qr({id:p.metadata.id,op:"restore",item_type:p.metadata.type,previous_status:b.document.metadata.status,status:p.metadata.status,previous:dt(b.document.metadata,S),current:dt(p.metadata,S),changed_fields:S});let Dr=l[u.historyIndex],Pr=q(l,!0);return{item:p.metadata,restored_from:{kind:u.kind,target:u.raw,history_index:u.historyIndex+1,version:Pr===null?null:Pr+u.historyIndex+1,entry_ts:Dr.ts,entry_op:Dr.op},changed_fields:S,warnings:[...C.warnings,...w?.recovered?["restore_unreadable_item_recovered"]:[],...a.historyPolicyWarnings,...R,...ke,...Ho]}}finally{await y()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="190eb119-9510-59d6-bb3a-d1f807c68281")}catch{}})();var Cs=["status","type","tag","priority","deadlineBefore","deadlineAfter","updatedAfter","updatedBefore","createdAfter","createdBefore","ids","assignee","assigneeFilter","parent","sprint","release"],As=["filterAcMissing","filterEstimatesMissing","filterResolutionMissing","filterMetadataMissing","filterReviewerMissing","filterRiskMissing","filterConfidenceMissing","filterSprintMissing","filterReleaseMissing","hasNotes","hasLearnings","hasFiles","hasDocs","hasTests","hasComments","hasDeps","hasBody","hasLinkedCommand","noNotes","noLearnings","noFiles","noDocs","noTests","noComments","noDeps","emptyBody","noLinkedCommand"];function Ts(e){return e!=null&&(typeof e!="string"||e.split(",").some(t=>t.trim().length>0))}function pd(e,t,r={}){let n=r.includePagination!==!1;return[t,...Cs.map(i=>e?.[i]),...n?[e?.limit,e?.offset]:[]].some(Ts)||As.some(i=>e?.[i]===!0)}function Mi(e){return{type:e.type,tag:e.tag,priority:e.priority,deadlineBefore:e.deadlineBefore,deadlineAfter:e.deadlineAfter,assignee:e.assignee,assigneeFilter:e.assigneeFilter,parent:e.parent,sprint:e.sprint,release:e.release}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="59f55926-8d04-52f8-a7fc-d32edd32b760")}catch{}})();var Fi=["parent","type","priority","status","assignee","tags","sprint","release"];function Pi(e,t){let r=qe(e,t,{strict:!0,flagLabel:"--status"});if(!(!r||r.length===0))return r}function Hi(e,t=["estimate","estimated_minutes","priority"]){let r=e.sum?.trim(),n=e.avg?.trim(),i=r&&r.length>0?r:void 0,o=n&&n.length>0?n:void 0;if(!i&&!o)return null;if(i&&o&&i!==o)throw new h("Aggregate --sum and --avg must target the same numeric field",f.USAGE);let s=i??o;if(!t.includes(s))throw new h(`Aggregate numeric field "${s}" is not registered. Allowed: ${t.join(", ")}`,f.USAGE);return{field:s,sum:i!==void 0,avg:o!==void 0}}function Li(e){let t=e?.trim()??"status";if(t.length===0)throw new h("--group-by requires at least one field name",f.USAGE);let r=qn(t);if(r.length===0)throw new h("--group-by requires a comma-separated list of fields",f.USAGE);for(let n of r)if(!Fi.includes(n))throw new h(`Aggregate group fields must be one of ${Fi.join("|")}; received "${n}"`,f.USAGE);return r}function Oi(e){let t=[...new Set(e.map(r=>r.trim().toLowerCase()).filter(r=>r.length>0))].sort((r,n)=>r.localeCompare(n));return t.length===0?null:t.join(",")}function ji(e,t){switch(e){case"parent":return t.parent??null;case"type":return t.type;case"priority":return t.priority;case"status":return t.status;case"assignee":return t.assignee??null;case"tags":return Oi(t.tags);case"sprint":return t.sprint??null;case"release":return t.release??null;default:return null}}function qi(e,t){let r=e??null,n=t??null;return r===n?0:r===null?1:n===null?-1:typeof r=="number"&&typeof n=="number"?r-n:String(r).localeCompare(String(n))}function Qe(e,t){return e.map(r=>`${r}:${JSON.stringify(t[r]??null)}`).join("|")}var Ms={parent:"(unparented)",type:"(untyped)",priority:"(no priority)",status:"(no status)",assignee:"(unassigned)",tags:"(untagged)",sprint:"(no sprint)",release:"(no release)"};function Di(e,t){return t==null||t===""?Ms[e]:String(t)}function Fs(e,t){return e.length===1?Di(e[0],t[e[0]]):e.map(r=>`${r}=${Di(r,t[r])}`).join(" | ")}function Ni(e,t,r){for(let n of r){let i=qi(e.group[n],t.group[n]);if(i!==0)return i}return 0}function Ui(e,t){let r=e[t];if(typeof r=="number"&&Number.isFinite(r))return r;if(typeof r=="string"){let n=r.trim();if(n.length===0)return null;let i=Number(n);if(Number.isFinite(i))return i}return null}function Gi(e,t){return t<=0?0:Math.round(e/t*1e4)/100}function Dt(e,t,r){let n=Xr(String(t),r)??t;if(n===r.open_status){e.open_count+=1;return}if(n==="in_progress"||r.active_statuses.has(n)&&n!==r.open_status){e.in_progress_count+=1;return}if(r.terminal_done_statuses.has(n)||n===r.close_status){e.closed_count+=1;return}e.other_count+=1}function Ds(e,t){return{row:{group:e,count:1},numeric_count:t===null?0:1,numeric_sum:t??0,null_count:t===null?1:0,open_count:0,in_progress_count:0,closed_count:0,other_count:0}}function Ps(e,t){if(t===null){e.null_count+=1;return}e.numeric_count+=1,e.numeric_sum+=t}function Hs(e){e.accumulator.row.count+=1,e.includeCompletion&&Dt(e.accumulator,e.item.status,e.statusRegistry),e.numericAggregation!==null&&Ps(e.accumulator,e.numericValue)}function Ls(e,t,r,n){for(let i of t){let o=Qe(r,i),s=e.get(o);if(s){Hs({...n,accumulator:s});continue}let a=Ds(i,n.numericValue);n.includeCompletion&&Dt(a,n.item.status,n.statusRegistry),e.set(o,a)}}function Os(e,t){let r={};for(let n of e)r[n]=ji(n,t);return r}function js(e,t,r){let n=[Os(e,t)];if(r==="tuple")return n;for(let i of e){let o=t[i];if(!Array.isArray(o))continue;let s=[...new Set(o.map(a=>a.trim().toLowerCase()).filter(Boolean))].sort();s.length!==0&&(n=n.flatMap(a=>s.map(c=>({...a,[i]:c}))))}return n}function qs(e,t,r,n){let i={...e.row,group_label:Fs(t,e.row.group)};return r&&(i.open=e.open_count,i.in_progress=e.in_progress_count,i.closed=e.closed_count,i.other=e.other_count,i.completion_pct=Gi(e.closed_count,e.row.count)),n!==null&&(i.null_count=e.null_count,n.sum&&(i.sum=e.numeric_sum),n.avg&&(i.avg=e.numeric_count===0?null:e.numeric_sum/e.numeric_count)),i}function Ns(e){return{group_by:e.groupBy,set_mode:e.setMode,count:!0,completion:e.includeCompletion,include_unparented:e.includeUnparented,status:e.status?.[0]??null,status_values:e.status,type:e.options.type??null,tag:e.options.tag??null,priority:e.options.priority??null,deadline_before:e.options.deadlineBefore??null,deadline_after:e.options.deadlineAfter??null,assignee:e.options.assignee??null,assignee_filter:e.options.assigneeFilter??null,parent:e.options.parent??null,sprint:e.options.sprint??null,release:e.options.release??null,...e.numericAggregation!==null?{sum:e.options.sum??null,avg:e.options.avg??null,numeric_field:e.numericAggregation.field}:{}}}async function vd(e,t){if(e.count===!1)throw new h("Aggregate grouped counts are always enabled; omit count=false.",f.USAGE);let r=k(process.cwd(),t.path),n=await L(r),i=j(n.schema),o=["estimate","estimated_minutes","priority",...J(n.schema).definitions.filter(E=>E.type==="number").map(E=>E.metadata_key)],s=Li(e.groupBy),a=e.setMode??"element";if(a!=="element"&&a!=="tuple")throw new h("Aggregate --set-mode must be element or tuple",f.USAGE);let c=Pi(e.status,i),d=Hi(e,[...new Set(o)].sort((E,b)=>E.localeCompare(b))),l=e.completion===!0,u=e.includeUnparented===!0,m=await Ve(void 0,{...Mi(e),status:e.status,noTruncate:!0,strictRead:!0},t),p=new Map,g=0,_=0,y=0;for(let E of m.items){let b=E;if(s.includes("parent")&&b.parent===void 0&&!u){g+=1;continue}let R=d===null?null:Ui(b,d.field),S=js(s,b,a);Ls(p,S,s,{item:b,statusRegistry:i,includeCompletion:l,numericAggregation:d,numericValue:R}),y+=S.length,_+=1}let w=[...p.values()].map(E=>qs(E,s,l,d)).sort((E,b)=>Ni(E,b,s)),v=m.warnings&&m.warnings.length>0?m.warnings:void 0;return{...Us(w,s,e),count:w.length,totals:{items_considered:m.items.length,items_grouped:_,items_skipped_unparented:g,group_memberships:y},filters:Ns({groupBy:s,setMode:a,includeCompletion:l,includeUnparented:u,status:c,options:e,numericAggregation:d}),now:I(),...v?{warnings:v}:{}}}function Us(e,t,r){let n=ii(r.limit,"limit")??50,i=r.after===void 0?-1:e.findIndex(a=>Qe(t,a.group)===r.after);if(r.after!==void 0&&i<0)throw new h("Aggregate --after cursor is absent from the current grouping; restart without --after.",f.USAGE);let o=e.slice(i+1,i+1+n),s=i+1+o.length<e.length;return{groups:o,returned_count:o.length,truncated:s,next_after:s?Qe(t,o.at(-1).group):null}}var Ed={buildGroupKey:Qe,compareAggregateRows:Ni,compareNullableGroupValue:qi,completionPct:Gi,normalizeTagGroupValue:Oi,parseGroupBy:Li,parseNumericAggregation:Hi,parseStatus:Pi,readNumericAggregateValue:Ui,resolveGroupValue:ji,updateCompletionCounts:Dt};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="21742dd3-12b5-5285-89d8-036693459eb8")}catch{}})();var $i=1e6,Bi=20;function Wi(e,t,r,n=Bi){if(!Number.isSafeInteger(n)||n<0)throw new h("Child projection sample limit must be a non-negative integer.",f.USAGE);let i=e.trim().toLowerCase(),o={},s=[],a=0;for(let y of t){if(a+=1,a>$i)throw new h(`Child projection exceeded the ${$i.toLocaleString("en-US")} item safety bound.`,f.GENERIC_FAILURE,{code:"child_projection_item_bound_exceeded",required:"Use an indexed or parent-filtered metadata source.",why:"Unbounded graph scans can exhaust memory in universal project stores.",nextSteps:["Build the derived item index, then retry the parent read."]});s.push(y)}let c=new Map(s.map(y=>[y.id.trim().toLowerCase(),y])),d=Jn(Xn(s,Yn())),l=new Set(d.children_by_parent.get(i)??[]);for(let y of s)y.parent?.trim().toLowerCase()===i&&l.add(y.id.trim().toLowerCase());let u=[...l].map(y=>c.get(y)),m=0;for(let y of u){let w=y.status.trim().toLowerCase();o[w]=(o[w]??0)+1,ce(w,r)||(m+=1)}u.sort((y,w)=>y.id.localeCompare(w.id));let p=u.slice(0,n).map(y=>({id:y.id,title:y.title,type:y.type,status:y.status,priority:y.priority})),g=u.length>p.length,_=n===0?Bi:n;return{count:u.length,active:m,by_status:Object.fromEntries(Object.entries(o).sort(([y],[w])=>y.localeCompare(w))),sample:p,sample_limit:n,truncated:g,next_offset:g?p.length:null,continuation:g?`pm list --status all --parent ${e} --offset ${p.length} --limit ${_}`:null,scanned:a}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="db3fe399-8eb8-5b17-8a9e-89eda4774234")}catch{}})();var Gs=new Set(["event","meeting","reminder"]);function $s(e){return Gs.has(e.type.trim().toLowerCase())||e.deadline!==void 0||(e.reminders?.length??0)>0||(e.events?.length??0)>0}function Pt(e){if(!$s(e))return;let t=[...e.events??[]].sort((n,i)=>n.start_at.localeCompare(i.start_at)),r=t[0];return{deadline:e.deadline??null,start_at:r?.start_at??null,end_at:r?.end_at??null,location:r?.location??null,reminders:[...e.reminders??[]],events:t}}import{readdir as Ws}from"node:fs/promises";import Ht 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]="e2c03bb3-e603-579b-bb44-0b3757a00ea8")}catch{}})();var zs=new Set(["epic","feature","milestone","plan"]),Vs=new Set(Object.keys(Hr).map(e=>e.toLowerCase()));function Ot(e){return Object.fromEntries(["comments","notes","learnings","files","tests","docs","reminders","events"].map(t=>[t,e[t]?.length??0]))}function Ks(e,t,r,n,i){let o=Ot(e);return[...t.length>0?["body"]:[],...Object.entries(o).flatMap(([s,a])=>a>0?[s]:[]),...o.files+o.tests+o.docs>0?["linked"]:[],...r===void 0?["children"]:r.count>0?["children"]:[],...typeof e.assignee=="string"&&e.assignee.trim().length>0?["claim_state"]:[],...Pt(e)?["schedule"]:[],...n&&bt(e).length>0?["blockers"]:[],...!i.full&&e.dependencies?.some(({id:s,kind:a,...c})=>Object.values(c).some(d=>d!==void 0))?["dependency_provenance"]:[]]}function Vi(e){let t=e.trim().toLowerCase();return t.length>0&&(zs.has(t)||!Vs.has(t))}function zi(e){return{ts:e.ts,author:e.author,message:e.message??null}}function Qs(e,t){let r=e?.trim(),n=r&&r.length>0?r:null,i=[...t].reverse().find(s=>s.op==="claim"),o=[...t].reverse().find(s=>s.op==="release");return{claimed:n!==null,assignee:n,last_claim:i?zi(i):null,last_release:o?zi(o):null}}function Ys(e){if(e===void 0||e.trim().length===0)return"standard";let t=e.trim().toLowerCase();if(t==="full")return"deep";if(ze.includes(t))return t;throw new h("Get --depth must be one of brief|standard|deep|full",f.USAGE,{field:"depth",value:e,recovery:{allowed_values:[...ze,"full"]}})}function Xs(e,t,r){let n=Ot(e),i={...e};if(!r&&e.dependencies!==void 0&&(i.dependencies=e.dependencies.map(({id:g,kind:_})=>({id:g,kind:_}))),t==="deep")return{...i,comments:e.comments??[],notes:e.notes??[],learnings:e.learnings??[],files:e.files??[],tests:e.tests??[],docs:e.docs??[],reminders:e.reminders??[],events:e.events??[],notes_count:n.notes,tests_count:n.tests,collection_counts:n};let{comments:o,notes:s,learnings:a,files:c,tests:d,docs:l,reminders:u,events:m,...p}=i;return{...p,notes_count:e.notes?.length??0,tests_count:e.tests?.length??0,collection_counts:n}}function Js(e){if(e===void 0)return null;let t=e.split(",").map(r=>r.trim()).filter(r=>r.length>0);if(t.length===0)throw new h("Get --fields requires a comma-separated list of field names",f.USAGE);return t}function Ye(e){return e.startsWith("item.")?e.slice(5):e}function Zs(e,t,r){if(e===null)return;let n=vt(t),i=new Set(n),o=e.filter(s=>{let a=Ye(s);return!i.has(s)&&!i.has(a)});if(o.length>0){let s=["get",r,"--fields",e.filter(a=>!o.includes(a)).join(",")||"id,title,status"];throw new h(`Unknown get --fields value(s): ${o.join(", ")}`,f.USAGE,{code:"unknown_field_projection",examples:["pm get <id> --fields id,title,status,type,updated_at","pm get <id> --fields id,title,claim_state","pm get <id> --fields id,title,body,linked.files"],recovery:{allowed_values:n,suggested_retry:X(s),suggested_retry_args:s}})}}var ea=new Set(["comments","notes","learnings","files","tests","test_runs","docs","reminders","events","dependencies","plan_steps","plan_decisions","plan_discoveries","plan_validation"]);function ta(e,t,r){return Object.hasOwn(t,r)?t[r]:e[r]!==void 0?e[r]:ea.has(r)?[]:void 0}function ra(e,t){let r=e,n={notes_count:e.notes?.length??0,tests_count:e.tests?.length??0,collection_counts:Ot(e)},i={id:e.id};for(let o of t){let s=Ye(o);s==="body"||s==="linked"||s.startsWith("linked.")||s==="claim_state"||s.startsWith("claim_state.")||s==="children"||s.startsWith("children.")||s==="schedule"||s.startsWith("schedule.")||s==="blockers"||(i[s]=ta(r,n,s))}return i}function we(e,t){return e?.some(r=>r===t||r===`item.${t}`)??!1}function re(e,t){return e.some(r=>{let n=Ye(r);return n===t||n.startsWith(`${t}.`)})}function na(e,t){if(e.full&&(e.fields!==void 0||e.depth!==void 0))throw new h("Get projection options are mutually exclusive; remove the extra projection flag and retry.",f.USAGE,{code:"projection_options_mutually_exclusive",flag:"--full",recovery:{suggested_retry:X(["get",t,"--full"]),suggested_retry_args:["get",t,"--full"]}});if(e.tree!==!0&&e.treeDepth!==void 0)throw new h("Get --tree-depth requires --tree",f.USAGE);if(e.at!==void 0&&e.tree===!0)throw new h("Get --at cannot be combined with --tree because workspace-level historical projections are not yet indexed.",f.USAGE);return{depth:e.full?"deep":Ys(e.depth),full:e.full===!0||e.depth?.trim().toLowerCase()==="full",treeDepth:e.tree===!0?$n(e.treeDepth,"--tree-depth"):void 0,fields:Js(e.fields),fieldProjection:e.fields!==void 0}}async function ia(e,t,r){let n=k(process.cwd(),t.path);await P(n);let i=await L(n),o=U(i,A());if(r!==void 0){let c=await Sn(e,r,{pmRoot:t.path});return{pmRoot:n,settings:i,typeToFolder:o.type_to_folder,locatedId:c.document.metadata.id,metadata:c.document.metadata,body:c.document.body,historical:c}}let s=await fe(n,e,i.id_prefix,i.item_format,o.type_to_folder);if(!s)throw await vn(n,e,i.id_prefix,o.type_to_folder);let a=await he(s,{schema:i.schema});return{pmRoot:n,settings:i,typeToFolder:o.type_to_folder,locatedId:s.id,metadata:a.document.metadata,body:a.document.body}}function oa(e,t,r,n){let i=J(t.schema).definitions.map(o=>o.metadata_key);if(Zs(e,i,n),r&&re(e??[],"children"))throw new h("Get --at cannot project children because workspace-level historical relationships are not yet indexed.",f.USAGE);if(r&&re(e??[],"blockers"))throw new h("Get --at cannot project current blocker statuses; read the current item with --fields blockers instead.",f.USAGE)}function Lt(e){let{fieldProjection:t,depth:r,fields:n,field:i}=e;return t?i==="body"||i==="linked"?we(n,i):re(n,i):r!=="brief"}async function sa(e,t){if(!t)return;let r=Ae(e.pmRoot,e.locatedId),n=await le(r,e.locatedId);return Qs(e.metadata.assignee,e.historical?n.slice(0,e.historical.target.historyIndex+1):n)}function aa(e,t,r,n){let i=n||we(r,"linked.files"),o=n||we(r,"linked.tests"),s=n||we(r,"linked.docs");!n&&!i&&!o&&!s||(e.linked={files:i?t.metadata.files??[]:[],tests:o?t.metadata.tests??[]:[],docs:s?t.metadata.docs??[]:[]})}async function ca(e,t){if(!t)return;let r=j(e.settings.schema),n=await je(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema);return Wi(e.locatedId,n,r)}function la(e,t){let r=new Map;for(let n of e){let i=n.external?n.id:t.get(n.id.toLowerCase())?.id??n.id;r.set(n.external?`external:${i}`:`local:${i.toLowerCase()}`,{...n,id:i})}return[...r.values()]}async function da(e,t){let r=Ht.basename(e),n=(await Ws(Ht.dirname(e)).catch(i=>{throw fi("Cannot verify the blocker's physical file identity",{exitCode:f.GENERIC_FAILURE,context:{code:"blocker_identity_read_failed",required:"Restore access to the blocker item directory, then retry the item read."},cause:i})})).filter(i=>i.toLowerCase()===r.toLowerCase()).sort((i,o)=>+(o===r)-+(i===r)||i.localeCompare(o)).map(i=>Ht.parse(i).name)[0];if(n===void 0)throw new h(`Blocker canonical file disappeared during identity verification: ${t}`,f.CONFLICT,{code:"item_identity_conflict",required:"Restore the canonical blocker file and validate storage integrity before retrying the item read."});return n}async function ua(e,t,r){if(t.historical!==void 0||!(r.fieldProjection?re(r.fields,"blockers"):r.depth!=="brief"))return;let n=bt(t.metadata);if(n.length===0)return;let i=new Map([t.metadata.blocked_by,...(t.metadata.dependencies??[]).filter(a=>a.kind==="blocked_by").map(a=>a.id)].filter(a=>typeof a=="string").map(a=>[a.trim().toLowerCase(),a.trim()])),o=new Map;for(let a of n){if(Nn(a)||!/^(?!\.{1,2}$)[^/\\:\0]+$/u.test(a)||t.metadata.dependencies?.some(l=>l.id.trim()===a&&l.kind==="blocked_by"&&Un(l.source_kind)))continue;let c=await fe(t.pmRoot,i.get(a),t.settings.id_prefix,t.settings.item_format,t.typeToFolder);if(c===null)continue;let d=await he(c,{schema:t.settings.schema});if(c.id=await da(c.itemPath,c.id),d.document.metadata.id!==c.id)throw new h(`Blocker identity differs from its canonical file: ${c.id}`,f.CONFLICT,{code:"item_identity_conflict",required:"Restore the canonical blocker identity and validate storage integrity before retrying the item read."});o.set(a.toLowerCase(),d.document.metadata)}let s=la(Gn({blocked_by:t.metadata.blocked_by,dependencies:t.metadata.dependencies,updated_at:t.metadata.updated_at},o,j(t.settings.schema)),o);e.blockers={scope:"declared",open:s.filter(a=>!a.resolved).map(({resolved:a,...c})=>c),closed_count:s.filter(a=>a.resolved).length},!r.fieldProjection&&!r.full&&delete e.item.blocked_by}function ma(e,t,r,n){if(!n)return;let i=Pt(t.metadata);if(i){if(r===null||we(r,"schedule")){e.schedule=i;return}e.schedule=Object.fromEntries(Object.entries(i).filter(([o])=>r.some(s=>Ye(s)===`schedule.${o}`)))}}async function fa(e,t,r,n){if(t.tree!==!0)return;let i=await Ve(void 0,{parent:e.locatedId,tree:!0,treeDepth:r===void 0?void 0:String(r),full:!0},n);return{root_id:e.locatedId,root_title:e.metadata.title,depth_limit:r??null,count:i.count,items:i.items.map(o=>o)}}async function Qd(e,t,r={}){let n=na(r,e),i=await ia(e,t,r.at);oa(n.fields,i.settings,i.historical!==void 0,i.locatedId);let o=Lt({...n,field:"body"}),s=Lt({...n,field:"linked"}),a=Lt({...n,field:"claim_state"}),c=i.historical===void 0&&(n.fieldProjection?re(n.fields,"children"):n.depth==="deep"&&(n.full||Vi(i.metadata.type))),d=n.fieldProjection?re(n.fields,"schedule"):n.depth!=="brief",l=await sa(i,a),u={item:n.fieldProjection?ra(i.metadata,n.fields):Xs(i.metadata,n.depth,n.full)};o&&(u.item.body=i.body),aa(u,i,n.fields,s),l&&(u.claim_state=l),ma(u,i,n.fields,d),await ua(u,i,n);let m=await ca(i,c);m!==void 0&&(u.children=m);let p=await fa(i,r,n.treeDepth,t);if(p!==void 0&&(u.tree=p),i.historical&&(u.reconstructed=!0,u.as_of_version=i.historical.as_of_version,u.as_of_timestamp=i.historical.as_of_timestamp),i.historical===void 0)try{await Yr({pmRoot:i.pmRoot,author:De(void 0,i.settings.author_default),itemIds:[i.locatedId],intent:"get"})}catch{}return Ur(u,n.fieldProjection?[]:Ks(i.metadata,i.body,m,i.historical===void 0,n)),u}var Yd={shouldAutoIncludeGetChildren:Vi};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9c9c1249-e52a-5203-8a84-d54211c30202")}catch{}})();function ha(e,t){return t===void 0?e:e.slice(Math.max(0,e.length-t))}function pa(e,t){return e.map(({entry:r,version:n})=>{let i=new Set,o=cn(r.patch);for(let s of o)i.add(_t(s.path)),s.from&&i.add(_t(s.from));return{index:n,...t?{version:t.offset===null?null:t.offset+n}:{},ts:r.ts,op:r.op,author:r.author,patch_ops:o.length,changed_fields:[...i].sort((s,a)=>s.localeCompare(a))}})}function ya(e){if(e[0]?.op!=="history_compact_baseline")return;let t=q(e,!0);return{offset:t,first_version:t===null?null:t+1,last_version:t===null?null:t+e.length}}async function ga(e,t){let r=k(process.cwd(),t.path);await P(r);let n=await L(r),i=U(n,A()),o=e.trim()===Pe,s=o?Pe:hn(e,n.id_prefix),a=await fe(r,s,n.id_prefix,n.item_format,i.type_to_folder),c=a?.id??s,d=o?dn(r):Ae(r,c);if(!a&&!await xe(d))throw new h(`Item ${e} not found`,f.NOT_FOUND);return a&&await He({pmRoot:r,settings:n,itemId:a.id,commandLabel:"history"}),{historyPath:d,located:a,resolvedId:c,settings:n}}async function su(e,t,r){let n=Ne(t.limit),{historyPath:i,located:o,resolvedId:s,settings:a}=await ga(e,r),c=await le(i,s),d=ya(c),l=a.agent_identity.identity_vocabulary,u=ai(a.agent_identity.harness_signals),m=li({harness:t.harness,agentInstance:t.agentInstance,provenance:t.provenanceFilter},l,u),p=_a(c).filter(({entry:S})=>m(S)),g=ha(p,n),_=g.map(({entry:S})=>S),y=t.compact===!0,w=y?pa(g,d):void 0,v=t.provenance===!0?g.map(({entry:S,durableVersion:C})=>ci(S,l,{itemId:s,version:C})):void 0,E=t.provenance===!0?"provenance":y?"compact":"full",b={compact:{compact_history:w},provenance:{provenance_history:v},full:{history:_}}[E],R={id:s,...b,compact:y,projection:{mode:E,row_key:{compact:"compact_history",provenance:"provenance_history",full:"history"}[E]},omission_receipt:Gr("history",E),count:_.length,limit:n??null,version_addressing:d,...t.provenanceSummary===!0?{provenance_summary:di(p.map(({entry:S})=>S),l,u)}:{}};if((t.diff||t.field!==void 0)&&(R.diff=An(c,{windowStartIndex:Math.max(0,c.length-_.length),field:t.field})),t.verify){let S=o?(await he(o,{schema:a.schema})).document:void 0;if(R.verification=En(c,S),s===Pe&&R.verification.ok){let C=await un(k(process.cwd(),r.path));R.verification={...R.verification,ok:C.ok,errors:C.ok?R.verification.errors:[...R.verification.errors,"verify_failed:workspace_state_mismatch"],workspace_state_matches_latest:C.ok,workspace_state_mismatches:C.mismatched_documents,workspace_state_missing:C.missing_documents,workspace_state_unreadable:C.unreadable_documents}}}return R}function _a(e){let t=q(e,!0);return e.map((r,n)=>({entry:r,version:n+1,durableVersion:t===null?void 0:t+n+1}))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f7f0c9be-34c2-55fb-8676-de58e96c382f")}catch{}})();function wa(e){if(e===void 0)return"keyword";let t=e.trim().toLowerCase();if(t!=="keyword"&&t!=="semantic"&&t!=="hybrid")throw new h("Search mode must be one of keyword|semantic|hybrid",f.USAGE);return t}function Xe(e){return e===!0}function Ki(e){return Or(e,0,1)??void 0}function Qi(e){if(e===void 0)return"or";let t=e.trim().toLowerCase();if(t!=="and"&&t!=="or"&&t!=="exact")throw new h("Search --match-mode must be one of and|or|exact",f.USAGE);return t}function Yi(e){if(e==null||e==="")return;let t=typeof e=="number"?e:Number(String(e).trim());if(!Number.isFinite(t)||t<0)throw new h("Search --min-score must be a finite number >= 0",f.USAGE);return t}function Q(e,t){if(e==null)return;let r=String(e).trim();if(r.length!==0)return ut(r,new Date,t)}function T(e){return e.toLowerCase().replace(/\s+/g," ").trim()}function jt(e,t){if(e!==void 0)return ut(e,new Date,t)}function ba(e){if(e===void 0)return;let t=e.split(",").map(r=>r.trim()).filter(r=>r.length>0);if(t.length===0)throw new h("Search --fields requires a comma-separated list of field names",f.USAGE);return[...new Set(t)]}function Je(e,t="<query>"){let r=e.compact===!0,n=e.full===!0,i=ba(e.fields);if(Number(r)+Number(n)+ +(i!==void 0)>1)throw new h("Search projection options are mutually exclusive. Use one of --compact, --full, or --fields.",f.USAGE,{code:"projection_options_mutually_exclusive",recovery:{suggested_retry:X(["search",t,"--full"]),suggested_retry_args:["search",t,"--full"]}});return r?{mode:"compact",fields:[...Zn]}:n?{mode:"full",fields:[]}:i?{mode:"fields",fields:i}:{mode:"full",fields:[]}}function qt(e,t,r="<query>"){if(e.mode!=="fields")return;let n=ei(t.definitions.flatMap(s=>[s.key,s.metadata_key])),i=new Set(n),o=e.fields.filter(s=>{let a=s.trim();return!i.has(a)});if(o.length>0){let s=["search",r,"--fields",e.fields.filter(a=>!o.includes(a)).join(",")||"id,title,status,score"];throw new h(`Unknown search --fields value(s): ${o.join(", ")}`,f.USAGE,{code:"unknown_field_projection",examples:["pm search <query> --fields id,title,status,score","pm search <query> --fields id,title,item.description,matched_fields"],nextSteps:["Use item.<field> for explicit item metadata fields, or run pm search --help for projection examples."],recovery:{allowed_values:n,suggested_retry:X(s),suggested_retry_args:s}})}}function Ze(e){let t=T(e);if(!t)throw new h("Search query must not be empty",f.USAGE);return t.split(/\s+/u).filter(Boolean)}function Nt(e){let t=e.search?.max_results;return typeof t=="number"&&Number.isFinite(t)&&t>0?Math.floor(t):50}var va=["auto","keyword","semantic","hybrid"];function Ea(e){let t=e.search?.default_mode;if(typeof t!="string")return"auto";let r=t.trim().toLowerCase();return va.includes(r)?r:"auto"}function Ut(e){if(typeof e.requested=="string"&&e.requested.trim().length>0)return{mode:wa(e.requested),source:"explicit"};let t=Ea(e.settings);return t!=="auto"?{mode:t,source:"settings"}:{mode:e.semanticRunnable?"hybrid":"keyword",source:"auto"}}function Gt(e){let t=e.search?.score_threshold;return typeof t=="number"&&Number.isFinite(t)?t:0}function $t(e){let t=e.search?.hybrid_semantic_weight;return typeof t=="number"&&Number.isFinite(t)&&t>=0&&t<=1?t:.7}function Bt(e){let t={title_exact_bonus:10,title_weight:48,description_weight:5,tags_weight:6,status_weight:2,body_weight:1,comments_weight:1,notes_weight:1,learnings_weight:1,reminders_weight:2,events_weight:2,dependencies_weight:3,linked_content_weight:1},r=e.search?.tuning;if(!r)return t;let n=(i,o)=>typeof i=="number"&&Number.isFinite(i)&&i>=0?i:o;return{title_exact_bonus:n(r.title_exact_bonus,t.title_exact_bonus),title_weight:n(r.title_weight,t.title_weight),description_weight:n(r.description_weight,t.description_weight),tags_weight:n(r.tags_weight,t.tags_weight),status_weight:n(r.status_weight,t.status_weight),body_weight:n(r.body_weight,t.body_weight),comments_weight:n(r.comments_weight,t.comments_weight),notes_weight:n(r.notes_weight,t.notes_weight),learnings_weight:n(r.learnings_weight,t.learnings_weight),reminders_weight:n(r.reminders_weight,t.reminders_weight),events_weight:n(r.events_weight,t.events_weight),dependencies_weight:n(r.dependencies_weight,t.dependencies_weight),linked_content_weight:n(r.linked_content_weight,t.linked_content_weight)}}import Sa 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]="e1f303b6-a641-5550-b58c-ef023b68d5e4")}catch{}})();function Wt(e){return Br("search",{pmRoot:e.pmRoot===void 0?void 0:Sa.resolve(e.pmRoot),query:e.query.trim(),mode:e.mode,options:$r(e.searchOptions,In)})}function Xi(e){let t=zr(e.sorted,{cursor:e.searchOptions.after,fingerprint:Wt(e),limit:e.limit,readId:r=>r.item.id});return{limited:t.rows,pageExtras:{applied_limit:e.limit,...t.has_more?{has_more:!0,truncated:!0}:{},...t.next_cursor?{next_cursor:t.next_cursor}:{}}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c8a2412e-2b0c-59c2-81ad-43de4d51562f")}catch{}})();function Ji(e){if(typeof e!="string")return!1;let t=e.split(",").map(r=>r.trim().toLowerCase()).filter(Boolean);return t.length===1&&t[0]==="all"}var Ia=[{optionKey:"status",summaryKey:"status",normalize:e=>Ji(e)?"all":e},{optionKey:"type",summaryKey:"type"},{optionKey:"tag",summaryKey:"tag"},{optionKey:"priority",summaryKey:"priority"},{optionKey:"deadlineBefore",summaryKey:"deadline_before"},{optionKey:"deadlineAfter",summaryKey:"deadline_after"},{optionKey:"updatedAfter",summaryKey:"updated_after"},{optionKey:"updatedBefore",summaryKey:"updated_before"},{optionKey:"createdAfter",summaryKey:"created_after"},{optionKey:"createdBefore",summaryKey:"created_before"},{optionKey:"assignee",summaryKey:"assignee"},{optionKey:"sprint",summaryKey:"sprint"},{optionKey:"release",summaryKey:"release"},{optionKey:"parent",summaryKey:"parent"}];function ne(e){let{mode:t,matchMode:r,options:n,includeLinked:i,titleExact:o,phraseExact:s,scoreThreshold:a,hybridSemanticWeight:c,runtimeFieldFilters:d}=e,l={};return ni(l,n,Ia),Object.assign(l,St(n)),Object.assign(l,Et(n)),r!==void 0&&r!=="or"&&(l.match_mode=r),i&&(l.include_linked=!0),o&&(l.title_exact=!0),s&&(l.phrase_exact=!0),a>0&&(l.score_threshold=a),t==="hybrid"&&n.semanticWeight!==void 0&&(l.hybrid_semantic_weight=c),n.limit!==void 0&&(l.limit=n.limit),d&&Object.keys(d).length>0&&(l.runtime_filters=d),l}function ie(e){let{effectiveMode:t,matchMode:r,options:n,includeLinked:i,titleExact:o,phraseExact:s,scoreThreshold:a,hybridSemanticWeight:c,queryExpansion:d,rerank:l,runtimeFieldFilters:u}=e,m=p=>p??null;return{mode:t,match_mode:r,status:n.status===void 0||Ji(n.status)?"all":n.status,type:m(n.type),tag:m(n.tag),priority:m(n.priority),deadline_before:m(n.deadlineBefore),deadline_after:m(n.deadlineAfter),updated_after:m(n.updatedAfter),updated_before:m(n.updatedBefore),created_after:m(n.createdAfter),created_before:m(n.createdBefore),assignee:m(n.assignee),sprint:m(n.sprint),release:m(n.release),parent:m(n.parent),...St(n),...Et(n),include_linked:i,title_exact:o,phrase_exact:s,score_threshold:a,hybrid_semantic_weight:t==="hybrid"?c:null,query_expansion_enabled:d.enabled,query_expansion_provider:d.provider,rerank_enabled:l.enabled,rerank_model:l.model,rerank_top_k:l.top_k,limit:m(n.limit),runtime_filters:u}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0272e482-0dab-5970-b19a-4da286fd112b")}catch{}})();var ka=1.2,xa=.75;function zt(e){return ee(e)}function Ra(e){let t=new Map;for(let r of e)t.set(r,(t.get(r)??0)+1);return t}function eo(e){let t=[],r=new Map,n=0;for(let o of e){let s=zt(o.text),a=Ra(s);n+=s.length;for(let c of a.keys())r.set(c,(r.get(c)??0)+1);t.push({id:o.id,termFrequencies:a,length:s.length})}let i=t.length;return{documents:t,documentFrequency:r,documentCount:i,averageDocumentLength:i>0?n/i:0}}function Ca(e,t){return Math.log(1+(e-t+.5)/(t+.5))}function to(e,t,r){let n=new Map;if(e.documentCount===0||e.averageDocumentLength===0)return n;let i=[...new Set(t.filter(s=>s.length>0))];if(i.length===0)return n;let o=new Map;for(let s of i){let a=e.documentFrequency.get(s);a!==void 0&&o.set(s,Ca(e.documentCount,a))}if(o.size===0)return n;for(let s of e.documents){let a=0;for(let[c,d]of o){let l=s.termFrequencies.get(c);if(l===void 0)continue;let u=1-r.b+r.b*s.length/e.averageDocumentLength,m=l+r.k1*u;a+=d*(l*(r.k1+1)/m)}a>0&&n.set(s.id,a)}return n}function Zi(e,t,r,n){return typeof e!="number"||!Number.isFinite(e)?t:Math.min(n,Math.max(r,e))}function ro(e){let t=r=>typeof r=="string"?[r]:typeof r=="number"?[String(r)]:Array.isArray(r)?r.flatMap(t):typeof r=="object"&&r!==null?Object.values(r).flatMap(t):[];return t(Object.values(e)).join(" ")}function no(e){let t=e?.search?.bm25;return{k1:Zi(t?.k1,ka,0,1e3),b:Zi(t?.b,xa,0,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]="b75c3c5e-e2b7-5e65-a56a-883dc896290e")}catch{}})();var Vt=4,Aa=20,Ta=200,Ma=new Set(["a","an","and","for","from","in","into","of","on","or","the","to","with"]);function Kt(e,t){let r=[],n=new Set;for(let i of e){let o=i.trim().replaceAll(/\s+/g," ");if(o.length===0)continue;let s=o.toLowerCase();if(!n.has(s)&&(n.add(s),r.push(o),r.length>=t))break}return r}function Fa(e){let t=e.toLowerCase();return t.length>4&&t.endsWith("ies")?`${t.slice(0,-3)}y`:t.length>4&&(t.endsWith("ches")||t.endsWith("shes")||t.endsWith("xes")||t.endsWith("zes")||t.endsWith("sses"))?t.slice(0,-2):t.length>3&&t.endsWith("s")&&!t.endsWith("ss")&&!t.endsWith("us")&&!t.endsWith("is")&&!t.endsWith("as")?t.slice(0,-1):t}function Da(e){let t=e.toLowerCase();return t.length>2&&(!t.endsWith("s")||t.endsWith("ss"))?t.endsWith("y")&&!/[aeiou]y$/u.test(t)?`${t.slice(0,-1)}ies`:t.endsWith("ch")||t.endsWith("sh")||t.endsWith("x")||t.endsWith("z")||t.endsWith("ss")?`${t}es`:`${t}s`:t}function io(e,t=Vt){let r=e.trim().replaceAll(/\s+/g," ");if(r.length===0)return[];let n=ee(r);if(n.length===0)return[r];let i=n.filter(a=>!Ma.has(a.toLowerCase())),o=n.map(a=>Fa(a)),s=i.map(a=>Da(a));return Kt([r,n.join(" "),i.join(" "),o.join(" "),s.join(" ")],Math.max(1,t))}function oo(e){let t=Array.isArray(e)?e:e?.queries;return Array.isArray(t)?Kt(t.filter(r=>typeof r=="string"),Vt):[]}function so(e,t,r){return Kt([...e,...t],Math.max(1,r))}function ao(e,t){let r=e.search?.query_expansion,n=se(r?.provider);return{enabled:r?.enabled===!0,provider:n??t,max_queries:Vt}}function co(e,t){let r=e.search?.rerank,n=se(r?.model),i=Ce(r?.top_k)??Aa;return{enabled:r?.enabled===!0,model:n??t,top_k:Math.min(Ta,i)}}function lo(e){let t=Array.isArray(e)?e:e?.hits;if(!Array.isArray(t))return[];let r=new Map;for(let i of t){if(typeof i!="object"||i===null)continue;let o=se(i.id),s=i.score;if(!o||typeof s!="number"||!Number.isFinite(s))continue;let a=r.get(o);(a===void 0||s>a)&&r.set(o,s)}let n=[...r.entries()].map(([i,o])=>({id:i,score:o}));return n.sort((i,o)=>i.score!==o.score?o.score-i.score:i.id.localeCompare(o.id)),n}function Pa(e,t){let r=e.length,n=0;for(let i=0;i<r;i+=1)n+=e[i]*t[i];return n}function uo(e){let t=0;for(let r=0;r<e.length;r+=1)t+=e[r]*e[r];return Math.sqrt(t)}function Ha(e,t,r){if(!e||!t||e.length===0||t.length===0||e.length!==t.length)return 0;let n=Pa(e,t),i=uo(t),o=r*i;return!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(i)||!Number.isFinite(o)||o===0?0:Math.max(-1,Math.min(1,n/o))}async function mo(e,t,r,n,i){if(n.length===0)return new Map;let o=se(t)??e.model,s=o===e.model?e:{...e,model:o},a=[r.trim(),...n.map(m=>m.text)],c=await Ue(s,a,i?{timeout_ms:i}:{}),d=c[0];if(!d)return new Map;let l=uo(d),u=new Map;for(let m=0;m<n.length;m+=1){let p=n[m],g=c[m+1];if(!g)continue;let _=Ha(d,g,l);u.set(p.id,Math.max(0,Math.min(1,(_+1)/2)))}return u}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a5d1f401-e5eb-5b6e-8b5a-d8135128f44b")}catch{}})();function oe(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function N(e){return Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null&&typeof t.text=="string"):[]}function be(e){return Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null&&typeof t.id=="string"&&typeof t.kind=="string"):[]}function Qt(e){let t=e.metadata;return[t.title,t.description,t.status,oe(t.tags).join(" "),e.body,N(t.comments).map(r=>r.text).join(" "),N(t.notes).map(r=>r.text).join(" "),N(t.learnings).map(r=>r.text).join(" "),Ge(t).join(" "),$e(t).join(" "),be(t.dependencies).map(r=>`${r.id} ${r.kind}`).join(" "),Be(t)]}function Yt(e,t){return Qt(e).some(r=>T(r).includes(t))}function Xt(e,t,r){return!r.titleExact&&!r.phraseExact?e:e.filter(n=>!(r.titleExact&&T(n.metadata.title)!==t||r.phraseExact&&!Yt(n,t)))}function La(e){if(e&&[...e].some(t=>t.toLowerCase()==="none"||t.toLowerCase()==="null"))throw new h('--assignee no longer accepts "none" or "null".',f.USAGE)}function Oa(e,t,r){let n=ye(e.assignee,{label:"--assignee"});La(n);let i=ti(e),o=ri(e);return{typeFilter:Bn(e.type,t),tagFilter:ye(e.tag,{label:"--tag",normalize:s=>s.toLowerCase()}),priorityFilter:Wn(e.priority),deadlineBefore:jt(e.deadlineBefore,"deadline-before"),deadlineAfter:jt(e.deadlineAfter,"deadline-after"),updatedAfter:Q(e.updatedAfter,"updated-after"),updatedBefore:Q(e.updatedBefore,"updated-before"),createdAfter:Q(e.createdAfter,"created-after"),createdBefore:Q(e.createdBefore,"created-before"),assigneeFilter:n,sprintFilter:ye(e.sprint,{label:"--sprint"}),releaseFilter:ye(e.release,{label:"--release"}),parentFilter:e.parent?.trim(),statusSet:r&&r.length>0?new Set(r):void 0,missingMetadataFilters:i,missingMetadataActive:zn(i),contentFieldFilters:o,contentFiltersActive:Kn(o)}}function ja(e,t){return qa(e,t)&&Kr(e,t)&&Na(e,t)}function qa(e,t){if(t.statusSet&&!t.statusSet.has(e.status)||t.typeFilter&&!t.typeFilter.has(e.type))return!1;let r=t.tagFilter;return!(r&&!oe(e.tags).some(n=>r.has(n))||t.priorityFilter!==void 0&&!t.priorityFilter.has(e.priority))}function Na(e,t){return!(t.assigneeFilter!==void 0&&(e.assignee===void 0||!t.assigneeFilter.has(e.assignee))||t.sprintFilter!==void 0&&(e.sprint===void 0||!t.sprintFilter.has(e.sprint))||t.releaseFilter!==void 0&&(e.release===void 0||!t.releaseFilter.has(e.release))||t.parentFilter!==void 0&&e.parent!==t.parentFilter)}function Ua(e,t,r,n){let i=e.metadata;return!(!ja(i,t)||!Mn(i,r)||t.missingMetadataActive&&!Vn(i,t.missingMetadataFilters,n)||t.contentFiltersActive&&!Qn(i,t.contentFieldFilters))}function Jt(e,t,r,n,i,o){let s=Oa(t,r,i);return e.filter(a=>Ua(a,s,n,o))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a3f9e7fa-7ebf-5fc7-93a4-f12cff30f4ff")}catch{}})();var Ga=2,$a=120,Ba=6,Wa=40,za=1e3,Va=900,Ka="\xAB",Qa="\xBB",fo=60;function et(e,t){let r=0,n=0;for(;;){let i=e.indexOf(t,n);if(i<0)return r;r+=1,n=i+t.length}}var ho=[{name:"title",weightKey:"title_weight",value:e=>e.metadata.title},{name:"description",weightKey:"description_weight",value:e=>e.metadata.description},{name:"tags",weightKey:"tags_weight",value:e=>oe(e.metadata.tags).join(" ")},{name:"status",weightKey:"status_weight",value:e=>typeof e.metadata.status=="string"?e.metadata.status:""},{name:"body",weightKey:"body_weight",value:e=>e.body},{name:"comments",weightKey:"comments_weight",value:e=>N(e.metadata.comments).map(t=>t.text).join(" ")},{name:"notes",weightKey:"notes_weight",value:e=>N(e.metadata.notes).map(t=>t.text).join(" ")},{name:"learnings",weightKey:"learnings_weight",value:e=>N(e.metadata.learnings).map(t=>t.text).join(" ")},{name:"reminders",weightKey:"reminders_weight",value:e=>Ge(e.metadata).join(" ")},{name:"events",weightKey:"events_weight",value:e=>$e(e.metadata).join(" ")},{name:"dependencies",weightKey:"dependencies_weight",value:e=>be(e.metadata.dependencies).map(t=>`${t.id} ${t.kind}`).join(" ")},{name:"plan",weightKey:"body_weight",value:e=>Be(e.metadata)}],Ya=new Map(ho.map(e=>[e.name,e]));function Zt(e,t){let r=t.filter(i=>i.length>0).sort((i,o)=>o.length-i.length).map(i=>i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"));if(r.length===0)return e;let n=new RegExp(r.join("|"),"gi");return e.replace(n,i=>`${Ka}${i}${Qa}`)}function er(e,t){if(e.length===0)return null;let r=e.toLowerCase(),n=-1,i=0;for(let l of t){if(l.length===0)continue;let u=r.indexOf(l);u>=0&&(n<0||u<n)&&(n=u,i=l.length)}if(n<0)return null;let o=Math.max(0,n-fo),s=Math.min(e.length,n+i+fo),a=Zt(e.slice(o,s),t),c=o>0?"\u2026":"",d=s<e.length?"\u2026":"";return`${c}${a}${d}`}function tt(e,t,r){let n=[];for(let i of t){let o=Ya.get(i);if(o===void 0)continue;let s=er(o.value(e),r);s!==null&&n.push({field:i,snippet:s})}return n}function Xa(e,t,r){return[...ho.map(n=>({name:n.name,value:n.value(e),weight:r[n.weightKey]})),{name:"linked_content",value:t,weight:r.linked_content_weight}]}function Ja(e,t,r){let n=T(e.id),i=typeof r=="string"?r.trim().toLowerCase():"",o=T(i),s=o.length>0&&n.startsWith(o)?n.slice(o.length).trim():n;return t!==n&&t!==s?null:{item:e,score:t===n?za:Va,matched_fields:["id"],matched_all_terms:!0,exact_id_match:!0}}function Za(e,t,r,n,i){for(let o of e){let s=t.get(o)??0;s>0&&(i.score+=s*n.title_exact_bonus,i.matched.add("title"),i.matchedTokens.add(o));for(let a of r){let c=et(a.value.toLowerCase(),o);c>0&&(i.score+=c*a.weight,i.matched.add(a.name),i.matchedTokens.add(o))}}}function ec(e,t,r,n){T(e.title)===t&&(n.score+=$a,n.matched.add("title"));for(let i of r){let o=et(T(i.value),t);o>0&&(n.score+=o*i.weight*Ba,n.matched.add(i.name))}}function tr(e,t,r,n,i,o,s=!1){let a=e.metadata,c=Ja(a,r,o);if(c)return c;let d=new Map;for(let g of ee(a.title))d.set(g,(d.get(g)??0)+1);let l=Xa(e,n,i),u={score:0,matched:new Set,matchedTokens:new Set};Za(t,d,l,i,u);let m=new Set(t),p=m.size>0&&u.matchedTokens.size===m.size;return s&&m.size>1&&p&&(u.score+=Wa),t.length>=Ga&&r.includes(" ")&&ec(a,r,l,u),u.score<=0?null:{item:a,score:u.score,matched_fields:[...u.matched].sort((g,_)=>g.localeCompare(_)),matched_all_terms:p}}function rr(e,t){return[...e].sort((r,n)=>{let i=n.score-r.score;if(i!==0)return i;let o=ce(r.item.status,t),s=ce(n.item.status,t);if(o!==s)return o?1:-1;let a=r.item.priority-n.item.priority;if(a!==0)return a;let c=Vr(n.item.updated_at,r.item.updated_at);return c!==0?c:r.item.id.localeCompare(n.item.id)})}function nr(e,t,r,n,i,o,s,a=!1){return tr(e,t,r,n?i.get(e.metadata.id)??"":"",o,s,a)}function ve(e){if(e.size===0)return new Map;let t=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY;for(let i of e.values())t=Math.min(t,i),r=Math.max(r,i);if(r===t)return new Map([...e.keys()].map(i=>[i,1]));let n=new Map;for(let[i,o]of e)n.set(i,(o-t)/(r-t));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]="c8484fbd-5fb2-56aa-9d69-26646be262a9")}catch{}})();function nt(e){let t=[],r=e;for(let n=0;n<5&&r&&typeof r=="object";n+=1){let i=r.code;typeof i=="string"&&t.push(i.toLowerCase()),r=r.cause}return t.join(" ")}function it(e){let t=(e instanceof Error?e.message:String(e)).toLowerCase(),r=nt(e),n=`${t} ${r}`;return n.includes("timed out")||n.includes("timeout")||n.includes("etimedout")?"timeout":n.includes("econnrefused")||n.includes("connection refused")||n.includes("connect ")||n.includes("enotfound")||n.includes("eai_again")||n.includes("econnreset")||n.includes("fetch failed")?"connection":"error"}function ir(e,t){let r=it(t);return`search_${e}_fallback:${r}:using_keyword_mode`}function po(e){return e?.commands?.some(t=>t.command.trim()==="reindex")===!0?{command:"pm reindex --mode hybrid",args:["reindex","--mode","hybrid"]}:{command:"pm install search-advanced --project",args:["install","search-advanced","--project"],follow_up_command:"pm reindex --mode hybrid",follow_up_args:["reindex","--mode","hybrid"]}}async function or(e,t,r){try{let n=await jn(e);n.warnings.length>0&&r.push(...n.warnings);let i=oi(t.map(s=>({id:s.metadata.id,updated_at:s.metadata.updated_at})),n.entries);if(i.length===0)return;let o=po(A());r.push(...yo(i.length,o)),process.stderr.write(`[pm] warning: ${i.length} item${i.length===1?" is":"s are"} new or modified since the last reindex and ${i.length===1?"is":"are"} NOT in the semantic index yet \u2014 run '${o.command}'${o.follow_up_command?`, then '${o.follow_up_command}'`:""}. (Write-time embedding is governed by search.mutation_refresh_policy; staleness means the embed was skipped, failed, or the backend was unreachable.)
|
|
3
3
|
`)}catch{}}function yo(e,t){return[`vector_index_stale:${e}`,`vector_index_recovery:${t.args.join(" ")}`,...t.follow_up_args?[`vector_index_recovery_follow_up:${t.follow_up_args.join(" ")}`]:[]]}function ot(e,t,r,n){if(!t.active)throw new h(`Search mode '${e}' requires a configured embedding provider in settings.providers.openai or settings.providers.ollama`,f.USAGE);if(!r.active&&!n)throw new h(`Search mode '${e}' requires a configured vector store in settings.vector_store.qdrant/settings.vector_store.lancedb or an extension adapter selected by settings.vector_store.adapter`,f.USAGE);return{provider:t.active,vectorStore:r.active??null}}var M=Re;function Ee(e){let t=A(),r=kn(t,e);if(!r)return null;let n=r.runtime_definition??r.definition,i=n.query,o=n.queryExpansion??n.query_expansion,s=n.rerank,a=M(n.name)??M(r.definition.name)??e;if(!a)return null;let c={providerName:a,...typeof i=="function"?{query:i}:{},...typeof o=="function"?{queryExpansion:o}:{},...typeof s=="function"?{rerank:s}:{}};return!c.query&&!c.queryExpansion&&!c.rerank?null:c}function sr(e){let t=M(e.search?.provider),r=Ee(t);return r?.query?{providerName:r.providerName,query:r.query}:null}function ar(e){let t=A(),r=M(e.vector_store?.adapter),n=xn(t,r);if(!n)return null;let i=n.runtime_definition??n.definition,o=i.query;if(typeof o!="function")return null;let s=i.upsert;return{adapterName:M(i.name)??M(n.definition.name)??r??"extension",query:o,...typeof s=="function"?{upsert:s}:{}}}function cr(e,t,r){let n=Array.isArray(t)?t:t?.hits;if(!Array.isArray(n))throw new h(`Extension search provider "${e}" must return an array of hits or { hits: [...] }`,f.GENERIC_FAILURE);let i=new Set,o=[];for(let s of n){if(typeof s!="object"||s===null)continue;let a=M(s.id),c=s.score;if(!a||typeof c!="number"||!Number.isFinite(c)||i.has(a))continue;let d=r.get(a);if(!d)continue;let l=s.matched_fields,u=Array.isArray(l)&&l.every(m=>typeof m=="string")?[...new Set(l.map(m=>m.trim()).filter(m=>m.length>0))].sort((m,p)=>m.localeCompare(p)):[`provider:${e}`];i.add(a),o.push({item:d.metadata,score:c,matched_fields:u})}return o}function lr(e,t){let r=[],n=new Map;for(let i of e){if(n.has(i.id))continue;let o=t.get(i.id);o&&(n.set(i.id,i.score),r.push({item:o.metadata,score:i.score,matched_fields:["semantic"]}))}return{semanticHits:r,semanticScores:n}}function rt(e,t){let r=t.filter(c=>c.exact_id_match===!0);if(r.length===0)return e;let n=new Set(r.map(c=>c.item.id)),i=e.filter(c=>!n.has(c.item.id)),o=i.reduce((c,d)=>Math.max(c,d.score),0),s=r.sort((c,d)=>d.score-c.score),a=o+s.length+1;return[...s.map((c,d)=>({...c,score:a-d,matched_fields:["id"]})),...i]}function st(e,t,r,n,i="semantic"){let o=new Map(r.map(u=>[u.item.id,u.score])),s=new Map(r.map(u=>[u.item.id,u.matched_fields])),a=ve(t),c=ve(o),d=new Set([...t.keys(),...o.keys()]),l=1-n;return[...d].map(u=>{let m=e.get(u),p=a.get(u)??0,g=c.get(u)??0,_=p*n+g*l;if(_<=0)return null;let y=new Set;t.has(u)&&y.add(i);for(let w of s.get(u)??[])y.add(w);return{item:m.metadata,score:_,matched_fields:[...y].sort((w,v)=>w.localeCompare(v))}}).filter(u=>u!==null)}function dr(e){let t=e.configuredProvider?.trim().toLowerCase();return t==="bm25"?"explicit":t==="auto"&&!e.hasEmbeddingProvider&&!e.hasExtensionSearchProvider?"auto-fallback":null}function ur(e){let t=e.filteredDocuments.map(s=>({id:s.metadata.id,text:ro(Ln(s,{fields:e.corpusFields}))})),r=eo(t),n=to(r,zt(e.query),e.bm25Params),i=new Map(e.filteredDocuments.map(s=>[s.metadata.id,s]));if(e.requestedMode==="semantic"){let s=[...n].map(([a,c])=>({item:i.get(a).metadata,score:c,matched_fields:["bm25"]}));return rt(s,e.keywordHits)}let o=st(i,n,e.keywordHits,e.hybridSemanticWeight,"bm25");return rt(o,e.keywordHits)}function mr(e){let t=new Map;for(let n of e)for(let i of n){let o=t.get(i.id);(!o||i.score>o.score)&&t.set(i.id,i)}let r=[...t.values()];return r.sort((n,i)=>n.score!==i.score?i.score-n.score:n.id.localeCompare(i.id)),r}function fr(e){let t=e.metadata,r=Array.isArray(t?.tags)?t.tags.join(" "):"";return[t?.title,t?.description,t?.type,t?.status,r,e.body].map(n=>typeof n=="string"?n.trim():"").filter(n=>n.length>0).join(`
|
|
4
4
|
`)}async function tc(e,t){let r=e.queryExpansion.enabled?io(t,e.queryExpansion.max_queries):[t],n=r.length>0?r:[t];if(!e.queryExpansion.enabled)return n;if(e.queryExpansionExtension?.expand)try{let i=await Promise.resolve(e.queryExpansionExtension.expand({query:t,mode:e.requestedMode,settings:e.settings}));return so(n,oo(i),e.queryExpansion.max_queries)}catch{return e.warnings.push(`search_query_expansion_provider_failed:${e.queryExpansionExtension.providerName}:using_builtin`),n}return e.queryExpansion.provider&&e.queryExpansion.provider!=="openai"&&e.queryExpansion.provider!=="ollama"&&e.warnings.push(`search_query_expansion_provider_unavailable:${e.queryExpansion.provider}:using_builtin`),n}async function rc(e,t,r,n){if(e.extensionVectorAdapter?.query)try{return await Promise.resolve(e.extensionVectorAdapter.query({vector:t,limit:r,settings:e.settings}))}catch(i){if(!e.vectorStore)throw new h(`Extension vector adapter query failed and no built-in fallback store is configured (${i instanceof Error?i.message:String(i)})`,f.GENERIC_FAILURE);return e.warnings.push(`search_vector_adapter_failed:${e.extensionVectorAdapter.adapterName}:using_builtin`),await wt(e.vectorStore,t,r,n)}if(e.vectorStore)return await wt(e.vectorStore,t,r,n);throw new h("Semantic search requires either a configured vector store or an extension vector adapter query handler",f.USAGE)}function nc(e,t,r){return[...e].sort((n,i)=>n.score!==i.score?i.score-n.score:n.item.id.localeCompare(i.item.id)).slice(0,r).map(n=>{let i=t.get(n.item.id);return i?{hit:n,text:fr(i)}:null}).filter(n=>n!==null)}async function ic(e,t,r){if(!e.rerankExtension?.rerank)return null;try{let n=await Promise.resolve(e.rerankExtension.rerank({query:t,mode:"hybrid",model:e.rerank.model,top_k:e.rerank.top_k,settings:e.settings,candidates:r.map(o=>({id:o.hit.item.id,text:o.text,score:o.hit.score}))})),i=lo(n);return i.length>0?new Map(i.map(o=>[o.id,o.score])):(e.warnings.push(`search_rerank_provider_invalid_response:${e.rerankExtension.providerName}:using_builtin`),null)}catch{return e.warnings.push(`search_rerank_provider_failed:${e.rerankExtension.providerName}:using_builtin`),null}}async function oc(e,t,r){let n=await ic(e,t,r);if(n)return n;let i=r.map(o=>({id:o.hit.item.id,text:o.text}));try{return await mo(e.provider,e.rerank.model,t,i,e.embeddingTimeoutMs)}catch{return e.warnings.push("search_rerank_failed:using_hybrid_scores"),null}}function sc(e,t){let r=new Set(t.keys()),n=e.map(i=>{let o=t.get(i.item.id);if(o===void 0)return i;let s=new Set(i.matched_fields);return s.add("rerank"),{...i,score:o,matched_fields:[...s].sort((a,c)=>a.localeCompare(c))}});return n.sort((i,o)=>{let s=r.has(i.item.id),a=r.has(o.item.id);return s!==a?s?-1:1:i.score!==o.score?o.score-i.score:i.item.id.localeCompare(o.item.id)}),n}async function ac(e,t,r,n){if(!e.rerank.enabled||r.length<=1)return r;let i=nc(r,n,e.rerank.top_k),o=await oc(e,t,i);return o&&o.size>0?sc(r,o):r}async function hr(e){let t=Math.max(e.limit??e.maxResults,e.maxResults),r=e.embeddingTimeoutMs!==void 0?{timeout_ms:e.embeddingTimeoutMs}:{},n=e.vectorQueryTimeoutMs!==void 0?{timeout_ms:e.vectorQueryTimeoutMs}:{},i=e.query.trim(),o=await tc(e,i),s=await Ue(e.provider,o,r),a=await Promise.all(s.map(async g=>await rc(e,g,t,n))),c=mr(a),d=new Map(e.filteredDocuments.map(g=>[g.metadata.id,g])),{semanticHits:l,semanticScores:u}=lr(c,d),m=u.size;if(e.requestedMode==="semantic")return{hits:rt(l,e.keywordHits),vectorMatchCount:m};let p=await ac(e,i,st(d,u,e.keywordHits,e.hybridSemanticWeight),d);return{hits:rt(p,e.keywordHits),vectorMatchCount:m}}function go(e){let t=Ee(e.provider??void 0);return t?.queryExpansion?{providerName:t.providerName,expand:t.queryExpansion}:null}function _o(e){let t=Ee(M(e.search?.provider));return t?.rerank?{providerName:t.providerName,rerank:t.rerank}:null}import at from"node:fs/promises";import pr 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]="de9a1cbd-f277-52ef-adc6-66225f2d2f4f")}catch{}})();function yr(e){let t=(e.files??[]).map(s=>({scope:s.scope,path:s.path.trim()})),r=(e.docs??[]).map(s=>({scope:s.scope,path:s.path.trim()})),n=(e.tests??[]).filter(s=>typeof s.path=="string"&&s.path.trim().length>0).map(s=>({scope:s.scope,path:s.path.trim()})),i=[...t,...r,...n].filter(s=>s.path.length>0).sort((s,a)=>s.scope.localeCompare(a.scope)||s.path.localeCompare(a.path)),o=new Map;for(let s of i)o.set(`${s.scope}:${s.path}`,s);return[...o.values()]}async function wo(e){let t=pr.resolve(e);try{let r=await at.realpath(t);return{resolved:t,realpath:r}}catch{return null}}async function gr(e,t){let[r,n]=await Promise.all([wo(e),wo(t)]);return{projectContainmentRoot:r,globalContainmentRoot:n}}async function _r(e,t){let r=yr(e.metadata),n=[];for(let i of r){let o=i.scope==="global"?t.globalContainmentRoot:t.projectContainmentRoot;if(!o)continue;let s=pr.resolve(o.resolved,i.path);if(!lt(o.resolved,s))continue;let a;try{a=await at.realpath(s)}catch{continue}if(lt(o.realpath,a))try{await ae({path:s,scope:i.scope}),n.push(await at.readFile(s,"utf8"))}catch{}}return n.join(`
|
|
5
5
|
`)}async function wr(e,t,r,n){let i=yn(A()),o=async(d,l,u)=>{let m=async(p,g)=>{await ae({path:p,scope:"project"});let _=await at.readFile(p,"utf8");return Jr(_,{format:g,schema:n,extensionFieldNames:i,onWarning:y=>s.push(y)}).body};try{return await m(l,u)}catch{let p=u==="toon"?"json_markdown":"toon",g=z(e,d.type,d.id,p,r);try{return await m(g,p)}catch{return s.push(`item_list_item_read_failed:${pr.relative(e,g)}`),""}}},s=[],a=await gn(e,t,r,s,n),c=[];if(a.length===0){let d=await wn(e,t,r,s,n);for(let l of d){let u=z(e,l.type,l.id,t,r),m=await o(l,u,t);c.push({metadata:l,body:m})}return{documents:c,warnings:[...new Set(s)].sort((l,u)=>l.localeCompare(u))}}for(let d of a){if(typeof d.body=="string"){c.push({metadata:d.metadata,body:d.body});continue}let l=await o(d.metadata,d.item_path,d.item_format);c.push({metadata:d.metadata,body:l})}return{documents:c,warnings:[...new Set(s)].sort((d,l)=>d.localeCompare(l))}}async function bo(e,t,r){let n=new Map;if(!e||t!=="keyword"&&t!=="hybrid")return n;let i=process.cwd(),o=await gr(i,jr(i)),s=await Promise.all(r.map(async a=>[a.metadata.id,await _r(a,o)]));for(let[a,c]of s)n.set(a,c);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]="17122985-4157-5732-9142-444327cb273d")}catch{}})();var vo=["tag","status","type","priority"];function br(e){let t={},r=[];for(let n of e.split(/\s+/).filter(i=>i.length>0)){let i=n.indexOf(":"),o=i>0?n.slice(0,i).toLowerCase():"",s=i>0?n.slice(i+1):"",a=vo.includes(o)?o:void 0;if(a&&s.length>0&&t[a]===void 0){t[a]=s;continue}r.push(n)}return{residualQuery:r.join(" "),inlineFilters:t}}function vr(e,t,r){let n={...e};for(let i of vo){let o=t[i];if(o!==void 0){if(Re(n[i])!==void 0){r.push(`search_inline_filter_ignored:${i}:flag_takes_precedence`);continue}n[i]=o}}return n}function Eo(e,t){let r=[],n=br(e),i=Object.keys(n.inlineFilters).length>0;if(i&&n.residualQuery.trim().length===0)throw new h("Inline field:value tokens consumed the entire query, leaving no search terms.",f.USAGE,{examples:["pm search auth tag:area:search","pm list --tag area:search --status open"],nextSteps:["Add keyword terms alongside the inline filters, or use pm list for pure tag/status/type/priority filtering."]});let o=i?n.residualQuery:e,s=vr(t,n.inlineFilters,r);return{query:o,options:s,inlineWarnings:r,highlight:s.highlight===!0,includeLinked:Xe(s.includeLinked),titleExact:Xe(s.titleExact),phraseExact:Xe(s.phraseExact),matchMode:Qi(typeof s.matchMode=="string"?s.matchMode:void 0),minScoreOverride:Yi(s.minScore),countOnly:s.count===!0,tokens:Ze(o),normalizedQuery:T(o),limit:Ne(s.limit),projection:Je(s,e),modeWasExplicit:typeof s.mode=="string"&&s.mode.trim().length>0}}function So(e){if(e.after!==void 0&&e.count===!0)throw new h("Search --after cannot be combined with --count.",f.USAGE)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d7beacb7-66a5-581f-93f0-68ceb4b8e41e")}catch{}})();function Sr(e,t,r,n,i,o,s,a,c,d,l,u,m,p){let g=m?{total:0,count_only:!0}:{};if(d.mode==="compact"&&n.compact===!0){let y=ne({mode:t,matchMode:r,options:n,includeLinked:i,titleExact:n.titleExact===!0,phraseExact:n.phraseExact===!0,scoreThreshold:o,hybridSemanticWeight:s,runtimeFieldFilters:u});return{query:e.trim(),mode:t,...Rr(p),items:[],count:0,...g,filters:y,...l.length>0?{warnings:l}:{}}}let _=d.mode==="full"?null:[...d.fields];return{query:e.trim(),mode:t,mode_source:p,items:[],count:0,...g,filters:ie({effectiveMode:t,matchMode:r,options:n,includeLinked:i,titleExact:n.titleExact===!0,phraseExact:n.phraseExact===!0,scoreThreshold:o,hybridSemanticWeight:s,queryExpansion:a,rerank:c,runtimeFieldFilters:u??{}}),projection:{mode:d.mode,fields:_},now:I(),...l.length>0?{warnings:l}:{}}}function Ir(e,t){let r=t.trim();if(r.length===0)return null;if(r==="score")return e.score;if(r==="matched_fields")return e.matched_fields;if(r.startsWith("item.")){let o=r.slice(5);return o.length===0?null:e.item[o]??null}let n=e,i=e.item;return Object.prototype.hasOwnProperty.call(i,r)?i[r]??null:Object.prototype.hasOwnProperty.call(n,r)?n[r]??null:null}function kr(e,t){return t.mode==="full"?e.map(({matched_all_terms:r,exact_id_match:n,...i})=>i):e.map(r=>{let n={};for(let i of t.fields)n[i]=Ir(r,i);return n})}function xr(e,t){return Sr(e.query,e.effectiveMode,e.matchMode,e.options,e.includeLinked,e.scoreThreshold,e.hybridSemanticWeight,e.queryExpansion,e.rerank,e.projection,e.warnings,e.runtimeFieldFilters,t,e.modeSource)}function Io(e,t){if(e.projection.mode==="compact"&&e.options.compact===!0)return Er({query:e.query.trim(),mode:e.effectiveMode,...Rr(e.modeSource),items:[],count:t,total:t,count_only:!0,filters:ne({mode:e.effectiveMode,matchMode:e.matchMode,options:e.options,includeLinked:e.includeLinked,titleExact:e.titleExact,phraseExact:e.phraseExact,scoreThreshold:e.scoreThreshold,hybridSemanticWeight:e.hybridSemanticWeight,runtimeFieldFilters:e.runtimeFieldFilters})},e.warnings);let r=e.projection.mode==="full"?null:[...e.projection.fields];return Er({query:e.query.trim(),mode:e.effectiveMode,mode_source:e.modeSource,items:[],count:t,total:t,count_only:!0,filters:ie({effectiveMode:e.effectiveMode,matchMode:e.matchMode,options:e.options,includeLinked:e.includeLinked,titleExact:e.titleExact,phraseExact:e.phraseExact,scoreThreshold:e.scoreThreshold,hybridSemanticWeight:e.hybridSemanticWeight,queryExpansion:e.queryExpansion,rerank:e.rerank,runtimeFieldFilters:e.runtimeFieldFilters}),projection:{mode:e.projection.mode,fields:r},now:I()},e.warnings)}function Rr(e){return e==="settings"?{mode_source:e}:{}}function Er(e,t){return t.length===0?e:{...e,warnings:t}}function Se(e,t){return t?{...e,workspace_memory:t}:e}function ko(e,t,r){if(!e.highlight)return{hits:r,projection:e.projection};let n=new Map(t.map(o=>[o.metadata.id,o])),i=r.map(o=>({...o,highlights:tt(n.get(o.item.id),o.matched_fields,e.tokens)}));return e.projection.mode==="full"||e.projection.fields.includes("highlights")?{hits:i,projection:e.projection}:{hits:i,projection:{mode:e.projection.mode,fields:[...e.projection.fields,"highlights"]}}}function xo(e,t,r,n,i,o){let s=n<r?{total:r}:{};if(e.projection.mode==="compact"&&e.options.compact===!0)return Er({query:e.query.trim(),mode:e.effectiveMode,...Rr(e.modeSource),items:t,count:t.length,...s,...o,filters:ne({mode:e.effectiveMode,matchMode:e.matchMode,options:e.options,includeLinked:e.includeLinked,titleExact:e.titleExact,phraseExact:e.phraseExact,scoreThreshold:e.scoreThreshold,hybridSemanticWeight:e.hybridSemanticWeight,runtimeFieldFilters:e.runtimeFieldFilters})},e.warnings);let a=i.mode==="full"?null:[...i.fields];return{query:e.query.trim(),mode:e.effectiveMode,mode_source:e.modeSource,items:t,count:t.length,...s,...o,filters:ie({effectiveMode:e.effectiveMode,matchMode:e.matchMode,options:e.options,includeLinked:e.includeLinked,titleExact:e.titleExact,phraseExact:e.phraseExact,scoreThreshold:e.scoreThreshold,hybridSemanticWeight:e.hybridSemanticWeight,queryExpansion:e.queryExpansion,rerank:e.rerank,runtimeFieldFilters:e.runtimeFieldFilters}),projection:{mode:i.mode,fields:a},now:I(),...e.warnings.length>0?{warnings:e.warnings}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3bfd872f-6ed7-551c-a027-3748493de3e9")}catch{}})();var rf={applyFilters:Jt,applyExactQueryFilters:Xt,applyInlineQueryFilters:vr,buildHitHighlights:tt,buildVerboseSearchFilters:ie,buildExplicitSemanticFallbackWarning:ir,buildCompactSearchFilterSummary:ne,buildHybridLexicalScore:nr,buildRerankCorpus:fr,buildSemanticHits:lr,classifyImplicitSemanticFallbackReason:it,collectErrorCauseCodes:nt,collectExactPhraseFields:Qt,collectLinkedPaths:yr,combineHybridHits:st,computeBuiltInBm25Hits:ur,computeSemanticOrHybridHits:hr,resolveBuiltInBm25Mode:dr,countOccurrences:et,dependencyEntries:be,documentContainsExactPhrase:Yt,emptySearchResult:Sr,highlightFieldSnippet:er,loadDocuments:wr,markTokenRuns:Zt,parseInlineQueryFilters:br,maybeEmitVectorIndexStaleWarning:or,loadLinkedCorpus:_r,mergeVectorHitsById:mr,normalizeExtensionProviderHits:cr,normalizeScoreMap:ve,parseProjectionConfig:Je,parseTimestampWindow:Q,parseTokens:Ze,projectSearchHits:kr,readSearchFieldValue:Ir,requireSemanticDependencies:ot,resolveExtensionSearchProvider:sr,resolveExtensionSearchProviderByName:Ee,resolveExtensionVectorAdapter:ar,resolveLinkedCorpusRoots:gr,scoreDocument:tr,sortHits:rr,stringArray:oe,textEntries:N,validateSearchProjectionFields:qt};async function cc(e,t){let r=k(process.cwd(),t.path);await P(r);let n=await L(r),i=Fn(n).settings,o=j(i.schema),s=J(i.schema);qt(e.projection,s,e.query);let a=Tn(e.options,s,"search"),c=U(i,A()),d=Pn(i),l=On(i,r),u=sr(i),m=ar(i),p=Ki(e.options.semanticWeight),g=ao(i,d.active?.name??null),_=co(i,d.active?.model??M(i.search?.embedding_model)??"text-embedding-3-small");return{pmRoot:r,settings:i,statusRegistry:o,runtimeFieldRegistry:s,runtimeFieldFilters:a,typeRegistry:c,maxResults:Nt(i),scoreThreshold:e.minScoreOverride??Gt(i),semanticWeightProvided:e.options.semanticWeight!==void 0,semanticWeightOverride:p,hybridSemanticWeight:p??$t(i),tuning:Bt(i),providerResolution:d,vectorResolution:l,extensionSearchProvider:u,extensionVectorAdapter:m,bm25Mode:dr({configuredProvider:M(i.search?.provider),hasEmbeddingProvider:d.active!==null,hasExtensionSearchProvider:u!==null}),queryExpansion:g,queryExpansionExtension:go(g),rerank:_,rerankExtension:_o(i),...lc({requested:e.options.mode,settings:i,configuredProvider:n.search?.provider??null,providerResolution:d,vectorResolution:l,extensionSearchProvider:u,extensionVectorAdapter:m})}}function lc(e){let t=Dn(e.providerResolution.active?.name,e.configuredProvider)==="configured"&&(e.vectorResolution.active!==null||e.extensionVectorAdapter!==null),r=e.extensionSearchProvider!==null||t,n=Ut({requested:e.requested,settings:e.settings,semanticRunnable:r});return{effectiveMode:n.mode,modeSource:n.source}}async function dc(e,t){let r=await wr(t.pmRoot,t.settings.item_format??"toon",t.typeRegistry.type_to_folder,t.settings.schema),n=qe(typeof e.options.status=="string"?e.options.status:void 0,t.statusRegistry,{strict:!0}),i=We(t.statusRegistry),o=Jt(r.documents,e.options,t.typeRegistry,t.runtimeFieldFilters,n,i);return{warnings:r.warnings,allDocuments:r.documents,filteredDocuments:Xt(o,e.normalizedQuery,{titleExact:e.titleExact,phraseExact:e.phraseExact||e.matchMode==="exact"})}}async function uc(e,t,r){let n=await bo(e.includeLinked,t.effectiveMode,r),i=e.matchMode==="or";return r.map(o=>nr(o,e.tokens,e.normalizedQuery,e.includeLinked,n,t.tuning,t.settings.id_prefix,i)).filter(o=>o!==null).filter(o=>e.matchMode!=="and"||o.matched_all_terms===!0)}async function mc(e,t,r,n,i){if(t.bm25Mode===null||t.effectiveMode==="keyword")return null;let o=ur({requestedMode:t.effectiveMode,query:e.query,filteredDocuments:r,keywordHits:n,corpusFields:Hn(t.settings),bm25Params:no(t.settings),hybridSemanticWeight:t.hybridSemanticWeight});return t.bm25Mode==="auto-fallback"&&i.push(`search_${t.effectiveMode}_offline_bm25:no_embedding_provider:using_lexical_bm25`),o}async function fc(e,t,r,n){if(!t.extensionSearchProvider)return null;let i=t.providerResolution.active!==null&&(t.vectorResolution.active!==null||t.extensionVectorAdapter!==null);try{let o=await Promise.resolve(t.extensionSearchProvider.query({query:e.query,mode:t.effectiveMode,tokens:e.tokens,options:e.options,settings:t.settings,documents:r}));return cr(t.extensionSearchProvider.providerName,o,n)}catch(o){if(!i)throw new h(`Extension search provider "${t.extensionSearchProvider.providerName}" failed: ${o instanceof Error?o.message:String(o)}`,f.GENERIC_FAILURE);return null}}function hc(e,t,r,n){return t.vectorMatchCount>0?t.hits:(n.push(`search_${e}_degraded:no_vector_matches:results_are_lexical`),e==="semantic"?r:t.hits)}async function pc(e,t,r,n,i){let o=!e.extensionSearchProvider&&e.providerResolution.active!==null&&(e.vectorResolution.active!==null||e.extensionVectorAdapter!==null);i&&o&&await or(e.pmRoot,r,n),e.extensionSearchProvider||ot(t,e.providerResolution,e.vectorResolution,e.extensionVectorAdapter!==null)}async function yc(e){let{prepared:t,runtime:r,filteredDocuments:n,keywordHits:i,warnings:o,modeWasExplicit:s}=e,a=i,c=await mc(t,r,n,i,o),d=r.effectiveMode;if(c!==null||d==="keyword")return{effectiveMode:r.effectiveMode,hits:c??a};try{if(await pc(r,d,n,o,s),n.length===0||t.limit===0)return{effectiveMode:r.effectiveMode,hits:[]};let l=new Map(n.map(u=>[u.metadata.id,u]));if(a=await fc(t,r,n,l)??a,a===i){let{provider:u,vectorStore:m}=ot(d,r.providerResolution,r.vectorResolution,r.extensionVectorAdapter!==null),p=await hr({requestedMode:d,query:t.query,filteredDocuments:n,keywordHits:i,hybridSemanticWeight:r.hybridSemanticWeight,limit:t.limit,maxResults:r.maxResults,provider:u,vectorStore:m,extensionVectorAdapter:r.extensionVectorAdapter,queryExpansion:r.queryExpansion,queryExpansionExtension:r.queryExpansionExtension,rerank:r.rerank,rerankExtension:r.rerankExtension,warnings:o,settings:r.settings});a=hc(d,p,i,o)}return{effectiveMode:r.effectiveMode,hits:a}}catch(l){return o.push(ir(r.effectiveMode,l)),{effectiveMode:"keyword",hits:i}}}function Ro(e){e.searchOptions.after!==void 0&&Wr(e.searchOptions.after,Wt(e))}async function Co(e,t,r){So(t);let n=Eo(e,t),i=await cc(n,r),o=await dc(n,i),s=o.warnings;s.push(...n.inlineWarnings);let a=await ui(o.allDocuments.map(b=>b.metadata),{pmRoot:i.pmRoot,statusRegistry:i.statusRegistry,now:I()});s.push(...a.warnings);let c=mi(a,n.query);i.effectiveMode==="hybrid"&&i.semanticWeightProvided&&i.semanticWeightOverride===void 0&&s.push("search_hybrid_semantic_weight_override_invalid:using_settings_default");let d={query:n.query,modeSource:i.modeSource,matchMode:n.matchMode,options:n.options,includeLinked:n.includeLinked,titleExact:n.titleExact,phraseExact:n.phraseExact,scoreThreshold:i.scoreThreshold,hybridSemanticWeight:i.hybridSemanticWeight,queryExpansion:i.queryExpansion,rerank:i.rerank,projection:n.projection,warnings:s,runtimeFieldFilters:i.runtimeFieldFilters};if(i.effectiveMode==="keyword"&&(o.filteredDocuments.length===0||n.limit===0&&!n.countOnly))return Ro({query:n.query,mode:i.effectiveMode,searchOptions:n.options,pmRoot:i.pmRoot}),Se(xr({...d,effectiveMode:i.effectiveMode},n.countOnly),c);let l=await uc(n,i,o.filteredDocuments),u=await yc({prepared:n,runtime:i,filteredDocuments:o.filteredDocuments,keywordHits:l,warnings:s,modeWasExplicit:n.modeWasExplicit});if(u.effectiveMode!=="keyword"&&u.hits.length===0&&(o.filteredDocuments.length===0||n.limit===0&&!n.countOnly))return Ro({query:n.query,mode:u.effectiveMode,searchOptions:n.options,pmRoot:i.pmRoot}),Se(xr({...d,effectiveMode:u.effectiveMode},n.countOnly),c);let m=u.hits.filter(b=>b.exact_id_match===!0||b.score>=i.scoreThreshold),p=rr(m,i.statusRegistry),g=p.length,_=Xi({pmRoot:i.pmRoot,sorted:p,query:n.query,mode:u.effectiveMode,searchOptions:n.options,limit:n.limit??i.maxResults}),y={...d,effectiveMode:u.effectiveMode};if(n.countOnly)return Se(Io(y,g),c);let{hits:w,projection:v}=ko(n,o.filteredDocuments,_.limited),E=kr(w,v);return Se(xo(y,E,g,_.limited.length,v,_.pageExtras),c)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f303192a-cac2-588b-b988-e3a8132f4199")}catch{}})();var Ao=["ndcg","mrr","precision","recall"];function Cr(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new TypeError("Eval minimum must be an object of metric floors");let t={};for(let[r,n]of Object.entries(e)){if(!Ao.some(i=>i===r))throw new TypeError(`Unknown eval minimum metric: ${r}`);if(typeof n!="number"||!Number.isFinite(n)||n<0||n>1)throw new TypeError(`Eval minimum.${r} must be a finite number in [0, 1]`);t[r]=n}return t}function To(e,t){let r=Cr(t),n=[];for(let i of Ao){let o=r[i];if(o===void 0)continue;let s=e[i];!Number.isFinite(s)||s<0||s>1?n.push(`${i}:invalid`):s<o&&n.push(`${i}:${s}<${o}`)}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]="c34cc860-67c7-548b-99ff-f4155ef44bb0")}catch{}})();var Fo=10,G="https://schema.unbrained.dev/pm/eval-query-set/v1",gc={schema:G,accepted_top_level:["array","object"],required_query_fields:["query","relevant_ids"],optional_fields:["mode","description","minimum"],modes:["keyword","semantic","hybrid"]},ct={schema:G,queries:[{query:"offline search",relevant_ids:["pm-75k9"],mode:"keyword"}]},F=class extends Error{constructor(t){super(t),this.name="EvalQuerySetError"}},_c=new Set(["keyword","semantic","hybrid"]);function Mo(e,t){let r=0,n=Math.min(t,e.length);for(let i=0;i<n;i+=1)r+=e[i]/Math.log2(i+2);return r}function wc(e,t,r){if(t.size===0)return 0;let n=e.map(a=>t.has(a)?1:0),i=Mo(n,r),o=Array.from({length:t.size},()=>1),s=Mo(o,r);return s===0?0:i/s}function bc(e,t,r){let n=Math.min(r,e.length);for(let i=0;i<n;i+=1)if(t.has(e[i]))return 1/(i+1);return 0}function Ar(e,t,r){let n=Math.min(r,e.length),i=0;for(let o=0;o<n;o+=1)t.has(e[o])&&(i+=1);return i}function vc(e,t,r){return r<=0?0:Ar(e,t,r)/r}function Ec(e,t,r){return t.size===0?0:Ar(e,t,r)/t.size}function Do(e,t,r){return{ndcg:wc(e,t,r),mrr:bc(e,t,r),precision:vc(e,t,r),recall:Ec(e,t,r),relevant_total:t.size,retrieved_relevant:Ar(e,t,r)}}function Po(e){let t=e.length;if(t===0)return{ndcg:0,mrr:0,precision:0,recall:0,query_count:0};let r=e.reduce((n,i)=>({ndcg:n.ndcg+i.ndcg,mrr:n.mrr+i.mrr,precision:n.precision+i.precision,recall:n.recall+i.recall}),{ndcg:0,mrr:0,precision:0,recall:0});return{ndcg:r.ndcg/t,mrr:r.mrr/t,precision:r.precision/t,recall:r.recall/t,query_count:t}}function Sc(e,t){if(typeof e!="object"||e===null)throw new F(`Eval query at index ${t} must be an object`);let r=e,n=typeof r.query=="string"?r.query.trim():"";if(n.length===0)throw new F(`Eval query at index ${t} must have a non-empty "query" string`);if(!Array.isArray(r.relevant_ids))throw new F(`Eval query at index ${t} must have a "relevant_ids" array`);if(r.relevant_ids.some(o=>typeof o!="string"))throw new F(`Eval query at index ${t} must have a "relevant_ids" array of strings`);let i=[...new Set(r.relevant_ids.map(o=>o.trim()).filter(o=>o.length>0))];if(i.length===0)throw new F(`Eval query at index ${t} must list at least one relevant id`);if(r.mode!==void 0&&(typeof r.mode!="string"||!_c.has(r.mode)))throw new F(`Eval query at index ${t} has an invalid mode (expected keyword|semantic|hybrid)`);return{query:n,relevant_ids:i,...r.minimum===void 0?{}:{minimum:Cr(r.minimum)},...r.mode!==void 0?{mode:r.mode}:{},...typeof r.description=="string"&&r.description.trim().length>0?{description:r.description.trim()}:{}}}function Tr(e){let t=typeof e=="object"&&e!==null&&!Array.isArray(e)?e.schema:void 0;if(t!==void 0&&t!==G)throw new F(`Unsupported eval query set schema; expected "${G}"`);let r=Array.isArray(e)?e:typeof e=="object"&&e!==null?e.queries:void 0;if(!Array.isArray(r))throw new F('Eval query set must be an array of queries or an object with a "queries" array');if(r.length===0)throw new F("Eval query set must contain at least one query");return{schema:G,queries:r.map((n,i)=>Sc(n,i))}}import Ic from"node:fs/promises";import Mr 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]="5d26721c-719a-5c7e-8baf-72cbf1088988")}catch{}})();var kc=Mr.join("search","eval-queries.json"),Fr={schema:G,examples:[JSON.stringify(ct)],nextSteps:["Create a git-tracked golden-query JSON file that follows the schema, then re-run pm eval."]},xc=new Set(["keyword","semantic","hybrid"]),Rc=e=>{if(e===void 0)return"keyword";let t=e.trim().toLowerCase();if(!xc.has(t))throw new h("Eval --mode must be one of keyword|semantic|hybrid",f.USAGE);return t},Cc=e=>{if(e===void 0||e==="")return Fo;let t=Ce(e);if(t===null)throw new h("Eval --k must be a positive integer",f.USAGE);return t},Ac=e=>{if(e===void 0||e==="")return;let t=String(e).trim(),r=Number(t);if([t.length===0,!Number.isFinite(r),r<0,r>1].includes(!0))throw new h("Eval --fail-under must be a number in the range [0, 1]",f.USAGE);return r},$=e=>Math.round(e*1e4)/1e4,Tc=async e=>{try{return await Ic.readFile(e,"utf8")}catch{throw new h(`Eval query set not found at ${e}`,f.NOT_FOUND,{...Fr,examples:[`echo '${JSON.stringify(ct)}' > ${e}`,"pm eval --queries ./my-eval.json"]})}},Mc=(e,t)=>{try{return JSON.parse(e)}catch(r){throw new h(`Eval query set at ${t} is not valid JSON: ${r instanceof Error?r.message:String(r)}`,f.USAGE,Fr)}},Fc=e=>{try{return Tr(e)}catch(t){throw new h(t instanceof Error?t.message:String(t),f.USAGE,Fr)}},Dc=async e=>Fc(Mc(await Tc(e),e)),Pc=async(e,t,r,n)=>{let i=e.mode??t,o=(await Co(e.query,{mode:i,limit:String(r),fields:"id"},n)).items.map(a=>a.id).filter(a=>typeof a=="string"),s=Do(o,new Set(e.relevant_ids),r);return{metrics:s,report:{query:e.query,...e.minimum===void 0?{}:{violations:To(s,e.minimum)},mode:i,relevant_total:s.relevant_total,retrieved_relevant:s.retrieved_relevant,ndcg:$(s.ndcg),mrr:$(s.mrr),precision:$(s.precision),recall:$(s.recall)}}},Hc=(e,t,r,n)=>{let i=Po(r);return{k:e,query_count:t.length,aggregate:{ndcg:$(i.ndcg),mrr:$(i.mrr),precision:$(i.precision),recall:$(i.recall)},queries:t,...n!==void 0?{fail_under:n}:{},passed:(n===void 0||i.ndcg>=n)&&t.every(o=>(o.violations?.length??0)===0)}},wf=async(e,t)=>{let r=k(process.cwd(),t.path);await P(r);let n=Cc(e.k),i=Rc(e.mode),o=Ac(e.failUnder),s=e.queries?Mr.resolve(process.cwd(),e.queries):Mr.join(r,kc),a=await Dc(s),c=[],d=[];for(let l of a.queries){let{report:u,metrics:m}=await Pc(l,i,n,t);d.push(m),c.push(u)}return Hc(n,c,d,o)};export{jo as a,jc as b,fi as c,No as d,Qo as e,Xo as f,sl as g,al as h,xl as i,Rl as j,Rt as k,ki as l,xi as m,Ri as n,Jl as o,pd as p,fd as q,vd as r,Ed as s,$i as t,Bi as u,Wi as v,$s as w,Pt as x,Qd as y,Yd as z,su as A,Nt as B,Ut as C,Gt as D,$t as E,Bt as F,Wt as G,Xi as H,ne as I,ie as J,nt as K,it as L,po as M,yo as N,rf as O,Co as P,Ao as Q,Cr as R,To as S,G as T,gc as U,ct as V,Tr as W,kc as X,wf as Y};
|
|
6
|
-
//# sourceMappingURL=chunk-
|
|
6
|
+
//# sourceMappingURL=chunk-2JYTSTQP.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{$c as w,Mf as $,R as p,T as h,Xc as I,Yc as C,Zc as L,_c as A,ad as v,dd as M,df as D,ef as F,g as P,gh as B,h as m,hh as k,if as V,j as S,k as N,kl as y,wb as _}from"./chunk-5TCQ5J3V.js";import{Command as Q}from"commander";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="089f4ea0-a211-5e3e-87d3-c5693de8918d")}catch{}})();function Ue(e){return new Q().name("pm").description("Universal, flexible, extensible, agent-optimized project management CLI for any project or programming language.").version(e).showHelpAfterError(!1).allowExcessArguments(!1).allowUnknownOption(!1).configureOutput({writeOut:t=>{$(t)},writeErr:()=>{}}).option("--json","Output JSON instead of TOON; mutations emit a flat receipt with top-level id/status/changed_field_count while reads use documented entity or collection envelopes").option("--lean","Omit null and empty containers from JSON output").option("--token-accounting","Attach a bounded per-section token-cost receipt to command output").option("--output-include <fields>","Retain comma-separated fields or sections in read output").option("--output-limit <count>","Bound rows in read output").option("--output-budget <tokens|unbounded>","Bound estimated tokens in read output or explicitly disable the default ceiling").option("--output-format <toon|json>","Select the result encoding for reads and mutations").option("--output-session <state>","Carry a JSON session budget and served-item ledger across read calls").option("--output-cursor <cursor>","Resume a budget-compacted declared row collection").option("--output-row-contract","Include row selectors, encoding metadata, and read-output receipts").option("--quiet","Suppress stdout output").option("--no-changed-fields","Omit the changed_fields array from mutation output (keeps changed_field_count)").option("--full-changed-fields","Restore the legacy full mutation envelope and changed_fields array").option("--id-only","Print only id and status for single-item mutation output").option("--pm-path <dir>","Explicit tracker storage path for this command (preferred over --path)").option("--path <dir>","Backward-compatible alias for --pm-path; this is the tracker storage path, not a workspace cwd").option("--no-extensions","Disable extension loading").option("--no-pager","Disable pager integration for help and long output").option("--explain","Render extended rationale and examples in help output").option("--all","Reveal every public command and compatibility alias").option("--profile","Print deterministic timing diagnostics").option("--author <id>","Override mutation author for this invocation").exitOverride()}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="be9abae1-85ae-5a68-96bc-c738218ace5e")}catch{}})();function Ke(e){return e instanceof h||e instanceof Error?e.message:"Unknown failure"}function ee(e){if(typeof e!="object"||e===null||!("exitCode"in e))return;let t=e.exitCode;return typeof t=="number"&&Number.isFinite(t)?t:void 0}function te(e){let t=Math.trunc(e);return t>p.SUCCESS?t:p.GENERIC_FAILURE}function Ye(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&e.code.startsWith("commander.")}function Xe(e,t){if(e instanceof Error)return e;let o=new Error(t),n=ee(e);return n!==void 0&&(o.exitCode=te(n)),o}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8efedca0-725e-520f-ad06-825a0cccddaa")}catch{}})();var R=new Set(["append","claim","close","close-task","comments","copy","delete","deps","docs","files","focus","get","history","history-compact","history-redact","history-repair","learnings","notes","pause-task","release","restore","start-task","test","update"]),z=new Map([["files","discover"],["item","complete"]]),ne=new Map([["append",1],["close",1],["close-task",1],["comments",1],["item complete",1],["learnings",1],["notes",1],["restore",1]]);function G(e){let t=m(e?.trim().toLowerCase()??"");return R.has(t)||z.has(t)}function oe(e,t,o){let n=R.has(o)?t+1:void 0,i=w(e.slice(t+1));if(i===void 0)return n;let s=t+1+i,a=`${o} ${e[s]}`,r=m(a);return r===a?o==="item"&&e[s]==="complete"?s+1:n:G(r)?O(e,s,r):void 0}function O(e,t,o){if(["history","context","ctx","update","close","item"].includes(o))return oe(e,t,o);let n=z.get(o);if(n===void 0)return t+1;let i=e[t+1]?.toLowerCase()===n;return t+(i?2:1)}function ie(e){let t=new Map;for(let o of y(e))for(let n of[o.flag,o.short,...o.aliases??[]])n&&t.set(n,o);return t}function se(e){let t=[];for(let o=0;o<e.length;o+=1){let n=e[o];if(n==="--")break;n==="--id"?(t.push({index:o,consumed:2,value:e[o+1]}),o+=1):n.startsWith("--id=")&&t.push({index:o,consumed:1,value:n.slice(5)})}return t}function re(e,t,o){if(e.indexOf("=")>=0||t===void 0||t.startsWith("-"))return!1;let n=o.get(e);return n!==void 0&&n.value_type!=="boolean"}function ae(e,t,o,n,i){let s=0;for(let a=t;a<e.length;a+=1){let r=e[a];if(r==="--")break;if(r==="--id"){a+=1;continue}if(!r.startsWith("--id=")){if(!r.startsWith("-")){if(a<n)return!0;s+=1;continue}re(r,e[a+1],i)&&(a+=1)}}return s>(ne.get(m(o))??0)}function U(e){let t=w(e),o=t===void 0?void 0:e[t]?.toLowerCase();if(o!=="context"&&o!=="ctx"&&!G(o))return{argv:[...e],changed:!1,conflict:!1};let n=O(e,t,o);if(n===void 0)return{argv:[...e],changed:!1,conflict:!1};let i=n>t+1?`${m(e.slice(t,n-1).join(" "))} ${e[n-1]}`:o,s=ie(i),a=se(e),r=a[0];if(!r||!r.value?.trim())return{argv:[...e],changed:!1,conflict:!1};if(a.length>1||ae(e,n,i,r.index,s))return{argv:[...e],changed:!1,conflict:!0,itemId:r.value};let l=[...e.slice(0,r.index),...e.slice(r.index+r.consumed)],c=w(l),u=O(l,c,o);return l.splice(u,0,r.value),{argv:l,changed:!0,conflict:!1,itemId:r.value}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f05cec18-5e48-5151-8ada-577c9df5885d")}catch{}})();var le=new Set(["--output-include","--output-limit","--output-budget","--output-format","--output-session","--output-cursor"]),ce=new Set(["toon","json"]);function ue(e,t,o){let n=e[t];if(C.has(n))return o.booleanFlags.add(n),1;let i=n.indexOf("="),s=i>0?n.slice(0,i):n;if(!I.has(s))return 1;let a=i>0?n.slice(i+1):void 0,r=a===void 0&&A(s,e[t+1]),l=a??(r?e[t+1]:void 0);return s==="--author"?o.author=l??"":typeof l=="string"&&l.length>0&&(le.has(s)?o.outputValues:o.pathValues).set(s,l),r?2:1}function de(e){let t={booleanFlags:new Set,outputValues:new Map,pathValues:new Map},o=0;for(;o<e.length&&e[o]!=="--";)o+=ue(e,o,t);return{path:t.pathValues.get("--pm-path")??t.pathValues.get("--path"),noExtensions:t.booleanFlags.has("--no-extensions")||["history attest","history-attest"].includes(X(e)??""),noPager:t.booleanFlags.has("--no-pager"),json:t.booleanFlags.has("--json")?t.outputValues.get("--output-format")!=="toon":t.outputValues.get("--output-format")==="json",quiet:t.booleanFlags.has("--quiet"),lean:t.booleanFlags.has("--lean"),tokenAccounting:t.booleanFlags.has("--token-accounting"),...t.booleanFlags.has("--output-row-contract")?{outputRowContract:!0}:{},...t.outputValues.get("--output-include")===void 0?{}:{outputInclude:t.outputValues.get("--output-include")},...t.outputValues.get("--output-limit")===void 0?{}:{outputLimit:t.outputValues.get("--output-limit")},...t.outputValues.get("--output-budget")===void 0?{}:{outputBudget:t.outputValues.get("--output-budget")},...ce.has(t.outputValues.get("--output-format"))?{outputFormat:t.outputValues.get("--output-format")}:{},...t.outputValues.get("--output-session")===void 0?{}:{outputSession:t.outputValues.get("--output-session")},...t.outputValues.get("--output-cursor")===void 0?{}:{outputCursor:t.outputValues.get("--output-cursor")},...t.author===""?{authorMissingValue:!0}:t.author!==void 0?{author:t.author}:{}}}function q(e){let t=[],o=0;for(;o<e.length;){let n=e[o];if(n==="--")break;if(C.has(n)||n==="--profile"||n==="--id-only"||n==="--full-changed-fields"||n==="--explain"){o+=1;continue}if(I.has(n)){o+=A(n,e[o+1])?2:1;continue}if(L(n)){o+=1;continue}t.push(n),o+=1}return t}function fe(e){let t=q(e);if(t[0]?.trim().toLowerCase()==="help"){let n=[];for(let i=1;i<t.length;i+=1){let s=t[i];if(s.startsWith("-"))break;n.push(s.trim().toLowerCase())}return{requested:!0,commandPathTokens:n}}if(t.findIndex(n=>n==="--help"||n==="-h")<0)return{requested:!1,commandPathTokens:[]};let o=[];for(let n of t){if(n.startsWith("-"))break;o.push(n.trim().toLowerCase())}return{requested:!0,commandPathTokens:o}}function T(e){return w(e)}function pe(e){return v(e)}function me(e,t){return t.noPager?!0:process.stdout.isTTY===!0?!1:fe(e).requested}function dt(e){let t=["PAGER","MANPAGER","GIT_PAGER","LESS"],o=t.map(s=>process.env[s]),n=()=>{for(let[s,a]of t.entries()){let r=o[s];r===void 0?delete process.env[a]:process.env[a]=r}},i=de(e);return me(e,i)&&(process.env.PAGER="cat",process.env.MANPAGER="cat",process.env.GIT_PAGER="cat",(typeof process.env.LESS!="string"||process.env.LESS.trim().length===0)&&(process.env.LESS="FRX")),n}var he=new Set(["install","uninstall","explore","manage","doctor","adopt","adopt-all","activate","deactivate"]);function ge(e){let t=T(e);if(t===void 0||e[t]!=="extension")return[...e];let o=e[t+1];if(!o||o.startsWith("-"))return[...e];if(!he.has(o))return[...e];if(e.includes("--help")||e.includes("-h"))return[...e];let n=`--${o}`;return e.includes(n)?[...e]:[...e.slice(0,t+1),n,...e.slice(t+2)]}var be=new Set(["pm","pm-cli"]);function ye(e,t){let o=T(e);if(o===void 0)return e;let n=e[o];return be.has(n.trim().toLowerCase())?(t.push({from:n,to:[],reason:"executable_alias",confidence:"high"}),[...e.slice(0,o),...e.slice(o+1)]):e}function we(e,t){let o=T(e);if(o!==void 0&&e[o]==="help"){let r=T(e.slice(o+1));o=r===void 0?void 0:o+1+r}if(o===void 0)return e;let n=e[o],i=N[n.trim().toLowerCase()];if(!i)return e;let s=i.split(" "),a=[...e.slice(0,o),...s,...e.slice(o+1)];return t.push({from:n,to:s,reason:"command_alias",confidence:"high"}),a}function E(e){return e.replace(/^--?/,"").replace(/_/g,"-").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}function W(e){return E(e).replace(/-/g,"")}function j(e,t,o){let n=e.get(t);if(n===void 0){e.set(t,o);return}n!==o&&e.set(t,null)}function Ie(e){let t=[],o=n=>{typeof n=="string"&&n.startsWith("--")&&t.push(n)};o(e.flag);for(let n of e.aliases??[])o(n);return t}function _e(e,t){let o=t??y(e),n=new Map,i=new Map,s=new Map,a=new Set;for(let r of o){let l=Ie(r);if(l.length===0)continue;let c=`--${E(l[0])}`;for(let f of l)j(n,E(f),c),j(i,W(f),c);let u=W(c);s.has(c)||s.set(c,u),r.list===!0&&a.add(c)}return{canonicalByNormalized:n,canonicalByCompact:i,canonicalComparables:[...s.entries()].map(([r,l])=>({canonicalFlag:r,comparable:l})),listCanonicalFlags:a}}function K(e,t){let o=E(e),n=t.canonicalByNormalized.get(o);if(typeof n=="string")return{flag:n,reason:"flag_alias",confidence:"high"};let i=o.replace(/-/g,""),s=t.canonicalByCompact.get(i);if(typeof s=="string")return{flag:s,reason:"flag_alias",confidence:"high"};let a=i.length>=8?2:1,r=Number.POSITIVE_INFINITY,l,c=!1;for(let u of t.canonicalComparables){let f=_(i,u.comparable,a);if(f!==null){if(f<r){r=f,l=u.canonicalFlag,c=!1;continue}f===r&&l!==u.canonicalFlag&&(c=!0)}}return!l||c||!Number.isFinite(r)||r<=0?null:{flag:l,reason:"flag_typo",confidence:r>=2?"medium":"high"}}function ft(e){let t=[`${e}s`];return e.endsWith("y")&&e.length>1&&t.push(`${e.slice(0,-1)}ies`),t}function Ce(e,t=!1){if(t||e.includes("://"))return null;let o=e.match(/^([A-Za-z][A-Za-z0-9_-]{1,63})([:=])(.*)$/);if(!o)return null;let n=o[1],i=o[3];return i.length===0?null:{key:n,value:i}}function ve(e,t,o=!1){if(o||!e.startsWith("--"))return{tokens:[e]};let n=e.indexOf("="),i=n>=0?e.slice(0,n):e,s=n>=0?e.slice(n+1):void 0,a=K(i,t);if(!a)return{tokens:[e]};let r=s===void 0?a.flag:`${a.flag}=${s}`;return r===e?{tokens:[e]}:{tokens:[r],event:{from:e,to:[r],reason:a.reason,confidence:a.confidence}}}function ke(e){let t=new Set,o=!1;for(let n=0;n<e.length;n+=1){if(o){t.add(n),o=!1;continue}let i=e[n];o=i==="--path"||i==="--pm-path"}return t}function Te(e){if(!e.startsWith("--"))return null;let t=e.indexOf("=");return t<0?{flag:e}:{flag:e.slice(0,t),inlineValue:e.slice(t+1)}}function Ee(e,t,o){o.push(e[t]);let n=e[t+1];return typeof n=="string"&&n!=="--"?(o.push(n),t+2):t+1}function xe(e,t,o,n){if(o.inlineValue!==void 0)return{originalTokens:[e[t]],value:o.inlineValue,consumed:1};let i=[],s=t+1;for(;s<e.length&&e[s]!=="--"&&!e[s].startsWith("-")&&(i.length===0||n.has(o.flag));)i.push(e[s]),s+=1;let a=i.length===0?1:1+i.length;return{originalTokens:e.slice(t,t+a),value:i.length===0?void 0:i.join(","),consumed:a}}function Se(e,t,o,n){let i=e.get(o);if(i){i.values.push(n.value),i.occurrences+=1;return}e.set(o,{outputIndex:t.length,originalTokens:n.originalTokens,values:[n.value],occurrences:1}),t.push(null)}function Ae(e,t){let o=[],n=[];for(let[i,s]of e){if(!(s.occurrences>=2||t.has(i)&&s.originalTokens.length>2)){n.push({outputIndex:s.outputIndex,tokens:s.originalTokens});continue}let a=`${i}=${s.values.join(",")}`;n.push({outputIndex:s.outputIndex,tokens:[a]}),o.push({from:`${i} (x${s.occurrences})`,to:[a],reason:"list_merge",confidence:"high"})}return{events:o,splices:n}}function Oe(e,t){t.sort((o,n)=>n.outputIndex-o.outputIndex);for(let o of t)e.splice(o.outputIndex,1,...o.tokens)}function Pe(e,t,o=new Set,n=new Set){if(t.size===0)return{argv:[...e],events:[]};let i=[],s=new Map,a=0;for(;a<e.length;){let c=e[a];if(c==="--"){i.push(...e.slice(a));break}if(o.has(c)){a=Ee(e,a,i);continue}let u=Te(c);if(!u||!t.has(u.flag)){i.push(c),a+=1;continue}let f=xe(e,a,u,n);if(f.value===void 0){i.push(c),a+=f.consumed;continue}Se(s,i,u.flag,{originalTokens:f.originalTokens,value:f.value}),a+=f.consumed}let{events:r,splices:l}=Ae(s,n);return Oe(i,l),{argv:i,events:r}}var Y=new Map([["--add",new Set(["command","cmd","path"])],["--remove",new Set(["command","path"])]]);function Ne(e,t){if(e!=="test"||t.length<2)return!1;let o=t[t.length-1],n=t[t.length-2],i=Y.get(n);return i!==void 0&&i.has(o)}function Le(e,t,o){if(t!=="test")return e;let n=[],i=0;for(;i<e.length;){let s=e[i];if(s==="--")return n.push(...e.slice(i)),n;let a=Y.get(s),r=a?e[i+1]:void 0;if(!a||typeof r!="string"||!a.has(r)){n.push(s),i+=1;continue}let l=i+2;for(;l<e.length&&!e[l].startsWith("-");)l+=1;if(l-(i+2)!==1){n.push(s),i+=1;continue}let c=e[i+2],u=`${r}=${c}`;n.push(s,u),o.push({from:`${s} ${r} ${c}`,to:[s,u],reason:"bare_key_value",confidence:"high"}),i+=3}return n}function Me(e,t,o,n){let i=[],s=ke(e);for(let a=0;a<e.length;a+=1){let r=e[a];if(r==="--"){i.push(...e.slice(a));break}let l=s.has(a),c=i[i.length-1];if(r.startsWith("--")){let b=ve(r,t,l);i.push(...b.tokens),b.event&&n.push(b.event);continue}let u=Ce(r,l);if(!u||typeof c=="string"&&c.startsWith("-")&&!c.includes("=")||["search","comments","notes","learnings"].includes(o)||Ne(o,i)){i.push(r);continue}let f=K(u.key,t);if(!f){i.push(r);continue}let g=u.value.startsWith("-")?[`${f.flag}=${u.value}`]:[f.flag,u.value];i.push(...g),n.push({from:r,to:g,reason:"bare_key_value",confidence:f.confidence})}return i}function De(e){for(let t=0;t<e.length;t+=1){let o=e[t];if(o==="--")break;if(o==="--verify"){let n=e[t+1];if(n===void 0||n==="--")throw new h("history attest --verify requires a bundle file.",p.USAGE);e.splice(t,2,`--verify=${n}`)}else(I.has(o)||o==="--output"||o==="--hash-algorithm")&&(t+=1)}}function Fe(e,t){if(!e.some(n=>n==="--help"||n==="-h"))return;let o=new Set(y(t).flatMap(n=>[n.flag,...n.aliases??[],...n.short===void 0?[]:[n.short]]));for(let n=0;n<e.length;n+=1){let i=e[n];if(i==="--")break;i!=="--help"&&i!=="-h"||o.has(e[n-1])&&!C.has(e[n-1])&&(e[n-1]=i)}}function pt(e){let t=[],o=ye(e,t),n=ge(o);(n.length!==o.length||n.some((b,J)=>b!==o[J]))&&t.push({from:o.join(" "),to:[...n],reason:"legacy_extension_action",confidence:"high"});let i=we(n,t),s=U(i);if(s.conflict)throw new h("Provide the item id either positionally or with --id, not both.",p.USAGE);s.changed&&t.push({from:`--id ${s.itemId}`,to:[s.itemId],reason:"item_id_alias",confidence:"high"});let a=pe(s.argv),r=X(s.argv),l=m(r??a??""),c=_e(r??a),u=Me(s.argv,c,l,t),f=Le(u,l,t),g=Pe(f,c.listCanonicalFlags,I,a==="create"?new Set(["--tags"]):new Set);for(let b of g.events)t.push(b);return Fe(g.argv,r??a),r==="history attest"&&De(g.argv),{argv:g.argv,commandName:a,trace:t}}function X(e){let t=q(e),o=t[0]?.trim().toLowerCase(),n=t[1]?.trim().toLowerCase(),i=P(t);return i?i.canonical:(o==="extension"||o==="package"||o==="packages")&&typeof n=="string"&&n.length>0&&!n.startsWith("-")?`${o} ${n}`:o}function mt(e){for(let t=0;t<e.length;t+=1){let o=e[t];if(o==="--")break;if(o==="--type"){let n=e[t+1];if(typeof n=="string"&&n.trim().length>0)return n.trim();continue}if(o.startsWith("--type=")){let n=o.slice(7).trim();if(n.length>0)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]="fb625cd9-f8a8-56cf-88ab-abef64051497")}catch{}})();function wt(e){if(e===void 0)return()=>{};let t=e.trim();if(t.length===0)throw new h("--author requires a non-empty value.",p.USAGE,{code:"missing_required_argument",nextSteps:["Pass an explicit author identifier with --author <id>."]});let o=B();k(t);let n=!1;return()=>{n||(n=!0,o===void 0?k(void 0):k(o))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d0e60f7e-e0a8-5ef4-9af7-4a1f102ccb7d")}catch{}})();var d=Object.freeze({clock:"PM_CLOCK",tickMs:"PM_CLOCK_TICK_MS",seed:"PM_SEED"});function x(e,t,o,n){return new h(e,p.USAGE,{code:"invalid_reproducible_process_environment",reason:t,field:o,required:`${d.clock} and ${d.seed}; ${d.tickMs} is optional`,nextSteps:[`Set ${d.clock} to an ISO-8601 instant with Z or a numeric UTC offset and ${d.seed} to a non-empty reproducibility seed.`,`Optionally set ${d.tickMs} to a non-negative integer; it defaults to 1.`,"Unset all three variables to retain normal wall-clock and cryptographic-random behavior."],recovery:{recovery_mode:"compact",provided_fields:n,missing_required_fields:t==="incomplete"?[d.clock,d.seed].filter(i=>!n.includes(i)):void 0}})}function Ve(e){let t=e[d.clock],o=e[d.tickMs],n=e[d.seed],i=[[d.clock,t],[d.tickMs,o],[d.seed,n]].filter(a=>a[1]!==void 0).map(([a])=>a);if(i.length===0)return;if(t===void 0||n===void 0)throw x("Reproducible process execution requires PM_CLOCK and PM_SEED together.","incomplete",t===void 0?d.clock:d.seed,i);if(n.trim().length===0)throw x(`${d.seed} must not be empty.`,"invalid_value",d.seed,i);if(!V(t))throw x(`${d.clock} must be a valid ISO-8601 instant with Z or a numeric UTC offset.`,"invalid_value",d.clock,i);let s=o===void 0?1:Number(o);if(o?.trim().length===0||!Number.isSafeInteger(s)||s<0)throw x(`${d.tickMs} must be a non-negative integer.`,"invalid_value",d.tickMs,i);return D({clock:t,seed:n,tickMs:s})}function $e(e){let t=Ve(e);return t===void 0?o=>o():F(t)}async function Tt(e,t){return $e(e)(t)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d5c48881-420f-5673-8696-e770db353cfc")}catch{}})();function Z(e){return e.trim().match(/--[a-z0-9][a-z0-9_-]*/i)?.[0]?.replaceAll("_","-").toLowerCase()}function Ot(e){if(!(!Array.isArray(e)||e.length===0))return v(e)}function Be(e,t){let o=Z(t);if(!o)return;let n=y(e).find(i=>i.flag===o||i.aliases?.includes(o));return n?n.value_type==="boolean"?null:`<${n.value_name??"value"}>`:"<value>"}function Pt(e,t,o){let n=[...e],i=n.indexOf("--"),s=i<0?n.length:i;for(let a of o){let r=Z(a);if(!r||n.slice(0,s).some(u=>u===r||u.startsWith(`${r}=`)))continue;let l=Be(t,r),c=l?[r,l]:[r];n.splice(s,0,...c),s+=c.length}return n.length===e.length?void 0:M(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]="bd9a8d3b-bc6f-5309-a3fb-7e5f41ef9dab")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a48c9a1f-b959-54a4-a27f-4f662ae7fd31")}catch{}})();var Re={add:["create","append"],fetch:["get"],inspect:["get","health"],log:["history","comments","notes"],ls:["list"],pause:["release"],read:["get"],remove:["delete"],rm:["delete"],show:["get"],start:["start-task"]};function H(e,t){let o=e.trim().toLowerCase(),n=t.trim().toLowerCase();if(n.length===0)return Number.POSITIVE_INFINITY;let i=o.split(" "),s=Re[n]?.indexOf(m(o));if(s!==void 0&&s>=0)return s;if(o===n)return 10;if(i.includes(n))return 11;if(i.some(l=>l.startsWith(n)))return 12;let a=n.length>=5?2:1,r=Number.POSITIVE_INFINITY;for(let l of i){let c=_(l,n,a);c!==null&&(r=Math.min(r,c))}return Number.isFinite(r)?20+r:o.includes(n)?30:Number.POSITIVE_INFINITY}function $t(e,t){return e.map(o=>({path:o,score:H(o,t)})).filter(o=>Number.isFinite(o.score)).sort((o,n)=>o.score!==n.score?o.score-n.score:o.path===n.path?0:o.path<n.path?-1:1).map(o=>o.path)}function Bt(e,t,o){let n=new Set(t),i=S.filter(r=>r.lifecycle==="deprecated").slice().sort((r,l)=>l.alias.length-r.alias.length),s=[],a=e.flatMap(r=>{let l=i.find(u=>r===u.alias||r.startsWith(`${u.alias} `)),c=r;if(l){let u=r.slice(l.alias.length);if(!n.has(`${l.canonical}${u}`))return[];c=`${l.canonical_argv.join(" ")}${u}`}return o!==void 0&&H(r,o)<10&&s.push(c),[c]});return[...new Set(s.length>0?s:a)]}export{Ue as a,Ke as b,ee as c,te as d,Ye as e,Xe as f,G as g,U as h,de as i,q as j,fe as k,T as l,pe as m,dt as n,ge as o,ft as p,Pe as q,Le as r,pt as s,mt as t,wt as u,d as v,Ve as w,$e as x,Tt as y,Ot as z,Be as A,Pt as B,H as C,$t as D,Bt as E};
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{$c as w,Mf as $,R as p,T as h,Xc as I,Yc as C,Zc as L,_c as A,ad as v,dd as M,df as D,ef as F,g as P,h as m,hh as B,if as V,ih as k,j as S,k as N,ll as y,wb as _}from"./chunk-YMLF6QT7.js";import{Command as Q}from"commander";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="089f4ea0-a211-5e3e-87d3-c5693de8918d")}catch{}})();function Ue(e){return new Q().name("pm").description("Universal, flexible, extensible, agent-optimized project management CLI for any project or programming language.").version(e).showHelpAfterError(!1).allowExcessArguments(!1).allowUnknownOption(!1).configureOutput({writeOut:t=>{$(t)},writeErr:()=>{}}).option("--json","Output JSON instead of TOON; mutations emit a flat receipt with top-level id/status/changed_field_count while reads use documented entity or collection envelopes").option("--lean","Omit null and empty containers from JSON output").option("--token-accounting","Attach a bounded per-section token-cost receipt to command output").option("--output-include <fields>","Retain comma-separated fields or sections in read output").option("--output-limit <count>","Bound rows in read output").option("--output-budget <tokens|unbounded>","Bound estimated tokens in read output or explicitly disable the default ceiling").option("--output-format <toon|json>","Select the result encoding for reads and mutations").option("--output-session <state>","Carry a JSON session budget and served-item ledger across read calls").option("--output-cursor <cursor>","Resume a budget-compacted declared row collection").option("--output-row-contract","Include row selectors, encoding metadata, and read-output receipts").option("--quiet","Suppress stdout output").option("--no-changed-fields","Omit the changed_fields array from mutation output (keeps changed_field_count)").option("--full-changed-fields","Restore the legacy full mutation envelope and changed_fields array").option("--id-only","Print only id and status for single-item mutation output").option("--pm-path <dir>","Explicit tracker storage path for this command (preferred over --path)").option("--path <dir>","Backward-compatible alias for --pm-path; this is the tracker storage path, not a workspace cwd").option("--no-extensions","Disable extension loading").option("--no-pager","Disable pager integration for help and long output").option("--explain","Render extended rationale and examples in help output").option("--all","Reveal every public command and compatibility alias").option("--profile","Print deterministic timing diagnostics").option("--author <id>","Override mutation author for this invocation").exitOverride()}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="be9abae1-85ae-5a68-96bc-c738218ace5e")}catch{}})();function Ke(e){return e instanceof h||e instanceof Error?e.message:"Unknown failure"}function ee(e){if(typeof e!="object"||e===null||!("exitCode"in e))return;let t=e.exitCode;return typeof t=="number"&&Number.isFinite(t)?t:void 0}function te(e){let t=Math.trunc(e);return t>p.SUCCESS?t:p.GENERIC_FAILURE}function Ye(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&e.code.startsWith("commander.")}function Xe(e,t){if(e instanceof Error)return e;let o=new Error(t),n=ee(e);return n!==void 0&&(o.exitCode=te(n)),o}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8efedca0-725e-520f-ad06-825a0cccddaa")}catch{}})();var R=new Set(["append","claim","close","close-task","comments","copy","delete","deps","docs","files","focus","get","history","history-compact","history-redact","history-repair","learnings","notes","pause-task","release","restore","start-task","test","update"]),z=new Map([["files","discover"],["item","complete"]]),ne=new Map([["append",1],["close",1],["close-task",1],["comments",1],["item complete",1],["learnings",1],["notes",1],["restore",1]]);function G(e){let t=m(e?.trim().toLowerCase()??"");return R.has(t)||z.has(t)}function oe(e,t,o){let n=R.has(o)?t+1:void 0,i=w(e.slice(t+1));if(i===void 0)return n;let s=t+1+i,a=`${o} ${e[s]}`,r=m(a);return r===a?o==="item"&&e[s]==="complete"?s+1:n:G(r)?O(e,s,r):void 0}function O(e,t,o){if(["history","context","ctx","update","close","item"].includes(o))return oe(e,t,o);let n=z.get(o);if(n===void 0)return t+1;let i=e[t+1]?.toLowerCase()===n;return t+(i?2:1)}function ie(e){let t=new Map;for(let o of y(e))for(let n of[o.flag,o.short,...o.aliases??[]])n&&t.set(n,o);return t}function se(e){let t=[];for(let o=0;o<e.length;o+=1){let n=e[o];if(n==="--")break;n==="--id"?(t.push({index:o,consumed:2,value:e[o+1]}),o+=1):n.startsWith("--id=")&&t.push({index:o,consumed:1,value:n.slice(5)})}return t}function re(e,t,o){if(e.indexOf("=")>=0||t===void 0||t.startsWith("-"))return!1;let n=o.get(e);return n!==void 0&&n.value_type!=="boolean"}function ae(e,t,o,n,i){let s=0;for(let a=t;a<e.length;a+=1){let r=e[a];if(r==="--")break;if(r==="--id"){a+=1;continue}if(!r.startsWith("--id=")){if(!r.startsWith("-")){if(a<n)return!0;s+=1;continue}re(r,e[a+1],i)&&(a+=1)}}return s>(ne.get(m(o))??0)}function U(e){let t=w(e),o=t===void 0?void 0:e[t]?.toLowerCase();if(o!=="context"&&o!=="ctx"&&!G(o))return{argv:[...e],changed:!1,conflict:!1};let n=O(e,t,o);if(n===void 0)return{argv:[...e],changed:!1,conflict:!1};let i=n>t+1?`${m(e.slice(t,n-1).join(" "))} ${e[n-1]}`:o,s=ie(i),a=se(e),r=a[0];if(!r||!r.value?.trim())return{argv:[...e],changed:!1,conflict:!1};if(a.length>1||ae(e,n,i,r.index,s))return{argv:[...e],changed:!1,conflict:!0,itemId:r.value};let l=[...e.slice(0,r.index),...e.slice(r.index+r.consumed)],c=w(l),u=O(l,c,o);return l.splice(u,0,r.value),{argv:l,changed:!0,conflict:!1,itemId:r.value}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f05cec18-5e48-5151-8ada-577c9df5885d")}catch{}})();var le=new Set(["--output-include","--output-limit","--output-budget","--output-format","--output-session","--output-cursor"]),ce=new Set(["toon","json"]);function ue(e,t,o){let n=e[t];if(C.has(n))return o.booleanFlags.add(n),1;let i=n.indexOf("="),s=i>0?n.slice(0,i):n;if(!I.has(s))return 1;let a=i>0?n.slice(i+1):void 0,r=a===void 0&&A(s,e[t+1]),l=a??(r?e[t+1]:void 0);return s==="--author"?o.author=l??"":typeof l=="string"&&l.length>0&&(le.has(s)?o.outputValues:o.pathValues).set(s,l),r?2:1}function de(e){let t={booleanFlags:new Set,outputValues:new Map,pathValues:new Map},o=0;for(;o<e.length&&e[o]!=="--";)o+=ue(e,o,t);return{path:t.pathValues.get("--pm-path")??t.pathValues.get("--path"),noExtensions:t.booleanFlags.has("--no-extensions")||["history attest","history-attest"].includes(X(e)??""),noPager:t.booleanFlags.has("--no-pager"),json:t.booleanFlags.has("--json")?t.outputValues.get("--output-format")!=="toon":t.outputValues.get("--output-format")==="json",quiet:t.booleanFlags.has("--quiet"),lean:t.booleanFlags.has("--lean"),tokenAccounting:t.booleanFlags.has("--token-accounting"),...t.booleanFlags.has("--output-row-contract")?{outputRowContract:!0}:{},...t.outputValues.get("--output-include")===void 0?{}:{outputInclude:t.outputValues.get("--output-include")},...t.outputValues.get("--output-limit")===void 0?{}:{outputLimit:t.outputValues.get("--output-limit")},...t.outputValues.get("--output-budget")===void 0?{}:{outputBudget:t.outputValues.get("--output-budget")},...ce.has(t.outputValues.get("--output-format"))?{outputFormat:t.outputValues.get("--output-format")}:{},...t.outputValues.get("--output-session")===void 0?{}:{outputSession:t.outputValues.get("--output-session")},...t.outputValues.get("--output-cursor")===void 0?{}:{outputCursor:t.outputValues.get("--output-cursor")},...t.author===""?{authorMissingValue:!0}:t.author!==void 0?{author:t.author}:{}}}function q(e){let t=[],o=0;for(;o<e.length;){let n=e[o];if(n==="--")break;if(C.has(n)||n==="--profile"||n==="--id-only"||n==="--full-changed-fields"||n==="--explain"){o+=1;continue}if(I.has(n)){o+=A(n,e[o+1])?2:1;continue}if(L(n)){o+=1;continue}t.push(n),o+=1}return t}function fe(e){let t=q(e);if(t[0]?.trim().toLowerCase()==="help"){let n=[];for(let i=1;i<t.length;i+=1){let s=t[i];if(s.startsWith("-"))break;n.push(s.trim().toLowerCase())}return{requested:!0,commandPathTokens:n}}if(t.findIndex(n=>n==="--help"||n==="-h")<0)return{requested:!1,commandPathTokens:[]};let o=[];for(let n of t){if(n.startsWith("-"))break;o.push(n.trim().toLowerCase())}return{requested:!0,commandPathTokens:o}}function T(e){return w(e)}function pe(e){return v(e)}function me(e,t){return t.noPager?!0:process.stdout.isTTY===!0?!1:fe(e).requested}function dt(e){let t=["PAGER","MANPAGER","GIT_PAGER","LESS"],o=t.map(s=>process.env[s]),n=()=>{for(let[s,a]of t.entries()){let r=o[s];r===void 0?delete process.env[a]:process.env[a]=r}},i=de(e);return me(e,i)&&(process.env.PAGER="cat",process.env.MANPAGER="cat",process.env.GIT_PAGER="cat",(typeof process.env.LESS!="string"||process.env.LESS.trim().length===0)&&(process.env.LESS="FRX")),n}var he=new Set(["install","uninstall","explore","manage","doctor","adopt","adopt-all","activate","deactivate"]);function ge(e){let t=T(e);if(t===void 0||e[t]!=="extension")return[...e];let o=e[t+1];if(!o||o.startsWith("-"))return[...e];if(!he.has(o))return[...e];if(e.includes("--help")||e.includes("-h"))return[...e];let n=`--${o}`;return e.includes(n)?[...e]:[...e.slice(0,t+1),n,...e.slice(t+2)]}var be=new Set(["pm","pm-cli"]);function ye(e,t){let o=T(e);if(o===void 0)return e;let n=e[o];return be.has(n.trim().toLowerCase())?(t.push({from:n,to:[],reason:"executable_alias",confidence:"high"}),[...e.slice(0,o),...e.slice(o+1)]):e}function we(e,t){let o=T(e);if(o!==void 0&&e[o]==="help"){let r=T(e.slice(o+1));o=r===void 0?void 0:o+1+r}if(o===void 0)return e;let n=e[o],i=N[n.trim().toLowerCase()];if(!i)return e;let s=i.split(" "),a=[...e.slice(0,o),...s,...e.slice(o+1)];return t.push({from:n,to:s,reason:"command_alias",confidence:"high"}),a}function E(e){return e.replace(/^--?/,"").replace(/_/g,"-").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}function W(e){return E(e).replace(/-/g,"")}function j(e,t,o){let n=e.get(t);if(n===void 0){e.set(t,o);return}n!==o&&e.set(t,null)}function Ie(e){let t=[],o=n=>{typeof n=="string"&&n.startsWith("--")&&t.push(n)};o(e.flag);for(let n of e.aliases??[])o(n);return t}function _e(e,t){let o=t??y(e),n=new Map,i=new Map,s=new Map,a=new Set;for(let r of o){let l=Ie(r);if(l.length===0)continue;let c=`--${E(l[0])}`;for(let f of l)j(n,E(f),c),j(i,W(f),c);let u=W(c);s.has(c)||s.set(c,u),r.list===!0&&a.add(c)}return{canonicalByNormalized:n,canonicalByCompact:i,canonicalComparables:[...s.entries()].map(([r,l])=>({canonicalFlag:r,comparable:l})),listCanonicalFlags:a}}function K(e,t){let o=E(e),n=t.canonicalByNormalized.get(o);if(typeof n=="string")return{flag:n,reason:"flag_alias",confidence:"high"};let i=o.replace(/-/g,""),s=t.canonicalByCompact.get(i);if(typeof s=="string")return{flag:s,reason:"flag_alias",confidence:"high"};let a=i.length>=8?2:1,r=Number.POSITIVE_INFINITY,l,c=!1;for(let u of t.canonicalComparables){let f=_(i,u.comparable,a);if(f!==null){if(f<r){r=f,l=u.canonicalFlag,c=!1;continue}f===r&&l!==u.canonicalFlag&&(c=!0)}}return!l||c||!Number.isFinite(r)||r<=0?null:{flag:l,reason:"flag_typo",confidence:r>=2?"medium":"high"}}function ft(e){let t=[`${e}s`];return e.endsWith("y")&&e.length>1&&t.push(`${e.slice(0,-1)}ies`),t}function Ce(e,t=!1){if(t||e.includes("://"))return null;let o=e.match(/^([A-Za-z][A-Za-z0-9_-]{1,63})([:=])(.*)$/);if(!o)return null;let n=o[1],i=o[3];return i.length===0?null:{key:n,value:i}}function ve(e,t,o=!1){if(o||!e.startsWith("--"))return{tokens:[e]};let n=e.indexOf("="),i=n>=0?e.slice(0,n):e,s=n>=0?e.slice(n+1):void 0,a=K(i,t);if(!a)return{tokens:[e]};let r=s===void 0?a.flag:`${a.flag}=${s}`;return r===e?{tokens:[e]}:{tokens:[r],event:{from:e,to:[r],reason:a.reason,confidence:a.confidence}}}function ke(e){let t=new Set,o=!1;for(let n=0;n<e.length;n+=1){if(o){t.add(n),o=!1;continue}let i=e[n];o=i==="--path"||i==="--pm-path"}return t}function Te(e){if(!e.startsWith("--"))return null;let t=e.indexOf("=");return t<0?{flag:e}:{flag:e.slice(0,t),inlineValue:e.slice(t+1)}}function Ee(e,t,o){o.push(e[t]);let n=e[t+1];return typeof n=="string"&&n!=="--"?(o.push(n),t+2):t+1}function xe(e,t,o,n){if(o.inlineValue!==void 0)return{originalTokens:[e[t]],value:o.inlineValue,consumed:1};let i=[],s=t+1;for(;s<e.length&&e[s]!=="--"&&!e[s].startsWith("-")&&(i.length===0||n.has(o.flag));)i.push(e[s]),s+=1;let a=i.length===0?1:1+i.length;return{originalTokens:e.slice(t,t+a),value:i.length===0?void 0:i.join(","),consumed:a}}function Se(e,t,o,n){let i=e.get(o);if(i){i.values.push(n.value),i.occurrences+=1;return}e.set(o,{outputIndex:t.length,originalTokens:n.originalTokens,values:[n.value],occurrences:1}),t.push(null)}function Ae(e,t){let o=[],n=[];for(let[i,s]of e){if(!(s.occurrences>=2||t.has(i)&&s.originalTokens.length>2)){n.push({outputIndex:s.outputIndex,tokens:s.originalTokens});continue}let a=`${i}=${s.values.join(",")}`;n.push({outputIndex:s.outputIndex,tokens:[a]}),o.push({from:`${i} (x${s.occurrences})`,to:[a],reason:"list_merge",confidence:"high"})}return{events:o,splices:n}}function Oe(e,t){t.sort((o,n)=>n.outputIndex-o.outputIndex);for(let o of t)e.splice(o.outputIndex,1,...o.tokens)}function Pe(e,t,o=new Set,n=new Set){if(t.size===0)return{argv:[...e],events:[]};let i=[],s=new Map,a=0;for(;a<e.length;){let c=e[a];if(c==="--"){i.push(...e.slice(a));break}if(o.has(c)){a=Ee(e,a,i);continue}let u=Te(c);if(!u||!t.has(u.flag)){i.push(c),a+=1;continue}let f=xe(e,a,u,n);if(f.value===void 0){i.push(c),a+=f.consumed;continue}Se(s,i,u.flag,{originalTokens:f.originalTokens,value:f.value}),a+=f.consumed}let{events:r,splices:l}=Ae(s,n);return Oe(i,l),{argv:i,events:r}}var Y=new Map([["--add",new Set(["command","cmd","path"])],["--remove",new Set(["command","path"])]]);function Ne(e,t){if(e!=="test"||t.length<2)return!1;let o=t[t.length-1],n=t[t.length-2],i=Y.get(n);return i!==void 0&&i.has(o)}function Le(e,t,o){if(t!=="test")return e;let n=[],i=0;for(;i<e.length;){let s=e[i];if(s==="--")return n.push(...e.slice(i)),n;let a=Y.get(s),r=a?e[i+1]:void 0;if(!a||typeof r!="string"||!a.has(r)){n.push(s),i+=1;continue}let l=i+2;for(;l<e.length&&!e[l].startsWith("-");)l+=1;if(l-(i+2)!==1){n.push(s),i+=1;continue}let c=e[i+2],u=`${r}=${c}`;n.push(s,u),o.push({from:`${s} ${r} ${c}`,to:[s,u],reason:"bare_key_value",confidence:"high"}),i+=3}return n}function Me(e,t,o,n){let i=[],s=ke(e);for(let a=0;a<e.length;a+=1){let r=e[a];if(r==="--"){i.push(...e.slice(a));break}let l=s.has(a),c=i[i.length-1];if(r.startsWith("--")){let b=ve(r,t,l);i.push(...b.tokens),b.event&&n.push(b.event);continue}let u=Ce(r,l);if(!u||typeof c=="string"&&c.startsWith("-")&&!c.includes("=")||["search","comments","notes","learnings"].includes(o)||Ne(o,i)){i.push(r);continue}let f=K(u.key,t);if(!f){i.push(r);continue}let g=u.value.startsWith("-")?[`${f.flag}=${u.value}`]:[f.flag,u.value];i.push(...g),n.push({from:r,to:g,reason:"bare_key_value",confidence:f.confidence})}return i}function De(e){for(let t=0;t<e.length;t+=1){let o=e[t];if(o==="--")break;if(o==="--verify"){let n=e[t+1];if(n===void 0||n==="--")throw new h("history attest --verify requires a bundle file.",p.USAGE);e.splice(t,2,`--verify=${n}`)}else(I.has(o)||o==="--output"||o==="--hash-algorithm")&&(t+=1)}}function Fe(e,t){if(!e.some(n=>n==="--help"||n==="-h"))return;let o=new Set(y(t).flatMap(n=>[n.flag,...n.aliases??[],...n.short===void 0?[]:[n.short]]));for(let n=0;n<e.length;n+=1){let i=e[n];if(i==="--")break;i!=="--help"&&i!=="-h"||o.has(e[n-1])&&!C.has(e[n-1])&&(e[n-1]=i)}}function pt(e){let t=[],o=ye(e,t),n=ge(o);(n.length!==o.length||n.some((b,J)=>b!==o[J]))&&t.push({from:o.join(" "),to:[...n],reason:"legacy_extension_action",confidence:"high"});let i=we(n,t),s=U(i);if(s.conflict)throw new h("Provide the item id either positionally or with --id, not both.",p.USAGE);s.changed&&t.push({from:`--id ${s.itemId}`,to:[s.itemId],reason:"item_id_alias",confidence:"high"});let a=pe(s.argv),r=X(s.argv),l=m(r??a??""),c=_e(r??a),u=Me(s.argv,c,l,t),f=Le(u,l,t),g=Pe(f,c.listCanonicalFlags,I,a==="create"?new Set(["--tags"]):new Set);for(let b of g.events)t.push(b);return Fe(g.argv,r??a),r==="history attest"&&De(g.argv),{argv:g.argv,commandName:a,trace:t}}function X(e){let t=q(e),o=t[0]?.trim().toLowerCase(),n=t[1]?.trim().toLowerCase(),i=P(t);return i?i.canonical:(o==="extension"||o==="package"||o==="packages")&&typeof n=="string"&&n.length>0&&!n.startsWith("-")?`${o} ${n}`:o}function mt(e){for(let t=0;t<e.length;t+=1){let o=e[t];if(o==="--")break;if(o==="--type"){let n=e[t+1];if(typeof n=="string"&&n.trim().length>0)return n.trim();continue}if(o.startsWith("--type=")){let n=o.slice(7).trim();if(n.length>0)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]="fb625cd9-f8a8-56cf-88ab-abef64051497")}catch{}})();function wt(e){if(e===void 0)return()=>{};let t=e.trim();if(t.length===0)throw new h("--author requires a non-empty value.",p.USAGE,{code:"missing_required_argument",nextSteps:["Pass an explicit author identifier with --author <id>."]});let o=B();k(t);let n=!1;return()=>{n||(n=!0,o===void 0?k(void 0):k(o))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d0e60f7e-e0a8-5ef4-9af7-4a1f102ccb7d")}catch{}})();var d=Object.freeze({clock:"PM_CLOCK",tickMs:"PM_CLOCK_TICK_MS",seed:"PM_SEED"});function x(e,t,o,n){return new h(e,p.USAGE,{code:"invalid_reproducible_process_environment",reason:t,field:o,required:`${d.clock} and ${d.seed}; ${d.tickMs} is optional`,nextSteps:[`Set ${d.clock} to an ISO-8601 instant with Z or a numeric UTC offset and ${d.seed} to a non-empty reproducibility seed.`,`Optionally set ${d.tickMs} to a non-negative integer; it defaults to 1.`,"Unset all three variables to retain normal wall-clock and cryptographic-random behavior."],recovery:{recovery_mode:"compact",provided_fields:n,missing_required_fields:t==="incomplete"?[d.clock,d.seed].filter(i=>!n.includes(i)):void 0}})}function Ve(e){let t=e[d.clock],o=e[d.tickMs],n=e[d.seed],i=[[d.clock,t],[d.tickMs,o],[d.seed,n]].filter(a=>a[1]!==void 0).map(([a])=>a);if(i.length===0)return;if(t===void 0||n===void 0)throw x("Reproducible process execution requires PM_CLOCK and PM_SEED together.","incomplete",t===void 0?d.clock:d.seed,i);if(n.trim().length===0)throw x(`${d.seed} must not be empty.`,"invalid_value",d.seed,i);if(!V(t))throw x(`${d.clock} must be a valid ISO-8601 instant with Z or a numeric UTC offset.`,"invalid_value",d.clock,i);let s=o===void 0?1:Number(o);if(o?.trim().length===0||!Number.isSafeInteger(s)||s<0)throw x(`${d.tickMs} must be a non-negative integer.`,"invalid_value",d.tickMs,i);return D({clock:t,seed:n,tickMs:s})}function $e(e){let t=Ve(e);return t===void 0?o=>o():F(t)}async function Tt(e,t){return $e(e)(t)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d5c48881-420f-5673-8696-e770db353cfc")}catch{}})();function Z(e){return e.trim().match(/--[a-z0-9][a-z0-9_-]*/i)?.[0]?.replaceAll("_","-").toLowerCase()}function Ot(e){if(!(!Array.isArray(e)||e.length===0))return v(e)}function Be(e,t){let o=Z(t);if(!o)return;let n=y(e).find(i=>i.flag===o||i.aliases?.includes(o));return n?n.value_type==="boolean"?null:`<${n.value_name??"value"}>`:"<value>"}function Pt(e,t,o){let n=[...e],i=n.indexOf("--"),s=i<0?n.length:i;for(let a of o){let r=Z(a);if(!r||n.slice(0,s).some(u=>u===r||u.startsWith(`${r}=`)))continue;let l=Be(t,r),c=l?[r,l]:[r];n.splice(s,0,...c),s+=c.length}return n.length===e.length?void 0:M(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]="bd9a8d3b-bc6f-5309-a3fb-7e5f41ef9dab")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a48c9a1f-b959-54a4-a27f-4f662ae7fd31")}catch{}})();var Re={add:["create","append"],fetch:["get"],inspect:["get","health"],log:["history","comments","notes"],ls:["list"],pause:["release"],read:["get"],remove:["delete"],rm:["delete"],show:["get"],start:["start-task"]};function H(e,t){let o=e.trim().toLowerCase(),n=t.trim().toLowerCase();if(n.length===0)return Number.POSITIVE_INFINITY;let i=o.split(" "),s=Re[n]?.indexOf(m(o));if(s!==void 0&&s>=0)return s;if(o===n)return 10;if(i.includes(n))return 11;if(i.some(l=>l.startsWith(n)))return 12;let a=n.length>=5?2:1,r=Number.POSITIVE_INFINITY;for(let l of i){let c=_(l,n,a);c!==null&&(r=Math.min(r,c))}return Number.isFinite(r)?20+r:o.includes(n)?30:Number.POSITIVE_INFINITY}function $t(e,t){return e.map(o=>({path:o,score:H(o,t)})).filter(o=>Number.isFinite(o.score)).sort((o,n)=>o.score!==n.score?o.score-n.score:o.path===n.path?0:o.path<n.path?-1:1).map(o=>o.path)}function Bt(e,t,o){let n=new Set(t),i=S.filter(r=>r.lifecycle==="deprecated").slice().sort((r,l)=>l.alias.length-r.alias.length),s=[],a=e.flatMap(r=>{let l=i.find(u=>r===u.alias||r.startsWith(`${u.alias} `)),c=r;if(l){let u=r.slice(l.alias.length);if(!n.has(`${l.canonical}${u}`))return[];c=`${l.canonical_argv.join(" ")}${u}`}return o!==void 0&&H(r,o)<10&&s.push(c),[c]});return[...new Set(s.length>0?s:a)]}export{Ue as a,Ke as b,ee as c,te as d,Ye as e,Xe as f,G as g,U as h,de as i,q as j,fe as k,T as l,pe as m,dt as n,ge as o,ft as p,Pe as q,Le as r,pt as s,mt as t,wt as u,d as v,Ve as w,$e as x,Tt as y,Ot as z,Be as A,Pt as B,H as C,$t as D,Bt as E};
|
|
2
|
+
//# sourceMappingURL=chunk-BXSXT5Z6.js.map
|