@unbrained/pm-cli 2026.10.2 → 2026.10.3
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 +15 -0
- package/dist/cli-bundle/bundle-manifest.json +99 -99
- package/dist/cli-bundle/chunks/{chunk-R4TUD355.js → chunk-3AF2R3Y6.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-TRYXVQ7W.js → chunk-44UGMMQ6.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-XOUBIF6Z.js → chunk-5XKF5SQV.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-WP6NRH72.js → chunk-6ST3SCQ6.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-CZLAWXDR.js → chunk-6Z4IV2MC.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-MTJMOI4I.js → chunk-FW5LJXQY.js} +31 -31
- package/dist/cli-bundle/chunks/{chunk-7FUEQOYG.js → chunk-H2DZW6I6.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-7NL3A2BY.js → chunk-H7CXQBGQ.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-ZI7F3FVE.js → chunk-KP7NBQK3.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-SV7CZEVV.js → chunk-MKXBCBAN.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-R7ULWMBG.js → chunk-QPKQKSQU.js} +7 -7
- package/dist/cli-bundle/chunks/{chunk-HY6M34B4.js → chunk-YCBGZF3T.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-Z2GYDSAO.js → chunk-YDWKGUQU.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-R4PHNB7W.js → register-list-query-DYCGUQEW.js} +2 -2
- package/dist/cli-bundle/chunks/{register-mutation-PDDAUDYV.js → register-mutation-5PT3NW3A.js} +2 -2
- package/dist/cli-bundle/chunks/{register-operations-A5HJT46K.js → register-operations-QDDQOAAV.js} +2 -2
- package/dist/cli-bundle/chunks/{register-setup-EZ2F25JI.js → register-setup-BBX67YMA.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-BLCTBSGT.js → chunk-73DA7ISY.js} +26 -26
- package/dist/cli-bundle/focused-chunks/{chunk-GBD4EN6S.js → chunk-HIA2ZF64.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-IR4UXLRP.js → chunk-WAJNX4RN.js} +2 -2
- package/dist/cli-bundle/main.js +2 -2
- package/dist/cli-bundle/sdk-core.js +31 -31
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +20 -20
- 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 +1 -1
- package/dist/core/shared/secret-rules.js +1 -1
- package/dist/sdk/linked-artifacts.d.ts +1 -1
- package/dist/sdk/linked-artifacts.js +1 -1
- package/dist/sdk/test/execution.js +2 -2
- package/dist/sdk/test/workspace-snapshot.d.ts +11 -0
- package/dist/sdk/test/workspace-snapshot.js +2 -0
- package/docs/DEVELOPMENT_DEPENDENCY_SECURITY.md +109 -0
- package/docs/TESTING.md +32 -5
- package/marketplace.json +2 -2
- package/package.json +5 -4
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-claude/package.json +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
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{A as $n,Ab as ro,Bb as We,Cc as co,D as Wn,E as Bn,O as zn,P as Vn,Rb as no,S as Kn,Tb as oo,Vb as io,Wb as so,a as fe,b as K,bb as to,c as bn,ca as wt,d as En,da as vt,ea as Qn,fa as Yn,ga as Xn,ha as Jn,ka as Zn,la as bt,ma as Et,na as $e,r as qn,ta as eo,v as me,w as Nn,x as Un,y as Ge,yc as ao,z as Gn}from"./chunk-SV7CZEVV.js";import{$h as ln,$i as He,Al as kn,Bh as en,C as q,Ch as tn,Dc as T,Dg as Xr,Dh as rn,Dm as Mn,E as ct,Eg as xe,Eh as nn,Fg as Re,Gi as hn,Gn as jn,Hm as Fn,Ic as jr,Im as Dn,Jc as lt,Ji as pn,Jm as je,Kh as V,Km as Pn,L as ie,Lh as on,Lm as qe,M as Ee,Mc as Y,Mi as Te,Mm as Ne,Nc as qr,Nh as mt,Nm as Ue,O as Se,Oc as se,Oh as le,Om as Hn,P as Hr,Ph as de,Qf as L,Qh as ht,Rh as O,Sh as sn,Sm as Ln,Tb as H,Th as ue,Ti as Me,Tm as _t,Ua as G,Uh as an,Vi as Fe,Wh as pt,Wi as gn,Wl as xn,Xi as De,Xl as Rn,Yi as Pe,Zh as cn,Zi as yn,Zl as yt,_h as Ce,_i as _n,_l as An,ab as x,ag as A,ai as dn,al as Sn,an as On,bg as ut,bj as wn,cb as Or,cd as X,cj as vn,eb as z,ed as Nr,ff as S,gb as Ie,ia as Lr,if as ke,ih as Ae,jf as zr,jh as Jr,jm as Le,kd as Ur,kf as Vr,kg as $,kh as ce,lf as dt,mf as Kr,mg as J,na as m,nm as Oe,pa as h,pd as Gr,pi as j,qd as $r,ri as N,ti as un,ud as Wr,uh as ft,ui as Z,un as ee,vi as gt,wd as Br,wf as Qr,wh as Zr,wi as fn,x as be,xg as Yr,ym as Cn,z as Pr,zg as ae,zi as mn,zl as In,zm as Tn}from"./chunk-R7ULWMBG.js";import uo from"node:fs/promises";import fo 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]="d51da34a-9f37-5441-91f0-15a16b601709")}catch{}})();function Di(e,t,r){let n=new Set,o=[];for(let i of e){let s=i.trim();if(s.length===0||n.has(s))continue;n.add(s);let a=t.get(s);if(a===void 0){o.push({id:s,entries:0,selected:!1,skip_reason:"no_stream"});continue}if(a.entries<=r){o.push({id:s,entries:a.entries,selected:!1,skip_reason:"already_compact"});continue}o.push({id:s,entries:a.entries,selected:!0,skip_reason:null})}return o}function Pi(e,t){let r=[...e].sort((o,i)=>i.entries-o.entries||o.id.localeCompare(i.id)),n=[];for(let o of r){if(t.scope==="closed"&&o.bucket!=="closed"){n.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"scope_mismatch"});continue}if(o.entries<=t.minEntries){n.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"already_compact"});continue}if(t.allOver!==void 0&&o.entries<=t.allOver){n.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"below_threshold"});continue}n.push({id:o.id,entries:o.entries,selected:!0,skip_reason:null})}return n}function lo(e,t){if(t.ids!==void 0&&t.ids.length>0){let r=new Map(e.map(n=>[n.id,n]));return Di(t.ids,r,t.minEntries)}return Pi(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]="1dede7b7-eeea-520d-97ce-a71687d93bc2")}catch{}})();function Hi(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.",m.USAGE);if(/^\d+$/.test(r)){let i=Number.parseInt(r,10),s=N(t);if(!Number.isSafeInteger(i)||i<s+1||i>s+t.length+1)throw new h(`history-compact --before version must be between ${s+1} and ${s+t.length+1}.`,m.USAGE);let a=i-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.`,m.USAGE);let o=0;for(let[i,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 ${i+1}.`,m.GENERIC_FAILURE);if(a>=n)break;o+=1}return{kind:"timestamp",raw:r,compactCount:o,retainedCount:t.length-o}}function Li(e,t){let r=le(),n=le();for(let o=0;o<e.length;o+=1){let i=e[o];r=Z(r,i.patch,o+1,i.op),o+1===t&&(n=structuredClone(r))}return{checkpoint:n,finalReplay:r}}function Oi(e,t){if(!e)return{loadedItem:null,currentItemRawBeforeLock:null,matchedChainBefore:null};let r=t[t.length-1];return{loadedItem:e,currentItemRawBeforeLock:e.raw,matchedChainBefore:Zr.some(n=>(r.item_hash_version===void 0||r.item_hash_version===n)&&ht(ue(e.document),n,A(r.hash_algorithm)).includes(r.after_hash))}}function ji(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 qi(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 Ni(e){if(!e.changed)return{rewrittenEntries:e.historyEntries,baselineEntryAdded:!1,auditEntryAdded:!1};let{checkpoint:t,finalReplay:r}=Li(e.historyEntries,e.boundary.compactCount),n=e.historyEntries.slice(e.boundary.compactCount),o=N(e.historyEntries,!0),i=e.historyEntries[e.boundary.compactCount-1],s=V({hashAlgorithm:A(i.hash_algorithm),nowIso:e.historyEntries[e.boundary.compactCount-1].ts,author:e.author,op:"history_compact_baseline",before:O(le()),after:O(t),message:qi(e.boundary),context:{history_compaction:{contract_version:1,version_offset:o===null?null:o+e.boundary.compactCount-1,checkpoint_timestamp_semantics:"last_compacted_entry",pruned_entry_count:e.boundary.compactCount,pruned_stream_digest:en(e.historyEntries.slice(0,e.boundary.compactCount)),retained_proof:"stream_digest_and_checkpoint",limitation:"individual_pruned_entries_require_pre_compaction_stream"}}}),a=[tn({...s,before_hash:ht(le(),i.item_hash_version??1,A(i.hash_algorithm))[0],after_hash:i.after_hash,item_hash_version:i.item_hash_version}),...n];return e.dryRun||a.push(V({nowIso:S(),author:e.author,op:"history_compact",before:O(r),after:O(r),message:ji(e.options,e.boundary)})),{rewrittenEntries:a,baselineEntryAdded:!0,auditEntryAdded:!e.dryRun}}async function Ui(e,t,r){let{pmRoot:n,settings:o,typeRegistry:i}=await fe(r.path),s=await K(n,e,o,i.type_to_folder);return We({pmRoot:n,subject:s,settings:o,typeRegistry:i,operation:"history-compact",options:t,transform:a=>Gi(s,t,a)})}function Gi(e,t,r){let n=e.historyPath,o=r.entries,i=r.verification;if(!i.ok)throw new h(`history-compact requires a valid history chain (${i.errors.join(", ")}). Run pm history-repair ${e.id} first.`,m.CONFLICT);let s=Hi(t.before,o),a=s.compactCount>0,l=!!t.dryRun,d=r.author,c=[];a||c.push("history_compact_noop_before_boundary");let u=Oi(r.loadedItem,o);u.matchedChainBefore===!1&&c.push("history_compact_item_chain_mismatch");let{rewrittenEntries:f,baselineEntryAdded:p,auditEntryAdded:y}=Ni({historyEntries:o,boundary:s,changed:a,dryRun:l,author:d,options:t}),_=N(o,!0),g=s.retainedCount>0&&_!==null?_+s.compactCount+1:null;return{changed:a,rewrittenEntries:f,report:({verification:w,warnings:b})=>({id:e.id,dry_run:l,changed:a,compact_boundary:{kind:s.kind,before:s.raw,entries_compacted:s.compactCount,entries_retained:s.retainedCount,first_retained_entry:g},history:{path:n,entries_scanned:o.length,entries_after:f.length,baseline_entry_added:p,audit_entry_added:y,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([...c,...b])].sort((v,E)=>v.localeCompare(E)),generated_at:S()})}}var $i=3;function Wi(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.`,m.USAGE)}let t=Rn(e.ids);if(e.ids!==void 0&&t==="")throw new h("history-compact ids requires at least one valid item ID.",m.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:xn(t)}}function $c(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).",m.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.",m.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.",m.USAGE)}function Bi(e){let t=0;for(let r of e.split(/\r?\n/))r.trim().length>0&&(t+=1);return t}async function zi(e){let t=$(e.settings.schema),r=Ge(t),n=await He(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema),o=new Map(n.map(d=>[d.id,r.classify(d.status)])),i=fo.join(e.pmRoot,"history"),s=[],a=[];if(!await be(i))return{candidates:s,preselectionErrors:a};let l=(await uo.readdir(i)).filter(d=>d.endsWith(".jsonl")).sort((d,c)=>d.localeCompare(c));for(let d of l){let c=fo.join(i,d),u=d.slice(0,-6);try{let f=await uo.readFile(c,"utf8");await se({path:c,scope:"project"}),s.push({id:u,entries:Bi(f),bucket:o.get(u)??null})}catch(f){a.push({id:u,outcome:"errored",entries_before:0,entries_after:null,skip_reason:null,changed:!1,error:f instanceof Error?f.message:String(f)})}}return{candidates:s,preselectionErrors:a}}async function Vi(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 Ui(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 Wc(e,t){let r=Wi(e),{pmRoot:n,settings:o,typeRegistry:i}=await fe(t.path),{candidates:s,preselectionErrors:a}=await zi({pmRoot:n,settings:o,typeToFolder:i.type_to_folder}),l=r.ids!==void 0&&r.ids.length>0?"ids":"scan",d=e.minEntries??$i,c=o.history.compact_policy,u=l==="scan"&&e.allOver===void 0&&c.enabled,f=e.allOver??(u?c.max_entries:void 0),p=lo(s,{ids:r.ids,scope:e.scope,minEntries:d,allOver:f}),y=!!e.dryRun,_=[...a],g={streams_considered:s.length+a.length,selected:0,items_compacted:0,items_skipped:0,items_errored:a.length};for(let w of p){let b=await Vi({row:w,options:r,dryRun:y,global:t});if(_.push(b.result),!b.selected){g.items_skipped+=1;continue}g.selected+=1,b.compacted&&(g.items_compacted+=1),b.errored&&(g.items_errored+=1)}return{bulk:!0,dry_run:y,mode:l,scope:e.scope??null,criteria:{min_entries:d,all_over:f??null,policy_threshold_applied:u},totals:g,results:_,generated_at:S()}}import St 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]="9d9d625b-152d-5417-8702-6e0e45839500")}catch{}})();function It(e){return Array.isArray(e)?e:typeof e=="string"?[e]:[]}function ho(e){let t=[];for(let r of e)t.includes(r)||t.push(r);return t.includes("g")||t.push("g"),t.join("")}function po(e){let t=e.trim();if(t.length===0)throw new h("history-redact --regex requires a non-empty pattern.",m.USAGE);let r=t,n="g";if(t.startsWith("/")&&t.length>1){let o=t.lastIndexOf("/");o>0&&(r=t.slice(1,o),n=ho(t.slice(o+1)))}if(r.length===0)throw new h("history-redact --regex cannot use an empty pattern.",m.USAGE);try{new RegExp(r,n)}catch{throw new h("Invalid --regex value; provide a valid JavaScript regular expression.",m.USAGE)}return{kind:"regex",source:r,flags:n}}function go(e,t){let r=[...new Set(It(e).map(i=>i.trim()))].filter(i=>i.length>0).map(i=>({kind:"literal",value:i})),n=[...new Set(It(t).map(i=>i.trim()))].filter(i=>i.length>0).map(po),o=[...r,...n];if(o.length===0)throw new h("history-redact requires at least one matcher via --literal or --regex.",m.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 o}function yo(e,t,r){if(t.length===0)return{value:e,replacements:0};let n=0,o=0;for(;n<=e.length;){let i=e.indexOf(t,n);if(i===-1)break;o+=1,n=i+Math.max(1,t.length)}return o===0?{value:e,replacements:0}:{value:e.split(t).join(r),replacements:o}}function _o(e,t,r){let n=new RegExp(t.source,t.flags),o=[...e.matchAll(n)];return o.length===0?{value:e,replacements:0}:{value:e.replace(n,r),replacements:o.length}}function kt(e,t,r){let n=e,o=0;for(let i of t){let s=i.kind==="literal"?yo(n,i.value,r):_o(n,i,r);n=s.value,o+=s.replacements}return{value:n,replacements:o}}function he(e,t,r){if(typeof e=="string")return kt(e,t,r);if(Array.isArray(e)){let n=0;return{value:e.map(i=>{let s=he(i,t,r);return n+=s.replacements,s.value}),replacements:n}}if(typeof e=="object"&&e!==null){let n=0,o={};for(let[i,s]of Object.entries(e)){let a=he(s,t,r);n+=a.replacements,o[i]=a.value}return{value:o,replacements:n}}return{value:e,replacements:0}}function mo(e,t,r){let n=0;return{patch:e.map(i=>{if(!Object.prototype.hasOwnProperty.call(i,"value"))return i;let s=he(i.value,t,r);return n+=s.replacements,s.replacements>0?{...i,value:s.value}:i}),replacements:n}}function Ki(e){let t=structuredClone(mt),r=0,n=0;for(let o=0;o<e.length;o+=1){let i=e[o];de(t,void 0,A(i.hash_algorithm))!==i.before_hash&&(r+=1),t=Z(t,i.patch,o+1,i.op),de(t,void 0,A(i.hash_algorithm))!==i.after_hash&&(n+=1)}return{hashMismatchesBefore:r,hashMismatchesAfter:n,finalDocument:t}}function Qi(e,t,r){let n=0,o=!1,i=!1,s=e.message;if(typeof e.message=="string"){let d=kt(e.message,t,r);s=d.value,n+=d.replacements,d.replacements>0&&(o=!0)}let a=mo(e.patch,t,r);n+=a.replacements,o||=a.replacements>0;let l=e.reanchor_evidence?.map(d=>{let c=d.patch?mo(d.patch,t,r):{patch:void 0,replacements:0},u=d.record?he(d.record,t,r):{value:void 0,replacements:0};n+=c.replacements,n+=u.replacements;let f=c.replacements>0||u.replacements>0;if(o||=f,!f)return d;i=!0;let{patch:p,record:y,record_hash:_,record_hash_version:g,...w}=d;return c.replacements>0?w:{...w,patch:d.patch}});return{entry:{...e,message:s,patch:a.patch,...l?{reanchor_evidence:l}:{}},replacements:n,changed:o,reanchorEvidenceRedacted:i}}function Yi(e,t,r){let n=structuredClone(mt),o=0,i=0,s=[];for(let a=0;a<e.length;a+=1){let l=e[a],d=rn(l);if(!d.ok)throw new h(`history-redact refuses invalid immutable record ${a+1} (${d.error}).`,m.GENERIC_FAILURE);let c=Qi(l,t,r);i+=c.replacements,c.changed&&(o+=1);let u=de(n,void 0,A(l.hash_algorithm));n=Z(n,c.entry.patch,a+1,c.entry.op);let f=de(n,void 0,A(l.hash_algorithm));s.push(nn(l,{...c.entry,before_hash:u,after_hash:f},{retainPriorRecord:c.changed,retainPriorRecordHash:!c.changed}))}return{entries:s,finalDocument:n,entriesChanged:o,replacements:i}}function wo(e){return Object.keys(e.metadata).length>0}function Xi(e){if(!wo(e.finalDocument))return{raw:null,path:null,document:null};let t=Re(O(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.",m.USAGE);return{document:t,path:z(e.pmRoot,t.metadata.type,e.subject.id,"toon",e.typeToFolder),raw:xe(t,{format:"toon",schema:e.settings.schema})}}function Ji(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 Zi(e){let t=[...e.rewritten.entries];if(e.dryRun||!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let r=e.nextItemDocument??O(e.rewritten.finalDocument);return t.push(V({nowIso:S(),author:e.author,op:"history_redact",before:r,after:r,message:e.message})),{rewrittenEntries:t,auditEntryAdded:!0}}function es(e){let t=[];return{applyRewrite:async({historyRawUnderLock:r})=>{let n=await Me(e.pmRoot,e.author),o=new Set;e.currentItem.path&&o.add(e.currentItem.path),e.nextItem.path&&o.add(e.nextItem.path);let i=new Map;e.currentItem.path&&e.currentItem.raw!==null&&i.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 q(e.nextItem.path,e.nextItem.raw),e.currentItem.path&&(!e.nextItem.path||e.nextItem.path!==e.currentItem.path)&&await St.rm(e.currentItem.path,{force:!0}),await q(e.subject.historyPath,cn(e.rewrittenEntries))}catch(l){try{await ts(e.subject.historyPath,r,o,i)}finally{await ft(e.subject.historyPath)}throw l}await ft(e.subject.historyPath);let a=e.nextItem.path??e.currentItem.path;a&&(t=await Fe({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 rs(e.subject.historyPath,[e.nextItem.path,e.currentItem.path])]}}async function ts(e,t,r,n){t===null?await St.rm(e,{force:!0}):await q(e,t);for(let o of r){let i=n.get(o);i===void 0?await St.rm(o,{force:!0}):await q(o,i)}}async function rs(e,t){let r=[],n=new Set(t.filter(o=>o!==null));for(let o of n)r.push(...await Y({path:o,scope:"project",op:"history_redact"}));return r.push(...await Y({path:e,scope:"project",op:"history_redact:history"})),r}async function ll(e,t,r){let{pmRoot:n,settings:o,typeRegistry:i}=await fe(r.path),s=t.replacement??"",a=s.length===0,l=a?"[redacted]":s,d=go(t.literal,t.regex),c=await K(n,e,o,i.type_to_folder);return We({pmRoot:n,subject:c,settings:o,typeRegistry:i,operation:"history-redact",options:t,transform:u=>ns({pmRoot:n,subject:c,settings:o,typeRegistry:i,options:t,rules:d,replacement:l,replacementIsDefault:a},u)})}function ns(e,t){let{pmRoot:r,subject:n,settings:o,typeRegistry:i,options:s,rules:a,replacement:l,replacementIsDefault:d}=e,c=t.entries,u=Ki(c),f=Yi(c,a,l),p=u.hashMismatchesBefore+u.hashMismatchesAfter,y=!!s.dryRun,_=f.replacements>0,g=[];p>0&&g.push(`history_redact_preexisting_hash_mismatches:${p}`),_||g.push("history_redact_no_matches");let w={raw:t.loadedItem?.raw??null,path:n.located?.itemPath??null,document:t.loadedItem?.document??null},b=Xi({pmRoot:r,subject:n,settings:o,typeToFolder:i.type_to_folder,finalDocument:f.finalDocument}),v=(w.path??null)!==(b.path??null)||(w.raw??null)!==(b.raw??null),E=t.author,C=Ji(s,f),{rewrittenEntries:k,auditEntryAdded:I}=Zi({rewritten:f,dryRun:y,changed:_,nextItemDocument:b.document,author:E,message:C});return{changed:_,rewrittenEntries:k,...es({pmRoot:r,subject:n,settings:o,typeRegistry:i,currentItem:w,nextItem:b,author:E,rewrittenEntries:k}),report:({verification:R,warnings:st})=>({id:n.id,dry_run:y,changed:_,patterns:{literal_count:a.filter(M=>M.kind==="literal").length,regex_count:a.filter(M=>M.kind==="regex").length,total_count:a.length,replacement_is_default:d},history:{path:n.historyPath,entries_scanned:c.length,entries_changed:f.entriesChanged,replacements:f.replacements,hash_mismatches_before:u.hashMismatchesBefore,hash_mismatches_after:u.hashMismatchesAfter,preexisting_hash_mismatches:p,audit_entry_added:I,verify_ok:R.ok,verify_errors:R.errors},item:{existed_before:w.path!==null,exists_after:b.path!==null,path_before:w.path,path_after:b.path,changed:v},warnings:[...new Set([...g,...st])].sort((M,at)=>M.localeCompare(at)),generated_at:S()})}}var dl={applyLiteralRule:yo,applyRegexRule:_o,buildRedactionRules:go,hasItemMetadata:wo,normalizeRegexFlags:ho,normalizeStringArrayInput:It,parseRegexRule:po,redactStringValue:kt,redactUnknownValue:he};(function(){try{var e=typeof window<"u"?window:typeof 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 xt={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 os}from"node:crypto";import{isUtf8 as is}from"node:buffer";import pe from"node:fs/promises";import Rt 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]="d0001f37-7941-5cad-8950-2c6925056d10")}catch{}})();async function vo(e){try{return(await pe.readdir(e)).filter(t=>t.endsWith(".jsonl")).sort()}catch(t){if(Pr(t))return[];throw t}}function ss(e,t,r,n){let o=t.at(-1),i;for(let l=t.length-1;l>=0;l-=1)if(["history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","merge_reconcile"].includes(t[l].op)){i=t[l];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:o?.after_hash??null,latest_record_hash:o?.record_hash??null,latest_hash_algorithm:o?A(o.hash_algorithm):null,rewrite_count:t.reduce((l,d)=>l+(d.reanchor_evidence?.length??0),0),checkpoint_digest:a,last_maintenance:i?{op:i.op,ts:i.ts,record_hash:i.record_hash??null}:null}}function as(e,t,r){try{if(!/^[A-Za-z0-9_-]+$/u.test(e)||!is(t))return null;let n=[];for(let o of t.toString("utf8").split(/\r?\n/u)){if(!o.trim())continue;let i=JSON.parse(o);if(typeof i!="object"||i===null||Array.isArray(i))return null;let s=i;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 pt(n).ok?ss(e,n,t.length,r):null}catch{return null}}async function At(e,t){if(!(await pe.stat(e)).isDirectory())throw new TypeError("attestation tracker root must be a directory");let r=Rt.join(e,"history"),n=await vo(r),o=new Map,i=[];for(let s of n){let a=s.slice(0,-6),l={id:a,digest:null,stream:null};i.push(l);let d=Rt.join(r,s);try{let c=await pe.lstat(d);if(o.set(s,H([c.ino,c.size,c.mtimeMs,c.ctimeMs])),!c.isFile())continue;let u=await pe.readFile(d);l.digest=os(t).update(u).digest("hex"),l.stream=as(a,u,l.digest)}catch{}}if(H(n)!==H(await vo(r)))throw new TypeError("attestation history inventory changed during read; retry");for(let[s,a]of o){let l=await pe.lstat(Rt.join(r,s));if(a!==H([l.ino,l.size,l.mtimeMs,l.ctimeMs]))throw new TypeError("attestation history stream changed during read; retry")}return i}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0a4b3fc5-70bb-5ec0-82b5-a7cdd03c09ea")}catch{}})();function Ct(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Tt(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 cs(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 ls(e){return e===null?!0:!Ct(e)||!Tt(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"&&ke(e.ts)&&(e.record_hash===null||te(e.record_hash,"sha256")||te(e.record_hash,"sha512"))}function ds(e,t){return!Ct(e)||!Tt(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)&&cs(e)&&(e.checkpoint_digest===null||te(e.checkpoint_digest,"sha256"))&&ls(e.last_maintenance)}function bo(e){if(!Ct(e)||!Tt(e,["format","version","hash_algorithm","generated_at","streams","workspace_digest"]))throw new TypeError("Invalid history attestation bundle");if(e.format!==xt.format||e.version!==1||typeof e.generated_at!="string"||!ke(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 i of e.streams){if(!ds(i,t))throw new TypeError("Invalid history attestation stream");let s=i.id;if(r!==void 0&&s<=r)throw new TypeError("Invalid history attestation stream order");r=s}let{workspace_digest:n,...o}=e;if(ut(H(o),t)!==n)throw new TypeError("History attestation rollup mismatch");return e}async function Eo(e={}){let t=A(e.hashAlgorithm),r=e.generatedAt??S();if(!ke(r))throw new TypeError("Invalid history attestation timestamp");let n=await At(x(e.cwd??process.cwd(),e.pmRoot),t),o=n.filter(s=>s.stream===null);if(o.length>0)throw new TypeError(`Cannot export history attestation: invalid streams ${o.map(s=>s.id).join(", ")}`);let i={format:xt.format,version:1,hash_algorithm:t,generated_at:r,streams:n.map(s=>s.stream)};return bo({...i,workspace_digest:ut(H(i),t)})}async function So(e,t={}){let r=bo(e),n=await At(x(t.cwd??process.cwd(),t.pmRoot),r.hash_algorithm),o=new Map(n.map(c=>[c.id,c])),i=new Map(r.streams.map(c=>[c.id,c])),s=r.streams.filter(c=>!o.has(c.id)).map(c=>c.id),a=n.filter(c=>!i.has(c.id)).map(c=>c.id),l=n.filter(c=>c.stream===null).map(c=>c.id),d=[];for(let c of r.streams){let u=o.get(c.id);u&&(u.digest!==c.stream_digest||H(u.stream)!==H(c))&&d.push({id:c.id,before_digest:c.stream_digest,after_digest:u.digest,last_maintenance:u.stream?.last_maintenance??null})}return{ok:s.length+a.length+l.length+d.length===0,workspace_digest:r.workspace_digest,streams_checked:n.length,changed_streams:d.map(c=>c.id),missing_streams:s,added_streams:a,invalid_streams:l,transitions:d}}import Io 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]="825d7132-a49d-584a-b4ac-0801cfe6ad49")}catch{}})();async function Hl(e,t){for(let n of["verify","output","hashAlgorithm"]){let o=e[n];if(!(n==="verify"&&typeof o=="object"&&o!==null)&&o!==void 0&&(typeof o!="string"||o.trim().length===0))throw new h(`history attest ${n} requires a nonempty string.`,m.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",m.USAGE);let n;try{n=typeof e.verify=="string"?JSON.parse(await Io.readFile(e.verify,"utf8")):e.verify}catch{throw new h("Cannot read history attestation proof. Provide --verify with a readable JSON proof file.",m.USAGE)}return So(n,{pmRoot:t.path})}let r=await Eo({pmRoot:t.path,hashAlgorithm:A(e.hashAlgorithm)});if(e.output===void 0)return r;try{await Io.writeFile(e.output,`${JSON.stringify(r,null,2)}
|
|
1
|
+
import{A as $n,Ab as ro,Bb as We,Cc as co,D as Wn,E as Bn,O as zn,P as Vn,Rb as no,S as Kn,Tb as oo,Vb as io,Wb as so,a as fe,b as K,bb as to,c as bn,ca as wt,d as En,da as vt,ea as Qn,fa as Yn,ga as Xn,ha as Jn,ka as Zn,la as bt,ma as Et,na as $e,r as qn,ta as eo,v as me,w as Nn,x as Un,y as Ge,yc as ao,z as Gn}from"./chunk-MKXBCBAN.js";import{$h as ln,$i as He,Al as kn,Bh as en,C as q,Ch as tn,Dc as T,Dg as Xr,Dh as rn,Dm as Mn,E as ct,Eg as xe,Eh as nn,Fg as Re,Gi as hn,Gn as jn,Hm as Fn,Ic as jr,Im as Dn,Jc as lt,Ji as pn,Jm as je,Kh as V,Km as Pn,L as ie,Lh as on,Lm as qe,M as Ee,Mc as Y,Mi as Te,Mm as Ne,Nc as qr,Nh as mt,Nm as Ue,O as Se,Oc as se,Oh as le,Om as Hn,P as Hr,Ph as de,Qf as L,Qh as ht,Rh as O,Sh as sn,Sm as Ln,Tb as H,Th as ue,Ti as Me,Tm as _t,Ua as G,Uh as an,Vi as Fe,Wh as pt,Wi as gn,Wl as xn,Xi as De,Xl as Rn,Yi as Pe,Zh as cn,Zi as yn,Zl as yt,_h as Ce,_i as _n,_l as An,ab as x,ag as A,ai as dn,al as Sn,an as On,bg as ut,bj as wn,cb as Or,cd as X,cj as vn,eb as z,ed as Nr,ff as S,gb as Ie,ia as Lr,if as ke,ih as Ae,jf as zr,jh as Jr,jm as Le,kd as Ur,kf as Vr,kg as $,kh as ce,lf as dt,mf as Kr,mg as J,na as m,nm as Oe,pa as h,pd as Gr,pi as j,qd as $r,ri as N,ti as un,ud as Wr,uh as ft,ui as Z,un as ee,vi as gt,wd as Br,wf as Qr,wh as Zr,wi as fn,x as be,xg as Yr,ym as Cn,z as Pr,zg as ae,zi as mn,zl as In,zm as Tn}from"./chunk-QPKQKSQU.js";import uo from"node:fs/promises";import fo 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]="d51da34a-9f37-5441-91f0-15a16b601709")}catch{}})();function Di(e,t,r){let n=new Set,o=[];for(let i of e){let s=i.trim();if(s.length===0||n.has(s))continue;n.add(s);let a=t.get(s);if(a===void 0){o.push({id:s,entries:0,selected:!1,skip_reason:"no_stream"});continue}if(a.entries<=r){o.push({id:s,entries:a.entries,selected:!1,skip_reason:"already_compact"});continue}o.push({id:s,entries:a.entries,selected:!0,skip_reason:null})}return o}function Pi(e,t){let r=[...e].sort((o,i)=>i.entries-o.entries||o.id.localeCompare(i.id)),n=[];for(let o of r){if(t.scope==="closed"&&o.bucket!=="closed"){n.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"scope_mismatch"});continue}if(o.entries<=t.minEntries){n.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"already_compact"});continue}if(t.allOver!==void 0&&o.entries<=t.allOver){n.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"below_threshold"});continue}n.push({id:o.id,entries:o.entries,selected:!0,skip_reason:null})}return n}function lo(e,t){if(t.ids!==void 0&&t.ids.length>0){let r=new Map(e.map(n=>[n.id,n]));return Di(t.ids,r,t.minEntries)}return Pi(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]="1dede7b7-eeea-520d-97ce-a71687d93bc2")}catch{}})();function Hi(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.",m.USAGE);if(/^\d+$/.test(r)){let i=Number.parseInt(r,10),s=N(t);if(!Number.isSafeInteger(i)||i<s+1||i>s+t.length+1)throw new h(`history-compact --before version must be between ${s+1} and ${s+t.length+1}.`,m.USAGE);let a=i-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.`,m.USAGE);let o=0;for(let[i,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 ${i+1}.`,m.GENERIC_FAILURE);if(a>=n)break;o+=1}return{kind:"timestamp",raw:r,compactCount:o,retainedCount:t.length-o}}function Li(e,t){let r=le(),n=le();for(let o=0;o<e.length;o+=1){let i=e[o];r=Z(r,i.patch,o+1,i.op),o+1===t&&(n=structuredClone(r))}return{checkpoint:n,finalReplay:r}}function Oi(e,t){if(!e)return{loadedItem:null,currentItemRawBeforeLock:null,matchedChainBefore:null};let r=t[t.length-1];return{loadedItem:e,currentItemRawBeforeLock:e.raw,matchedChainBefore:Zr.some(n=>(r.item_hash_version===void 0||r.item_hash_version===n)&&ht(ue(e.document),n,A(r.hash_algorithm)).includes(r.after_hash))}}function ji(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 qi(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 Ni(e){if(!e.changed)return{rewrittenEntries:e.historyEntries,baselineEntryAdded:!1,auditEntryAdded:!1};let{checkpoint:t,finalReplay:r}=Li(e.historyEntries,e.boundary.compactCount),n=e.historyEntries.slice(e.boundary.compactCount),o=N(e.historyEntries,!0),i=e.historyEntries[e.boundary.compactCount-1],s=V({hashAlgorithm:A(i.hash_algorithm),nowIso:e.historyEntries[e.boundary.compactCount-1].ts,author:e.author,op:"history_compact_baseline",before:O(le()),after:O(t),message:qi(e.boundary),context:{history_compaction:{contract_version:1,version_offset:o===null?null:o+e.boundary.compactCount-1,checkpoint_timestamp_semantics:"last_compacted_entry",pruned_entry_count:e.boundary.compactCount,pruned_stream_digest:en(e.historyEntries.slice(0,e.boundary.compactCount)),retained_proof:"stream_digest_and_checkpoint",limitation:"individual_pruned_entries_require_pre_compaction_stream"}}}),a=[tn({...s,before_hash:ht(le(),i.item_hash_version??1,A(i.hash_algorithm))[0],after_hash:i.after_hash,item_hash_version:i.item_hash_version}),...n];return e.dryRun||a.push(V({nowIso:S(),author:e.author,op:"history_compact",before:O(r),after:O(r),message:ji(e.options,e.boundary)})),{rewrittenEntries:a,baselineEntryAdded:!0,auditEntryAdded:!e.dryRun}}async function Ui(e,t,r){let{pmRoot:n,settings:o,typeRegistry:i}=await fe(r.path),s=await K(n,e,o,i.type_to_folder);return We({pmRoot:n,subject:s,settings:o,typeRegistry:i,operation:"history-compact",options:t,transform:a=>Gi(s,t,a)})}function Gi(e,t,r){let n=e.historyPath,o=r.entries,i=r.verification;if(!i.ok)throw new h(`history-compact requires a valid history chain (${i.errors.join(", ")}). Run pm history-repair ${e.id} first.`,m.CONFLICT);let s=Hi(t.before,o),a=s.compactCount>0,l=!!t.dryRun,d=r.author,c=[];a||c.push("history_compact_noop_before_boundary");let u=Oi(r.loadedItem,o);u.matchedChainBefore===!1&&c.push("history_compact_item_chain_mismatch");let{rewrittenEntries:f,baselineEntryAdded:p,auditEntryAdded:y}=Ni({historyEntries:o,boundary:s,changed:a,dryRun:l,author:d,options:t}),_=N(o,!0),g=s.retainedCount>0&&_!==null?_+s.compactCount+1:null;return{changed:a,rewrittenEntries:f,report:({verification:w,warnings:b})=>({id:e.id,dry_run:l,changed:a,compact_boundary:{kind:s.kind,before:s.raw,entries_compacted:s.compactCount,entries_retained:s.retainedCount,first_retained_entry:g},history:{path:n,entries_scanned:o.length,entries_after:f.length,baseline_entry_added:p,audit_entry_added:y,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([...c,...b])].sort((v,E)=>v.localeCompare(E)),generated_at:S()})}}var $i=3;function Wi(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.`,m.USAGE)}let t=Rn(e.ids);if(e.ids!==void 0&&t==="")throw new h("history-compact ids requires at least one valid item ID.",m.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:xn(t)}}function $c(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).",m.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.",m.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.",m.USAGE)}function Bi(e){let t=0;for(let r of e.split(/\r?\n/))r.trim().length>0&&(t+=1);return t}async function zi(e){let t=$(e.settings.schema),r=Ge(t),n=await He(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema),o=new Map(n.map(d=>[d.id,r.classify(d.status)])),i=fo.join(e.pmRoot,"history"),s=[],a=[];if(!await be(i))return{candidates:s,preselectionErrors:a};let l=(await uo.readdir(i)).filter(d=>d.endsWith(".jsonl")).sort((d,c)=>d.localeCompare(c));for(let d of l){let c=fo.join(i,d),u=d.slice(0,-6);try{let f=await uo.readFile(c,"utf8");await se({path:c,scope:"project"}),s.push({id:u,entries:Bi(f),bucket:o.get(u)??null})}catch(f){a.push({id:u,outcome:"errored",entries_before:0,entries_after:null,skip_reason:null,changed:!1,error:f instanceof Error?f.message:String(f)})}}return{candidates:s,preselectionErrors:a}}async function Vi(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 Ui(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 Wc(e,t){let r=Wi(e),{pmRoot:n,settings:o,typeRegistry:i}=await fe(t.path),{candidates:s,preselectionErrors:a}=await zi({pmRoot:n,settings:o,typeToFolder:i.type_to_folder}),l=r.ids!==void 0&&r.ids.length>0?"ids":"scan",d=e.minEntries??$i,c=o.history.compact_policy,u=l==="scan"&&e.allOver===void 0&&c.enabled,f=e.allOver??(u?c.max_entries:void 0),p=lo(s,{ids:r.ids,scope:e.scope,minEntries:d,allOver:f}),y=!!e.dryRun,_=[...a],g={streams_considered:s.length+a.length,selected:0,items_compacted:0,items_skipped:0,items_errored:a.length};for(let w of p){let b=await Vi({row:w,options:r,dryRun:y,global:t});if(_.push(b.result),!b.selected){g.items_skipped+=1;continue}g.selected+=1,b.compacted&&(g.items_compacted+=1),b.errored&&(g.items_errored+=1)}return{bulk:!0,dry_run:y,mode:l,scope:e.scope??null,criteria:{min_entries:d,all_over:f??null,policy_threshold_applied:u},totals:g,results:_,generated_at:S()}}import St 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]="9d9d625b-152d-5417-8702-6e0e45839500")}catch{}})();function It(e){return Array.isArray(e)?e:typeof e=="string"?[e]:[]}function ho(e){let t=[];for(let r of e)t.includes(r)||t.push(r);return t.includes("g")||t.push("g"),t.join("")}function po(e){let t=e.trim();if(t.length===0)throw new h("history-redact --regex requires a non-empty pattern.",m.USAGE);let r=t,n="g";if(t.startsWith("/")&&t.length>1){let o=t.lastIndexOf("/");o>0&&(r=t.slice(1,o),n=ho(t.slice(o+1)))}if(r.length===0)throw new h("history-redact --regex cannot use an empty pattern.",m.USAGE);try{new RegExp(r,n)}catch{throw new h("Invalid --regex value; provide a valid JavaScript regular expression.",m.USAGE)}return{kind:"regex",source:r,flags:n}}function go(e,t){let r=[...new Set(It(e).map(i=>i.trim()))].filter(i=>i.length>0).map(i=>({kind:"literal",value:i})),n=[...new Set(It(t).map(i=>i.trim()))].filter(i=>i.length>0).map(po),o=[...r,...n];if(o.length===0)throw new h("history-redact requires at least one matcher via --literal or --regex.",m.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 o}function yo(e,t,r){if(t.length===0)return{value:e,replacements:0};let n=0,o=0;for(;n<=e.length;){let i=e.indexOf(t,n);if(i===-1)break;o+=1,n=i+Math.max(1,t.length)}return o===0?{value:e,replacements:0}:{value:e.split(t).join(r),replacements:o}}function _o(e,t,r){let n=new RegExp(t.source,t.flags),o=[...e.matchAll(n)];return o.length===0?{value:e,replacements:0}:{value:e.replace(n,r),replacements:o.length}}function kt(e,t,r){let n=e,o=0;for(let i of t){let s=i.kind==="literal"?yo(n,i.value,r):_o(n,i,r);n=s.value,o+=s.replacements}return{value:n,replacements:o}}function he(e,t,r){if(typeof e=="string")return kt(e,t,r);if(Array.isArray(e)){let n=0;return{value:e.map(i=>{let s=he(i,t,r);return n+=s.replacements,s.value}),replacements:n}}if(typeof e=="object"&&e!==null){let n=0,o={};for(let[i,s]of Object.entries(e)){let a=he(s,t,r);n+=a.replacements,o[i]=a.value}return{value:o,replacements:n}}return{value:e,replacements:0}}function mo(e,t,r){let n=0;return{patch:e.map(i=>{if(!Object.prototype.hasOwnProperty.call(i,"value"))return i;let s=he(i.value,t,r);return n+=s.replacements,s.replacements>0?{...i,value:s.value}:i}),replacements:n}}function Ki(e){let t=structuredClone(mt),r=0,n=0;for(let o=0;o<e.length;o+=1){let i=e[o];de(t,void 0,A(i.hash_algorithm))!==i.before_hash&&(r+=1),t=Z(t,i.patch,o+1,i.op),de(t,void 0,A(i.hash_algorithm))!==i.after_hash&&(n+=1)}return{hashMismatchesBefore:r,hashMismatchesAfter:n,finalDocument:t}}function Qi(e,t,r){let n=0,o=!1,i=!1,s=e.message;if(typeof e.message=="string"){let d=kt(e.message,t,r);s=d.value,n+=d.replacements,d.replacements>0&&(o=!0)}let a=mo(e.patch,t,r);n+=a.replacements,o||=a.replacements>0;let l=e.reanchor_evidence?.map(d=>{let c=d.patch?mo(d.patch,t,r):{patch:void 0,replacements:0},u=d.record?he(d.record,t,r):{value:void 0,replacements:0};n+=c.replacements,n+=u.replacements;let f=c.replacements>0||u.replacements>0;if(o||=f,!f)return d;i=!0;let{patch:p,record:y,record_hash:_,record_hash_version:g,...w}=d;return c.replacements>0?w:{...w,patch:d.patch}});return{entry:{...e,message:s,patch:a.patch,...l?{reanchor_evidence:l}:{}},replacements:n,changed:o,reanchorEvidenceRedacted:i}}function Yi(e,t,r){let n=structuredClone(mt),o=0,i=0,s=[];for(let a=0;a<e.length;a+=1){let l=e[a],d=rn(l);if(!d.ok)throw new h(`history-redact refuses invalid immutable record ${a+1} (${d.error}).`,m.GENERIC_FAILURE);let c=Qi(l,t,r);i+=c.replacements,c.changed&&(o+=1);let u=de(n,void 0,A(l.hash_algorithm));n=Z(n,c.entry.patch,a+1,c.entry.op);let f=de(n,void 0,A(l.hash_algorithm));s.push(nn(l,{...c.entry,before_hash:u,after_hash:f},{retainPriorRecord:c.changed,retainPriorRecordHash:!c.changed}))}return{entries:s,finalDocument:n,entriesChanged:o,replacements:i}}function wo(e){return Object.keys(e.metadata).length>0}function Xi(e){if(!wo(e.finalDocument))return{raw:null,path:null,document:null};let t=Re(O(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.",m.USAGE);return{document:t,path:z(e.pmRoot,t.metadata.type,e.subject.id,"toon",e.typeToFolder),raw:xe(t,{format:"toon",schema:e.settings.schema})}}function Ji(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 Zi(e){let t=[...e.rewritten.entries];if(e.dryRun||!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let r=e.nextItemDocument??O(e.rewritten.finalDocument);return t.push(V({nowIso:S(),author:e.author,op:"history_redact",before:r,after:r,message:e.message})),{rewrittenEntries:t,auditEntryAdded:!0}}function es(e){let t=[];return{applyRewrite:async({historyRawUnderLock:r})=>{let n=await Me(e.pmRoot,e.author),o=new Set;e.currentItem.path&&o.add(e.currentItem.path),e.nextItem.path&&o.add(e.nextItem.path);let i=new Map;e.currentItem.path&&e.currentItem.raw!==null&&i.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 q(e.nextItem.path,e.nextItem.raw),e.currentItem.path&&(!e.nextItem.path||e.nextItem.path!==e.currentItem.path)&&await St.rm(e.currentItem.path,{force:!0}),await q(e.subject.historyPath,cn(e.rewrittenEntries))}catch(l){try{await ts(e.subject.historyPath,r,o,i)}finally{await ft(e.subject.historyPath)}throw l}await ft(e.subject.historyPath);let a=e.nextItem.path??e.currentItem.path;a&&(t=await Fe({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 rs(e.subject.historyPath,[e.nextItem.path,e.currentItem.path])]}}async function ts(e,t,r,n){t===null?await St.rm(e,{force:!0}):await q(e,t);for(let o of r){let i=n.get(o);i===void 0?await St.rm(o,{force:!0}):await q(o,i)}}async function rs(e,t){let r=[],n=new Set(t.filter(o=>o!==null));for(let o of n)r.push(...await Y({path:o,scope:"project",op:"history_redact"}));return r.push(...await Y({path:e,scope:"project",op:"history_redact:history"})),r}async function ll(e,t,r){let{pmRoot:n,settings:o,typeRegistry:i}=await fe(r.path),s=t.replacement??"",a=s.length===0,l=a?"[redacted]":s,d=go(t.literal,t.regex),c=await K(n,e,o,i.type_to_folder);return We({pmRoot:n,subject:c,settings:o,typeRegistry:i,operation:"history-redact",options:t,transform:u=>ns({pmRoot:n,subject:c,settings:o,typeRegistry:i,options:t,rules:d,replacement:l,replacementIsDefault:a},u)})}function ns(e,t){let{pmRoot:r,subject:n,settings:o,typeRegistry:i,options:s,rules:a,replacement:l,replacementIsDefault:d}=e,c=t.entries,u=Ki(c),f=Yi(c,a,l),p=u.hashMismatchesBefore+u.hashMismatchesAfter,y=!!s.dryRun,_=f.replacements>0,g=[];p>0&&g.push(`history_redact_preexisting_hash_mismatches:${p}`),_||g.push("history_redact_no_matches");let w={raw:t.loadedItem?.raw??null,path:n.located?.itemPath??null,document:t.loadedItem?.document??null},b=Xi({pmRoot:r,subject:n,settings:o,typeToFolder:i.type_to_folder,finalDocument:f.finalDocument}),v=(w.path??null)!==(b.path??null)||(w.raw??null)!==(b.raw??null),E=t.author,C=Ji(s,f),{rewrittenEntries:k,auditEntryAdded:I}=Zi({rewritten:f,dryRun:y,changed:_,nextItemDocument:b.document,author:E,message:C});return{changed:_,rewrittenEntries:k,...es({pmRoot:r,subject:n,settings:o,typeRegistry:i,currentItem:w,nextItem:b,author:E,rewrittenEntries:k}),report:({verification:R,warnings:st})=>({id:n.id,dry_run:y,changed:_,patterns:{literal_count:a.filter(M=>M.kind==="literal").length,regex_count:a.filter(M=>M.kind==="regex").length,total_count:a.length,replacement_is_default:d},history:{path:n.historyPath,entries_scanned:c.length,entries_changed:f.entriesChanged,replacements:f.replacements,hash_mismatches_before:u.hashMismatchesBefore,hash_mismatches_after:u.hashMismatchesAfter,preexisting_hash_mismatches:p,audit_entry_added:I,verify_ok:R.ok,verify_errors:R.errors},item:{existed_before:w.path!==null,exists_after:b.path!==null,path_before:w.path,path_after:b.path,changed:v},warnings:[...new Set([...g,...st])].sort((M,at)=>M.localeCompare(at)),generated_at:S()})}}var dl={applyLiteralRule:yo,applyRegexRule:_o,buildRedactionRules:go,hasItemMetadata:wo,normalizeRegexFlags:ho,normalizeStringArrayInput:It,parseRegexRule:po,redactStringValue:kt,redactUnknownValue:he};(function(){try{var e=typeof window<"u"?window:typeof 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 xt={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 os}from"node:crypto";import{isUtf8 as is}from"node:buffer";import pe from"node:fs/promises";import Rt 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]="d0001f37-7941-5cad-8950-2c6925056d10")}catch{}})();async function vo(e){try{return(await pe.readdir(e)).filter(t=>t.endsWith(".jsonl")).sort()}catch(t){if(Pr(t))return[];throw t}}function ss(e,t,r,n){let o=t.at(-1),i;for(let l=t.length-1;l>=0;l-=1)if(["history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","merge_reconcile"].includes(t[l].op)){i=t[l];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:o?.after_hash??null,latest_record_hash:o?.record_hash??null,latest_hash_algorithm:o?A(o.hash_algorithm):null,rewrite_count:t.reduce((l,d)=>l+(d.reanchor_evidence?.length??0),0),checkpoint_digest:a,last_maintenance:i?{op:i.op,ts:i.ts,record_hash:i.record_hash??null}:null}}function as(e,t,r){try{if(!/^[A-Za-z0-9_-]+$/u.test(e)||!is(t))return null;let n=[];for(let o of t.toString("utf8").split(/\r?\n/u)){if(!o.trim())continue;let i=JSON.parse(o);if(typeof i!="object"||i===null||Array.isArray(i))return null;let s=i;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 pt(n).ok?ss(e,n,t.length,r):null}catch{return null}}async function At(e,t){if(!(await pe.stat(e)).isDirectory())throw new TypeError("attestation tracker root must be a directory");let r=Rt.join(e,"history"),n=await vo(r),o=new Map,i=[];for(let s of n){let a=s.slice(0,-6),l={id:a,digest:null,stream:null};i.push(l);let d=Rt.join(r,s);try{let c=await pe.lstat(d);if(o.set(s,H([c.ino,c.size,c.mtimeMs,c.ctimeMs])),!c.isFile())continue;let u=await pe.readFile(d);l.digest=os(t).update(u).digest("hex"),l.stream=as(a,u,l.digest)}catch{}}if(H(n)!==H(await vo(r)))throw new TypeError("attestation history inventory changed during read; retry");for(let[s,a]of o){let l=await pe.lstat(Rt.join(r,s));if(a!==H([l.ino,l.size,l.mtimeMs,l.ctimeMs]))throw new TypeError("attestation history stream changed during read; retry")}return i}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0a4b3fc5-70bb-5ec0-82b5-a7cdd03c09ea")}catch{}})();function Ct(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Tt(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 cs(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 ls(e){return e===null?!0:!Ct(e)||!Tt(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"&&ke(e.ts)&&(e.record_hash===null||te(e.record_hash,"sha256")||te(e.record_hash,"sha512"))}function ds(e,t){return!Ct(e)||!Tt(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)&&cs(e)&&(e.checkpoint_digest===null||te(e.checkpoint_digest,"sha256"))&&ls(e.last_maintenance)}function bo(e){if(!Ct(e)||!Tt(e,["format","version","hash_algorithm","generated_at","streams","workspace_digest"]))throw new TypeError("Invalid history attestation bundle");if(e.format!==xt.format||e.version!==1||typeof e.generated_at!="string"||!ke(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 i of e.streams){if(!ds(i,t))throw new TypeError("Invalid history attestation stream");let s=i.id;if(r!==void 0&&s<=r)throw new TypeError("Invalid history attestation stream order");r=s}let{workspace_digest:n,...o}=e;if(ut(H(o),t)!==n)throw new TypeError("History attestation rollup mismatch");return e}async function Eo(e={}){let t=A(e.hashAlgorithm),r=e.generatedAt??S();if(!ke(r))throw new TypeError("Invalid history attestation timestamp");let n=await At(x(e.cwd??process.cwd(),e.pmRoot),t),o=n.filter(s=>s.stream===null);if(o.length>0)throw new TypeError(`Cannot export history attestation: invalid streams ${o.map(s=>s.id).join(", ")}`);let i={format:xt.format,version:1,hash_algorithm:t,generated_at:r,streams:n.map(s=>s.stream)};return bo({...i,workspace_digest:ut(H(i),t)})}async function So(e,t={}){let r=bo(e),n=await At(x(t.cwd??process.cwd(),t.pmRoot),r.hash_algorithm),o=new Map(n.map(c=>[c.id,c])),i=new Map(r.streams.map(c=>[c.id,c])),s=r.streams.filter(c=>!o.has(c.id)).map(c=>c.id),a=n.filter(c=>!i.has(c.id)).map(c=>c.id),l=n.filter(c=>c.stream===null).map(c=>c.id),d=[];for(let c of r.streams){let u=o.get(c.id);u&&(u.digest!==c.stream_digest||H(u.stream)!==H(c))&&d.push({id:c.id,before_digest:c.stream_digest,after_digest:u.digest,last_maintenance:u.stream?.last_maintenance??null})}return{ok:s.length+a.length+l.length+d.length===0,workspace_digest:r.workspace_digest,streams_checked:n.length,changed_streams:d.map(c=>c.id),missing_streams:s,added_streams:a,invalid_streams:l,transitions:d}}import Io 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]="825d7132-a49d-584a-b4ac-0801cfe6ad49")}catch{}})();async function Hl(e,t){for(let n of["verify","output","hashAlgorithm"]){let o=e[n];if(!(n==="verify"&&typeof o=="object"&&o!==null)&&o!==void 0&&(typeof o!="string"||o.trim().length===0))throw new h(`history attest ${n} requires a nonempty string.`,m.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",m.USAGE);let n;try{n=typeof e.verify=="string"?JSON.parse(await Io.readFile(e.verify,"utf8")):e.verify}catch{throw new h("Cannot read history attestation proof. Provide --verify with a readable JSON proof file.",m.USAGE)}return So(n,{pmRoot:t.path})}let r=await Eo({pmRoot:t.path,hashAlgorithm:A(e.hashAlgorithm)});if(e.output===void 0)return r;try{await Io.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.",m.USAGE)}return{output:e.output,workspace_digest:r.workspace_digest,streams:r.streams.length}}import us from"fast-json-patch";import Mt 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]="85aa928d-92b8-5f67-8482-0fe5715fef45")}catch{}})();async function ko(e,t,r){let n=await yn(e,{schema:t.schema});return n.error===null?{raw:n.raw,document:n.document}:{raw:n.raw,document:xo(r),recovered:!0}}function fs(e,t){return un(e,t,{errorSubject:"restore",allowFutureTimestamp:!0})}function xo(e){let t=gt(e,e.length-1);return Object.keys(t.metadata).length===0?{metadata:{},body:t.body}:Re(O(t))}async function ms(e,t,r,n){let o=await K(e,t,r,n),i=o.located?await Te({pmRoot:e,settings:r,itemId:o.id,commandLabel:"restore"}):{warnings:[]};return{...o,historyPolicyWarnings:i.warnings}}function hs(e,t){let r=ue(e),n=ue(t),o=us.compare(r,n),i=new Set;for(let s of o){if(s.path==="/body"||s.path.startsWith("/body/")){i.add("body");continue}let a=s.path.replace(/^\/(?:metadata|front_matter)\/?/,"").split("/")[0];i.add(a.replaceAll("~1","/").replaceAll("~0","~"))}return Array.from(i).sort((s,a)=>s.localeCompare(a))}async function ps(e){let t=await ro({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:"restore",readItem:r=>ko(r,e.settings,e.history)});return{loadedItemUnderLock:t.loadedItemUnderLock,existingItemPath:t.locatedUnderLock?.itemPath??null}}function gs(e,t){return e?{document:e.document,originalRaw:e.raw}:{document:xo(t),originalRaw:null}}function ys(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.`,m.CONFLICT);return e.enforcement==="warn"?[`ownership_warning:assignee_conflict:${e.resolvedId}:${t}`]:[]}async function _s(e){if(e.existingItemPath&&e.resolvedOriginalRaw!==null&&e.restoredItemPath!==e.existingItemPath){await q(e.existingItemPath,e.resolvedOriginalRaw),await Mt.rm(e.restoredItemPath,{force:!0});return}if(e.existingItemPath&&e.resolvedOriginalRaw!==null){await q(e.existingItemPath,e.resolvedOriginalRaw);return}await Mt.rm(e.restoredItemPath,{force:!0})}async function ws(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 Yl(e,t,r,n){let o=x(process.cwd(),n.path);await L(o);let i=await j(o),s=G(i,T()),a=await ms(o,e,i,s.type_to_folder),l=a.id,{raw:d,entries:c}=await Jr(a.historyPath,l);if(c.length===0)throw new h(`No history exists for ${l}; restore is unavailable.`,m.NOT_FOUND);let u=fs(t,c),f=fn(gt(c,u.historyIndex),u),p=sn(f,{schema:i.schema});if(p.metadata.id!==l)throw new h(`Restore target resolved to item ${p.metadata.id}, expected ${l}.`,m.GENERIC_FAILURE);let _=(a.located?await ko(a.located,i,c):null)?.raw??null,g=Ae(r.author,i.author_default),w=await Kr(o,l,i.locks.ttl_seconds,g,!!r.force,i.governance.force_required_for_stale_lock,i.locks.wait_ms);try{let{loadedItemUnderLock:b,existingItemPath:v}=await ps({pmRoot:o,subject:a,settings:i,typeRegistry:s,historyRawBeforeLock:d,currentItemRawBeforeLock:_,history:c}),E="toon",C=gs(b,c),k=ys({document:C.document,author:g,force:r.force,enforcement:i.governance.ownership_enforcement,resolvedId:l}),I=hs(C.document,p),R=await hn({pmRoot:o,settings:i,operation:"restore",author:g,before:C.document,after:p});await qr({pm_root:o,operation:"restore",before:C.document,after:p,changed_fields:I,sdk:wn({pmRoot:o,settings:i,typeToFolder:s.type_to_folder})});let st=xe(p,{format:E,schema:i.schema}),M=z(o,p.metadata.type,l,E,s.type_to_folder),at=await Me(o,g),Mr=[];try{await q(M,st),v&&M!==v&&await Mt.rm(v);let Mi=V({nowIso:S(),author:g,op:"restore",before:C.document,after:p,message:r.message,context:R.decisions.length===0?void 0:{workflow_policies:R.decisions}});try{await on(a.historyPath,Mi)}catch(Fi){throw await _s({existingItemPath:v,resolvedOriginalRaw:C.originalRaw,restoredItemPath:M}),Fi}Mr=await Fe({pmRoot:o,preferredFormat:i.item_format,typeToFolder:s.type_to_folder,schema:i.schema,itemPath:M,previousItemPath:v??void 0,document:p})}finally{await at()}let Ti=await ws({restoredItemPath:M,historyPath:a.historyPath,before:C.document,after:p});jr({id:p.metadata.id,op:"restore",item_type:p.metadata.type,previous_status:C.document.metadata.status,status:p.metadata.status,previous:lt(C.document.metadata,I),current:lt(p.metadata,I),changed_fields:I});let Fr=c[u.historyIndex],Dr=N(c,!0);return{item:p.metadata,restored_from:{kind:u.kind,target:u.raw,history_index:u.historyIndex+1,version:Dr===null?null:Dr+u.historyIndex+1,entry_ts:Fr.ts,entry_op:Fr.op},changed_fields:I,warnings:[...R.warnings,...b?.recovered?["restore_unreadable_item_recovered"]:[],...a.historyPolicyWarnings,...k,...Mr,...Ti]}}finally{await w()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2a9a4dc0-8027-5761-9bbf-cac1ef83bd10")}catch{}})();var vs=["status","type","tag","priority","deadlineBefore","deadlineAfter","updatedAfter","updatedBefore","createdAfter","createdBefore","ids","assignee","assigneeFilter","parent","sprint","release"],bs=["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 Es(e){return e!=null&&(typeof e!="string"||e.split(",").some(t=>t.trim().length>0))}function Jl(e,t,r={}){let n=r.includePagination!==!1;return[t,...vs.map(i=>e?.[i]),...n?[e?.limit,e?.offset]:[]].some(Es)||bs.some(i=>e?.[i]===!0)}function Ro(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]="7a4a98b2-3872-506d-b88d-877b0033dd2d")}catch{}})();var Ao=["parent","type","priority","status","assignee","tags","sprint","release"];function To(e,t){let r=Le(e,t,{strict:!0,flagLabel:"--status"});if(!(!r||r.length===0))return r}function Mo(e,t=["estimate","estimated_minutes","priority"]){let r=e.sum?.trim(),n=e.avg?.trim(),o=r&&r.length>0?r:void 0,i=n&&n.length>0?n:void 0;if(!o&&!i)return null;if(o&&i&&o!==i)throw new h("Aggregate --sum and --avg must target the same numeric field",m.USAGE);let s=o??i;if(!t.includes(s))throw new h(`Aggregate numeric field "${s}" is not registered. Allowed: ${t.join(", ")}`,m.USAGE);return{field:s,sum:o!==void 0,avg:i!==void 0}}function Fo(e){let t=e?.trim()??"status";if(t.length===0)throw new h("--group-by requires at least one field name",m.USAGE);let r=jn(t);if(r.length===0)throw new h("--group-by requires a comma-separated list of fields",m.USAGE);for(let n of r)if(!Ao.includes(n))throw new h(`Aggregate group fields must be one of ${Ao.join("|")}; received "${n}"`,m.USAGE);return r}function Do(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 Po(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 Do(t.tags);case"sprint":return t.sprint??null;case"release":return t.release??null;default:return null}}function Ho(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 Be(e,t){return e.map(r=>`${r}:${JSON.stringify(t[r]??null)}`).join("|")}var Ss={parent:"(unparented)",type:"(untyped)",priority:"(no priority)",status:"(no status)",assignee:"(unassigned)",tags:"(untagged)",sprint:"(no sprint)",release:"(no release)"};function Co(e,t){return t==null||t===""?Ss[e]:String(t)}function Is(e,t){return e.length===1?Co(e[0],t[e[0]]):e.map(r=>`${r}=${Co(r,t[r])}`).join(" | ")}function Lo(e,t,r){for(let n of r){let o=Ho(e.group[n],t.group[n]);if(o!==0)return o}return 0}function Oo(e,t){let n=e[t];if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"){let o=n.trim();if(o.length===0)return null;let i=Number(o);if(Number.isFinite(i))return i}return null}function jo(e,t){return t<=0?0:Math.round(e/t*1e4)/100}function Ft(e,t,r){let n=Yr(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 ks(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 xs(e,t){if(t===null){e.null_count+=1;return}e.numeric_count+=1,e.numeric_sum+=t}function Rs(e){e.accumulator.row.count+=1,e.includeCompletion&&Ft(e.accumulator,e.item.status,e.statusRegistry),e.numericAggregation!==null&&xs(e.accumulator,e.numericValue)}function As(e,t,r,n){for(let o of t){let i=Be(r,o),s=e.get(i);if(s){Rs({...n,accumulator:s});continue}let a=ks(o,n.numericValue);n.includeCompletion&&Ft(a,n.item.status,n.statusRegistry),e.set(i,a)}}function Cs(e,t){let r={};for(let n of e)r[n]=Po(n,t);return r}function Ts(e,t,r){let n=[Cs(e,t)];if(r==="tuple")return n;for(let o of e){let i=t[o];if(!Array.isArray(i))continue;let s=[...new Set(i.map(a=>a.trim().toLowerCase()).filter(Boolean))].sort();s.length!==0&&(n=n.flatMap(a=>s.map(l=>({...a,[o]:l}))))}return n}function Ms(e,t,r,n){let o={...e.row,group_label:Is(t,e.row.group)};return r&&(o.open=e.open_count,o.in_progress=e.in_progress_count,o.closed=e.closed_count,o.other=e.other_count,o.completion_pct=jo(e.closed_count,e.row.count)),n!==null&&(o.null_count=e.null_count,n.sum&&(o.sum=e.numeric_sum),n.avg&&(o.avg=e.numeric_count===0?null:e.numeric_sum/e.numeric_count)),o}function Fs(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 od(e,t){if(e.count===!1)throw new h("Aggregate grouped counts are always enabled; omit count=false.",m.USAGE);let r=x(process.cwd(),t.path),n=await j(r),o=$(n.schema),i=["estimate","estimated_minutes","priority",...J(n.schema).definitions.filter(v=>v.type==="number").map(v=>v.metadata_key)],s=Fo(e.groupBy),a=e.setMode??"element";if(a!=="element"&&a!=="tuple")throw new h("Aggregate --set-mode must be element or tuple",m.USAGE);let l=To(e.status,o),d=Mo(e,[...new Set(i)].sort((v,E)=>v.localeCompare(E))),c=e.completion===!0,u=e.includeUnparented===!0,f=await $e(void 0,{...Ro(e),status:e.status,noTruncate:!0,strictRead:!0},t),p=new Map,y=0,_=0,g=0;for(let v of f.items){let E=v;if(s.includes("parent")&&E.parent===void 0&&!u){y+=1;continue}let C=d===null?null:Oo(E,d.field),k=Ts(s,E,a);As(p,k,s,{item:E,statusRegistry:o,includeCompletion:c,numericAggregation:d,numericValue:C}),g+=k.length,_+=1}let w=[...p.values()].map(v=>Ms(v,s,c,d)).sort((v,E)=>Lo(v,E,s)),b=f.warnings&&f.warnings.length>0?f.warnings:void 0;return{...Ds(w,s,e),count:w.length,totals:{items_considered:f.items.length,items_grouped:_,items_skipped_unparented:y,group_memberships:g},filters:Fs({groupBy:s,setMode:a,includeCompletion:c,includeUnparented:u,status:l,options:e,numericAggregation:d}),now:S(),...b?{warnings:b}:{}}}function Ds(e,t,r){let n=eo(r.limit,"limit")??50,o=r.after===void 0?-1:e.findIndex(a=>Be(t,a.group)===r.after);if(r.after!==void 0&&o<0)throw new h("Aggregate --after cursor is absent from the current grouping; restart without --after.",m.USAGE);let i=e.slice(o+1,o+1+n),s=o+1+i.length<e.length;return{groups:i,returned_count:i.length,truncated:s,next_after:s?Be(t,i.at(-1).group):null}}var id={buildGroupKey:Be,compareAggregateRows:Lo,compareNullableGroupValue:Ho,completionPct:jo,normalizeTagGroupValue:Do,parseGroupBy:Fo,parseNumericAggregation:Mo,parseStatus:To,readNumericAggregateValue:Oo,resolveGroupValue:Po,updateCompletionCounts:Ft};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="acda1c64-cb50-57b5-868d-a27ca6912979")}catch{}})();var qo=1e6,No=20;function Uo(e,t,r,n=No){if(!Number.isSafeInteger(n)||n<0)throw new h("Child projection sample limit must be a non-negative integer.",m.USAGE);let o=e.trim().toLowerCase(),i={},s=[],a=0;for(let g of t){if(a+=1,a>qo)throw new h(`Child projection exceeded the ${qo.toLocaleString("en-US")} item safety bound.`,m.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(g)}let l=new Map(s.map(g=>[g.id.trim().toLowerCase(),g])),d=Kn(Vn(s,zn())),c=new Set(d.children_by_parent.get(o)??[]);for(let g of s)g.parent?.trim().toLowerCase()===o&&c.add(g.id.trim().toLowerCase());let u=[...c].map(g=>l.get(g)),f=0;for(let g of u){let w=g.status.trim().toLowerCase();i[w]=(i[w]??0)+1,ae(w,r)||(f+=1)}u.sort((g,w)=>g.id.localeCompare(w.id));let p=u.slice(0,n).map(g=>({id:g.id,title:g.title,type:g.type,status:g.status,priority:g.priority})),y=u.length>p.length,_=n===0?No:n;return{count:u.length,active:f,by_status:Object.fromEntries(Object.entries(i).sort(([g],[w])=>g.localeCompare(w))),sample:p,sample_limit:n,truncated:y,next_offset:y?p.length:null,continuation:y?`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]="926ca5b2-8cfc-56e7-8cbf-fb0e7152d834")}catch{}})();var Ps=new Set(["event","meeting","reminder"]);function Hs(e){return Ps.has(e.type.trim().toLowerCase())||e.deadline!==void 0||(e.reminders?.length??0)>0||(e.events?.length??0)>0}function Dt(e){if(!Hs(e))return;let t=[...e.events??[]].sort((n,o)=>n.start_at.localeCompare(o.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}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="33c1e75c-e348-5ab1-933f-2f7b6394fe40")}catch{}})();var Os=new Set(["epic","feature","milestone","plan"]),js=new Set(Object.keys(Lr).map(e=>e.toLowerCase()));function Ht(e){return Object.fromEntries(["comments","notes","learnings","files","tests","docs","reminders","events"].map(r=>[r,e[r]?.length??0]))}function qs(e,t,r){let n=Ht(e);return[...t.length>0?["body"]:[],...Object.entries(n).flatMap(([o,i])=>i>0?[o]:[]),...n.files+n.tests+n.docs>0?["linked"]:[],...r===void 0?["children"]:r.count>0?["children"]:[],...typeof e.assignee=="string"&&e.assignee.trim().length>0?["claim_state"]:[],...Dt(e)?["schedule"]:[]]}function $o(e){let t=e.trim().toLowerCase();return t.length>0&&(Os.has(t)||!js.has(t))}function Go(e){return{ts:e.ts,author:e.author,message:e.message??null}}function Ns(e,t){let r=e?.trim(),n=r&&r.length>0?r:null,o=[...t].reverse().find(s=>s.op==="claim"),i=[...t].reverse().find(s=>s.op==="release");return{claimed:n!==null,assignee:n,last_claim:o?Go(o):null,last_release:i?Go(i):null}}function Us(e){if(e===void 0||e.trim().length===0)return"standard";let t=e.trim().toLowerCase();if(t==="full")return"deep";if(wt.includes(t))return t;throw new h("Get --depth must be one of brief|standard|deep|full",m.USAGE)}function Gs(e,t){let r=Ht(e);if(t==="deep")return{...e,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:r.notes,tests_count:r.tests,collection_counts:r};let{comments:n,notes:o,learnings:i,files:s,tests:a,docs:l,reminders:d,events:c,...u}=e;return{...u,notes_count:e.notes?.length??0,tests_count:e.tests?.length??0,collection_counts:r}}function $s(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",m.USAGE);return t}function Ve(e){return e.startsWith("item.")?e.slice(5):e}function Ws(e,t,r){if(e===null)return;let n=vt(t),o=new Set(n),i=e.filter(s=>{let a=Ve(s);return!o.has(s)&&!o.has(a)});if(i.length>0){let s=["get",r,"--fields",e.filter(a=>!i.includes(a)).join(",")||"id,title,status"];throw new h(`Unknown get --fields value(s): ${i.join(", ")}`,m.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 Bs=new Set(["comments","notes","learnings","files","tests","test_runs","docs","reminders","events","dependencies","plan_steps","plan_decisions","plan_discoveries","plan_validation"]);function zs(e,t,r){return Object.hasOwn(t,r)?t[r]:e[r]!==void 0?e[r]:Bs.has(r)?[]:void 0}function Vs(e,t){let r=e,n={notes_count:e.notes?.length??0,tests_count:e.tests?.length??0,collection_counts:Ht(e)},o={id:e.id};for(let i of t){let s=Ve(i);s==="body"||s==="linked"||s.startsWith("linked.")||s==="claim_state"||s.startsWith("claim_state.")||s==="children"||s.startsWith("children.")||s==="schedule"||s.startsWith("schedule.")||(o[s]=zs(r,n,s))}return o}function ge(e,t){return e?.some(r=>r===t||r===`item.${t}`)??!1}function ze(e,t){return e.some(r=>{let n=Ve(r);return n===t||n.startsWith(`${t}.`)})}function Ks(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.",m.USAGE,{code:"projection_options_mutually_exclusive",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",m.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.",m.USAGE);return{depth:e.full?"deep":Us(e.depth),full:e.full===!0||e.depth?.trim().toLowerCase()==="full",treeDepth:e.tree===!0?qn(e.treeDepth,"--tree-depth"):void 0,fields:$s(e.fields),fieldProjection:e.fields!==void 0}}async function Qs(e,t,r){let n=x(process.cwd(),t.path);await L(n);let o=await j(n),i=G(o,T());if(r!==void 0){let l=await En(e,r,{pmRoot:t.path});return{pmRoot:n,settings:o,typeToFolder:i.type_to_folder,locatedId:l.document.metadata.id,metadata:l.document.metadata,body:l.document.body,historical:l}}let s=await De(n,e,o.id_prefix,o.item_format,i.type_to_folder);if(!s)throw await vn(n,e,o.id_prefix,i.type_to_folder);let a=await Pe(s,{schema:o.schema});return{pmRoot:n,settings:o,typeToFolder:i.type_to_folder,locatedId:s.id,metadata:a.document.metadata,body:a.document.body}}function Ys(e,t,r,n){let o=J(t.schema).definitions.map(i=>i.metadata_key);if(Ws(e,o,n),r&&ze(e??[],"children"))throw new h("Get --at cannot project children because workspace-level historical relationships are not yet indexed.",m.USAGE)}function Pt(e){let{fieldProjection:t,depth:r,fields:n,field:o}=e;return t?o==="body"||o==="linked"?ge(n,o):ze(n,o):r!=="brief"}async function Xs(e,t){if(!t)return;let r=Ie(e.pmRoot,e.locatedId),n=await ce(r,e.locatedId);return Ns(e.metadata.assignee,e.historical?n.slice(0,e.historical.target.historyIndex+1):n)}function Js(e,t,r,n){let o=n||ge(r,"linked.files"),i=n||ge(r,"linked.tests"),s=n||ge(r,"linked.docs");!n&&!o&&!i&&!s||(e.linked={files:o?t.metadata.files??[]:[],tests:i?t.metadata.tests??[]:[],docs:s?t.metadata.docs??[]:[]})}async function Zs(e,t){if(!t)return;let r=$(e.settings.schema),n=await He(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema);return Uo(e.locatedId,n,r)}function ea(e,t,r,n){if(!n)return;let o=Dt(t.metadata);if(o){if(r===null||ge(r,"schedule")){e.schedule=o;return}e.schedule=Object.fromEntries(Object.entries(o).filter(([i])=>r.some(s=>Ve(s)===`schedule.${i}`)))}}async function ta(e,t,r,n){if(t.tree!==!0)return;let o=await $e(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:o.count,items:o.items.map(i=>i)}}async function Rd(e,t,r={}){let n=Ks(r,e),o=await Qs(e,t,r.at);Ys(n.fields,o.settings,o.historical!==void 0,o.locatedId);let i=Pt({...n,field:"body"}),s=Pt({...n,field:"linked"}),a=Pt({...n,field:"claim_state"}),l=o.historical===void 0&&(n.fieldProjection?ze(n.fields,"children"):n.depth==="deep"&&(n.full||$o(o.metadata.type))),d=n.fieldProjection?ze(n.fields,"schedule"):n.depth!=="brief",c=await Xs(o,a),u={item:n.fieldProjection?Vs(o.metadata,n.fields):Gs(o.metadata,n.depth)};i&&(u.item.body=o.body),Js(u,o,n.fields,s),c&&(u.claim_state=c),ea(u,o,n.fields,d);let f=await Zs(o,l);f!==void 0&&(u.children=f);let p=await ta(o,r,n.treeDepth,t);if(p!==void 0&&(u.tree=p),o.historical&&(u.reconstructed=!0,u.as_of_version=o.historical.as_of_version,u.as_of_timestamp=o.historical.as_of_timestamp),o.historical===void 0)try{await Qr({pmRoot:o.pmRoot,author:Ae(void 0,o.settings.author_default),itemIds:[o.locatedId],intent:"get"})}catch{}return Nr(u,qs(o.metadata,o.body,f)),u}var Ad={shouldAutoIncludeGetChildren:$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]="0cc18a30-5068-5c59-b559-7afc4d446ed8")}catch{}})();function ra(e,t){return t===void 0?e:e.slice(Math.max(0,e.length-t))}function na(e,t){return e.map(({entry:r,version:n})=>{let o=new Set,i=an(r.patch);for(let s of i)o.add(yt(s.path)),s.from&&o.add(yt(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:i.length,changed_fields:[...o].sort((s,a)=>s.localeCompare(a))}})}function oa(e){if(e[0]?.op!=="history_compact_baseline")return;let t=N(e,!0);return{offset:t,first_version:t===null?null:t+1,last_version:t===null?null:t+e.length}}async function ia(e,t){let r=x(process.cwd(),t.path);await L(r);let n=await j(r),o=G(n,T()),i=e.trim()===Ce,s=i?Ce:mn(e,n.id_prefix),a=await De(r,s,n.id_prefix,n.item_format,o.type_to_folder),l=a?.id??s,d=i?ln(r):Ie(r,l);if(!a&&!await be(d))throw new h(`Item ${e} not found`,m.NOT_FOUND);return a&&await Te({pmRoot:r,settings:n,itemId:a.id,commandLabel:"history"}),{historyPath:d,located:a,resolvedId:l,settings:n}}async function jd(e,t,r){let n=Oe(t.limit),{historyPath:o,located:i,resolvedId:s,settings:a}=await ia(e,r),l=await ce(o,s),d=oa(l),c=a.agent_identity.identity_vocabulary,u=no(a.agent_identity.harness_signals),f=io({harness:t.harness,agentInstance:t.agentInstance,provenance:t.provenanceFilter},c,u),p=sa(l).filter(({entry:I})=>f(I)),y=ra(p,n),_=y.map(({entry:I})=>I),g=t.compact===!0,w=g?na(y,d):void 0,b=t.provenance===!0?y.map(({entry:I,durableVersion:R})=>oo(I,c,{itemId:s,version:R})):void 0,v=t.provenance===!0?"provenance":g?"compact":"full",E={compact:{compact_history:w},provenance:{provenance_history:b},full:{history:_}}[v],k={id:s,...E,compact:g,projection:{mode:v,row_key:{compact:"compact_history",provenance:"provenance_history",full:"history"}[v]},omission_receipt:Ur("history",v),count:_.length,limit:n??null,version_addressing:d,...t.provenanceSummary===!0?{provenance_summary:so(p.map(({entry:I})=>I),c,u)}:{}};if((t.diff||t.field!==void 0)&&(k.diff=An(l,{windowStartIndex:Math.max(0,l.length-_.length),field:t.field})),t.verify){let I=i?(await Pe(i,{schema:a.schema})).document:void 0;if(k.verification=bn(l,I),s===Ce&&k.verification.ok){let R=await dn(x(process.cwd(),r.path));k.verification={...k.verification,ok:R.ok,errors:R.ok?k.verification.errors:[...k.verification.errors,"verify_failed:workspace_state_mismatch"],workspace_state_matches_latest:R.ok,workspace_state_mismatches:R.mismatched_documents,workspace_state_missing:R.missing_documents,workspace_state_unreadable:R.unreadable_documents}}}return k}function sa(e){let t=N(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]="8920d604-004f-5546-a855-a192e7a86e0a")}catch{}})();function aa(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",m.USAGE);return t}function Ke(e){return e===!0}function Wo(e){return Hr(e,0,1)??void 0}function Bo(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",m.USAGE);return t}function zo(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",m.USAGE);return t}function Q(e,t){if(e==null)return;let r=String(e).trim();if(r.length!==0)return dt(r,new Date,t)}function F(e){return e.toLowerCase().replace(/\s+/g," ").trim()}function Lt(e,t){if(e!==void 0)return dt(e,new Date,t)}function ca(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",m.USAGE);return[...new Set(t)]}function Qe(e,t="<query>"){let r=e.compact===!0,n=e.full===!0,o=ca(e.fields);if(Number(r)+Number(n)+ +(o!==void 0)>1)throw new h("Search projection options are mutually exclusive. Use one of --compact, --full, or --fields.",m.USAGE,{code:"projection_options_mutually_exclusive",recovery:{suggested_retry:X(["search",t,"--full"]),suggested_retry_args:["search",t,"--full"]}});return r?{mode:"compact",fields:[...Qn]}:n?{mode:"full",fields:[]}:o?{mode:"fields",fields:o}:{mode:"full",fields:[]}}function Ot(e,t,r="<query>"){if(e.mode!=="fields")return;let n=Yn(t.definitions.flatMap(s=>[s.key,s.metadata_key])),o=new Set(n),i=e.fields.filter(s=>{let a=s.trim();return!o.has(a)});if(i.length>0){let s=["search",r,"--fields",e.fields.filter(a=>!i.includes(a)).join(",")||"id,title,status,score"];throw new h(`Unknown search --fields value(s): ${i.join(", ")}`,m.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 Ye(e){let t=F(e);if(!t)throw new h("Search query must not be empty",m.USAGE);return t.split(/\s+/u).filter(Boolean)}function jt(e){let t=e.search?.max_results;return typeof t=="number"&&Number.isFinite(t)&&t>0?Math.floor(t):50}var la=["auto","keyword","semantic","hybrid"];function da(e){let t=e.search?.default_mode;if(typeof t!="string")return"auto";let r=t.trim().toLowerCase();return la.includes(r)?r:"auto"}function qt(e){if(typeof e.requested=="string"&&e.requested.trim().length>0)return{mode:aa(e.requested),source:"explicit"};let t=da(e.settings);return t!=="auto"?{mode:t,source:"settings"}:{mode:e.semanticRunnable?"hybrid":"keyword",source:"auto"}}function Nt(e){let t=e.search?.score_threshold;return typeof t=="number"&&Number.isFinite(t)?t:0}function Ut(e){let t=e.search?.hybrid_semantic_weight;return typeof t=="number"&&Number.isFinite(t)&&t>=0&&t<=1?t:.7}function Gt(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=(o,i)=>typeof o=="number"&&Number.isFinite(o)&&o>=0?o:i;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)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="18c21143-96a8-5031-b288-42f6188f8821")}catch{}})();function $t(e){return $r("search",{pmRoot:e.pmRoot,query:e.query.trim(),mode:e.mode,options:Gr(e.searchOptions,Sn)})}function Vo(e){let t=Br(e.sorted,{cursor:e.searchOptions.after,fingerprint:$t(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]="48888c80-60e1-5905-afd5-8c1b6e532f99")}catch{}})();function Ko(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 ua=[{optionKey:"status",summaryKey:"status",normalize:e=>Ko(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 re(e){let{mode:t,matchMode:r,options:n,includeLinked:o,titleExact:i,phraseExact:s,scoreThreshold:a,hybridSemanticWeight:l,runtimeFieldFilters:d}=e,c={};return Zn(c,n,ua),Object.assign(c,Et(n)),Object.assign(c,bt(n)),r!==void 0&&r!=="or"&&(c.match_mode=r),o&&(c.include_linked=!0),i&&(c.title_exact=!0),s&&(c.phrase_exact=!0),a>0&&(c.score_threshold=a),t==="hybrid"&&n.semanticWeight!==void 0&&(c.hybrid_semantic_weight=l),n.limit!==void 0&&(c.limit=n.limit),d&&Object.keys(d).length>0&&(c.runtime_filters=d),c}function ne(e){let{effectiveMode:t,matchMode:r,options:n,includeLinked:o,titleExact:i,phraseExact:s,scoreThreshold:a,hybridSemanticWeight:l,queryExpansion:d,rerank:c,runtimeFieldFilters:u}=e,f=p=>p??null;return{mode:t,match_mode:r,status:n.status===void 0||Ko(n.status)?"all":n.status,type:f(n.type),tag:f(n.tag),priority:f(n.priority),deadline_before:f(n.deadlineBefore),deadline_after:f(n.deadlineAfter),updated_after:f(n.updatedAfter),updated_before:f(n.updatedBefore),created_after:f(n.createdAfter),created_before:f(n.createdBefore),assignee:f(n.assignee),sprint:f(n.sprint),release:f(n.release),parent:f(n.parent),...Et(n),...bt(n),include_linked:o,title_exact:i,phrase_exact:s,score_threshold:a,hybrid_semantic_weight:t==="hybrid"?l:null,query_expansion_enabled:d.enabled,query_expansion_provider:d.provider,rerank_enabled:c.enabled,rerank_model:c.model,rerank_top_k:c.top_k,limit:f(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]="bc52818b-d37f-5d00-954d-d50203a433c2")}catch{}})();var fa=1.2,ma=.75;function Wt(e){return ee(e)}function ha(e){let t=new Map;for(let r of e)t.set(r,(t.get(r)??0)+1);return t}function Yo(e){let t=[],r=new Map,n=0;for(let i of e){let s=Wt(i.text),a=ha(s);n+=s.length;for(let l of a.keys())r.set(l,(r.get(l)??0)+1);t.push({id:i.id,termFrequencies:a,length:s.length})}let o=t.length;return{documents:t,documentFrequency:r,documentCount:o,averageDocumentLength:o>0?n/o:0}}function pa(e,t){return Math.log(1+(e-t+.5)/(t+.5))}function Xo(e,t,r){let n=new Map;if(e.documentCount===0||e.averageDocumentLength===0)return n;let o=[...new Set(t.filter(s=>s.length>0))];if(o.length===0)return n;let i=new Map;for(let s of o){let a=e.documentFrequency.get(s);a!==void 0&&i.set(s,pa(e.documentCount,a))}if(i.size===0)return n;for(let s of e.documents){let a=0;for(let[l,d]of i){let c=s.termFrequencies.get(l);if(c===void 0)continue;let u=1-r.b+r.b*s.length/e.averageDocumentLength,f=c+r.k1*u;a+=d*(c*(r.k1+1)/f)}a>0&&n.set(s.id,a)}return n}function Qo(e,t,r,n){return typeof e!="number"||!Number.isFinite(e)?t:Math.min(n,Math.max(r,e))}function Jo(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 Zo(e){let t=e?.search?.bm25;return{k1:Qo(t?.k1,fa,0,1e3),b:Qo(t?.b,ma,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]="e2985104-efdb-59e5-9674-2dd865ebdf56")}catch{}})();var Bt=4,ga=20,ya=200,_a=new Set(["a","an","and","for","from","in","into","of","on","or","the","to","with"]);function zt(e,t){let r=[],n=new Set;for(let o of e){let i=o.trim().replaceAll(/\s+/g," ");if(i.length===0)continue;let s=i.toLowerCase();if(!n.has(s)&&(n.add(s),r.push(i),r.length>=t))break}return r}function wa(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 va(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 ei(e,t=Bt){let r=e.trim().replaceAll(/\s+/g," ");if(r.length===0)return[];let n=ee(r);if(n.length===0)return[r];let o=n.filter(a=>!_a.has(a.toLowerCase())),i=n.map(a=>wa(a)),s=o.map(a=>va(a));return zt([r,n.join(" "),o.join(" "),i.join(" "),s.join(" ")],Math.max(1,t))}function ti(e){let t=Array.isArray(e)?e:e?.queries;return Array.isArray(t)?zt(t.filter(r=>typeof r=="string"),Bt):[]}function ri(e,t,r){return zt([...e,...t],Math.max(1,r))}function ni(e,t){let n=e.search?.query_expansion,o=ie(n?.provider);return{enabled:n?.enabled===!0,provider:o??t,max_queries:Bt}}function oi(e,t){let n=e.search?.rerank,o=ie(n?.model),s=Se(n?.top_k)??ga;return{enabled:n?.enabled===!0,model:o??t,top_k:Math.min(ya,s)}}function ii(e){let t=Array.isArray(e)?e:e?.hits;if(!Array.isArray(t))return[];let r=new Map;for(let o of t){if(typeof o!="object"||o===null)continue;let i=ie(o.id),s=o.score;if(!i||typeof s!="number"||!Number.isFinite(s))continue;let a=r.get(i);(a===void 0||s>a)&&r.set(i,s)}let n=[...r.entries()].map(([o,i])=>({id:o,score:i}));return n.sort((o,i)=>o.score!==i.score?i.score-o.score:o.id.localeCompare(i.id)),n}function ba(e,t){let r=e.length,n=0;for(let o=0;o<r;o+=1)n+=e[o]*t[o];return n}function si(e){let t=0;for(let r=0;r<e.length;r+=1)t+=e[r]*e[r];return Math.sqrt(t)}function Ea(e,t,r){if(!e||!t||e.length===0||t.length===0||e.length!==t.length)return 0;let n=ba(e,t),o=si(t),i=r*o;return!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(o)||!Number.isFinite(i)||i===0?0:Math.max(-1,Math.min(1,n/i))}async function ai(e,t,r,n,o){if(n.length===0)return new Map;let i=ie(t)??e.model,s=i===e.model?e:{...e,model:i},a=[r.trim(),...n.map(f=>f.text)],l=await je(s,a,o?{timeout_ms:o}:{}),d=l[0];if(!d)return new Map;let c=si(d),u=new Map;for(let f=0;f<n.length;f+=1){let p=n[f],y=l[f+1];if(!y)continue;let _=Ea(d,y,c);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]="a5e4bd88-a099-559f-8194-7b56f325eb0e")}catch{}})();function oe(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function U(e){return Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null&&typeof t.text=="string"):[]}function ye(e){return Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null&&typeof t.id=="string"&&typeof t.kind=="string"):[]}function Vt(e){let t=e.metadata;return[t.title,t.description,t.status,oe(t.tags).join(" "),e.body,U(t.comments).map(r=>r.text).join(" "),U(t.notes).map(r=>r.text).join(" "),U(t.learnings).map(r=>r.text).join(" "),qe(t).join(" "),Ne(t).join(" "),ye(t.dependencies).map(r=>`${r.id} ${r.kind}`).join(" "),Ue(t)]}function Kt(e,t){return Vt(e).some(r=>F(r).includes(t))}function Qt(e,t,r){return!r.titleExact&&!r.phraseExact?e:e.filter(n=>!(r.titleExact&&F(n.metadata.title)!==t||r.phraseExact&&!Kt(n,t)))}function Sa(e){if(e&&[...e].some(t=>t.toLowerCase()==="none"||t.toLowerCase()==="null"))throw new h('--assignee no longer accepts "none" or "null".',m.USAGE)}function Ia(e,t,r){let n=me(e.assignee,{label:"--assignee"});Sa(n);let o=Xn(e),i=Jn(e);return{typeFilter:Nn(e.type,t),tagFilter:me(e.tag,{label:"--tag",normalize:s=>s.toLowerCase()}),priorityFilter:Un(e.priority),deadlineBefore:Lt(e.deadlineBefore,"deadline-before"),deadlineAfter:Lt(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:me(e.sprint,{label:"--sprint"}),releaseFilter:me(e.release,{label:"--release"}),parentFilter:e.parent?.trim(),statusSet:r&&r.length>0?new Set(r):void 0,missingMetadataFilters:o,missingMetadataActive:Gn(o),contentFieldFilters:i,contentFiltersActive:Wn(i)}}function ka(e,t){return xa(e,t)&&Vr(e,t)&&Ra(e,t)}function xa(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 Ra(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 Aa(e,t,r,n){let o=e.metadata;return!(!ka(o,t)||!Tn(o,r)||t.missingMetadataActive&&!$n(o,t.missingMetadataFilters,n)||t.contentFiltersActive&&!Bn(o,t.contentFieldFilters))}function Yt(e,t,r,n,o,i){let s=Ia(t,r,o);return e.filter(a=>Aa(a,s,n,i))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5a927991-1dbe-5906-a0eb-7da2534b6905")}catch{}})();var Ca=2,Ta=120,Ma=6,Fa=40,Da=1e3,Pa=900,Ha="\xAB",La="\xBB",ci=60;function Xe(e,t){let r=0,n=0;for(;;){let o=e.indexOf(t,n);if(o<0)return r;r+=1,n=o+t.length}}var li=[{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=>U(e.metadata.comments).map(t=>t.text).join(" ")},{name:"notes",weightKey:"notes_weight",value:e=>U(e.metadata.notes).map(t=>t.text).join(" ")},{name:"learnings",weightKey:"learnings_weight",value:e=>U(e.metadata.learnings).map(t=>t.text).join(" ")},{name:"reminders",weightKey:"reminders_weight",value:e=>qe(e.metadata).join(" ")},{name:"events",weightKey:"events_weight",value:e=>Ne(e.metadata).join(" ")},{name:"dependencies",weightKey:"dependencies_weight",value:e=>ye(e.metadata.dependencies).map(t=>`${t.id} ${t.kind}`).join(" ")},{name:"plan",weightKey:"body_weight",value:e=>Ue(e.metadata)}],Oa=new Map(li.map(e=>[e.name,e]));function Xt(e,t){let r=t.filter(o=>o.length>0).sort((o,i)=>i.length-o.length).map(o=>o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"));if(r.length===0)return e;let n=new RegExp(r.join("|"),"gi");return e.replace(n,o=>`${Ha}${o}${La}`)}function Jt(e,t){if(e.length===0)return null;let r=e.toLowerCase(),n=-1,o=0;for(let c of t){if(c.length===0)continue;let u=r.indexOf(c);u>=0&&(n<0||u<n)&&(n=u,o=c.length)}if(n<0)return null;let i=Math.max(0,n-ci),s=Math.min(e.length,n+o+ci),a=Xt(e.slice(i,s),t),l=i>0?"\u2026":"",d=s<e.length?"\u2026":"";return`${l}${a}${d}`}function Je(e,t,r){let n=[];for(let o of t){let i=Oa.get(o);if(i===void 0)continue;let s=Jt(i.value(e),r);s!==null&&n.push({field:o,snippet:s})}return n}function ja(e,t,r){return[...li.map(n=>({name:n.name,value:n.value(e),weight:r[n.weightKey]})),{name:"linked_content",value:t,weight:r.linked_content_weight}]}function qa(e,t,r){let n=F(e.id),o=typeof r=="string"?r.trim().toLowerCase():"",i=F(o),s=i.length>0&&n.startsWith(i)?n.slice(i.length).trim():n;return t!==n&&t!==s?null:{item:e,score:t===n?Da:Pa,matched_fields:["id"],matched_all_terms:!0,exact_id_match:!0}}function Na(e,t,r,n,o){for(let i of e){let s=t.get(i)??0;s>0&&(o.score+=s*n.title_exact_bonus,o.matched.add("title"),o.matchedTokens.add(i));for(let a of r){let l=Xe(a.value.toLowerCase(),i);l>0&&(o.score+=l*a.weight,o.matched.add(a.name),o.matchedTokens.add(i))}}}function Ua(e,t,r,n){F(e.title)===t&&(n.score+=Ta,n.matched.add("title"));for(let i of r){let s=Xe(F(i.value),t);s>0&&(n.score+=s*i.weight*Ma,n.matched.add(i.name))}}function Zt(e,t,r,n,o,i,s=!1){let a=e.metadata,l=qa(a,r,i);if(l)return l;let d=new Map;for(let _ of ee(a.title))d.set(_,(d.get(_)??0)+1);let c=ja(e,n,o),u={score:0,matched:new Set,matchedTokens:new Set};Na(t,d,c,o,u);let f=new Set(t),p=f.size>0&&u.matchedTokens.size===f.size;return s&&f.size>1&&p&&(u.score+=Fa),t.length>=Ca&&r.includes(" ")&&Ua(a,r,c,u),u.score<=0?null:{item:a,score:u.score,matched_fields:[...u.matched].sort((_,g)=>_.localeCompare(g)),matched_all_terms:p}}function er(e,t){return[...e].sort((r,n)=>{let o=n.score-r.score;if(o!==0)return o;let i=ae(r.item.status,t),s=ae(n.item.status,t);if(i!==s)return i?1:-1;let a=r.item.priority-n.item.priority;if(a!==0)return a;let l=zr(n.item.updated_at,r.item.updated_at);return l!==0?l:r.item.id.localeCompare(n.item.id)})}function tr(e,t,r,n,o,i,s,a=!1){return Zt(e,t,r,n?o.get(e.metadata.id)??"":"",i,s,a)}function _e(e){if(e.size===0)return new Map;let t=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY;for(let o of e.values())t=Math.min(t,o),r=Math.max(r,o);if(r===t)return new Map([...e.keys()].map(o=>[o,1]));let n=new Map;for(let[o,i]of e)n.set(o,(i-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]="0175d395-3f87-5a93-8d4f-a3150aaf16ae")}catch{}})();function et(e){let t=[],r=e;for(let n=0;n<5&&r&&typeof r=="object";n+=1){let o=r.code;typeof o=="string"&&t.push(o.toLowerCase()),r=r.cause}return t.join(" ")}function tt(e){let t=(e instanceof Error?e.message:String(e)).toLowerCase(),r=et(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 rr(e,t){let r=tt(t);return`search_${e}_fallback:${r}:using_keyword_mode`}function di(e){return e?.commands?.some(r=>r.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 nr(e,t,r){try{let n=await On(e);n.warnings.length>0&&r.push(...n.warnings);let o=to(t.map(s=>({id:s.metadata.id,updated_at:s.metadata.updated_at})),n.entries);if(o.length===0)return;let i=di(T());r.push(...ui(o.length,i)),process.stderr.write(`[pm] warning: ${o.length} item${o.length===1?" is":"s are"} new or modified since the last reindex and ${o.length===1?"is":"are"} NOT in the semantic index yet \u2014 run '${i.command}'${i.follow_up_command?`, then '${i.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 ui(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 rt(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`,m.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`,m.USAGE);return{provider:t.active,vectorStore:r.active??null}}var D=Ee;function we(e){let t=T(),r=In(t,e);if(!r)return null;let n=r.runtime_definition??r.definition,o=n.query,i=n.queryExpansion??n.query_expansion,s=n.rerank,a=D(n.name)??D(r.definition.name)??e;if(!a)return null;let l={providerName:a,...typeof o=="function"?{query:o}:{},...typeof i=="function"?{queryExpansion:i}:{},...typeof s=="function"?{rerank:s}:{}};return!l.query&&!l.queryExpansion&&!l.rerank?null:l}function or(e){let t=D(e.search?.provider),r=we(t);return r?.query?{providerName:r.providerName,query:r.query}:null}function ir(e){let t=T(),r=D(e.vector_store?.adapter),n=kn(t,r);if(!n)return null;let o=n.runtime_definition??n.definition,i=o.query;if(typeof i!="function")return null;let s=o.upsert;return{adapterName:D(o.name)??D(n.definition.name)??r??"extension",query:i,...typeof s=="function"?{upsert:s}:{}}}function sr(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: [...] }`,m.GENERIC_FAILURE);let o=new Set,i=[];for(let s of n){if(typeof s!="object"||s===null)continue;let a=D(s.id),l=s.score;if(!a||typeof l!="number"||!Number.isFinite(l)||o.has(a))continue;let d=r.get(a);if(!d)continue;let c=s.matched_fields,u=Array.isArray(c)&&c.every(f=>typeof f=="string")?[...new Set(c.map(f=>f.trim()).filter(f=>f.length>0))].sort((f,p)=>f.localeCompare(p)):[`provider:${e}`];o.add(a),i.push({item:d.metadata,score:l,matched_fields:u})}return i}function ar(e,t){let r=[],n=new Map;for(let o of e){if(n.has(o.id))continue;let i=t.get(o.id);i&&(n.set(o.id,o.score),r.push({item:i.metadata,score:o.score,matched_fields:["semantic"]}))}return{semanticHits:r,semanticScores:n}}function Ze(e,t){let r=t.filter(d=>d.exact_id_match===!0);if(r.length===0)return e;let n=new Set(r.map(d=>d.item.id)),o=e.filter(d=>!n.has(d.item.id)),i=o.reduce((d,c)=>Math.max(d,c.score),0),s=r.sort((d,c)=>c.score-d.score),a=i+s.length+1;return[...s.map((d,c)=>({...d,score:a-c,matched_fields:["id"]})),...o]}function nt(e,t,r,n,o="semantic"){let i=new Map(r.map(u=>[u.item.id,u.score])),s=new Map(r.map(u=>[u.item.id,u.matched_fields])),a=_e(t),l=_e(i),d=new Set([...t.keys(),...i.keys()]),c=1-n;return[...d].map(u=>{let f=e.get(u),p=a.get(u)??0,y=l.get(u)??0,_=p*n+y*c;if(_<=0)return null;let g=new Set;t.has(u)&&g.add(o);for(let w of s.get(u)??[])g.add(w);return{item:f.metadata,score:_,matched_fields:[...g].sort((w,b)=>w.localeCompare(b))}}).filter(u=>u!==null)}function cr(e){let t=e.configuredProvider?.trim().toLowerCase();return t==="bm25"?"explicit":t==="auto"&&!e.hasEmbeddingProvider&&!e.hasExtensionSearchProvider?"auto-fallback":null}function lr(e){let t=e.filteredDocuments.map(s=>({id:s.metadata.id,text:Jo(Hn(s,{fields:e.corpusFields}))})),r=Yo(t),n=Xo(r,Wt(e.query),e.bm25Params),o=new Map(e.filteredDocuments.map(s=>[s.metadata.id,s]));if(e.requestedMode==="semantic"){let s=[...n].map(([a,l])=>({item:o.get(a).metadata,score:l,matched_fields:["bm25"]}));return Ze(s,e.keywordHits)}let i=nt(o,n,e.keywordHits,e.hybridSemanticWeight,"bm25");return Ze(i,e.keywordHits)}function dr(e){let t=new Map;for(let n of e)for(let o of n){let i=t.get(o.id);(!i||o.score>i.score)&&t.set(o.id,o)}let r=[...t.values()];return r.sort((n,o)=>n.score!==o.score?o.score-n.score:n.id.localeCompare(o.id)),r}function ur(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 Ga(e,t){let r=e.queryExpansion.enabled?ei(t,e.queryExpansion.max_queries):[t],n=r.length>0?r:[t];if(!e.queryExpansion.enabled)return n;if(e.queryExpansionExtension?.expand)try{let o=await Promise.resolve(e.queryExpansionExtension.expand({query:t,mode:e.requestedMode,settings:e.settings}));return ri(n,ti(o),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 $a(e,t,r,n){if(e.extensionVectorAdapter?.query)try{return await Promise.resolve(e.extensionVectorAdapter.query({vector:t,limit:r,settings:e.settings}))}catch(o){if(!e.vectorStore)throw new h(`Extension vector adapter query failed and no built-in fallback store is configured (${o instanceof Error?o.message:String(o)})`,m.GENERIC_FAILURE);return e.warnings.push(`search_vector_adapter_failed:${e.extensionVectorAdapter.adapterName}:using_builtin`),await _t(e.vectorStore,t,r,n)}if(e.vectorStore)return await _t(e.vectorStore,t,r,n);throw new h("Semantic search requires either a configured vector store or an extension vector adapter query handler",m.USAGE)}function Wa(e,t,r){return[...e].sort((o,i)=>o.score!==i.score?i.score-o.score:o.item.id.localeCompare(i.item.id)).slice(0,r).map(o=>{let i=t.get(o.item.id);return i?{hit:o,text:ur(i)}:null}).filter(o=>o!==null)}async function Ba(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(i=>({id:i.hit.item.id,text:i.text,score:i.hit.score}))})),o=ii(n);return o.length>0?new Map(o.map(i=>[i.id,i.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 za(e,t,r){let n=await Ba(e,t,r);if(n)return n;let o=r.map(i=>({id:i.hit.item.id,text:i.text}));try{return await ai(e.provider,e.rerank.model,t,o,e.embeddingTimeoutMs)}catch{return e.warnings.push("search_rerank_failed:using_hybrid_scores"),null}}function Va(e,t){let r=new Set(t.keys()),n=e.map(o=>{let i=t.get(o.item.id);if(i===void 0)return o;let s=new Set(o.matched_fields);return s.add("rerank"),{...o,score:i,matched_fields:[...s].sort((a,l)=>a.localeCompare(l))}});return n.sort((o,i)=>{let s=r.has(o.item.id),a=r.has(i.item.id);return s!==a?s?-1:1:o.score!==i.score?i.score-o.score:o.item.id.localeCompare(i.item.id)}),n}async function Ka(e,t,r,n){if(!e.rerank.enabled||r.length<=1)return r;let o=Wa(r,n,e.rerank.top_k),i=await za(e,t,o);return i&&i.size>0?Va(r,i):r}async function fr(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}:{},o=e.query.trim(),i=await Ga(e,o),s=await je(e.provider,i,r),a=await Promise.all(s.map(async y=>await $a(e,y,t,n))),l=dr(a),d=new Map(e.filteredDocuments.map(y=>[y.metadata.id,y])),{semanticHits:c,semanticScores:u}=ar(l,d),f=u.size;if(e.requestedMode==="semantic")return{hits:Ze(c,e.keywordHits),vectorMatchCount:f};let p=await Ka(e,o,nt(d,u,e.keywordHits,e.hybridSemanticWeight),d);return{hits:Ze(p,e.keywordHits),vectorMatchCount:f}}function fi(e){let t=we(e.provider??void 0);return t?.queryExpansion?{providerName:t.providerName,expand:t.queryExpansion}:null}function mi(e){let t=we(D(e.search?.provider));return t?.rerank?{providerName:t.providerName,rerank:t.rerank}:null}import ot 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]="6e743cc1-3ff0-58b1-bf11-351d1655864c")}catch{}})();function hr(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()})),o=[...t,...r,...n].filter(s=>s.path.length>0).sort((s,a)=>s.scope.localeCompare(a.scope)||s.path.localeCompare(a.path)),i=new Map;for(let s of o)i.set(`${s.scope}:${s.path}`,s);return[...i.values()]}async function hi(e){let t=mr.resolve(e);try{let r=await ot.realpath(t);return{resolved:t,realpath:r}}catch{return null}}async function pr(e,t){let[r,n]=await Promise.all([hi(e),hi(t)]);return{projectContainmentRoot:r,globalContainmentRoot:n}}async function gr(e,t){let r=hr(e.metadata),n=[];for(let o of r){let i=o.scope==="global"?t.globalContainmentRoot:t.projectContainmentRoot;if(!i)continue;let s=mr.resolve(i.resolved,o.path);if(!ct(i.resolved,s))continue;let a;try{a=await ot.realpath(s)}catch{continue}if(ct(i.realpath,a))try{await se({path:s,scope:o.scope}),n.push(await ot.readFile(s,"utf8"))}catch{}}return n.join(`
|
|
5
5
|
`)}async function yr(e,t,r,n){let o=pn(T()),i=async(d,c,u)=>{let f=async(p,y)=>{await se({path:p,scope:"project"});let _=await ot.readFile(p,"utf8");return Xr(_,{format:y,schema:n,extensionFieldNames:o,onWarning:w=>s.push(w)}).body};try{return await f(c,u)}catch{let p=u==="toon"?"json_markdown":"toon",y=z(e,d.type,d.id,p,r);try{return await f(y,p)}catch{return s.push(`item_list_item_read_failed:${mr.relative(e,y)}`),""}}},s=[],a=await gn(e,t,r,s,n),l=[];if(a.length===0){let d=await _n(e,t,r,s,n);for(let c of d){let u=z(e,c.type,c.id,t,r),f=await i(c,u,t);l.push({metadata:c,body:f})}return{documents:l,warnings:[...new Set(s)].sort((c,u)=>c.localeCompare(u))}}for(let d of a){if(typeof d.body=="string"){l.push({metadata:d.metadata,body:d.body});continue}let c=await i(d.metadata,d.item_path,d.item_format);l.push({metadata:d.metadata,body:c})}return{documents:l,warnings:[...new Set(s)].sort((d,c)=>d.localeCompare(c))}}async function pi(e,t,r){let n=new Map;if(!e||t!=="keyword"&&t!=="hybrid")return n;let o=process.cwd(),i=await pr(o,Or(o)),s=await Promise.all(r.map(async a=>[a.metadata.id,await gr(a,i)]));for(let[a,l]of s)n.set(a,l);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]="5ff2b814-42b0-50fc-92dd-17e9fc521982")}catch{}})();var gi=["tag","status","type","priority"];function _r(e){let t={},r=[];for(let n of e.split(/\s+/).filter(o=>o.length>0)){let o=n.indexOf(":"),i=o>0?n.slice(0,o).toLowerCase():"",s=o>0?n.slice(o+1):"",a=gi.includes(i)?i: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 wr(e,t,r){let n={...e};for(let o of gi){let i=t[o];if(i!==void 0){if(Ee(n[o])!==void 0){r.push(`search_inline_filter_ignored:${o}:flag_takes_precedence`);continue}n[o]=i}}return n}function yi(e,t){let r=[],n=_r(e),o=Object.keys(n.inlineFilters).length>0;if(o&&n.residualQuery.trim().length===0)throw new h("Inline field:value tokens consumed the entire query, leaving no search terms.",m.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 i=o?n.residualQuery:e,s=wr(t,n.inlineFilters,r);return{query:i,options:s,inlineWarnings:r,highlight:s.highlight===!0,includeLinked:Ke(s.includeLinked),titleExact:Ke(s.titleExact),phraseExact:Ke(s.phraseExact),matchMode:Bo(typeof s.matchMode=="string"?s.matchMode:void 0),minScoreOverride:zo(s.minScore),countOnly:s.count===!0,tokens:Ye(i),normalizedQuery:F(i),limit:Oe(s.limit),projection:Qe(s,e),modeWasExplicit:typeof s.mode=="string"&&s.mode.trim().length>0}}function _i(e){if(e.after!==void 0&&e.count===!0)throw new h("Search --after cannot be combined with --count.",m.USAGE)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="984a6fdc-9383-5f89-8e71-b0d3ed2a35cc")}catch{}})();function br(e,t,r,n,o,i,s,a,l,d,c,u,f,p){let y=f?{total:0,count_only:!0}:{};if(d.mode==="compact"&&n.compact===!0){let w=re({mode:t,matchMode:r,options:n,includeLinked:o,titleExact:n.titleExact===!0,phraseExact:n.phraseExact===!0,scoreThreshold:i,hybridSemanticWeight:s,runtimeFieldFilters:u});return{query:e.trim(),mode:t,...kr(p),items:[],count:0,...y,filters:w,...c.length>0?{warnings:c}:{}}}let g=d.mode==="full"?null:[...d.fields];return{query:e.trim(),mode:t,mode_source:p,items:[],count:0,...y,filters:ne({effectiveMode:t,matchMode:r,options:n,includeLinked:o,titleExact:n.titleExact===!0,phraseExact:n.phraseExact===!0,scoreThreshold:i,hybridSemanticWeight:s,queryExpansion:a,rerank:l,runtimeFieldFilters:u??{}}),projection:{mode:d.mode,fields:g},now:S(),...c.length>0?{warnings:c}:{}}}function Er(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 i=r.slice(5);return i.length===0?null:e.item[i]??null}let n=e,o=e.item;return Object.prototype.hasOwnProperty.call(o,r)?o[r]??null:Object.prototype.hasOwnProperty.call(n,r)?n[r]??null:null}function Sr(e,t){return t.mode==="full"?e.map(({matched_all_terms:r,exact_id_match:n,...o})=>o):e.map(r=>{let n={};for(let o of t.fields)n[o]=Er(r,o);return n})}function Ir(e,t){return br(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 wi(e,t){if(e.projection.mode==="compact"&&e.options.compact===!0)return vr({query:e.query.trim(),mode:e.effectiveMode,...kr(e.modeSource),items:[],count:t,total:t,count_only:!0,filters:re({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 vr({query:e.query.trim(),mode:e.effectiveMode,mode_source:e.modeSource,items:[],count:t,total:t,count_only:!0,filters:ne({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:S()},e.warnings)}function kr(e){return e==="settings"?{mode_source:e}:{}}function vr(e,t){return t.length===0?e:{...e,warnings:t}}function ve(e,t){return t?{...e,workspace_memory:t}:e}function vi(e,t,r){if(!e.highlight)return{hits:r,projection:e.projection};let n=new Map(t.map(i=>[i.metadata.id,i])),o=r.map(i=>({...i,highlights:Je(n.get(i.item.id),i.matched_fields,e.tokens)}));return e.projection.mode==="full"||e.projection.fields.includes("highlights")?{hits:o,projection:e.projection}:{hits:o,projection:{mode:e.projection.mode,fields:[...e.projection.fields,"highlights"]}}}function bi(e,t,r,n,o,i){let s=n<r?{total:r}:{};if(e.projection.mode==="compact"&&e.options.compact===!0)return vr({query:e.query.trim(),mode:e.effectiveMode,...kr(e.modeSource),items:t,count:t.length,...s,...i,filters:re({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=o.mode==="full"?null:[...o.fields];return{query:e.query.trim(),mode:e.effectiveMode,mode_source:e.modeSource,items:t,count:t.length,...s,...i,filters:ne({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:o.mode,fields:a},now:S(),...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]="59612a0b-e84f-5a7c-b9ae-a26ec9a939e2")}catch{}})();var Pf={applyFilters:Yt,applyExactQueryFilters:Qt,applyInlineQueryFilters:wr,buildHitHighlights:Je,buildVerboseSearchFilters:ne,buildExplicitSemanticFallbackWarning:rr,buildCompactSearchFilterSummary:re,buildHybridLexicalScore:tr,buildRerankCorpus:ur,buildSemanticHits:ar,classifyImplicitSemanticFallbackReason:tt,collectErrorCauseCodes:et,collectExactPhraseFields:Vt,collectLinkedPaths:hr,combineHybridHits:nt,computeBuiltInBm25Hits:lr,computeSemanticOrHybridHits:fr,resolveBuiltInBm25Mode:cr,countOccurrences:Xe,dependencyEntries:ye,documentContainsExactPhrase:Kt,emptySearchResult:br,highlightFieldSnippet:Jt,loadDocuments:yr,markTokenRuns:Xt,parseInlineQueryFilters:_r,maybeEmitVectorIndexStaleWarning:nr,loadLinkedCorpus:gr,mergeVectorHitsById:dr,normalizeExtensionProviderHits:sr,normalizeScoreMap:_e,parseProjectionConfig:Qe,parseTimestampWindow:Q,parseTokens:Ye,projectSearchHits:Sr,readSearchFieldValue:Er,requireSemanticDependencies:rt,resolveExtensionSearchProvider:or,resolveExtensionSearchProviderByName:we,resolveExtensionVectorAdapter:ir,resolveLinkedCorpusRoots:pr,scoreDocument:Zt,sortHits:er,stringArray:oe,textEntries:U,validateSearchProjectionFields:Ot};async function Qa(e,t){let r=x(process.cwd(),t.path);await L(r);let n=await j(r),o=Mn(n).settings,i=$(o.schema),s=J(o.schema);Ot(e.projection,s,e.query);let a=Cn(e.options,s,"search"),l=G(o,T()),d=Dn(o),c=Ln(o,r),u=or(o),f=ir(o),p=Wo(e.options.semanticWeight),y=ni(o,d.active?.name??null),_=oi(o,d.active?.model??D(o.search?.embedding_model)??"text-embedding-3-small");return{pmRoot:r,settings:o,statusRegistry:i,runtimeFieldRegistry:s,runtimeFieldFilters:a,typeRegistry:l,maxResults:jt(o),scoreThreshold:e.minScoreOverride??Nt(o),semanticWeightProvided:e.options.semanticWeight!==void 0,semanticWeightOverride:p,hybridSemanticWeight:p??Ut(o),tuning:Gt(o),providerResolution:d,vectorResolution:c,extensionSearchProvider:u,extensionVectorAdapter:f,bm25Mode:cr({configuredProvider:D(o.search?.provider),hasEmbeddingProvider:d.active!==null,hasExtensionSearchProvider:u!==null}),queryExpansion:y,queryExpansionExtension:fi(y),rerank:_,rerankExtension:mi(o),...Ya({requested:e.options.mode,settings:o,configuredProvider:n.search?.provider??null,providerResolution:d,vectorResolution:c,extensionSearchProvider:u,extensionVectorAdapter:f})}}function Ya(e){let r=Fn(e.providerResolution.active?.name,e.configuredProvider)==="configured"&&(e.vectorResolution.active!==null||e.extensionVectorAdapter!==null),n=e.extensionSearchProvider!==null||r,o=qt({requested:e.requested,settings:e.settings,semanticRunnable:n});return{effectiveMode:o.mode,modeSource:o.source}}async function Xa(e,t){let r=await yr(t.pmRoot,t.settings.item_format??"toon",t.typeRegistry.type_to_folder,t.settings.schema),n=Le(typeof e.options.status=="string"?e.options.status:void 0,t.statusRegistry,{strict:!0}),o=Ge(t.statusRegistry),i=Yt(r.documents,e.options,t.typeRegistry,t.runtimeFieldFilters,n,o);return{warnings:r.warnings,allDocuments:r.documents,filteredDocuments:Qt(i,e.normalizedQuery,{titleExact:e.titleExact,phraseExact:e.phraseExact||e.matchMode==="exact"})}}async function Ja(e,t,r){let n=await pi(e.includeLinked,t.effectiveMode,r),o=e.matchMode==="or";return r.map(i=>tr(i,e.tokens,e.normalizedQuery,e.includeLinked,n,t.tuning,t.settings.id_prefix,o)).filter(i=>i!==null).filter(i=>e.matchMode!=="and"||i.matched_all_terms===!0)}async function Za(e,t,r,n,o){if(t.bm25Mode===null||t.effectiveMode==="keyword")return null;let i=lr({requestedMode:t.effectiveMode,query:e.query,filteredDocuments:r,keywordHits:n,corpusFields:Pn(t.settings),bm25Params:Zo(t.settings),hybridSemanticWeight:t.hybridSemanticWeight});return t.bm25Mode==="auto-fallback"&&o.push(`search_${t.effectiveMode}_offline_bm25:no_embedding_provider:using_lexical_bm25`),i}async function ec(e,t,r,n){if(!t.extensionSearchProvider)return null;let o=t.providerResolution.active!==null&&(t.vectorResolution.active!==null||t.extensionVectorAdapter!==null);try{let i=await Promise.resolve(t.extensionSearchProvider.query({query:e.query,mode:t.effectiveMode,tokens:e.tokens,options:e.options,settings:t.settings,documents:r}));return sr(t.extensionSearchProvider.providerName,i,n)}catch(i){if(!o)throw new h(`Extension search provider "${t.extensionSearchProvider.providerName}" failed: ${i instanceof Error?i.message:String(i)}`,m.GENERIC_FAILURE);return null}}function tc(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 rc(e,t,r,n,o){let i=!e.extensionSearchProvider&&e.providerResolution.active!==null&&(e.vectorResolution.active!==null||e.extensionVectorAdapter!==null);o&&i&&await nr(e.pmRoot,r,n),e.extensionSearchProvider||rt(t,e.providerResolution,e.vectorResolution,e.extensionVectorAdapter!==null)}async function nc(e){let{prepared:t,runtime:r,filteredDocuments:n,keywordHits:o,warnings:i,modeWasExplicit:s}=e,a=o,l=await Za(t,r,n,o,i),d=r.effectiveMode;if(l!==null||d==="keyword")return{effectiveMode:r.effectiveMode,hits:l??a};try{if(await rc(r,d,n,i,s),n.length===0||t.limit===0)return{effectiveMode:r.effectiveMode,hits:[]};let c=new Map(n.map(u=>[u.metadata.id,u]));if(a=await ec(t,r,n,c)??a,a===o){let{provider:u,vectorStore:f}=rt(d,r.providerResolution,r.vectorResolution,r.extensionVectorAdapter!==null),p=await fr({requestedMode:d,query:t.query,filteredDocuments:n,keywordHits:o,hybridSemanticWeight:r.hybridSemanticWeight,limit:t.limit,maxResults:r.maxResults,provider:u,vectorStore:f,extensionVectorAdapter:r.extensionVectorAdapter,queryExpansion:r.queryExpansion,queryExpansionExtension:r.queryExpansionExtension,rerank:r.rerank,rerankExtension:r.rerankExtension,warnings:i,settings:r.settings});a=tc(d,p,o,i)}return{effectiveMode:r.effectiveMode,hits:a}}catch(c){return i.push(rr(r.effectiveMode,c)),{effectiveMode:"keyword",hits:o}}}function Ei(e){e.searchOptions.after!==void 0&&Wr(e.searchOptions.after,$t(e))}async function Si(e,t,r){_i(t);let n=yi(e,t),o=await Qa(n,r),i=await Xa(n,o),s=i.warnings;s.push(...n.inlineWarnings);let a=await ao(i.allDocuments.map(E=>E.metadata),{pmRoot:o.pmRoot,statusRegistry:o.statusRegistry,now:S()});s.push(...a.warnings);let l=co(a,n.query);o.effectiveMode==="hybrid"&&o.semanticWeightProvided&&o.semanticWeightOverride===void 0&&s.push("search_hybrid_semantic_weight_override_invalid:using_settings_default");let d={query:n.query,modeSource:o.modeSource,matchMode:n.matchMode,options:n.options,includeLinked:n.includeLinked,titleExact:n.titleExact,phraseExact:n.phraseExact,scoreThreshold:o.scoreThreshold,hybridSemanticWeight:o.hybridSemanticWeight,queryExpansion:o.queryExpansion,rerank:o.rerank,projection:n.projection,warnings:s,runtimeFieldFilters:o.runtimeFieldFilters};if(o.effectiveMode==="keyword"&&(i.filteredDocuments.length===0||n.limit===0&&!n.countOnly))return Ei({query:n.query,mode:o.effectiveMode,searchOptions:n.options,pmRoot:o.pmRoot}),ve(Ir({...d,effectiveMode:o.effectiveMode},n.countOnly),l);let c=await Ja(n,o,i.filteredDocuments),u=await nc({prepared:n,runtime:o,filteredDocuments:i.filteredDocuments,keywordHits:c,warnings:s,modeWasExplicit:n.modeWasExplicit});if(u.effectiveMode!=="keyword"&&u.hits.length===0&&(i.filteredDocuments.length===0||n.limit===0&&!n.countOnly))return Ei({query:n.query,mode:u.effectiveMode,searchOptions:n.options,pmRoot:o.pmRoot}),ve(Ir({...d,effectiveMode:u.effectiveMode},n.countOnly),l);let f=u.hits.filter(E=>E.exact_id_match===!0||E.score>=o.scoreThreshold),p=er(f,o.statusRegistry),y=p.length,_=Vo({pmRoot:o.pmRoot,sorted:p,query:n.query,mode:u.effectiveMode,searchOptions:n.options,limit:n.limit??o.maxResults}),g={...d,effectiveMode:u.effectiveMode};if(n.countOnly)return ve(wi(g,y),l);let{hits:w,projection:b}=vi(n,i.filteredDocuments,_.limited),v=Sr(w,b);return ve(bi(g,v,y,_.limited.length,b,_.pageExtras),l)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b152a753-033c-593f-8b81-feb68b0a895f")}catch{}})();var Ii=["ndcg","mrr","precision","recall"];function xr(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(!Ii.some(o=>o===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 ki(e,t){let r=xr(t),n=[];for(let o of Ii){let i=r[o];if(i===void 0)continue;let s=e[o];!Number.isFinite(s)||s<0||s>1?n.push(`${o}:invalid`):s<i&&n.push(`${o}:${s}<${i}`)}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="451970e8-8403-5527-b795-a873241c015e")}catch{}})();var Ri=10,W="https://schema.unbrained.dev/pm/eval-query-set/v1",oc={schema:W,accepted_top_level:["array","object"],required_query_fields:["query","relevant_ids"],optional_fields:["mode","description","minimum"],modes:["keyword","semantic","hybrid"]},it={schema:W,queries:[{query:"offline search",relevant_ids:["pm-75k9"],mode:"keyword"}]},P=class extends Error{constructor(t){super(t),this.name="EvalQuerySetError"}},ic=new Set(["keyword","semantic","hybrid"]);function xi(e,t){let r=0,n=Math.min(t,e.length);for(let o=0;o<n;o+=1)r+=e[o]/Math.log2(o+2);return r}function sc(e,t,r){if(t.size===0)return 0;let n=e.map(a=>t.has(a)?1:0),o=xi(n,r),i=Array.from({length:t.size},()=>1),s=xi(i,r);return s===0?0:o/s}function ac(e,t,r){let n=Math.min(r,e.length);for(let o=0;o<n;o+=1)if(t.has(e[o]))return 1/(o+1);return 0}function Rr(e,t,r){let n=Math.min(r,e.length),o=0;for(let i=0;i<n;i+=1)t.has(e[i])&&(o+=1);return o}function cc(e,t,r){return r<=0?0:Rr(e,t,r)/r}function lc(e,t,r){return t.size===0?0:Rr(e,t,r)/t.size}function Ai(e,t,r){return{ndcg:sc(e,t,r),mrr:ac(e,t,r),precision:cc(e,t,r),recall:lc(e,t,r),relevant_total:t.size,retrieved_relevant:Rr(e,t,r)}}function Ci(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,o)=>({ndcg:n.ndcg+o.ndcg,mrr:n.mrr+o.mrr,precision:n.precision+o.precision,recall:n.recall+o.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 dc(e,t){if(typeof e!="object"||e===null)throw new P(`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 P(`Eval query at index ${t} must have a non-empty "query" string`);if(!Array.isArray(r.relevant_ids))throw new P(`Eval query at index ${t} must have a "relevant_ids" array`);if(r.relevant_ids.some(i=>typeof i!="string"))throw new P(`Eval query at index ${t} must have a "relevant_ids" array of strings`);let o=[...new Set(r.relevant_ids.map(i=>i.trim()).filter(i=>i.length>0))];if(o.length===0)throw new P(`Eval query at index ${t} must list at least one relevant id`);if(r.mode!==void 0&&(typeof r.mode!="string"||!ic.has(r.mode)))throw new P(`Eval query at index ${t} has an invalid mode (expected keyword|semantic|hybrid)`);return{query:n,relevant_ids:o,...r.minimum===void 0?{}:{minimum:xr(r.minimum)},...r.mode!==void 0?{mode:r.mode}:{},...typeof r.description=="string"&&r.description.trim().length>0?{description:r.description.trim()}:{}}}function Ar(e){let t=typeof e=="object"&&e!==null&&!Array.isArray(e)?e.schema:void 0;if(t!==void 0&&t!==W)throw new P(`Unsupported eval query set schema; expected "${W}"`);let r=Array.isArray(e)?e:typeof e=="object"&&e!==null?e.queries:void 0;if(!Array.isArray(r))throw new P('Eval query set must be an array of queries or an object with a "queries" array');if(r.length===0)throw new P("Eval query set must contain at least one query");return{schema:W,queries:r.map((n,o)=>dc(n,o))}}import uc from"node:fs/promises";import Cr 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]="d4020969-4ce5-5f87-ae41-f5a3dec0a197")}catch{}})();var fc=Cr.join("search","eval-queries.json"),Tr={schema:W,examples:[JSON.stringify(it)],nextSteps:["Create a git-tracked golden-query JSON file that follows the schema, then re-run pm eval."]},mc=new Set(["keyword","semantic","hybrid"]),hc=e=>{if(e===void 0)return"keyword";let t=e.trim().toLowerCase();if(!mc.has(t))throw new h("Eval --mode must be one of keyword|semantic|hybrid",m.USAGE);return t},pc=e=>{if(e===void 0||e==="")return Ri;let t=Se(e);if(t===null)throw new h("Eval --k must be a positive integer",m.USAGE);return t},gc=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]",m.USAGE);return r},B=e=>Math.round(e*1e4)/1e4,yc=async e=>{try{return await uc.readFile(e,"utf8")}catch{throw new h(`Eval query set not found at ${e}`,m.NOT_FOUND,{...Tr,examples:[`echo '${JSON.stringify(it)}' > ${e}`,"pm eval --queries ./my-eval.json"]})}},_c=(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)}`,m.USAGE,Tr)}},wc=e=>{try{return Ar(e)}catch(t){throw new h(t instanceof Error?t.message:String(t),m.USAGE,Tr)}},vc=async e=>wc(_c(await yc(e),e)),bc=async(e,t,r,n)=>{let o=e.mode??t,s=(await Si(e.query,{mode:o,limit:String(r),fields:"id"},n)).items.map(l=>l.id).filter(l=>typeof l=="string"),a=Ai(s,new Set(e.relevant_ids),r);return{metrics:a,report:{query:e.query,...e.minimum===void 0?{}:{violations:ki(a,e.minimum)},mode:o,relevant_total:a.relevant_total,retrieved_relevant:a.retrieved_relevant,ndcg:B(a.ndcg),mrr:B(a.mrr),precision:B(a.precision),recall:B(a.recall)}}},Ec=(e,t,r,n)=>{let o=Ci(r);return{k:e,query_count:t.length,aggregate:{ndcg:B(o.ndcg),mrr:B(o.mrr),precision:B(o.precision),recall:B(o.recall)},queries:t,...n!==void 0?{fail_under:n}:{},passed:(n===void 0||o.ndcg>=n)&&t.every(i=>(i.violations?.length??0)===0)}},Yf=async(e,t)=>{let r=x(process.cwd(),t.path);await L(r);let n=pc(e.k),o=hc(e.mode),i=gc(e.failUnder),s=e.queries?Cr.resolve(process.cwd(),e.queries):Cr.join(r,fc),a=await vc(s),l=[],d=[];for(let c of a.queries){let{report:u,metrics:f}=await bc(c,o,n,t);d.push(f),l.push(u)}return Ec(n,l,d,i)};export{Ui as a,$i as b,$c as c,Wc as d,ll as e,dl as f,xt as g,bo as h,Eo as i,So as j,Hl as k,Jl as l,Yl as m,od as n,id as o,qo as p,No as q,Uo as r,Hs as s,Dt as t,Rd as u,Ad as v,jd as w,jt as x,qt as y,Nt as z,Ut as A,Gt as B,$t as C,Vo as D,re as E,ne as F,et as G,tt as H,di as I,ui as J,Pf as K,Si as L,Ii as M,xr as N,ki as O,W as P,oc as Q,it as R,Ar as S,fc as T,Yf as U};
|
|
6
|
-
//# sourceMappingURL=chunk-
|
|
6
|
+
//# sourceMappingURL=chunk-3AF2R3Y6.js.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{aa as f,ba as _,da as p,fa as g}from"./chunk-
|
|
1
|
+
import{aa as f,ba as _,da as p,fa as g}from"./chunk-MKXBCBAN.js";import{yf as c}from"./chunk-QPKQKSQU.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},r=new e.Error().stack;r&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[r]="d3714178-d64c-564c-a1bc-e5393fc57758")}catch{}})();var m="not-a-declared-intent",n="not-a-declared-field";function y(){let e={get:["pm-domain"],search:["Domain query"]},r=[...new Set(c.map(({command:o})=>o))].map(o=>{let i=c.filter(d=>d.command===o),s=i[0],u=e[s.command]??[];return{probe_id:`${s.command}-invalid-intent`,command:s.command,flag:"--for",rejected_value:m,refusal_args:[s.command,...u,"--for",m],allowed_values:i.map(({intent:d})=>d).sort(),suggested_retry_args:[s.command,...u,"--for",s.intent],error_code:"unknown_context_intent"}}),t=_(),l=Object.keys(f).map(o=>({probe_id:`${o}-invalid-field`,command:o,flag:"--fields",rejected_value:n,refusal_args:[o,"--fields",n],allowed_values:t,suggested_retry_args:[o,"--fields","id,title,status"],error_code:"unknown_field_projection"}));return[...r,...l,{probe_id:"get-invalid-field",command:"get",flag:"--fields",rejected_value:n,refusal_args:["get","pm-domain","--fields",n],allowed_values:p(),suggested_retry_args:["get","pm-domain","--fields","id,title,status"],error_code:"unknown_field_projection"},{probe_id:"list-mutually-exclusive-projection",command:"list",flag:"--projection",rejected_value:"--brief+--full",refusal_args:["list","--brief","--full"],allowed_values:[],suggested_retry_args:["list","--brief"],error_code:"projection_options_mutually_exclusive",allowed_values_required:!1},{probe_id:"get-mutually-exclusive-projection",command:"get",flag:"--projection",rejected_value:"--full+--fields",refusal_args:["get","pm-domain","--full","--fields","id"],allowed_values:[],suggested_retry_args:["get","pm-domain","--full"],error_code:"projection_options_mutually_exclusive",allowed_values_required:!1},{probe_id:"search-mutually-exclusive-projection",command:"search",flag:"--projection",rejected_value:"--full+--fields",refusal_args:["search","Domain query","--full","--fields","id"],allowed_values:[],suggested_retry_args:["search","Domain query","--full"],error_code:"projection_options_mutually_exclusive",allowed_values_required:!1},{probe_id:"package-upgrade-mutually-exclusive-modes",command:"package upgrade",flag:"--cli-only/--packages-only",rejected_value:"--cli-only+--packages-only",refusal_args:["package","upgrade","--cli-only","--packages-only","--dry-run"],allowed_values:[],suggested_retry_args:["package","upgrade","--packages-only","--dry-run"],error_code:"package_upgrade_modes_mutually_exclusive",allowed_values_required:!1},{probe_id:"search-invalid-field",command:"search",flag:"--fields",rejected_value:n,refusal_args:["search","Domain query","--fields",n],allowed_values:g(),suggested_retry_args:["search","Domain query","--fields","id,title,status,score"],error_code:"unknown_field_projection"}].sort((o,i)=>o.probe_id.localeCompare(i.probe_id))}function j(e,r){let t=y().find(o=>o.command===e&&o.flag===r);if(!t)return"No stable core values are declared.";let l=t.allowed_values.filter(o=>!o.startsWith("item.")),a=r==="--fields"?" item.<field> aliases and configured runtime metadata fields are also accepted.":" Configured package and workspace intents may extend this domain.";return`Allowed core values: ${l.join("|")}.${a}`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},r=new e.Error().stack;r&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[r]="c56ec8fb-56b5-57a6-9d77-843c774dcc20")}catch{}})();function w(e){return e.map((r,t)=>{if(typeof r!="object"||r===null||Array.isArray(r))throw new TypeError(`NDJSON row ${t} must be a non-null object.`);let l=JSON.stringify(r);if(l===void 0)throw new TypeError(`NDJSON row ${t} must serialize to a non-null object.`);let a=JSON.parse(l);if(typeof a!="object"||a===null||Array.isArray(a))throw new TypeError(`NDJSON row ${t} must serialize to a non-null object.`);return l}).join(`
|
|
2
2
|
`)}function S(e,r){if(r.count!==e.length)throw new TypeError(`NDJSON trailer count ${r.count} does not match ${e.length} ${e.length===1?"row":"rows"}.`);for(let[t,l]of e.entries())if(typeof l=="object"&&l!==null&&!Array.isArray(l)&&Reflect.get(l,"record_type")==="pm.stream.trailer")throw new TypeError(`NDJSON row ${t} uses reserved record_type pm.stream.trailer`);return w([...e,{...r,record_type:"pm.stream.trailer"}])}export{y as a,j as b,w as c,S as d};
|
|
3
|
-
//# sourceMappingURL=chunk-
|
|
3
|
+
//# sourceMappingURL=chunk-44UGMMQ6.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as nt,b as En,c as fc,d as _c,g as hc,i as jc}from"./chunk-Z2GYDSAO.js";import{L as Yo,U as tl,a as Gc,c as Uc,d as qc,e as zc,k as Hc,l as Dt,m as Ge,n as Bo,u as Ko,w as el}from"./chunk-R4TUD355.js";import{$c as Ho,Aa as cc,Ba as lc,Ca as kn,Da as dc,Ea as Sn,Fa as In,Ga as mc,Gb as Fc,Gd as Jo,Ia as et,J as Le,Ja as pc,Jb as Pc,Jd as dl,Ka as Po,Kb as Lc,La as An,Mc as jo,Na as tt,Pb as Lt,Pc as Ie,Qc as Wc,Qd as ml,Rc as Uo,Rd as pl,Sc as Vc,Tc as Bc,Uc as ot,Vc as Kc,Wa as uc,Yc as Xc,Zc,_c as Qc,ad as Wo,b as Oo,bd as Vo,ed as ol,fc as Rn,fd as rl,ga as fn,gd as il,ha as nc,hd as sl,i as Ta,ia as Ft,id as al,j as Ca,ja as h,ka as oc,kd as cl,l as Ra,la as rc,ld as ll,mb as yc,mc as Dc,na as J,nb as bc,oa as ic,oc as Mc,pa as bn,qa as sc,ra as $o,sa as Pt,sb as Lo,ta as wn,tb as No,ua as Me,ub as Do,va as ac,vc as Nt,wa as vn,wb as wc,xa as U,xb as vc,ya as Fo,yb as Mo,za as j}from"./chunk-MTJMOI4I.js";import{$a as yn,E as xa,K as Oa,M as Ne,N as $a,O as hn,P as Fa,Pa as Qe,Q as De,R as Pa,S as gn,T as La,Wa as Qa,Z as Na,aa as Da,c as ms,ca as Ma,da as ja,db as ec,ea as Ga,fa as Ua,ga as qa,gb as tc,ha as za,i as _n,ia as Ha,ja as Wa,ka as Va,la as Ba,ma as Ka,na as Ya,oa as Ja,pa as Xa,qa as Za}from"./chunk-ZI7F3FVE.js";import{$a as kc,Db as Se,Eb as Nc,Fb as Cn,Jb as Go,Uc as qo,Xb as Yc,Yb as Jc,Zc as zo,ad as nl,d as ls,f as ds,ib as Sc,jb as Ic,kb as Ac,na as de,nb as Ec,ob as Tc,pb as Cc,qb as Rc,sb as je,tb as xc,ua as gc,ub as Oc,xb as Tn,zb as $c}from"./chunk-SV7CZEVV.js";import{$ as fi,$i as Rt,$k as qs,$m as To,A as ae,Ab as hi,Ac as ho,Af as qi,Ai as So,Aj as rn,Al as Ys,Bb as gi,Bc as go,Bj as _s,C as oe,Cb as yi,Cc as yo,D as kt,Db as bi,Dc as $,Df as Ke,Dg as nn,Dl as Ot,Dm as pa,Eb as wi,Eg as Et,Ek as Ts,El as Js,Em as ua,Fb as vi,Fg as bo,Fk as Cs,Fl as Xs,Gb as ki,Gi as rs,Gk as Rs,Gl as Zs,Gn as Ro,Hf as zi,Hj as hs,Hl as Qs,Ho as Ea,Ia as io,Ic as Ii,Im as Ao,In as xo,Ja as so,Jc as Ai,Ji as Ze,Jk as xs,K as ci,Ka as ao,Kh as Tt,Km as Eo,La as co,Ld as tn,Lh as Ct,Lj as gs,M as li,Mc as G,Ml as Io,N as be,Nk as Os,Nl as ea,Oe as Ni,Ok as $s,Ol as Pe,Om as fa,Pf as Hi,Pk as Fs,Pm as _a,Qc as Ei,Qf as F,Qj as ys,Qk as Ps,Ql as ta,Qm as ha,Rc as Ti,Rg as Ji,Rj as bs,Rk as Ls,Rl as na,Rm as ga,Sg as Xi,Sm as ya,T as oo,Tb as It,Tg as Zi,Ti as is,Tj as ws,Tk as Ns,Tl as mn,U as di,Ua as P,Ub as Jt,Uk as Ds,Um as ba,Va as Yt,Vc as H,Ve as Di,Vi as ss,Vk as Ms,Vl as oa,Vm as wa,Wc as en,Wi as as,Wj as vs,Wk as js,Wl as ra,Wm as va,Xi as ce,Xk as Gs,Xl as ia,Xm as $t,Y as mi,Ye as Mi,Yi as ve,Yk as Us,Ym as ka,Z as pi,Zm as un,_ as ui,_m as Sa,ab as A,al as sn,an as Co,bd as Ci,bl as zs,bn as Ia,ca as _i,cd as Ri,cg as Ye,cj as on,cl as Hs,db as we,de as Fi,dg as Oe,di as Qi,eb as lo,ee as Pi,eg as Wi,ei as Xe,f as Y,ff as S,fg as Vi,fj as xt,fm as sa,gb as xe,gg as $e,gj as cs,gl as ke,h as to,he as Li,hg as Bi,hh as wo,hi as vo,hl as E,ih as R,il as Ws,j as ai,jf as ji,ji as es,jl as Vs,jm as aa,kc as Xt,kg as V,kk as ks,lc as Zt,lf as Gi,li as ts,mc as Qt,mf as te,mg as At,na as u,ng as Ki,ni as ns,nk as Ss,nm as ca,oc as Si,oj as ps,ok as Is,p as Kt,pa as m,pi as T,qa as St,qd as xi,qg as Yi,qi as os,qm as le,rl as Bs,sa as ro,sf as Ui,sl as an,td as Oi,tl as cn,tm as la,u as Ve,uc as mo,ul as ln,um as da,vl as dn,vo as Aa,wc as po,wd as $i,wk as As,wm as pn,x as ye,xc as uo,xg as Fe,xj as us,xl as re,xm as ma,y as Be,yc as fo,yk as Es,z as no,zc as _o,zg as Je,zi as ko,zj as fs,zl as Ks}from"./chunk-R7ULWMBG.js";import{AsyncLocalStorage as Dg}from"node:async_hooks";import{readFile as pp}from"node:fs/promises";import up 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]="c64f304d-9081-5bad-8187-7bf6b65e4a07")}catch{}})();var Xo="context-intents.json";function xn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function fp(e,t,n){if(!xn(e))throw new TypeError(`${t} context intent at index ${String(n)} must be an object`);let o=e.included_field_groups;if(typeof e.command!="string"||typeof e.intent!="string"||typeof e.description!="string"||!Array.isArray(o)||!o.every(r=>typeof r=="string")||typeof e.token_budget!="number")throw new TypeError(`${t} context intent at index ${String(n)} has an invalid contract shape`);return{command:e.command,intent:e.intent,description:e.description,included_field_groups:o,token_budget:e.token_budget}}function ul(e,t){let n=Array.isArray(e)?e:xn(e)&&Array.isArray(e.intents)?e.intents:void 0;if(!n)throw new TypeError(`${t} context intents must be an array or an object with an intents array`);return n.map((o,r)=>fp(o,t,r))}async function _p(e){let t=up.join(e,Xo),n;try{n=await pp(t,"utf8")}catch(r){if(Be(r))return[];throw await Hi(e),r}let o;try{o=JSON.parse(n)}catch(r){let i=r instanceof Error?r.message:String(r);throw new TypeError(`Invalid ${Xo}: ${i}`,{cause:r})}return ul(o,Xo)}function hp(e){if(!xn(e))return;let t=e.contextIntents??e.context_intents;if(t!==void 0)return t;let n=e.default;return xn(n)?n.contextIntents??n.context_intents:void 0}function gp(e){return e.flatMap(t=>{let n=hp(t.module);return n===void 0?[]:ul(n,`package ${t.name}`)})}async function yp(e){let t=await _p(e.pmRoot),n=gp(e.packages??[]);return{workspaceContracts:t,packageContracts:n}}async function On(e,t){let n=await yp(e);return await qi(n,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]="c2766f4e-6354-55bb-9e40-676273ee901f")}catch{}})();async function fl(e,t,n=Ui){try{await n({pmRoot:e,result:t})}catch{if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let o=t,r=Array.isArray(o.warnings)?o.warnings.filter(i=>typeof i=="string"):[];o.warnings=[...new Set([...r,"context_usage_feedback_write_failed"])].sort()}}}import{createHash as Cp}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9133d39d-b2fb-5f99-8fd3-87a7d2f8df6d")}catch{}})();var _l="PmCliError";function bp(e){if(!Number.isFinite(e))throw new TypeError("createPmCliExpectedError options.exitCode must be a finite number");let t=Math.trunc(e);if(t<=u.SUCCESS)throw new TypeError("createPmCliExpectedError options.exitCode must be a positive exit code");return t}function wp(e,t={}){if(typeof e!="string"||e.trim().length===0)throw new TypeError("createPmCliExpectedError message must be a non-empty string");let n=new m(e,bp(t.exitCode??u.USAGE),t.context??{});return"cause"in t&&Object.defineProperty(n,"cause",{value:t.cause,enumerable:!1,configurable:!0,writable:!0}),n}function Zo(e){if(!(e instanceof Error)||e.name!==_l)return!1;let t=e;return typeof t.exitCode=="number"&&Number.isFinite(t.exitCode)}import{constants as Mt}from"node:fs";import{lstat as hl,mkdir as er,open as gl}from"node:fs/promises";import me 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]="e57a9bca-1190-5ffd-bb7d-d76a22fc9e57")}catch{}})();function Qo(e,t){if(typeof e!="string"||e.trim().length===0)throw new TypeError(`Relationship event ${t} must be non-empty`);return e.trim()}function tr(e,t){let n=t.require(e.kind),o=n.direction==="undirected"?[e.source,e.target].sort().join("\0"):`${e.source}\0${e.target}`;return`${n.kind}\0${o}`}function vp(e){return Object.freeze({...e,...e.payload===void 0?{}:{payload:Object.freeze(structuredClone(e.payload))}})}function kp(e,t,n,o){let r=n.require(e.kind),i=o.outgoingOne.get(`${r.kind}\0${e.source}`);if(i!==void 0&&i!==t)throw new TypeError(`Relationship outgoing cardinality exceeded for ${r.kind}`);let s=o.incomingOne.get(`${r.kind}\0${e.target}`);if(s!==void 0&&s!==t)throw new TypeError(`Relationship incoming cardinality exceeded for ${r.kind}`);let a=tr(e,n),c=o.identities.get(a);if(c!==void 0&&c!==t)throw new TypeError(`Relationship edge already active: ${a}`)}function Sp(e){let t=new Map;for(let n of e)n.action==="remove"?t.delete(n.relationshipId):t.set(n.relationshipId,n.edge);return t}function Ip(e,t,n){if(e.expectedVersion!==void 0&&e.expectedVersion!==t)throw new TypeError(`Relationship event version conflict: expected ${e.expectedVersion}, current ${t}`);let o=Qo(e.eventId,"eventId");if(n.has(o))throw new TypeError(`Relationship event already exists: ${o}`);if(e.action!=="add"&&e.action!=="remove"&&e.action!=="supersede")throw new TypeError(`Unknown relationship event action: ${e.action}`);if(!Number.isFinite(Date.parse(e.timestamp)))throw new TypeError("Relationship event timestamp must be valid");return{eventId:o,relationshipId:Qo(e.relationshipId,"relationshipId"),author:Qo(e.author,"author"),timestamp:new Date(e.timestamp).toISOString()}}function Ap(e,t,n,o,r,i){let s=n.has(t);if(e.action==="add"&&s)throw new TypeError(`Relationship is already active: ${t}`);if(e.action!=="add"&&!s)throw new TypeError(`Relationship is not active: ${t}`);if(e.action==="remove")return;if(!e.edge)throw new TypeError(`Relationship ${e.action} event requires an edge`);let a=typeof e.edge.source=="string"?e.edge.source.trim():"",c=typeof e.edge.target=="string"?e.edge.target.trim():"";if(!o.has(a)||!o.has(c))throw new TypeError(`Relationship endpoint not found: ${a} -> ${c}`);let l=new Ve([a,c],[e.edge],r).edges()[0];return kp(l,t,r,i),vp(l)}var jt=class{#t;#n;#o=[];#i=new Set;#e=new Map;#r={identities:new Map,outgoingOne:new Map,incomingOne:new Map};constructor(t,n={}){this.#t=new Set([...t].filter(o=>typeof o=="string").map(o=>o.trim()).filter(Boolean)),this.#n=n.registry??Kt()}get version(){return this.#o.length}events(){return Object.freeze([...this.#o])}*stream(t={}){let n=t.fromVersion??1,o=t.toVersion??this.version,r=t.batchSize??100;if(!Number.isInteger(n)||n<1)throw new TypeError("Relationship event stream fromVersion must be positive");if(!Number.isInteger(o)||o<0||o>this.version)throw new TypeError(`Relationship event stream toVersion out of range: ${o}`);if(!Number.isInteger(r)||r<1)throw new TypeError("Relationship event stream batchSize must be positive");if(n>o+1)throw new TypeError("Relationship event stream fromVersion exceeds the selected prefix");for(let i=n-1;i<o;i+=r)yield Object.freeze(this.#o.slice(i,Math.min(i+r,o)))}project(t,n,o={}){if(typeof n!="function")throw new TypeError("Relationship event projection requires a reducer");let r=t,i=0,s;for(let a of this.stream({...o,batchSize:256}))for(let c of a)r=n(r,c),i+=1,s=c;return Object.freeze({state:r,version:s?.sequence??Math.max(0,(o.fromVersion??1)-1),processed:i,...s===void 0?{}:{asOf:s.timestamp}})}#s(t,n){let o=this.#n.require(n.kind);this.#r.identities.set(tr(n,this.#n),t),o.outgoing==="one"&&this.#r.outgoingOne.set(`${o.kind}\0${n.source}`,t),o.incoming==="one"&&this.#r.incomingOne.set(`${o.kind}\0${n.target}`,t)}#a(t){let n=this.#n.require(t.kind);this.#r.identities.delete(tr(t,this.#n)),n.outgoing==="one"&&this.#r.outgoingOne.delete(`${n.kind}\0${t.source}`),n.incoming==="one"&&this.#r.incomingOne.delete(`${n.kind}\0${t.target}`)}append(t){let n=Ip(t,this.version,this.#i),o=this.#e.get(n.relationshipId),r=Ap(t,n.relationshipId,this.#e,this.#t,this.#n,this.#r),i=Object.freeze({eventId:n.eventId,relationshipId:n.relationshipId,action:t.action,...r===void 0?{}:{edge:r},author:n.author,timestamp:n.timestamp,...t.reason?.trim()?{reason:t.reason.trim()}:{},sequence:this.version+1});return this.#o.push(i),this.#i.add(n.eventId),o&&this.#a(o),t.action==="remove"?this.#e.delete(n.relationshipId):(this.#e.set(n.relationshipId,r),this.#s(n.relationshipId,r)),i}snapshot(t={}){if(t.atVersion!==void 0&&t.atTimestamp!==void 0)throw new TypeError("Relationship snapshot accepts one target");let n;if(t.atTimestamp!==void 0){let i=Date.parse(t.atTimestamp);if(!Number.isFinite(i))throw new TypeError("Relationship snapshot timestamp must be valid");n=this.#o.filter(s=>Date.parse(s.timestamp)<=i)}else{let i=t.atVersion??this.version;if(!Number.isInteger(i)||i<0||i>this.version)throw new TypeError(`Relationship snapshot version out of range: ${i}`);n=this.#o.slice(0,i)}let o=Sp(n),r=new Ve(this.#t,o.values(),this.#n);return Object.freeze({version:n.at(-1)?.sequence??0,...n.at(-1)?{asOf:n.at(-1).timestamp}:{},edges:r.edges(),graph:r})}page(t){if(!Number.isInteger(t.limit)||t.limit<1)throw new TypeError("Relationship event page limit must be positive");let n=xi("relationship-events",{order:"append-sequence"}),o=t.cursor===void 0?this.version:Number(Oi(t.cursor,n).snapshot);if(!Number.isSafeInteger(o)||o<0||o>this.version)throw new TypeError("Relationship event cursor snapshot version is invalid");let r=$i(this.#o.slice(0,o),{cursor:t.cursor,fingerprint:n,limit:t.limit,readId:i=>i.eventId,snapshot:String(o)});return{version:o,events:r.rows,hasMore:r.has_more,...r.next_cursor?{nextCursor:r.next_cursor}:{}}}},Ep="relationship-event-store",yl=Mt.O_NOFOLLOW;function $n(e){return te(e,Ep,30,`relationship-store:${process.pid}`,!1,!1,3e3)}async function Ue(e,t="relationships/events.jsonl"){let n=me.resolve(e),o=me.resolve(n,t),r=me.relative(n,o);if(r.length===0)throw new TypeError("Relationship event path must name a file within the tracker root");if(r===".."||r.startsWith(`..${me.sep}`)||me.isAbsolute(r))throw new TypeError("Relationship event path must stay within the tracker root");if(await er(n,{recursive:!0}),(await hl(n)).isSymbolicLink())throw new TypeError("Relationship event tracker root must not be a symbolic link");let s=n;for(let a of r.split(me.sep)){s=me.join(s,a);try{if((await hl(s)).isSymbolicLink())throw new TypeError("Relationship event path must not contain symbolic links")}catch(c){if(no(c))break;throw c}}return o}async function Fn(e,t,n){let o=new jt(t,{registry:n}),r,i;try{i=await gl(e,Mt.O_RDONLY|yl),r=await i.readFile("utf8")}catch(a){if(no(a))return{log:o,raw:""};throw a}finally{await i?.close()}let s=r.split(`
|
|
1
|
+
import{a as nt,b as En,c as fc,d as _c,g as hc,i as jc}from"./chunk-YDWKGUQU.js";import{L as Yo,U as tl,a as Gc,c as Uc,d as qc,e as zc,k as Hc,l as Dt,m as Ge,n as Bo,u as Ko,w as el}from"./chunk-3AF2R3Y6.js";import{$c as Ho,Aa as cc,Ba as lc,Ca as kn,Da as dc,Ea as Sn,Fa as In,Ga as mc,Gb as Fc,Gd as Jo,Ia as et,J as Le,Ja as pc,Jb as Pc,Jd as dl,Ka as Po,Kb as Lc,La as An,Mc as jo,Na as tt,Pb as Lt,Pc as Ie,Qc as Wc,Qd as ml,Rc as Uo,Rd as pl,Sc as Vc,Tc as Bc,Uc as ot,Vc as Kc,Wa as uc,Yc as Xc,Zc,_c as Qc,ad as Wo,b as Oo,bd as Vo,ed as ol,fc as Rn,fd as rl,ga as fn,gd as il,ha as nc,hd as sl,i as Ta,ia as Ft,id as al,j as Ca,ja as h,ka as oc,kd as cl,l as Ra,la as rc,ld as ll,mb as yc,mc as Dc,na as J,nb as bc,oa as ic,oc as Mc,pa as bn,qa as sc,ra as $o,sa as Pt,sb as Lo,ta as wn,tb as No,ua as Me,ub as Do,va as ac,vc as Nt,wa as vn,wb as wc,xa as U,xb as vc,ya as Fo,yb as Mo,za as j}from"./chunk-FW5LJXQY.js";import{$a as yn,E as xa,K as Oa,M as Ne,N as $a,O as hn,P as Fa,Pa as Qe,Q as De,R as Pa,S as gn,T as La,Wa as Qa,Z as Na,aa as Da,c as ms,ca as Ma,da as ja,db as ec,ea as Ga,fa as Ua,ga as qa,gb as tc,ha as za,i as _n,ia as Ha,ja as Wa,ka as Va,la as Ba,ma as Ka,na as Ya,oa as Ja,pa as Xa,qa as Za}from"./chunk-KP7NBQK3.js";import{$a as kc,Db as Se,Eb as Nc,Fb as Cn,Jb as Go,Uc as qo,Xb as Yc,Yb as Jc,Zc as zo,ad as nl,d as ls,f as ds,ib as Sc,jb as Ic,kb as Ac,na as de,nb as Ec,ob as Tc,pb as Cc,qb as Rc,sb as je,tb as xc,ua as gc,ub as Oc,xb as Tn,zb as $c}from"./chunk-MKXBCBAN.js";import{$ as fi,$i as Rt,$k as qs,$m as To,A as ae,Ab as hi,Ac as ho,Af as qi,Ai as So,Aj as rn,Al as Ys,Bb as gi,Bc as go,Bj as _s,C as oe,Cb as yi,Cc as yo,D as kt,Db as bi,Dc as $,Df as Ke,Dg as nn,Dl as Ot,Dm as pa,Eb as wi,Eg as Et,Ek as Ts,El as Js,Em as ua,Fb as vi,Fg as bo,Fk as Cs,Fl as Xs,Gb as ki,Gi as rs,Gk as Rs,Gl as Zs,Gn as Ro,Hf as zi,Hj as hs,Hl as Qs,Ho as Ea,Ia as io,Ic as Ii,Im as Ao,In as xo,Ja as so,Jc as Ai,Ji as Ze,Jk as xs,K as ci,Ka as ao,Kh as Tt,Km as Eo,La as co,Ld as tn,Lh as Ct,Lj as gs,M as li,Mc as G,Ml as Io,N as be,Nk as Os,Nl as ea,Oe as Ni,Ok as $s,Ol as Pe,Om as fa,Pf as Hi,Pk as Fs,Pm as _a,Qc as Ei,Qf as F,Qj as ys,Qk as Ps,Ql as ta,Qm as ha,Rc as Ti,Rg as Ji,Rj as bs,Rk as Ls,Rl as na,Rm as ga,Sg as Xi,Sm as ya,T as oo,Tb as It,Tg as Zi,Ti as is,Tj as ws,Tk as Ns,Tl as mn,U as di,Ua as P,Ub as Jt,Uk as Ds,Um as ba,Va as Yt,Vc as H,Ve as Di,Vi as ss,Vk as Ms,Vl as oa,Vm as wa,Wc as en,Wi as as,Wj as vs,Wk as js,Wl as ra,Wm as va,Xi as ce,Xk as Gs,Xl as ia,Xm as $t,Y as mi,Ye as Mi,Yi as ve,Yk as Us,Ym as ka,Z as pi,Zm as un,_ as ui,_m as Sa,ab as A,al as sn,an as Co,bd as Ci,bl as zs,bn as Ia,ca as _i,cd as Ri,cg as Ye,cj as on,cl as Hs,db as we,de as Fi,dg as Oe,di as Qi,eb as lo,ee as Pi,eg as Wi,ei as Xe,f as Y,ff as S,fg as Vi,fj as xt,fm as sa,gb as xe,gg as $e,gj as cs,gl as ke,h as to,he as Li,hg as Bi,hh as wo,hi as vo,hl as E,ih as R,il as Ws,j as ai,jf as ji,ji as es,jl as Vs,jm as aa,kc as Xt,kg as V,kk as ks,lc as Zt,lf as Gi,li as ts,mc as Qt,mf as te,mg as At,na as u,ng as Ki,ni as ns,nk as Ss,nm as ca,oc as Si,oj as ps,ok as Is,p as Kt,pa as m,pi as T,qa as St,qd as xi,qg as Yi,qi as os,qm as le,rl as Bs,sa as ro,sf as Ui,sl as an,td as Oi,tl as cn,tm as la,u as Ve,uc as mo,ul as ln,um as da,vl as dn,vo as Aa,wc as po,wd as $i,wk as As,wm as pn,x as ye,xc as uo,xg as Fe,xj as us,xl as re,xm as ma,y as Be,yc as fo,yk as Es,z as no,zc as _o,zg as Je,zi as ko,zj as fs,zl as Ks}from"./chunk-QPKQKSQU.js";import{AsyncLocalStorage as Dg}from"node:async_hooks";import{readFile as pp}from"node:fs/promises";import up 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]="c64f304d-9081-5bad-8187-7bf6b65e4a07")}catch{}})();var Xo="context-intents.json";function xn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function fp(e,t,n){if(!xn(e))throw new TypeError(`${t} context intent at index ${String(n)} must be an object`);let o=e.included_field_groups;if(typeof e.command!="string"||typeof e.intent!="string"||typeof e.description!="string"||!Array.isArray(o)||!o.every(r=>typeof r=="string")||typeof e.token_budget!="number")throw new TypeError(`${t} context intent at index ${String(n)} has an invalid contract shape`);return{command:e.command,intent:e.intent,description:e.description,included_field_groups:o,token_budget:e.token_budget}}function ul(e,t){let n=Array.isArray(e)?e:xn(e)&&Array.isArray(e.intents)?e.intents:void 0;if(!n)throw new TypeError(`${t} context intents must be an array or an object with an intents array`);return n.map((o,r)=>fp(o,t,r))}async function _p(e){let t=up.join(e,Xo),n;try{n=await pp(t,"utf8")}catch(r){if(Be(r))return[];throw await Hi(e),r}let o;try{o=JSON.parse(n)}catch(r){let i=r instanceof Error?r.message:String(r);throw new TypeError(`Invalid ${Xo}: ${i}`,{cause:r})}return ul(o,Xo)}function hp(e){if(!xn(e))return;let t=e.contextIntents??e.context_intents;if(t!==void 0)return t;let n=e.default;return xn(n)?n.contextIntents??n.context_intents:void 0}function gp(e){return e.flatMap(t=>{let n=hp(t.module);return n===void 0?[]:ul(n,`package ${t.name}`)})}async function yp(e){let t=await _p(e.pmRoot),n=gp(e.packages??[]);return{workspaceContracts:t,packageContracts:n}}async function On(e,t){let n=await yp(e);return await qi(n,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]="c2766f4e-6354-55bb-9e40-676273ee901f")}catch{}})();async function fl(e,t,n=Ui){try{await n({pmRoot:e,result:t})}catch{if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let o=t,r=Array.isArray(o.warnings)?o.warnings.filter(i=>typeof i=="string"):[];o.warnings=[...new Set([...r,"context_usage_feedback_write_failed"])].sort()}}}import{createHash as Cp}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9133d39d-b2fb-5f99-8fd3-87a7d2f8df6d")}catch{}})();var _l="PmCliError";function bp(e){if(!Number.isFinite(e))throw new TypeError("createPmCliExpectedError options.exitCode must be a finite number");let t=Math.trunc(e);if(t<=u.SUCCESS)throw new TypeError("createPmCliExpectedError options.exitCode must be a positive exit code");return t}function wp(e,t={}){if(typeof e!="string"||e.trim().length===0)throw new TypeError("createPmCliExpectedError message must be a non-empty string");let n=new m(e,bp(t.exitCode??u.USAGE),t.context??{});return"cause"in t&&Object.defineProperty(n,"cause",{value:t.cause,enumerable:!1,configurable:!0,writable:!0}),n}function Zo(e){if(!(e instanceof Error)||e.name!==_l)return!1;let t=e;return typeof t.exitCode=="number"&&Number.isFinite(t.exitCode)}import{constants as Mt}from"node:fs";import{lstat as hl,mkdir as er,open as gl}from"node:fs/promises";import me 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]="e57a9bca-1190-5ffd-bb7d-d76a22fc9e57")}catch{}})();function Qo(e,t){if(typeof e!="string"||e.trim().length===0)throw new TypeError(`Relationship event ${t} must be non-empty`);return e.trim()}function tr(e,t){let n=t.require(e.kind),o=n.direction==="undirected"?[e.source,e.target].sort().join("\0"):`${e.source}\0${e.target}`;return`${n.kind}\0${o}`}function vp(e){return Object.freeze({...e,...e.payload===void 0?{}:{payload:Object.freeze(structuredClone(e.payload))}})}function kp(e,t,n,o){let r=n.require(e.kind),i=o.outgoingOne.get(`${r.kind}\0${e.source}`);if(i!==void 0&&i!==t)throw new TypeError(`Relationship outgoing cardinality exceeded for ${r.kind}`);let s=o.incomingOne.get(`${r.kind}\0${e.target}`);if(s!==void 0&&s!==t)throw new TypeError(`Relationship incoming cardinality exceeded for ${r.kind}`);let a=tr(e,n),c=o.identities.get(a);if(c!==void 0&&c!==t)throw new TypeError(`Relationship edge already active: ${a}`)}function Sp(e){let t=new Map;for(let n of e)n.action==="remove"?t.delete(n.relationshipId):t.set(n.relationshipId,n.edge);return t}function Ip(e,t,n){if(e.expectedVersion!==void 0&&e.expectedVersion!==t)throw new TypeError(`Relationship event version conflict: expected ${e.expectedVersion}, current ${t}`);let o=Qo(e.eventId,"eventId");if(n.has(o))throw new TypeError(`Relationship event already exists: ${o}`);if(e.action!=="add"&&e.action!=="remove"&&e.action!=="supersede")throw new TypeError(`Unknown relationship event action: ${e.action}`);if(!Number.isFinite(Date.parse(e.timestamp)))throw new TypeError("Relationship event timestamp must be valid");return{eventId:o,relationshipId:Qo(e.relationshipId,"relationshipId"),author:Qo(e.author,"author"),timestamp:new Date(e.timestamp).toISOString()}}function Ap(e,t,n,o,r,i){let s=n.has(t);if(e.action==="add"&&s)throw new TypeError(`Relationship is already active: ${t}`);if(e.action!=="add"&&!s)throw new TypeError(`Relationship is not active: ${t}`);if(e.action==="remove")return;if(!e.edge)throw new TypeError(`Relationship ${e.action} event requires an edge`);let a=typeof e.edge.source=="string"?e.edge.source.trim():"",c=typeof e.edge.target=="string"?e.edge.target.trim():"";if(!o.has(a)||!o.has(c))throw new TypeError(`Relationship endpoint not found: ${a} -> ${c}`);let l=new Ve([a,c],[e.edge],r).edges()[0];return kp(l,t,r,i),vp(l)}var jt=class{#t;#n;#o=[];#i=new Set;#e=new Map;#r={identities:new Map,outgoingOne:new Map,incomingOne:new Map};constructor(t,n={}){this.#t=new Set([...t].filter(o=>typeof o=="string").map(o=>o.trim()).filter(Boolean)),this.#n=n.registry??Kt()}get version(){return this.#o.length}events(){return Object.freeze([...this.#o])}*stream(t={}){let n=t.fromVersion??1,o=t.toVersion??this.version,r=t.batchSize??100;if(!Number.isInteger(n)||n<1)throw new TypeError("Relationship event stream fromVersion must be positive");if(!Number.isInteger(o)||o<0||o>this.version)throw new TypeError(`Relationship event stream toVersion out of range: ${o}`);if(!Number.isInteger(r)||r<1)throw new TypeError("Relationship event stream batchSize must be positive");if(n>o+1)throw new TypeError("Relationship event stream fromVersion exceeds the selected prefix");for(let i=n-1;i<o;i+=r)yield Object.freeze(this.#o.slice(i,Math.min(i+r,o)))}project(t,n,o={}){if(typeof n!="function")throw new TypeError("Relationship event projection requires a reducer");let r=t,i=0,s;for(let a of this.stream({...o,batchSize:256}))for(let c of a)r=n(r,c),i+=1,s=c;return Object.freeze({state:r,version:s?.sequence??Math.max(0,(o.fromVersion??1)-1),processed:i,...s===void 0?{}:{asOf:s.timestamp}})}#s(t,n){let o=this.#n.require(n.kind);this.#r.identities.set(tr(n,this.#n),t),o.outgoing==="one"&&this.#r.outgoingOne.set(`${o.kind}\0${n.source}`,t),o.incoming==="one"&&this.#r.incomingOne.set(`${o.kind}\0${n.target}`,t)}#a(t){let n=this.#n.require(t.kind);this.#r.identities.delete(tr(t,this.#n)),n.outgoing==="one"&&this.#r.outgoingOne.delete(`${n.kind}\0${t.source}`),n.incoming==="one"&&this.#r.incomingOne.delete(`${n.kind}\0${t.target}`)}append(t){let n=Ip(t,this.version,this.#i),o=this.#e.get(n.relationshipId),r=Ap(t,n.relationshipId,this.#e,this.#t,this.#n,this.#r),i=Object.freeze({eventId:n.eventId,relationshipId:n.relationshipId,action:t.action,...r===void 0?{}:{edge:r},author:n.author,timestamp:n.timestamp,...t.reason?.trim()?{reason:t.reason.trim()}:{},sequence:this.version+1});return this.#o.push(i),this.#i.add(n.eventId),o&&this.#a(o),t.action==="remove"?this.#e.delete(n.relationshipId):(this.#e.set(n.relationshipId,r),this.#s(n.relationshipId,r)),i}snapshot(t={}){if(t.atVersion!==void 0&&t.atTimestamp!==void 0)throw new TypeError("Relationship snapshot accepts one target");let n;if(t.atTimestamp!==void 0){let i=Date.parse(t.atTimestamp);if(!Number.isFinite(i))throw new TypeError("Relationship snapshot timestamp must be valid");n=this.#o.filter(s=>Date.parse(s.timestamp)<=i)}else{let i=t.atVersion??this.version;if(!Number.isInteger(i)||i<0||i>this.version)throw new TypeError(`Relationship snapshot version out of range: ${i}`);n=this.#o.slice(0,i)}let o=Sp(n),r=new Ve(this.#t,o.values(),this.#n);return Object.freeze({version:n.at(-1)?.sequence??0,...n.at(-1)?{asOf:n.at(-1).timestamp}:{},edges:r.edges(),graph:r})}page(t){if(!Number.isInteger(t.limit)||t.limit<1)throw new TypeError("Relationship event page limit must be positive");let n=xi("relationship-events",{order:"append-sequence"}),o=t.cursor===void 0?this.version:Number(Oi(t.cursor,n).snapshot);if(!Number.isSafeInteger(o)||o<0||o>this.version)throw new TypeError("Relationship event cursor snapshot version is invalid");let r=$i(this.#o.slice(0,o),{cursor:t.cursor,fingerprint:n,limit:t.limit,readId:i=>i.eventId,snapshot:String(o)});return{version:o,events:r.rows,hasMore:r.has_more,...r.next_cursor?{nextCursor:r.next_cursor}:{}}}},Ep="relationship-event-store",yl=Mt.O_NOFOLLOW;function $n(e){return te(e,Ep,30,`relationship-store:${process.pid}`,!1,!1,3e3)}async function Ue(e,t="relationships/events.jsonl"){let n=me.resolve(e),o=me.resolve(n,t),r=me.relative(n,o);if(r.length===0)throw new TypeError("Relationship event path must name a file within the tracker root");if(r===".."||r.startsWith(`..${me.sep}`)||me.isAbsolute(r))throw new TypeError("Relationship event path must stay within the tracker root");if(await er(n,{recursive:!0}),(await hl(n)).isSymbolicLink())throw new TypeError("Relationship event tracker root must not be a symbolic link");let s=n;for(let a of r.split(me.sep)){s=me.join(s,a);try{if((await hl(s)).isSymbolicLink())throw new TypeError("Relationship event path must not contain symbolic links")}catch(c){if(no(c))break;throw c}}return o}async function Fn(e,t,n){let o=new jt(t,{registry:n}),r,i;try{i=await gl(e,Mt.O_RDONLY|yl),r=await i.readFile("utf8")}catch(a){if(no(a))return{log:o,raw:""};throw a}finally{await i?.close()}let s=r.split(`
|
|
2
2
|
`);for(let a=0;a<s.length;a+=1){let c=s[a].trim();if(!c)continue;let l;try{l=JSON.parse(c)}catch{throw new TypeError(`Invalid relationship event JSONL at line ${a+1}`)}if(l.sequence!==o.version+1)throw new TypeError(`Invalid relationship event sequence at line ${a+1}`);o.append({eventId:l.eventId,relationshipId:l.relationshipId,action:l.action,...l.edge===void 0?{}:{edge:l.edge},author:l.author,timestamp:l.timestamp,...l.reason===void 0?{}:{reason:l.reason},expectedVersion:o.version})}return{log:o,raw:r}}function Tp(e,t,n,o){let r=Date.parse(t.timestamp),i;return t.action!=="remove"&&t.edge!==void 0&&(i=new Ve(n,[t.edge],o).edges()[0]),e.eventId===t.eventId.trim()&&e.relationshipId===t.relationshipId.trim()&&e.action===t.action&&e.author===t.author.trim()&&Number.isFinite(r)&&e.timestamp===new Date(r).toISOString()&&e.reason===(t.reason?.trim()||void 0)&&It(e.edge)===It(i)}var Pn=class e{#t;#n;#o;#i;#e;constructor(t,n,o,r){this.#t=t.pmRoot,this.#n=n,this.#o=t.registry,this.#i=o,this.#e=r}static async open(t){let n=Object.freeze([...t.nodes]),o=await Ue(t.pmRoot,t.relativePath),r=await $n(t.pmRoot);try{await Ue(t.pmRoot,o);let{log:i}=await Fn(o,n,t.registry);return new e(t,n,o,i)}finally{await r()}}get path(){return this.#i}async currentVersion(){return this.#e=await this.#r(),this.#e.version}async append(t){let n=await $n(this.#t);try{let o=await Ue(this.#t,this.#i),{log:r}=await Fn(o,this.#n,this.#o),i=r.append(t);await er(me.dirname(o),{recursive:!0}),await Ue(this.#t,o);let s=await gl(o,Mt.O_APPEND|Mt.O_CREAT|Mt.O_WRONLY|yl);try{await s.appendFile(`${JSON.stringify(i)}
|
|
3
3
|
`,"utf8")}finally{await s.close()}return this.#e=r,i}finally{await n()}}async appendBatch(t,n={}){let o=await $n(this.#t);try{let r=await Ue(this.#t,this.#i),{log:i,raw:s}=await Fn(r,this.#n,this.#o),a=i.version,c=new Map(i.events().map(d=>[d.eventId,d])),l=[],p=[];for(let d of t){let f=d.eventId.trim(),_=c.get(f);if(_!==void 0){if(n.existingEventPolicy==="skip_identical"&&Tp(_,d,this.#n,this.#o)){p.push(_.eventId);continue}if(n.existingEventPolicy==="skip_identical")throw new TypeError(`Relationship event id collision with different content: ${f}`)}let w=i.append(d);c.set(w.eventId,w),l.push(w)}if(l.length>0){let d=s.length===0||s.endsWith(`
|
|
4
4
|
`)?s:`${s}
|
|
@@ -2244,4 +2244,4 @@ compdef _pm pm`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"
|
|
|
2244
2244
|
`);M(e.progressEnabled,"writing keyword artifacts"),await oe(t,`${JSON.stringify(e.manifest,null,2)}
|
|
2245
2245
|
`),await oe(n,`${r}
|
|
2246
2246
|
`);let i=[];if(e.mode!=="keyword")try{M(e.progressEnabled,"writing vectorization status ledger"),await Ia(e.pmRoot,e.vectorizationLedgerEntries,e.vectorizationEmbeddingMetadata)}catch(s){i.push(`search_vectorization_status_ledger_write_failed:${s instanceof Error?s.message:String(s)}`)}return i}async function Ng(e,t){let n=_g(e.mode),o=fg(e),r=e.full===!0;M(o,`start mode=${n}`);let i=A(process.cwd(),t.path);await F(i);let s=pa(await T(i)).settings,a=null;try{a=await te(i,ua,s.locks.ttl_seconds,R(void 0,"pm-reindex"),!1,s.governance.force_required_for_stale_lock,s.locks.wait_ms)}catch(c){throw c instanceof m&&c.exitCode===u.CONFLICT?new m("Another pm reindex run is already active for this project. Wait for it to finish before starting a new keyword, semantic, or hybrid reindex.",u.CONFLICT,{code:"reindex_already_running",type:"urn:pm-cli:error:reindex_already_running",why:"Semantic reindex can be expensive and duplicate runs compete for the same local embedding model and vector store.",nextSteps:["Check active pm reindex processes before starting another reindex.","Rerun with --progress when you need non-interactive visibility."]}):c}try{let c=yg(s),l=bg(s),p=Ag({requestedMode:n,pmRoot:i,settings:s,extensionEmbedding:c,extensionVectorAdapter:l}),d=n;M(o,"loading item corpus");let f=await Eg({pmRoot:i,settings:s}),_=f.warnings,{documentCandidates:w,metadataDocuments:k}=f;M(o,`loaded_items=${k.length}`);let y=S(),v=Ig(d,y,k),g=Bt.join(i,ei),I=Bt.join(i,ti),x=d==="keyword"?await oi(i,w,s.schema,_):k,N=[],W={},O=null,C=Sg(d);if(d==="keyword"&&await Tg({pmRoot:i,settings:s,forceFullSemantic:r,extensionEmbedding:c,reindexWarnings:_}),d!=="keyword"){let ne=await Pg({pmRoot:i,settings:s,requestedMode:n,activeEmbeddingProvider:p.activeEmbeddingProvider,activeVectorStore:p.activeVectorStore,extensionEmbedding:c,extensionVectorAdapter:l,documentCandidates:w,metadataDocuments:k,documentsForKeywordArtifacts:x,forceFullSemantic:r,reindexWarnings:_,semanticWarnings:N,semanticSummary:C,progressEnabled:o});x=ne.documentsForKeywordArtifacts,W=ne.vectorizationLedgerEntries,O=ne.vectorizationEmbeddingMetadata}let se=await Lg({pmRoot:i,mode:d,manifest:v,documentsForKeywordArtifacts:x,settings:s,vectorizationLedgerEntries:W,vectorizationEmbeddingMetadata:O,progressEnabled:o}),Re=[...await G({path:g,scope:"project",op:"reindex:manifest"}),...await G({path:I,scope:"project",op:"reindex:embeddings"}),...await Ei({mode:d,total_items:k.length})];return M(o,"done"),{ok:!0,mode:d,total_items:k.length,semantic:C,artifacts:{manifest:ei,embeddings:ti},warnings:[..._,...N,...se,...Re],generated_at:y}}finally{await 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]="ff0e0921-43ca-5278-ab61-21bef91ce4aa")}catch{}})();var lp=Symbol("pm.active-extension-host-context");function Q(e){return{fullChangedFields:!0,options:e}}var b=class e{defaults;constructor(t={}){this.defaults={...t.pmRoot===void 0?{}:{path:t.pmRoot},...t.cwd===void 0?{}:{cwd:t.cwd},...t.author===void 0?{}:{author:t.author},...t.noExtensions===void 0?{}:{noExtensions:t.noExtensions}}}static forActiveExtensionHost(t){let n=new e({...t,noExtensions:!0});return n.defaults[lp]=!0,n}run(t,n={}){return Ug({...this.defaults,...n,action:t})}runTyped(t,n={}){return this.run(t,n)}context(t={}){return this.runTyped("context",{options:t})}listAllItemMetadataLight(){return vl(this.defaults.path,this.defaults.cwd)}list(t={}){return this.runTyped("list",{options:t})}async listAllComplete(t={}){return Nn(await this.list(or(t)))}search(t,n={}){return this.runTyped("search",{query:t,options:n})}get(t,n={}){return this.runTyped("get",{id:t,options:n})}next(t={}){return this.runTyped("next",{options:t})}aggregate(t={}){return this.runTyped("aggregate",{options:t})}stats(t={}){return this.runTyped("stats",{options:t})}duplicates(t={}){return this.runTyped("duplicates",{options:t})}comments(t,n={}){return this.runTyped("comments",{id:t,options:n})}notes(t,n={}){return this.runTyped("notes",{id:t,options:n})}learnings(t,n={}){return this.runTyped("learnings",{id:t,options:n})}files(t,n={}){return this.runTyped("files",{id:t,options:n})}filesDiscover(t,n={}){return this.runTyped("files-discover",{id:t,options:n})}filesLookup(t){return this.runTyped("files-lookup",{options:t})}docs(t,n={}){return this.runTyped("docs",{id:t,options:n})}deps(t,n={}){return this.runTyped("deps",{id:t,options:n})}graph(t,n={},o={}){return this.runTyped("graph",{subcommand:t,...n,options:o})}append(t,n,o={}){return this.runTyped("append",{id:t,...Q(Ft(o,{body:n}))})}init(t,n={}){return this.runTyped("init",{...t===void 0?{}:{prefix:t},options:n})}config(t,n,o,r,i={}){return this.runTyped("config",{scope:t,configAction:n,...o===void 0?{}:{key:o},...r===void 0?{}:{value:r},options:i})}schema(t,n={}){return this.runTyped("schema",{options:{...n,subcommand:t}})}workflowPolicy(t,n,o={}){return this.runTyped("schema",{name:n,options:{...o,subcommand:t}})}schemaList(){return this.runTyped("schema",{options:{subcommand:"list"}})}schemaShow(t){return this.runTyped("schema",{name:t,options:{subcommand:"show"}})}schemaAddType(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-type"}})}schemaRemoveType(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-type"}})}schemaAddStatus(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-status"}})}schemaRemoveStatus(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-status"}})}schemaAddField(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-field"}})}schemaRemoveField(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-field"}})}schemaListFields(){return this.runTyped("schema",{options:{subcommand:"list-fields"}})}schemaShowField(t){return this.runTyped("schema",{name:t,options:{subcommand:"show-field"}})}schemaApplyPreset(t,n={}){return this.runTyped("schema",{typePreset:t,options:{...n,subcommand:"apply-preset"}})}schemaInferTypes(t={}){return this.runTyped("schema",{options:{...t,subcommand:"add-type",infer:!0}})}schemaRenameType(t,n,o){return this.runTyped("schema",{name:t,options:{...o,subcommand:"rename-type",to:n}})}schemaRenameField(t,n,o,r){return this.runTyped("schema",{name:t,options:{...o,subcommand:"rename-field",to:n,...r?{fieldTypeScope:r}:{}}})}schemaRemapStatus(t,n,o){return this.runTyped("schema",{name:t,options:{...o,subcommand:"remap-status",to:n}})}schemaShowStatus(t){return this.runTyped("schema",{name:t,options:{subcommand:"show-status"}})}profile(t,n={}){return this.runTyped("profile",{options:{...n,subcommand:t}})}profileList(){return this.runTyped("profile",{options:{subcommand:"list"}})}profileShow(t){return this.runTyped("profile",{name:t,options:{subcommand:"show"}})}profileApply(t,n={}){return this.runTyped("profile",{name:t,options:{...n,subcommand:"apply"}})}profileLint(t){return this.runTyped("profile",{name:t,options:{subcommand:"lint"}})}validate(t={}){return this.runTyped("validate",{options:t})}health(t={}){return this.runTyped("health",{options:t})}gc(t={}){return this.runTyped("gc",{options:t})}assurance(t){return this.runTyped("assurance",{options:{...t,subcommand:t.action}})}historyRedact(t,n){return this.runTyped("history-redact",{id:t,options:n})}historyRepair(t,n={}){return this.runTyped("history-repair",{id:t,options:n})}historyRepairAll(t={}){return this.runTyped("history-repair",{options:{...t,all:!0}})}historyAttest(t={}){return this.runTyped("history-attest",{options:t})}historyCompact(t,n={}){return this.runTyped("history-compact",{id:t,options:n})}historyCompactBulk(t){return this.runTyped("history-compact",{options:t})}historyAuthorAcknowledge(t){return this.runTyped("history-author-acknowledge",{historyEvent:(t.events??[]).map(n=>`${n.item_id}:${String(n.line)}`),allActionable:t.all_actionable===!0,dryRun:t.dry_run===!0,planFingerprint:t.plan_fingerprint,limit:t.coordinate_limit,attributedAuthor:t.attributed_author,reviewer:t.reviewer,reason:t.reason})}plan(t,n,o={},r,i){return this.runTyped("plan",{fullChangedFields:!0,...n===void 0?{}:{id:n},...r===void 0?{}:{stepRef:r},...i===void 0?{}:{reorderTo:i},options:Ft(o,{subcommand:t})})}planCreate(t){return this.plan("create",void 0,t)}planShow(t,n={}){return this.plan("show",t,n)}planAddStep(t,n){return this.plan("add-step",t,n)}planUpdateStep(t,n,o){return this.plan("update-step",t,o,n)}planCompleteStep(t,n,o={}){return this.plan("complete-step",t,o,n)}planBlockStep(t,n,o){return this.plan("block-step",t,o,n)}planReorderStep(t,n,o,r={}){return this.plan("reorder-step",t,r,n,o)}planRemoveStep(t,n,o={}){return this.plan("remove-step",t,o,n)}planLink(t,n,o){return this.plan("link",t,o,n)}planUnlink(t,n,o){return this.plan("unlink",t,o,n)}planDecision(t,n){return this.plan("decision",t,n)}planDiscovery(t,n){return this.plan("discovery",t,n)}planValidation(t,n){return this.plan("validation",t,n)}planResume(t,n){return this.plan("resume",t,n)}planApprove(t,n={}){return this.plan("approve",t,n)}planMaterialize(t,n){return this.plan("materialize",t,n)}create(t={}){return this.runTyped("create",Q(t))}update(t,n={}){return this.runTyped("update",{id:t,...Q(n)})}reopen(t,n,o={}){return this.runTyped("item-reopen",{id:t,reason:n,fullChangedFields:!0,options:o})}close(t,n,o={}){return this.runTyped("close",{id:t,reason:n,...Q(o)})}claim(t,n={}){return this.runTyped("claim",{id:t,...Q(n)})}claimNext(t={}){return this.runTyped("claim",{next:!0,...Q(t)})}release(t,n={}){return this.runTyped("release",{id:t,...Q(n)})}copy(t,n={}){return this.runTyped("copy",{id:t,...Q(n)})}delete(t,n={}){return this.runTyped("delete",{id:t,...Q(n)})}restore(t,n,o={}){return this.runTyped("restore",{fullChangedFields:!0,id:t,options:{...o,target:n}})}focus(t,n={}){return this.runTyped("focus",{...t===void 0?{}:{id:t},...Q(n)})}startTask(t,n={}){return this.runTyped("start-task",{id:t,...Q(n)})}pauseTask(t,n={}){return this.runTyped("pause-task",{id:t,...Q(n)})}closeTask(t,n,o={}){return this.runTyped("close-task",{id:t,reason:n,...Q(o)})}extension(t,n={}){return this.runTyped("extension",{...t===void 0?{}:{target:t},options:n})}extensionList(t={}){return this.extension("list",t)}extensionActivate(t,n={}){return this.runTyped("extension-activate",{target:t,options:n})}extensionDeactivate(t,n={}){return this.runTyped("extension-deactivate",{target:t,options:n})}package(t,n={}){return this.runTyped("package",{...t===void 0?{}:{target:t},options:{...n,vocabulary:"package"}})}packageList(t={}){return this.package("list",t)}packageInstall(t,n={}){return this.runTyped("package-install",{target:t,options:n})}packageUninstall(t,n={}){return this.runTyped("package-uninstall",{target:t,options:n})}packageDoctor(t={}){return this.runTyped("package-doctor",{options:t})}packageManage(t,n={}){return this.runTyped("package-manage",{...t===void 0?{}:{target:t},options:n})}packageDescribe(t,n={}){return this.runTyped("package-describe",{...t===void 0?{}:{target:t},options:n})}packageReload(t={}){return this.runTyped("package-reload",{options:t})}packageCatalog(t={}){return this.runTyped("package-catalog",{options:t})}packageActivate(t,n={}){return this.runTyped("package-activate",{target:t,options:n})}packageDeactivate(t,n={}){return this.runTyped("package-deactivate",{target:t,options:n})}packageMigrate(t={}){return this.package(void 0,{...t,migrate:!0})}upgrade(t,n={}){return this.runTyped("upgrade",{...t===void 0?{}:{target:t},options:n})}};function AT(e={},t={}){return new b(t).context(e)}function ET(e={},t={}){return new b(t).list(e)}function TT(e={},t={}){return new b(t).listAllComplete(e)}function CT(e,t={},n={}){return new b(n).search(e,t)}function RT(e,t={},n={}){return new b(n).get(e,t)}function xT(e={},t={}){return new b(t).next(e)}function OT(e={},t={}){return new b(t).aggregate(e)}function $T(e={},t={}){return new b(t).stats(e)}function FT(e={},t={}){return new b(t).duplicates(e)}function PT(e,t={},n={}){return new b(n).comments(e,t)}function LT(e,t={},n={}){return new b(n).notes(e,t)}function NT(e,t={},n={}){return new b(n).learnings(e,t)}function DT(e,t={},n={}){return new b(n).files(e,t)}function MT(e,t={},n={}){return new b(n).filesDiscover(e,t)}function jT(e,t={}){return new b(t).filesLookup(e)}function GT(e,t={},n={}){return new b(n).docs(e,t)}function UT(e,t={},n={}){return new b(n).deps(e,t)}function qT(e,t={},n={},o={}){return new b(o).graph(e,t,n)}function zT(e,t,n={},o={}){return new b(o).append(e,t,n)}function HT(e,t={},n={}){return new b(n).init(e,t)}function WT(e,t,n,o,r={},i={}){return new b(i).config(e,t,n,o,r)}function VT(e,t={},n={}){return new b(n).schema(e,t)}function BT(e={}){return new b(e).schemaList()}function KT(e,t={}){return new b(t).schemaShow(e)}function YT(e,t={},n={}){return new b(n).schemaAddType(e,t)}function JT(e,t={},n={}){return new b(n).schemaRemoveType(e,t)}function XT(e,t={},n={}){return new b(n).schemaAddStatus(e,t)}function ZT(e,t={},n={}){return new b(n).schemaRemoveStatus(e,t)}function QT(e,t={},n={}){return new b(n).schemaAddField(e,t)}function eC(e,t={},n={}){return new b(n).schemaRemoveField(e,t)}function tC(e={}){return new b(e).schemaListFields()}function nC(e,t={}){return new b(t).schemaShowField(e)}function oC(e,t={},n={}){return new b(n).schemaApplyPreset(e,t)}function rC(e={},t={}){return new b(t).schemaInferTypes(e)}function iC(e,t,n,o={}){return new b(o).schemaRenameType(e,t,n)}function sC(e,t,n,o,r={}){return new b(r).schemaRenameField(e,t,n,o)}function aC(e,t,n,o={}){return new b(o).schemaRemapStatus(e,t,n)}function cC(e,t={}){return new b(t).schemaShowStatus(e)}function lC(e,t={},n={}){return new b(n).profile(e,t)}function dC(e={}){return new b(e).profileList()}function mC(e,t={}){return new b(t).profileShow(e)}function pC(e,t={},n={}){return new b(n).profileApply(e,t)}function uC(e,t={}){return new b(t).profileLint(e)}function fC(e={},t={}){return new b(t).validate(e)}function _C(e={},t={}){return new b(t).health(e)}function hC(e={},t={}){return new b(t).gc(e)}function gC(e,t,n={}){return new b(n).historyRedact(e,t)}function yC(e,t={},n={}){return new b(n).historyRepair(e,t)}function bC(e={},t={}){return new b(t).historyRepairAll(e)}function wC(e,t={},n={}){return new b(n).historyCompact(e,t)}function vC(e,t={}){return new b(t).historyCompactBulk(e)}function kC(e={},t={}){return new b(t).create(e)}function SC(e,t={},n={}){return new b(n).update(e,t)}function IC(e,t,n={},o={}){return new b(o).reopen(e,t,n)}function AC(e,t,n={},o={}){return new b(o).close(e,t,n)}function EC(e,t={},n={}){return new b(n).claim(e,t)}function TC(e={},t={}){return new b(t).claimNext(e)}function CC(e,t={},n={}){return new b(n).release(e,t)}function RC(e,t={},n={}){return new b(n).copy(e,t)}function xC(e,t={},n={}){return new b(n).delete(e,t)}function OC(e,t,n={},o={}){return new b(o).restore(e,t,n)}function $C(e,t={},n={}){return new b(n).focus(e,t)}function FC(e,t={},n={}){return new b(n).startTask(e,t)}function PC(e,t={},n={}){return new b(n).pauseTask(e,t)}function LC(e,t,n={},o={}){return new b(o).closeTask(e,t,n)}function NC(e,t={},n={}){return new b(n).extension(e,t)}function DC(e={},t={}){return new b(t).extensionList(e)}function MC(e,t={},n={}){return new b(n).extensionActivate(e,t)}function jC(e,t={},n={}){return new b(n).extensionDeactivate(e,t)}function GC(e,t={},n={}){return new b(n).package(e,t)}function UC(e={},t={}){return new b(t).packageList(e)}function qC(e,t={},n={}){return new b(n).packageInstall(e,t)}function zC(e,t={},n={}){return new b(n).packageUninstall(e,t)}function HC(e={},t={}){return new b(t).packageDoctor(e)}function WC(e,t={},n={}){return new b(n).packageManage(e,t)}function VC(e,t={},n={}){return new b(n).packageDescribe(e,t)}function BC(e={},t={}){return new b(t).packageReload(e)}function KC(e={},t={}){return new b(t).packageCatalog(e)}function YC(e,t={},n={}){return new b(n).packageActivate(e,t)}function JC(e,t={},n={}){return new b(n).packageDeactivate(e,t)}function XC(e,t={},n={}){return new b(n).upgrade(e,t)}async function ZC(e,t={}){let n=typeof e=="string"?{...t,pmRoot:e}:e??t,o={json:!0,quiet:n.quiet??!0,noExtensions:n.noExtensions??!1,noPager:!0,profile:n.profile??!1,path:n.pmRoot};return fn(n,o)}var ap=Si(),ii=new Dg;function eo(){po(hi()),uo(gi()),fo(yi()),_o(bi()),ho(wi()),go(vi()),yo(ki())}async function dp(e,t,n,o){return mo(()=>t===void 0?ap.read(()=>cp(e,n,o)):ap.write(()=>jg(t,()=>cp(e,n,o))))}async function QC(e,t){let n=e.cwd;if(ii.getStore()===!0&&n===void 0&&e.noExtensions===!0){let r=A(process.cwd(),e.path);return mo(()=>On({pmRoot:r},t))}let o=n??process.cwd();return dp(bn({path:e.path,noExtensions:e.noExtensions}),n,o,()=>ii.run(!0,t))}async function cp(e,t,n){let o=A(t,e.path);if(e.noExtensions)return eo(),On({pmRoot:o},()=>n(null));if(!await ye(we(o)))return eo(),n(null);let r=null,i;try{let s=await T(o),a=await Xt({pmRoot:o,settings:s,cwd:t,noExtensions:!1}),c=await Qt({...a,loaded:a.loaded});i={loadResult:a,activationResult:c},po(c.hooks),uo(c.commands),fo(c.parsers),_o(c.preflight),ho(c.services),go(c.renderers),yo(c.registrations),r={registrations:c.registrations,commands:c.commands,pmRoot:o,packages:a.loaded}}catch(s){eo(),console.error("[pm-sdk] extension activation failed; continuing without active extensions:",s)}try{return await On({pmRoot:o,packages:r?.packages},()=>n(r))}finally{eo(),i&&await Zt(i.loadResult,i.activationResult).catch(()=>{})}}async function Mg(e,t,n,o,r){if(!r)throw new m(`Unsupported native pm action: ${e}`,u.USAGE);let i=Me(e),a=r.registrations.commands.find(p=>Me(p.action)===i)?.command??r.commands.handlers.find(p=>Me(p.command)===i)?.command;if(!a)throw new m(`Unsupported native pm action: ${e}`,u.USAGE);let c=typeof o.author=="string"&&o.author.trim()?o.author.trim():"pm-extension",l=await Ti({command:vn(a),args:U(n.args??t.args),options:Fo(t,n),global:o,pm_root:r.pmRoot,sdk:bl(r.pmRoot,b.forActiveExtensionHost({pmRoot:r.pmRoot,author:c}),c,vn(a))});if(!l.handled){let p=l.warnings.length>0?` (${l.warnings.join(", ")})`:"";throw new m(`Unsupported native pm action: ${e}${p}`,u.USAGE)}return l.result}async function jg(e,t){let n=process.cwd();process.chdir(e);try{return await t()}finally{process.chdir(n)}}function Gg(e){let t=K(e,"action"),n=Me(t),o=_e(rr,n),r=o?.action??n,i={...e,action:r};return o?.options!==void 0&&(i.options={...o.options,...oo(e.options)}),r==="package"&&(i.options={...oo(i.options),vocabulary:"package"}),{action:r,args:i}}async function Ug(e){let t=Gg(e),n=bn(t.args),o=ac(t.action),r=h(t.args,"cwd"),i=r??process.cwd();t.action==="init"&&(n[ec]=i),(t.action!=="init"||n.path!==void 0||(process.env.PM_PATH?.trim().length??0)>0)&&(n.path=A(i,n.path));try{return t.action==="history-attest"?await ri(t.action,t.args,n,null):e[lp]===!0||ii.getStore()===!0?await ri(t.action,t.args,n,null):await dp(n,r,i,s=>ri(t.action,t.args,n,s))}finally{o&&Ur()}}function eR(e=Li){return e.map(t=>{let n=Me(t),o=_e(rr,n),r=o?.action??n,i=_e(Gr,r)!==void 0;return{action:t,resolved_action:r,covered:i,route:i?o?"alias":"native":"missing"}})}async function ri(e,t,n,o){let r=$o(t,e);Di(e,r),Mi(e,r);let i={action:e,args:t,options:r,id:h(t,"id"),force:t.force===!0||r.force===!0,global:n,activeExtensions:o},s=_e(Gr,e),a=s?await s(i):await Mg(e,t,r,n,o);if(e==="history-attest")return a;{r.resolvedOutputFormat="json";let c=zi(e,r,a);return await fl(A(process.cwd(),n.path),c),c}}var qg={closeManyOptionsFromFlat:kn,extensionOptionsFromArgs:Fo,globalOptions:bn,mutationListOptions:cc,normalizeActionName:Me,normalizeCommandPath:vn,normalizeMcpUpdateOptions:dc,normalizeMcpOptionsArrays:sc,optionsWithAuthor:$o,readRequiredString:K,readScalarString:oc,readScalarStringAllowBlank:rc,readStringArray:U,updateManyOptionsFromFlat:Sn,withAddNoteOption:Pt,withFilesDiscoveryOptions:wn,withMutationCompaction:j};(process.env.NODE_ENV==="test"||process.env.VITEST!==void 0||process.env.VITEST_WORKER_ID!==void 0)&&(globalThis.__pmCliActionRunnerTestHooks=qg);export{Xo as a,ul as b,_p as c,gp as d,yp as e,On as f,_l as g,wp as h,Zo as i,jt as j,Pn as k,bl as l,Rp as m,Ln as n,or as o,wl as p,Nn as q,Np as r,Il as s,Tl as t,Rl as u,Fl as v,cr as w,lr as x,dr as y,mr as z,du as A,jl as B,gr as C,Xl as D,nd as E,od as F,st as G,Cr as H,qf as I,aw as J,cw as K,Or as L,id as M,Iw as N,Aw as O,ad as P,dd as Q,Hw as R,i_ as S,Mr as T,a_ as U,c_ as V,Sd as W,Id as X,Ad as Y,Ed as Z,Td as _,_v as $,hv as aa,gv as ba,yv as ca,Cd as da,Rd as ea,$d as fa,Ld as ga,Nd as ha,Dd as ia,K as ja,Ur as ka,VS as la,BS as ma,KS as na,YS as oa,JS as pa,Kd as qa,XS as ra,dh as sa,uh as ta,gh as ua,yh as va,bh as wa,z as xa,wh as ya,vh as za,kh as Aa,Sh as Ba,zr as Ca,Zd as Da,lt as Ea,qr as Fa,Qd as Ga,Ih as Ha,em as Ia,Ah as Ja,Eh as Ka,Th as La,Ch as Ma,Rh as Na,Nh as Oa,rm as Pa,Dh as Qa,Hh as Ra,Xh as Sa,Qh as Ta,mg as Ua,Ng as Va,b as Wa,AT as Xa,ET as Ya,TT as Za,CT as _a,RT as $a,xT as ab,OT as bb,$T as cb,FT as db,PT as eb,LT as fb,NT as gb,DT as hb,MT as ib,jT as jb,GT as kb,UT as lb,qT as mb,zT as nb,HT as ob,WT as pb,VT as qb,BT as rb,KT as sb,YT as tb,JT as ub,XT as vb,ZT as wb,QT as xb,eC as yb,tC as zb,nC as Ab,oC as Bb,rC as Cb,iC as Db,sC as Eb,aC as Fb,cC as Gb,lC as Hb,dC as Ib,mC as Jb,pC as Kb,uC as Lb,fC as Mb,_C as Nb,hC as Ob,gC as Pb,yC as Qb,bC as Rb,wC as Sb,vC as Tb,kC as Ub,SC as Vb,IC as Wb,AC as Xb,EC as Yb,TC as Zb,CC as _b,RC as $b,xC as ac,OC as bc,$C as cc,FC as dc,PC as ec,LC as fc,NC as gc,DC as hc,MC as ic,jC as jc,GC as kc,UC as lc,qC as mc,zC as nc,HC as oc,WC as pc,VC as qc,BC as rc,KC as sc,YC as tc,JC as uc,XC as vc,ZC as wc,QC as xc,Ug as yc,eR as zc};
|
|
2247
|
-
//# sourceMappingURL=chunk-
|
|
2247
|
+
//# sourceMappingURL=chunk-5XKF5SQV.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Fa as p,Ga as i,Ha as v,Ia as _}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{Fa as p,Ga as i,Ha as v,Ia as _}from"./chunk-KP7NBQK3.js";import{cb as h}from"./chunk-QPKQKSQU.js";import u from"node:fs/promises";import c from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},r=new e.Error().stack;r&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[r]="3425a1da-ef02-5235-a3b7-158d9efd12a2")}catch{}})();function f(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function b(e){return e!=="invalid"&&e!=="unreadable"}function j(e){let r=JSON.parse(e);if(typeof r!="object"||r===null||Array.isArray(r))throw new SyntaxError("Invalid settings object");let t=r.extensions;if(t===void 0)return{enabled:[],disabled:[]};if(typeof t!="object"||t===null||Array.isArray(t))throw new SyntaxError("Invalid extensions settings");let n=t;if(n.enabled!==void 0&&(!Array.isArray(n.enabled)||!n.enabled.every(a=>typeof a=="string"))||n.disabled!==void 0&&(!Array.isArray(n.disabled)||!n.disabled.every(a=>typeof a=="string")))throw new SyntaxError("Invalid extension enablement lists");return{enabled:n.enabled??[],disabled:n.disabled??[]}}async function S(e){let r;try{r=await u.readFile(e,"utf8")}catch(t){return f(t)?{status:"absent",enabled:[],disabled:[]}:{status:"unreadable",enabled:[],disabled:[],error:{code:"settings_unreadable",path:e}}}try{return{status:"ok",...j(r)}}catch{return{status:"invalid",enabled:[],disabled:[],error:{code:"settings_invalid",path:e}}}}async function A(e){let r;try{r=await u.readFile(e,"utf8")}catch(t){if(f(t))try{if((await u.stat(c.dirname(e))).isDirectory())return{status:"absent",entries:[]}}catch(n){if(f(n))return{status:"absent",entries:[]}}return{status:"unreadable",entries:[],error:{code:"managed_state_unreadable",path:e}}}try{let t=JSON.parse(r),n=_(t);if(!n||typeof t!="object"||t===null||!Array.isArray(t.entries)||n.entries.length!==t.entries.length)throw new SyntaxError("Invalid managed extension state");return{status:"ok",entries:n.entries}}catch{return{status:"invalid",entries:[],error:{code:"managed_state_invalid",path:e}}}}async function I(e){try{return{directories:(await u.readdir(e,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name).sort((t,n)=>t.localeCompare(n))}}catch(r){return f(r)?{directories:[]}:{directories:[],error:{code:"extensions_unreadable",path:e}}}}async function D(e){let r;try{r=await u.readFile(e,"utf8")}catch(t){return f(t)?{manifest:null,error:{code:"manifest_invalid",path:e}}:{manifest:null,error:{code:"manifest_unreadable",path:e}}}try{let t=v(JSON.parse(r));return t?{manifest:t}:{manifest:null,error:{code:"manifest_invalid",path:e}}}catch{return{manifest:null,error:{code:"manifest_invalid",path:e}}}}function M(e){let r=e.manifest?.name??e.directory,t=new Set(p(e.settings.enabled)),n=new Set(p(e.settings.disabled)),a=!b(e.settings.status)||!e.manifest?null:!n.has(r)&&(t.size===0||t.has(r)),o=b(e.managed.status)?e.managed.entries.some(d=>i(d.name)===i(r)||i(d.directory)===i(e.directory)):null;return{name:r,directory:e.directory,scope:e.scope,installed:!0,status:e.manifest?a===!1?"inactive":"installed":"malformed_manifest",configured_enabled:a,managed:o,runtime_active:null,...e.manifest?{version:e.manifest.version}:{}}}async function R(e){let r=e.scope??"project",t=r==="global"?h(e.cwd??process.cwd()):e.pmRoot,n=c.join(t,"extensions"),a=await S(c.join(t,"settings.json")),o=await A(c.join(n,".managed-extensions.json")),d=await I(n),l=[];for(let s of[a,o,d])s.error&&l.push(s.error);let m=e.name?.trim(),y=[];for(let s of d.directories){let x=c.join(n,s,"manifest.json"),g=await D(x);g.error&&l.push(g.error);let w=M({directory:s,scope:r,manifest:g.manifest,settings:a,managed:o});m&&![w.name,s].some(E=>i(E)===i(m))||y.push(w)}return m&&y.length===0&&l.every(s=>s.code!=="extensions_unreadable")&&y.push({name:m,directory:null,scope:r,installed:!1,status:"absent",configured_enabled:b(a.status)?!1:null,managed:b(o.status)?!1:null,runtime_active:null}),{scope:r,complete:l.length===0,settings_status:a.status,managed_state_status:o.status,extensions:y,errors:l}}export{R as a};
|
|
2
|
+
//# sourceMappingURL=chunk-6ST3SCQ6.js.map
|