@unbrained/pm-cli 2026.11.25 → 2026.11.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/dist/cli/commander-usage.js +9 -9
- package/dist/cli/error-guidance.js +5 -5
- package/dist/cli/help-content.js +4 -4
- package/dist/cli/register-setup.js +1 -1
- package/dist/cli/runtime/selection.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/{chunk-LPW7S5KA.js → chunk-5AAIRHNE.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-5BPDT7G2.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-7EPYCU7U.js → chunk-5FY2VHRF.js} +5 -5
- package/dist/cli-bundle/chunks/{chunk-YIGBEY7K.js → chunk-7F3UFYZA.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-B2GM6KOM.js +2 -0
- package/dist/cli-bundle/chunks/chunk-BITDGTAX.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-L6VS7F3R.js → chunk-CBBKXTJG.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-DUJSME77.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-OWK2JL4I.js → chunk-DYL2N3OC.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-GBVF2ZB3.js → chunk-FWBR3OW7.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-OS5W4ZG2.js → chunk-GQXK4KKH.js} +31 -31
- package/dist/cli-bundle/chunks/{chunk-FHLOGAGA.js → chunk-HOLQZ56F.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-HTGN24XM.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-K34FR5CO.js → chunk-IGW3RVJC.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-FVY7U3SU.js → chunk-KCRRTJ4X.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-DF6A7C32.js → chunk-KES4VHU4.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-CZEMEPPQ.js → chunk-LNZKNVMT.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-MNFCJNQA.js +35 -0
- package/dist/cli-bundle/chunks/{chunk-CONBVY2O.js → chunk-NDS4MXZX.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-BVJMVU4Z.js → chunk-PQSEEVOA.js} +6 -6
- package/dist/cli-bundle/chunks/chunk-QMM46SJM.js +4 -0
- package/dist/cli-bundle/chunks/chunk-RFK3ERYX.js +2 -0
- package/dist/cli-bundle/chunks/chunk-T3GJPXIZ.js +69 -0
- package/dist/cli-bundle/chunks/{chunk-CNUFU454.js → chunk-WZOJSHJT.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-C4KIZQHW.js → chunk-XRCE4QNL.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-SCIPT7WF.js → chunk-ZDL45VTB.js} +2 -2
- package/dist/cli-bundle/chunks/{field-option-collisions-QE65APSD.js → field-option-collisions-CGRJEAPQ.js} +2 -2
- package/dist/cli-bundle/chunks/{item-revision-INDHJV6X.js → item-revision-FGDR5NSF.js} +2 -2
- package/dist/cli-bundle/chunks/item-transaction-C3KAMEYO.js +2 -0
- package/dist/cli-bundle/chunks/{mutation-actor-KU7BMLUN.js → mutation-actor-HGG47KXV.js} +2 -2
- package/dist/cli-bundle/chunks/{mutation-admission-3OMCTQD4.js → mutation-admission-LLHIRY6O.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-3GV3LBOT.js → register-list-query-EKSCZWEZ.js} +2 -2
- package/dist/cli-bundle/chunks/{register-mutation-GZLF47SX.js → register-mutation-ZIAOKKUJ.js} +2 -2
- package/dist/cli-bundle/chunks/{register-operations-PBJZGCAL.js → register-operations-ECVBZ5FM.js} +2 -2
- package/dist/cli-bundle/chunks/register-setup-3QYD5H4H.js +2 -0
- package/dist/cli-bundle/chunks/{stage-3WIZBD4N.js → stage-RSCSUYEJ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-VU2PH4PF.js → chunk-3BR5NWQI.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-BOIMP2AR.js → chunk-3GQRWIT5.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-X4EWD6TL.js → chunk-AAB3ZR7Z.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-C3FEDTSD.js → chunk-AVLB4L7M.js} +26 -26
- package/dist/cli-bundle/focused-chunks/{chunk-5RBC4WSE.js → chunk-FQWKESMI.js} +58 -59
- package/dist/cli-bundle/focused-chunks/{chunk-BYQK5DGH.js → chunk-FW5Q26HA.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-GQBWI4KA.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-TQIKDFOD.js → chunk-IWEGGRRD.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-ZLRRII55.js → chunk-JUG3BAZZ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-KEZ4VXYD.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-XKLBTDJ7.js → chunk-NSFS3VWP.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-TRL4JDWX.js → chunk-NXUFVQ33.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-YYEWIKNI.js → chunk-QNWNUQSJ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-QSRXF6XS.js +15 -0
- package/dist/cli-bundle/focused-chunks/{chunk-WVA5KOXF.js → chunk-R6QFPHWW.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-PKX2EHE3.js → chunk-RDELKGLS.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-3Y5PTQ2F.js → chunk-RFJ3MEFP.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-SXC2EO3E.js → chunk-RMJKVQYE.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-UWWAVXG4.js → chunk-TNVLDU7Z.js} +3 -3
- package/dist/cli-bundle/focused-chunks/chunk-UA2JNKMY.js +4 -0
- package/dist/cli-bundle/focused-chunks/{chunk-7SSGTGZO.js → chunk-VV2QF5IE.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-MB56Y4M6.js → chunk-WHHFPATO.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-JOKRDFMQ.js → chunk-YNRW2FWB.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-4LQL4EO6.js → chunk-YSZZSV6M.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{field-option-collisions-5ROXGUME.js → field-option-collisions-WV6GPYYP.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{item-revision-KYMSQVZE.js → item-revision-RPTXN7WW.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{item-transaction-I4HLVHEJ.js → item-transaction-A6MVNPT7.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{mutation-actor-GGOQKAE6.js → mutation-actor-6ZVW6OME.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{mutation-admission-OS36ZCMH.js → mutation-admission-2DA4CINP.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{stage-4ZFWJUKO.js → stage-RG3PKST7.js} +2 -2
- package/dist/cli-bundle/main.js +26 -26
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +4 -4
- package/dist/cli-bundle/sdk-core.js +1 -1
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-graph.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +63 -63
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +11 -11
- package/dist/core/reproducibility/context.d.ts +2 -0
- package/dist/core/reproducibility/context.js +1 -1
- package/dist/sdk/cli-bootstrap.d.ts +17 -0
- package/dist/sdk/cli-bootstrap.js +1 -1
- package/dist/sdk/cli-contracts/command-aliases.js +1 -1
- package/dist/sdk/cli-contracts/flag-contracts.d.ts +2 -0
- package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
- package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
- package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
- package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
- package/dist/sdk/cli-contracts/tool-schema.d.ts +1 -1
- package/dist/sdk/cli-contracts/tool-schema.js +1 -1
- package/dist/sdk/cli-contracts.d.ts +1 -1
- package/dist/sdk/cli-contracts.js +1 -1
- package/dist/sdk/completion/shared.d.ts +1 -1
- package/dist/sdk/completion/shared.js +1 -1
- package/dist/sdk/extension/bundled-catalog.js +1 -1
- package/dist/sdk/extension/install-sources.js +5 -5
- package/dist/sdk/extension/listing-fields.d.ts +15 -0
- package/dist/sdk/extension/listing-fields.js +2 -0
- package/dist/sdk/extension/managed-update-status.js +1 -1
- package/dist/sdk/extension/npm-spec.d.ts +18 -0
- package/dist/sdk/extension/npm-spec.js +2 -0
- package/dist/sdk/extension/static-inventory.d.ts +53 -1
- package/dist/sdk/extension/static-inventory.js +1 -1
- package/dist/sdk/extension/update-check.js +1 -1
- package/dist/sdk/extension/update-observations.js +3 -0
- package/dist/sdk/extension/upgrade-hints.js +2 -0
- package/dist/sdk/extension.d.ts +2 -0
- package/dist/sdk/extension.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
- package/dist/sdk/governance/upgrade.d.ts +7 -2
- package/dist/sdk/governance/upgrade.js +2 -2
- package/dist/sdk/index.d.ts +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/context.d.ts +20 -7
- package/dist/sdk/query/context.js +4 -2
- package/dist/sdk/runtime-input.js +1 -1
- package/dist/sdk/testing.d.ts +20 -2
- package/docs/COMMANDS.md +19 -1
- package/docs/DIAGNOSTIC_OUTPUT_CONTRACTS.md +6 -0
- package/docs/EXTENSION_LIFECYCLE.md +72 -2
- package/docs/SDK.md +21 -2
- package/marketplace.json +1 -1
- package/package.json +1 -1
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-claude/package.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/pm-codex/package.json +1 -1
- package/plugins/pm-codex/plugin.json +1 -1
- package/runtime-dependencies.json +1 -1
- package/dist/cli-bundle/chunks/chunk-4FZH5BTV.js +0 -2
- package/dist/cli-bundle/chunks/chunk-GZI7ZAB7.js +0 -2
- package/dist/cli-bundle/chunks/chunk-LOX3VY4T.js +0 -2
- package/dist/cli-bundle/chunks/chunk-VA4T37Q4.js +0 -70
- package/dist/cli-bundle/chunks/chunk-WQOEVGLQ.js +0 -2
- package/dist/cli-bundle/chunks/chunk-XHCIOLJP.js +0 -3
- package/dist/cli-bundle/chunks/chunk-XKWJONAO.js +0 -2
- package/dist/cli-bundle/chunks/chunk-ZBOQEZ2H.js +0 -33
- package/dist/cli-bundle/chunks/chunk-ZLICQPRG.js +0 -3
- package/dist/cli-bundle/chunks/item-transaction-LCKK4XXB.js +0 -2
- package/dist/cli-bundle/chunks/register-setup-ZLJEF6NZ.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-A4R57E4K.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-IAOKVKWW.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-VMYVN36N.js +0 -13
- package/dist/cli-bundle/focused-chunks/chunk-WL2R7T5G.js +0 -2
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{H as Ie,I as Te,L as Le,X as Se,j as Ee}from"./chunk-7SSGTGZO.js";import{s as be,y as Re}from"./chunk-MB56Y4M6.js";import{a as N,b as R}from"./chunk-X6CXWWNB.js";import{Cf as ye,Df as ke,Gb as G,Hf as we,Q as ae,Qe as A,W as ue,cf as me,dg as xe,eg as ve,hf as ge,je as z,jg as Ce,ke as fe,q as E,qf as he,v as de,vf as _e,ze as Y}from"./chunk-XKLBTDJ7.js";import{B as F,c as le}from"./chunk-WVA5KOXF.js";import{O as pe}from"./chunk-OCKKIECS.js";import{A as w,z as x}from"./chunk-NGFDPEP7.js";function v(){let e=E();for(let n of z()?.relationship_kinds??[])for(let o of n.definitions)e.register(o);return e}function M(e){if(typeof e!="string")return;let n=e.trim().toLowerCase();return n.length>0?n:void 0}function K(e){return[e.parent_id,e.child_id,e.source,e.kind,e.holder_id,e.target_id??""].join("\0")}function Qe(e,n){let o=new Set,t=[];for(let r of[...e].sort()){if(o.has(r))continue;o.add(r);let i=[{nodeId:r,children:[...n.get(r)??[]].sort(),nextChild:0}];for(;i.length>0;){let s=i.at(-1),c=s.children[s.nextChild];c===void 0?(t.push(s.nodeId),i.pop()):(s.nextChild+=1,o.has(c)||(o.add(c),i.push({nodeId:c,children:[...n.get(c)??[]].sort(),nextChild:0})))}}return t}function Ze(e,n){let o=[...e].sort(),t=Qe(o,n),r=new Set,i=et(o,n),s=[];for(let c of t.reverse()){if(r.has(c))continue;let d=tt(c,i,r);(d.length>1||n.get(d[0])?.has(d[0]))&&s.push(d)}return s.sort((c,d)=>c.join("\0").localeCompare(d.join("\0")))}function et(e,n){let o=new Map(e.map(t=>[t,new Set]));for(let[t,r]of n)for(let i of r)o.get(i)?.add(t);return o}function tt(e,n,o){let t=[],r=[e];for(o.add(e);r.length>0;){let i=r.pop();t.push(i);for(let s of[...n.get(i)].sort())o.has(s)||(o.add(s),r.push(s))}return t.sort()}function Oe(e){let n=new Map;for(let o of e){let t=M(o?.id);t&&!n.has(t)&&n.set(t,o)}return n}function nt(e,n,o){let t=M(n.parent);if(!(!t||!o.has(t)))return{parent_id:t,child_id:e,source:"scalar_parent",kind:"parent",holder_id:e,child_cardinality:"one"}}function ot(e,n,o,t){let r=M(n?.id),i=t.resolve(n?.kind);if(!r||!o.has(r)||!i?.hierarchy)return;let s=i.hierarchyDirection==="source_parent";return{parent_id:s?e:r,child_id:s?r:e,source:"dependency",kind:i.kind,holder_id:e,target_id:r,child_cardinality:s?i.incoming:i.outgoing}}function De(e,n){let o=new Map;for(let[t,r]of e){let i=nt(t,r,e);i&&o.set(K(i),i);for(let s of r.dependencies??[]){let c=ot(t,s,e,n);c&&o.set(K(c),c)}}return[...o.values()].sort((t,r)=>K(t).localeCompare(K(r)))}function un(e,n=v()){return De(Oe(e),n)}function rt(e,n,o){let t=new Set(e.filter(r=>r.child_cardinality==="one").map(r=>r.child_id));return[...n].filter(([r,i])=>i.length>1&&t.has(r)).map(([r,i])=>({child_id:r,parent_ids:[...i],legacy_terminal:o.has(r)&&i.every(s=>o.has(s))})).sort((r,i)=>r.child_id.localeCompare(i.child_id))}function it(e,n,o){let t=new Map;for(let i of n){if(i.source!=="dependency")continue;let s=t.get(i.child_id)??new Set;s.add(i.parent_id),t.set(i.child_id,s)}let r=[];for(let[i,s]of e){let c=M(s.parent);if(!c||!e.has(c))continue;let d=[...t.get(i)??[]].filter(u=>u!==c).sort();d.length!==0&&r.push({child_id:i,scalar_parent_id:c,dependency_parent_ids:d,legacy_terminal:o.has(i)&&o.has(c)&&d.every(u=>o.has(u))})}return r.sort((i,s)=>i.child_id.localeCompare(s.child_id))}function H(e,n=t=>t==="closed"||t==="canceled",o=v()){let t=Oe(e),r=De(t,o),i=st(r),s=new Set([...t].filter(([,d])=>n(d.status)).map(([d])=>d)),c=Ze([...t.keys()],new Map([...i.children_by_parent].map(([d,u])=>[d,new Set(u)]))).map(d=>({item_ids:d,legacy_terminal:d.every(u=>s.has(u))}));return{relations:r,cycles:c,cardinality_violations:rt(r,i.parents_by_child,s),divergences:it(t,r,s)}}function ln(e){return e.source==="scalar_parent"?`${e.parent_id} -> ${e.child_id} (scalar parent on ${e.holder_id})`:`${e.parent_id} -> ${e.child_id} (${e.kind} dependency on ${e.holder_id})`}function st(e){let n=new Map,o=new Map;for(let t of e){let r=n.get(t.child_id)??new Set;r.add(t.parent_id),n.set(t.child_id,r);let i=o.get(t.parent_id)??new Set;i.add(t.child_id),o.set(t.parent_id,i)}return{parents_by_child:new Map([...n].map(([t,r])=>[t,[...r].sort()])),children_by_parent:new Map([...o].map(([t,r])=>[t,[...r].sort()]))}}function J(e,n){let o=new Set(n);return e.every(t=>o.has(t))}function pn(e,n,o,t,r){let i=M(o);if(!i)return;let s=H(e,t,r),c=H(n,t,r),d=c.divergences.find(a=>!s.divergences.some(p=>p.child_id===a.child_id&&p.scalar_parent_id===a.scalar_parent_id&&J(a.dependency_parent_ids,p.dependency_parent_ids)));if(d){let a=[d.scalar_parent_id,...d.dependency_parent_ids].sort();throw new w(`Hierarchy mutation would assign ${d.child_id} to multiple parents: ${a.join(", ")}.`,x.CONFLICT,{code:"hierarchy_parent_divergence_created",source_id:i,target_id:d.child_id,verification_errors:a})}let u=c.cardinality_violations.find(a=>(a.child_id===i||a.parent_ids.includes(i))&&!s.cardinality_violations.some(p=>p.child_id===a.child_id&&J(a.parent_ids,p.parent_ids)));if(u)throw new w(`Hierarchy mutation would assign ${u.child_id} to multiple parents: ${u.parent_ids.join(", ")}.`,x.CONFLICT,{code:"hierarchy_cardinality_created",source_id:i,target_id:u.child_id,verification_errors:u.parent_ids});let l=c.cycles.find(a=>a.item_ids.includes(i)&&!s.cycles.some(p=>J(a.item_ids,p.item_ids)));if(l)throw new w(`Hierarchy mutation would create a cycle: ${l.item_ids.join(" -> ")}.`,x.CONFLICT,{code:"hierarchy_cycle_created",source_id:i,verification_errors:l.item_ids})}var ct="global";function hn(e){let n=e?.trim();if(n)return R(n)?ct:n}function _n(e,n,o){return dt(e,n,o)}function dt(e,n,o){let t=e.trim();return R(o)||N(t)?t:Ee(t,n)}function L(e){if(typeof e!="string")return;let n=e.trim();if(!(!n||["none","null","n/a","na"].includes(n.toLowerCase())))return n}function $(e){let n=L(e);return n?.toLowerCase()==="no-active-blocker"?void 0:n}function B(e,n,o=!0){let t=L(e);return o&&(R(n)||t!==void 0&&N(t))}function Q(e,n){return B(e,n)?`external\0${e}`:`local\0${e.toLowerCase()}`}function Ae(e,n,o,t){return B(e,n)?t.get(e):o.get(e.toLowerCase())}function T(e,n){let o=e.toLowerCase(),t=n.toLowerCase();return o!==t?o<t?-1:1:e!==n?e<n?-1:1:0}function at(e){let n=new Map;for(let o of e.dependencies??[]){if(typeof o!="object"||o===null)continue;let t=o,r=L(t.id);if(!r)continue;let i=typeof t.kind=="string"?t.kind:"related",s=`${i}\0${Q(r,t.source_kind)}`,c=n.get(s);c?c.count+=1:n.set(s,{target_id:r,kind:i,count:1})}return n}function ut(e,n=o=>o==="closed"||o==="canceled"){let o=[];for(let t of e)if(!(typeof t?.id!="string"||t.id.trim().length===0))for(let r of at(t).values())r.count<2||o.push({holder_id:t.id.trim(),target_id:r.target_id,kind:r.kind,occurrences:r.count,holder_status:t.status,legacy_terminal:n(t.status)});return o.sort((t,r)=>{let i=T(t.holder_id,r.holder_id);if(i!==0)return i;let s=T(t.target_id,r.target_id);return s!==0?s:T(t.kind,r.kind)})}function lt(e,n,o,t,r){if(typeof o!="object"||o===null)return;let i=L(o.id);if(!i||Q(i,o.source_kind)!==Q(n))return;let s=r.resolve(typeof o.kind=="string"?o.kind:"related");if(!(s?.ordering!==!0||(s.precedence??"source_before_target")!=="source_before_target"))return{holder_id:e.id.trim(),target_id:i,dependency_kind:s.kind,holder_status:e.status,legacy_terminal:t(e.status)}}function pt(e,n=t=>t==="closed"||t==="canceled",o=v()){let t=new Map;for(let r of e){if(typeof r?.id!="string"||r.id.trim().length===0)continue;let i=L(r.blocked_by);if(i)for(let s of r.dependencies??[]){let c=lt(r,i,s,n,o);c&&t.set(`${c.holder_id.toLowerCase()}\0${c.target_id.toLowerCase()}\0${c.dependency_kind}`,c)}}return[...t.values()].sort((r,i)=>{let s=T(r.holder_id,i.holder_id);if(s!==0)return s;let c=T(r.target_id,i.target_id);return c!==0?c:T(r.dependency_kind,i.dependency_kind)})}function Z(e,n=o=>o==="closed"||o==="canceled"){let o=e.filter(d=>typeof d?.id=="string"&&d.id.trim().length>0),t=new Set(o.map(d=>d.id.trim().toLowerCase())),r=new Map,i=(d,u,l,a,p)=>{let m=L(u);if(!m||t.has(m.toLowerCase())||B(m,void 0,p))return;let f={holder_id:d.id.trim(),target_id:m,kind:l,source:a,holder_status:d.status,legacy_terminal:n(d.status),no_active_blocker_sentinel:m.toLowerCase()==="no-active-blocker"};r.set(`${f.holder_id}::${f.target_id}::${f.kind}::${f.source}`,f)};for(let d of o){i(d,d.parent,"parent","parent",!1),i(d,d.blocked_by,"blocked_by","blocked_by",!0);for(let u of d.dependencies??[]){if(typeof u!="object"||u===null)continue;let l=u;R(l.source_kind)||i(d,l.id,typeof l.kind=="string"?l.kind:"related","dependency",!0)}}let s=[...r.values()].sort((d,u)=>d.holder_id.localeCompare(u.holder_id)||d.target_id.localeCompare(u.target_id)||d.kind.localeCompare(u.kind)||d.source.localeCompare(u.source)),c=s.filter(d=>d.legacy_terminal);return{active:s.filter(d=>!d.legacy_terminal),legacy_terminal:c,no_active_blocker_sentinels:s.filter(d=>d.no_active_blocker_sentinel)}}function ft(e){let n=new Map;for(let o of[...e.active,...e.legacy_terminal]){if(o.no_active_blocker_sentinel)continue;let t=o.target_id.trim(),r=t.toLowerCase();n.has(r)||n.set(r,t)}return[...n.values()].sort((o,t)=>o.localeCompare(t))}function mt(e){let n=new Map;for(let o of e){let t=$(o.blocked_by);t&&B(t)&&!n.has(t)&&n.set(t,t);for(let r of o.dependencies??[]){if(typeof r!="object"||r===null||!B(r.id,r.source_kind))continue;let i=$(r.id);i&&!n.has(i)&&n.set(i,i)}}return[...n.values()].sort((o,t)=>o.localeCompare(t))}var Ne=new WeakMap;function En(e){return e.hierarchyIntegrity??Ne.get(e)}function gt(e,n=v()){let o={};for(let t of e)for(let r of t.dependencies??[]){if(typeof r!="object"||r===null)continue;let i=r.kind;if(typeof i!="string")continue;let s=i.trim().toLowerCase().replaceAll("-","_"),c=n.resolve(i);c&&s!==c.kind&&(o[s]=(o[s]??0)+1)}return Object.fromEntries(Object.entries(o).sort(([t],[r])=>t.localeCompare(r)))}function ee(e,n,o){let t=o??v(),r=e.filter(f=>typeof f?.id=="string"&&f.id.trim().length>0),i=new Map(r.map(f=>[f.id.trim().toLowerCase(),f.id.trim()])),s=Z(r,n),c=ft(s);for(let f of c)i.set(f.toLowerCase(),f);let d=mt(r),u=new Set(i.keys()),l=new Map;for(let f of d){let _=f;for(;u.has(_.toLowerCase());)_=`external:${_}`;l.set(f,_),u.add(_.toLowerCase())}let a=r.map(f=>{let _=$(f.parent),g=$(f.blocked_by),h=(f.dependencies??[]).flatMap(k=>{if(typeof k!="object"||k===null)return[];let y=k,C=$(y.id);return C?[{id:Ae(C,y.source_kind,i,l),kind:typeof y.kind=="string"?y.kind:"related"}]:[]});return{id:f.id.trim(),..._?{parent:i.get(_.toLowerCase())}:{},...g?{blocked_by:Ae(g,void 0,i,l)}:{},dependencies:h}}),p=H(r,n,t),m={graph:de.fromItems([...a,...c.map(f=>({id:f})),...d.map(f=>({id:l.get(f)}))],t),details:[...r.map(f=>({id:f.id.trim(),title:f.title,status:f.status,...typeof f.type=="string"&&f.type.trim().length>0?{type:f.type.trim()}:{}})),...c.map(f=>({id:f,title:`[missing] ${f}`,status:"missing"})),...d.map(f=>({id:l.get(f),title:`[external] ${f}`,status:"external"}))],missingIdSet:new Set(c.map(f=>f.toLowerCase())),dangling:s,duplicateRows:ut(r,n),orderingContradictions:pt(r,n,t),legacyAliasCounts:gt(r,t),hierarchyIntegrity:p};return Ne.set(m,p),m}import{createHash as ht}from"node:crypto";var _t=64,yt=8;function kt(e,n){let o=(e.dependencies??[]).map(t=>{if(typeof t!="object"||t===null)return"";let r=t;return`${typeof r.kind=="string"?r.kind:"related"}:${typeof r.id=="string"?r.id:""}`}).sort().join(",");return[e.id,e.title,e.status,n(e.status)?"1":"0",typeof e.type=="string"?e.type.trim():"",e.parent??"",e.blocked_by??"",o].join("\0")}function $e(e,n=t=>t==="closed"||t==="canceled",o=E()){let t=e.filter(i=>typeof i?.id=="string"&&i.id.trim().length>0).map(i=>kt(i,n)).sort(),r=o.list().map(i=>le(i)).sort();return ht("sha256").update(t.join("")).update("").update(r.join("")).digest("hex")}function Me(e,n,o){let t=n??o;if(!Number.isInteger(t)||t<1)throw new TypeError(`Invalid ${e} bound: ${String(n)}`);return t}var te=class{#e=new Map;#t;#n;constructor(n={}){this.#t=Me("maxResultsPerWorkspace",n.maxResultsPerWorkspace,_t),this.#n=Me("maxWorkspaces",n.maxWorkspaces,yt)}lookup(n,o,t){let r=this.#e.get(n),i=!0;(r===void 0||r.fingerprint!==o)&&(r={fingerprint:o,assembly:t(),results:new Map},i=!1,!this.#e.has(n)&&this.#e.size>=this.#n&&this.#e.delete(this.#e.keys().next().value)),this.#e.delete(n),this.#e.set(n,r);let s=r,c=this.#t;return{assembly:s.assembly,assemblyReused:i,fingerprint:o,memoize(d,u){let l=s.results.get(d);if(l!==void 0||s.results.has(d))return s.results.delete(d),s.results.set(d,l),{value:structuredClone(l),reused:!0};let a=u();return s.results.size>=c&&s.results.delete(s.results.keys().next().value),s.results.set(d,structuredClone(a)),{value:a,reused:!1}}}}clear(){this.#e.clear()}},Be=new te;function Pe(){return Be}function Sn(){Be.clear()}var U=1200,wt=["prerequisite","dependent","ancestor","descendant","provenance","related"],xt=new TextEncoder;function ne(e,n,o){let t=e??n;if(!Number.isInteger(t)||t<1)throw new TypeError(`Relationship context ${o} must be positive`);return t}function P(e){return Math.max(1,Math.ceil(xt.encode(JSON.stringify(e)).byteLength/4))}function W(e,n,o){let t=o.resolve(e.kind);if(t?.ordering){let i=(t.precedence??"source_before_target")==="source_before_target"?e.source:e.target;return n===i?"prerequisite":"dependent"}if(t?.hierarchy){let i=t.hierarchyDirection==="source_parent"?e.source:e.target;return n===i?"ancestor":"descendant"}return e.kind==="discovered_from"||e.kind==="incident_from"?"provenance":"related"}function vt(e,n,o,t){let r=e.filter(i=>i.source===n&&i.target===o||i.target===n&&i.source===o).map(i=>W(i,o,t));return[...new Set(r)].sort()}function Ct(e){return wt.find(n=>e.includes(n))}function Et(e,n,o,t){let r=t.direction??"both",i=t.maxDepth??3;if(!Number.isInteger(i)||i<0)throw new TypeError("Relationship context maxDepth must be non-negative");let s=new Set([n]),c=[{id:n,distance:0}],d=[],u=0,l=!1;for(let a=0;a<c.length;a+=1){t.signal?.throwIfAborted();let p=c[a];if(p.distance>=i&&l)continue;let m=e.neighborEdges(p.id,{direction:r,kinds:t.kinds,signal:t.signal});if(u+=m.meta.inspectedEdges,p.distance>=i){m.value.some(f=>!s.has(f.id))&&(l=!0);continue}for(let{id:f,edge:_}of m.value){if(s.has(f))continue;s.add(f);let g={id:f,distance:p.distance+1,via:p.id,role:W(_,f,o)};d.push(g),c.push(g)}}return{rows:d,visitedNodes:c.length,inspectedEdges:u,depthTruncated:l}}function bt(e,n,o,t){let r={prerequisite:0,dependent:0,ancestor:0,descendant:0,provenance:0,related:0},i=e.neighborEdges(n,{direction:t.direction??"both",kinds:t.kinds,signal:t.signal}).value;for(let{id:s,edge:c}of i)r[W(c,s,o)]+=1;return{directEdges:r,directTotal:i.length,rootEdges:i.map(({edge:s})=>s)}}function Rt(e,n,o,t){let r=new Set;for(let i of n){let s=i.source===o?i.target:i.source,c=W(i,s,t);(c==="prerequisite"||c==="ancestor")&&r.add(s)}return[...e].sort((i,s)=>Number(r.has(s.id))-Number(r.has(i.id))||i.distance-s.distance||i.id.localeCompare(s.id))}function It(e,n){let o=e.distance===1?vt(n.rootEdges,n.rootId,e.id,n.registry):[];return{...n.details.get(e.id)??{id:e.id},distance:e.distance,role:o.length>0?Ct(o):e.role,via:e.via,reasons:o.length>0?o:[`${e.role} via ${e.via} (depth ${e.distance})`]}}function Tt(e){let n=[],o=e.initialTokens,t=0;for(let r of e.candidates){if(n.length>=e.nodeLimit)break;let i=It(r,e),s=P(i);if(o+s>e.tokenBudget)break;let c=e.rootEdges.filter(d=>d.source===r.id||d.target===r.id).reduce((d,u)=>d+P(u),0);if(o+t+s+c>e.tokenBudget){if(n.length>0)break}else t+=c;n.push(i),o+=s}if(e.candidates.length>0&&n.length===0)throw new TypeError("Relationship context tokenBudget cannot fit one node");return{nodes:n,usedTokens:o}}function Lt(e){let n=e.options.kinds?new Set(e.options.kinds.map(i=>e.registry.require(i).kind)):void 0,o=e.graph.edges().filter(i=>{if(!e.included.has(i.source)||!e.included.has(i.target))return!1;if(n===void 0||n.has(i.kind))return!0;let s=e.registry.resolve(i.kind)?.inverse;return s!==void 0&&n.has(s)}).sort((i,s)=>+(s.source===e.rootId||s.target===e.rootId)-+(i.source===e.rootId||i.target===e.rootId)),t=[],r=e.initialTokens;for(let i of o){if(t.length>=e.edgeLimit)break;let s=P(i);r+s>e.tokenBudget||(t.push(i),r+=s)}return{edges:t,usedTokens:r,candidateCount:o.length}}function Ue(e,n,o,t={}){if(!e.nodes().includes(n))throw new TypeError(`Relationship node not found: ${n}`);let r=ne(t.nodeLimit,20,"nodeLimit"),i=ne(t.edgeLimit,40,"edgeLimit"),s=ne(t.tokenBudget,U,"tokenBudget"),c=t.registry??E(),d=new Map(o.map(I=>[I.id,I])),u=d.get(n)??{id:n},{evidence:l=[],...a}=u,p=[...l],m=Et(e,n,c,t),{rootEdges:f,..._}=bt(e,n,c,t),g=Rt(m.rows,f,n,c),h=ye("relationship-context",{rootId:n,direction:t.direction??"both",kinds:[...t.kinds??[]].sort(),maxDepth:t.maxDepth??3,ordering:"required-root-evidence-first-v1"}),k=we(g,t.cursor,h,({id:I})=>I,"--cursor"),y=g.slice(k),C=P(a)+P(p);if(C>s)throw new TypeError("Relationship context tokenBudget cannot fit root and evidence");let O=Tt({candidates:y,details:d,rootEdges:f,rootId:n,registry:c,nodeLimit:r,tokenBudget:s,initialTokens:C}),{nodes:D}=O,Ve=new Set([n,...D.map(({id:I})=>I)]),ie=Lt({graph:e,rootId:n,included:Ve,options:t,registry:c,edgeLimit:i,tokenBudget:s,initialTokens:O.usedTokens}),{edges:X,usedTokens:Ye}=ie,j=k+D.length,q=j<g.length,se=D.at(-1),V=ie.candidateCount-X.length,ce=m.depthTruncated||q||V>0,Je={rootId:n,...a.status===void 0?{}:{rootStatus:a.status},..._,discoveredNodes:g.length,returnedNodes:D.length,returnedEdges:X.length,omittedNodes:g.length-j,omittedEdges:V,evidenceCount:p.length,hasMore:q};return{root:a,summary:Je,nodes:D,edges:X,evidence:p,meta:{exact:!0,truncated:ce,completeness:ce?"truncated":"complete",nodeLimit:r,edgeLimit:i,tokenBudget:s,usedTokens:Ye,visitedNodes:m.visitedNodes,inspectedEdges:m.inspectedEdges,omittedNodes:g.length-j,omittedEdges:V,...q&&se?{nextCursor:ke(h,se.id,j-1)}:{}}}}var St=["tree","graph","context"],Ot=["none","repeated"],Dt=["outgoing","incoming","both"],At=32,Nt=200,Mt=400,$t=16e3;function Bt(e){let n=e?.trim().toLowerCase()??"tree";if(St.includes(n))return n;throw new w(`Invalid --format value "${e}". Use "tree", "graph", or "context".`,x.USAGE)}function S(e,n){if(e===void 0)return;let o=typeof e=="number"?e:Number(e.trim());if(!Number.isInteger(o)||o<1)throw new w(`Invalid --${n} value "${e}". Use a positive integer.`,x.USAGE);return o}function Fe(e){if(e===void 0)return;let n=typeof e=="number"?e:Number(e.trim());if(!Number.isInteger(n)||n<0)throw new w(`Invalid --max-depth value "${e}". Use a non-negative integer.`,x.USAGE);return n}function Pt(e){let n=e?.trim().toLowerCase()??"none";if(Ot.includes(n))return n;throw new w(`Invalid --collapse value "${e}". Use "none" or "repeated".`,x.USAGE)}function Ut(e){let n=e?.trim().toLowerCase()??"both";if(Dt.includes(n))return n;throw new w(`Invalid --direction value "${e}". Use "outgoing", "incoming", or "both".`,x.USAGE)}function jt(e,n=E()){if(e===void 0)return;let o=(Array.isArray(e)?e:[e]).flatMap(r=>r.split(",")).map(r=>r.trim()).filter(r=>r.length>0);if(o.length===0)return;let t=new Set;for(let r of o){let i=n.resolve(r);if(!i){let s=n.list().map(c=>c.kind).join(", ");throw new w(`Invalid --kind value "${r}". Registered kinds: ${s}.`,x.USAGE)}t.add(i.kind)}return[...t].sort()}function Ft(e){if(!e||e.length===0)return[];let n=e.map(({id:t,kind:r})=>({id:t.trim(),kind:r.trim().toLowerCase()})).sort((t,r)=>{let i=t.kind.localeCompare(r.kind);return i!==0?i:t.id.localeCompare(r.id)}),o=new Map;for(let t of n){let r=`${t.kind.toLowerCase()}::${t.id.toLowerCase()}`;o.has(r)||o.set(r,{id:t.id,kind:t.kind})}return[...o.values()]}function Gt(e){return{id:e.id,title:e.title,type:e.type,status:e.status,dependencies:Ft(e.dependencies)}}function zt(e){return A(new TextEncoder().encode(JSON.stringify({...e,dependencies:void 0})).byteLength)}function Kt(e,n,o,t,r,i,s,c,d){for(let u of n.dependencies){let l=Math.max(1,Math.ceil(JSON.stringify({from:e.id,to:u.id,kind:u.kind}).length/3));if(c.nodes>=c.nodeLimit){e.truncated=!0,c.reasons.add("node_limit");break}if(c.edges>=c.edgeLimit){e.truncated=!0,c.reasons.add("edge_limit");break}if(c.estimatedTokens+l>=c.tokenBudget){e.truncated=!0,c.reasons.add("token_budget");break}c.edges+=1,c.estimatedTokens+=l,e.dependencies.push(Ge(u.id,o,t,r,i,s,c,d+1,u.kind))}}function Ht(e,n,o,t,r,i,s,c){return s.estimatedTokens>=s.tokenBudget&&n?.dependencies.length?(e.truncated=!0,s.reasons.add("token_budget"),!0):!n||e.cycle?!0:t!==void 0&&c>=t?(n.dependencies.length>0&&(e.truncated=!0,s.reasons.add("max_depth")),!0):r==="repeated"&&i.has(o)?(e.collapsed=!0,!0):!1}function Ge(e,n,o,t,r,i,s,c=0,d){let u=e.trim().toLowerCase(),l=n.get(u),a={id:l?.id??e,title:l?.title,type:l?.type,status:l?.status,via:d,missing:!l,cycle:o.has(u),dependencies:[]};if(s.nodes+=1,s.estimatedTokens+=zt(a),Ht(a,l,u,t,r,i,s,c))return a;r==="repeated"&&i.add(u);let p=new Set(o);return p.add(u),Kt(a,l,n,p,t,r,i,s,c),a}function je(e,n){return!e||e.missing&&!n.missing?n:{...e,title:e.title??n.title,type:e.type??n.type,status:e.status??n.status}}function Wt(e){let n=new Map,o=new Map,t=[e];for(;t.length>0;){let c=t.pop();n.set(c.id,je(n.get(c.id),{id:c.id,title:c.title,type:c.type,status:c.status,missing:c.missing}));for(let d of c.dependencies){n.set(d.id,je(n.get(d.id),{id:d.id,title:d.title,type:d.type,status:d.status,missing:d.missing}));let u=d.via??"related",l=`${c.id}::${d.id}::${u}`;o.has(l)||o.set(l,{from:c.id,to:d.id,kind:u}),d.cycle||t.push(d)}}let r=[...n.values()].sort((c,d)=>c.id.localeCompare(d.id)),i=[...o.values()].sort((c,d)=>{let u=c.from.localeCompare(d.from);if(u!==0)return u;let l=c.to.localeCompare(d.to);return l!==0?l:c.kind.localeCompare(d.kind)}),s=r.filter(c=>c.missing).map(c=>c.id);return{root_id:e.id,nodes:r,edges:i,missing_ids:s}}function ze(e,n,o){let t=new Set,r=new Set,i=new Set,s=new Set,c=[{id:e,depth:0}],d=0;for(;d<c.length;){let u=c[d++],l=u.id.trim().toLowerCase();t.add(l);let a=n.get(l);if(!a){i.add(l);continue}if(!(o!==void 0&&u.depth>=o)&&!s.has(l)){s.add(l);for(let p of a.dependencies)r.add(`${l}::${p.id.trim().toLowerCase()}::${p.kind}`),c.push({id:p.id,depth:u.depth+1})}}return{node_count:t.size,edge_count:r.size,edge_basis:"deduplicated_directed",missing_count:i.size}}function Xt(e,n=E()){let o=Fe(e.maxDepth),t=S(e.nodeLimit,"node-limit"),r=S(e.edgeLimit,"edge-limit"),i=S(e.tokenBudget,"token-budget"),s=jt(e.kind,n);return{direction:Ut(e.direction),...s===void 0?{}:{kinds:s},...o===void 0?{}:{maxDepth:o},...t===void 0?{}:{nodeLimit:t},...r===void 0?{}:{edgeLimit:r},...i===void 0?{}:{tokenBudget:i},...e.cursor?.trim()?{cursor:e.cursor.trim()}:{}}}function qt(e,n,o,t){return Ue(e.graph,n,e.details.map(r=>r.id===n&&t.length>0?{...r,evidence:t}:r),o)}function oe(e,n,o,t){for(let r of o.slice(0,t)){let i=r?.trim();i&&e.push(`${n}:${i}`)}}async function Vt(e,n,o,t){let r=await Ie(e,n,o.id_prefix,o.item_format,t);if(!r)return[];let{document:i}=await Te(r,{schema:o.schema}),s=i.metadata,c=s.files??[],d=s.tests??[],u=s.docs??[],l=[["files",c.length],["tests",d.length],["docs",u.length],["comments",(s.comments??[]).length],["notes",(s.notes??[]).length],["learnings",(s.learnings??[]).length]];if(l.every(([,p])=>p===0))return[];let a=[`linked:${l.map(([p,m])=>`${p}=${m}`).join(",")}`];return oe(a,"file",c.map(p=>p.path),3),oe(a,"test",d.map(p=>p.command??p.path),2),oe(a,"doc",u.map(p=>p.path),2),a}function Yt(e){let{canonicalId:n,context:o,missingCount:t,missingReferences:r,referenceLimit:i,summaryOnly:s}=e;return{id:n,format:"context",node_count:o.nodes.length+1,edge_count:o.edges.length,edge_basis:"deduplicated_directed",missing_count:t,missing_scope:"traversal",missing_reference_count:r.length,...s?{}:{missing_references:r.slice(0,i),context:o}}}function Jt(e){let{row:n,missingReachableSet:o,packetIds:t,filteredKinds:r,registry:i}=e;if(n.no_active_blocker_sentinel||!o.has(n.target_id.trim().toLowerCase())||!t.has(n.holder_id))return!1;if(r===void 0)return!0;let s=i.resolve(n.kind);return s!==void 0&&(r.has(s.kind)||s.inverse!==void 0&&r.has(s.inverse))}function Ke(e,n){let o=fe(),t=n.commandOptionsOverride??(o?.command==="deps"?o.options:n.commandOptions);return xe("deps",{...t,...n.global,resolvedOutputFormat:n.format},e)}function re(e,n){let o=Ke(e,n),t=r=>Ce(r,n.format,n.global.lean===!0);return t(n.global.tokenAccounting===!0?ve(o,t):o)}function He(e,n,o){let t;for(;;){let r=A(new TextEncoder().encode(re(e,n)).byteLength);if(r===t)return r;o(r),t=r}}function We(e){return e instanceof TypeError&&e.message.startsWith("Relationship context tokenBudget cannot fit ")}function Xe(e){let{assembly:n,canonicalId:o,contextOptions:t,rootEvidence:r,summaryOnly:i,rendering:s,missingCount:c,missingReferences:d}=e,u=t.edgeLimit??40,l=Math.min(u,d.length),a=t.tokenBudget,p;for(;;){let m=qt(n,o,{...t,...a===void 0?{}:{tokenBudget:a}},r);p??=m.meta.tokenBudget,a??=p;let f=Yt({canonicalId:o,context:m,missingCount:c,missingReferences:d,referenceLimit:l,summaryOnly:i});if(i){if(A(new TextEncoder().encode(re(b(f,!0,s.legacyAliasCounts),s)).byteLength)>p)throw new TypeError("Relationship context tokenBudget cannot fit the rendered summary");return f}if(m.meta.tokenBudget=p,m.meta.usedTokens=He(b(f,!1,s.legacyAliasCounts),s,h=>{m.meta.usedTokens=h}),m.meta.usedTokens<=p)return f;if(l>0){l-=1;continue}let _=a,g=_*p/m.meta.usedTokens;a=Math.min(_-1,Math.max(1,Math.floor(g*.9)))}}function qe(e,n){let o=e.contextOptions,t={...e.rendering.global,outputFormat:e.rendering.format},r=["--pm-path",e.pmRoot,"item","deps",e.canonicalId,"--format","context","--output-format",e.rendering.format,"--token-budget"],i=r.length;r.push(String(n));let s=new Set(["--pm-path","--format","--output-format","--token-budget"]),c={format:"context",tokenBudget:n,kind:o.kinds},d=[["--max-depth","maxDepth",o.maxDepth],["--node-limit","nodeLimit",o.nodeLimit],["--edge-limit","edgeLimit",o.edgeLimit],["--direction","direction",o.direction],["--cursor","cursor",o.cursor],["--output-include","outputInclude",t.outputInclude],["--output-limit","outputLimit",t.outputLimit],["--output-budget","outputBudget",t.outputBudget],["--output-session","outputSession",t.outputSession],["--output-cursor","outputCursor",t.outputCursor]];for(let[a,p,m]of d)m!==void 0&&(r.push(a,String(m)),s.add(a),c[p]=m);for(let a of o.kinds??[])r.push("--kind",a),s.add("--kind");let u=[["--summary","summary",e.summaryOnly],["--full","full",e.rendering.commandOptions.full],["--json","json",t.json],["--lean","lean",t.lean],["--output-row-contract","outputRowContract",t.outputRowContract],["--token-accounting","tokenAccounting",t.tokenAccounting],["--no-extensions","noExtensions",t.noExtensions],["--no-pager","noPager",t.noPager]];for(let[a,p,m]of u)m===!0&&(r.push(a),s.add(a),c[p]=!0);let l=ge.find(a=>a.command==="deps");return Reflect.set(c,me,{canonical_include_modes:[],cli_invocation_observed:!0,explicit_legacy_aliases:Object.values(l.dimensions).flatMap(a=>a.legacy_aliases.flatMap(p=>s.has(p.flag)?[p.flag]:[]))}),he("deps",c),Y(c.summary===!0,c.full===!0,"--summary"),t.outputInclude=c.outputInclude,{args:r,budgetIndex:i,summaryOnly:c.summary===!0,rendering:{...e.rendering,global:t,commandOptionsOverride:c}}}function Qt(e,n,o){let t={...n.rendering,commandOptionsOverride:{...n.rendering.commandOptionsOverride,tokenBudget:o}},r;try{r=Xe({...e,contextOptions:{...e.contextOptions,tokenBudget:o},summaryOnly:n.summaryOnly,rootEvidence:n.summaryOnly?[]:e.rootEvidence,rendering:t})}catch(s){if(!We(s))throw s;return"native_floor"}let i=Ke(b(r,n.summaryOnly,t.legacyAliasCounts),t);return _e(i)?"output_constraints":"fits"}async function Zt(e,n){let o=e.contextOptions.tokenBudget??U,t=qe(e,o),i=(t.summaryOnly?1:1+Math.min(e.contextOptions.edgeLimit??40,e.missingReferences.length))*(e.assembly.details.reduce((p,m)=>p+m.id.length+m.title.length+m.status.length+(m.type?.length??0),e.assembly.graph.edges().length+e.missingReferences.length)+(t.summaryOnly?[]:e.rootEvidence).reduce((p,m)=>p+m.length,0)),{findContextBudgetRecovery:s}=await import("./context-budget-recovery-CSJV3TY3.js"),c=s({requested:o,initialBudget:U,workUnits:i,probe:p=>Qt(e,t,p)}),d=["--pm-path",e.pmRoot,"item","deps",e.canonicalId,"--format","tree","--summary"],u=F(d),l=c.feasible_tokens===null?d:[...t.args];c.feasible_tokens!==null&&(l[t.budgetIndex]=String(c.feasible_tokens));let a=F(l);return Se("Relationship context tokenBudget cannot fit the required rendered packet",{exitCode:x.USAGE,cause:n,context:{code:"invalid_argument_value",field:"tokenBudget",value:String(o),required:c.feasible_tokens===null?"Inspect the compact summary and review the output constraints.":"Retry the preserved context query with --token-budget "+c.feasible_tokens+".",why:"Budget advice is verified against the current query. A minimum is reported only after every smaller positive budget is checked.",examples:[a,u],nextSteps:[a],recovery:{recovery_mode:"compact",suggested_flags:["--token-budget"],token_budget:c,suggested_retry_args:l,suggested_retry:a,next_best_command:u,fallback_candidates:[{source:"relationship_summary",command:u,reason:"Inspect bounded counts separately from context rows."}]}}})}async function en(e){let{pmRoot:n,assembly:o,canonicalId:t,options:r,rootEvidence:i,summaryOnly:s,rendering:c}=e,d=Xt(r,o.graph.registry()),u=o.graph.closure(t,{direction:d.direction,...d.kinds===void 0?{}:{kinds:d.kinds},maxDepth:d.maxDepth??3}),l=u.value.filter(h=>o.missingIdSet.has(h.toLowerCase())),a=new Set(l.map(h=>h.toLowerCase())),p=o.graph.registry(),m=d.kinds?new Set(d.kinds.map(h=>p.require(h).kind)):void 0,f=new Set([t,...u.value]),_=[...o.dangling.active,...o.dangling.legacy_terminal].filter(h=>Jt({row:h,missingReachableSet:a,packetIds:f,filteredKinds:m,registry:p})),g={pmRoot:n,assembly:o,canonicalId:t,contextOptions:d,rootEvidence:i,summaryOnly:s,rendering:c,missingCount:l.length,missingReferences:_};try{return Xe(g)}catch(h){if(h instanceof w&&h.code==="invalid_query_cursor"){let k=qe({...g,contextOptions:{...d,cursor:void 0},rendering:{...c,global:{...c.global,outputCursor:void 0}}},d.tokenBudget??U),y=F(k.args);throw new w(h.message,h.exitCode,{...h.context,nextSteps:[...h.context.nextSteps,y],recovery:{suggested_retry:y,suggested_retry_args:k.args}})}throw We(h)?await Zt(g,h):h}}function tn(e){let n=[e],o;for(;n.length>0;){let t=n.pop();t.dependencies.length>0&&(o=t,n.push(...t.dependencies))}return o?(o.dependencies.pop(),o.truncated=!0,!0):!1}function nn(e,n,o,t,r,i,s){let c=r??At,d=S(o.nodeLimit,"node-limit")??Nt,u=S(o.edgeLimit,"edge-limit")??Mt,l=S(o.tokenBudget,"token-budget")??$t,a={nodeLimit:d,edgeLimit:u,tokenBudget:l,nodes:0,edges:0,estimatedTokens:0,reasons:new Set},p=Ge(e,t,new Set,c,n==="graph"?"repeated":i,new Set,a),m=ze(e,t,void 0),f;for(;;){let _=Wt(p),g=a.reasons.size===0?void 0:{reasons:[...a.reasons].sort(),limits:{max_depth:c,node_limit:d,edge_limit:u,token_budget:l},estimated_tokens:0,total_node_count:m.node_count,total_edge_count:m.edge_count,omitted_node_count:Math.max(0,m.node_count-_.nodes.length),omitted_edge_count:Math.max(0,m.edge_count-_.edges.length)},h={id:e,format:n,node_count:_.nodes.length,edge_count:_.edges.length,edge_basis:"deduplicated_directed",missing_count:_.missing_ids.length,...g?{truncation:g}:{}};if(f=n==="tree"?{...h,tree:p}:{...h,graph:_},(f.truncation===void 0?A(new TextEncoder().encode(re(b(f,!1,s.legacyAliasCounts),s)).byteLength):He(b(f,!1,s.legacyAliasCounts),s,y=>{f.truncation.estimated_tokens=y}))<=l)return f;if(!tn(p))return a.reasons.add("token_budget"),f;a.reasons.add("token_budget")}}function b(e,n,o={}){let t={name:e.format==="tree"?"dependency_tree":e.format==="graph"?"dependency_graph":"relationship_context",restore_with:"--full"},r=e.context?.meta.truncated?[{name:"relationship_context_bounds",restore_with:"--token-budget <n> --node-limit <n> --edge-limit <n> --max-depth <n>"}]:[];return{...e,legacy_alias_counts:o,projection:{mode:n?"summary":"full",declared_field_groups:[t,...r],included_field_groups:n?[]:[t.name]}}}async function ro(e,n,o){let t=ue(process.cwd(),o.path);await Re(t);let r=Bt(n.format),i=Fe(n.maxDepth),s=Pt(n.collapse);Y(n.summary===!0,n.full===!0,"--summary");let c=n.summary===!0,d=await be(t),u=ae(d,z()),l=await Le(t,d.item_format,u.type_to_folder,void 0,d.schema),a=pe(d.schema),p=new Map(l.map(g=>[g.id.trim().toLowerCase(),Gt(g)])),m=Z(l,g=>G(g,a));for(let g of[...m.active,...m.legacy_terminal]){let h=p.get(g.holder_id.trim().toLowerCase()),k=g.kind.trim().toLowerCase();h&&!h.dependencies.some(y=>y.id.trim().toLowerCase()===g.target_id.trim().toLowerCase()&&y.kind===k)&&h.dependencies.push({id:g.target_id,kind:k})}if(!p.has(e.trim().toLowerCase()))throw new w(`Item ${e} not found`,x.NOT_FOUND);let f=o.outputFormat??(o.json===!0||o.json===void 0&&o.defaultOutputFormat==="json"?"json":"toon");if(r==="context"){let g=p.get(e.trim().toLowerCase()).id,h=c?[]:await Vt(t,g,d,u.type_to_folder),k=O=>G(O,a),y=v(),C=Pe().lookup(t,$e(l,k,y),()=>ee(l,k,y));return b(await en({pmRoot:t,assembly:C.assembly,canonicalId:g,options:n,rootEvidence:h,summaryOnly:c,rendering:{format:f,global:o,commandOptions:n,legacyAliasCounts:C.assembly.legacyAliasCounts}}),c,C.assembly.legacyAliasCounts)}let _=Object.fromEntries(Object.entries(ee(l,g=>G(g,a)).legacyAliasCounts));return c?b({id:e,format:r,...ze(e,p,i)},!0,_):b(nn(e,r,n,p,i,s,{format:f,global:o,commandOptions:n,legacyAliasCounts:_}),!1,_)}export{hn as a,_n as b,dt as c,v as d,un as e,H as f,ln as g,st as h,pn as i,$ as j,ut as k,pt as l,Z as m,ft as n,En as o,ee as p,$e as q,te as r,Pe as s,Sn as t,U as u,Ue as v,S as w,Fe as x,Ut as y,jt as z,ro as A};
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{H as Ie,I as Te,L as Le,X as Se,j as Ee}from"./chunk-VV2QF5IE.js";import{s as be,y as Re}from"./chunk-WHHFPATO.js";import{a as N,b as R}from"./chunk-X6CXWWNB.js";import{Cf as ye,Df as ke,Gb as G,Hf as we,Q as ae,Qe as A,W as ue,cf as me,dg as xe,eg as ve,hf as ge,je as z,jg as Ce,ke as fe,q as E,qf as he,v as de,vf as _e,ze as Y}from"./chunk-NSFS3VWP.js";import{C as F,c as le}from"./chunk-R6QFPHWW.js";import{O as pe}from"./chunk-OCKKIECS.js";import{A as w,z as x}from"./chunk-NGFDPEP7.js";function v(){let e=E();for(let n of z()?.relationship_kinds??[])for(let o of n.definitions)e.register(o);return e}function M(e){if(typeof e!="string")return;let n=e.trim().toLowerCase();return n.length>0?n:void 0}function K(e){return[e.parent_id,e.child_id,e.source,e.kind,e.holder_id,e.target_id??""].join("\0")}function Qe(e,n){let o=new Set,t=[];for(let r of[...e].sort()){if(o.has(r))continue;o.add(r);let i=[{nodeId:r,children:[...n.get(r)??[]].sort(),nextChild:0}];for(;i.length>0;){let s=i.at(-1),c=s.children[s.nextChild];c===void 0?(t.push(s.nodeId),i.pop()):(s.nextChild+=1,o.has(c)||(o.add(c),i.push({nodeId:c,children:[...n.get(c)??[]].sort(),nextChild:0})))}}return t}function Ze(e,n){let o=[...e].sort(),t=Qe(o,n),r=new Set,i=et(o,n),s=[];for(let c of t.reverse()){if(r.has(c))continue;let d=tt(c,i,r);(d.length>1||n.get(d[0])?.has(d[0]))&&s.push(d)}return s.sort((c,d)=>c.join("\0").localeCompare(d.join("\0")))}function et(e,n){let o=new Map(e.map(t=>[t,new Set]));for(let[t,r]of n)for(let i of r)o.get(i)?.add(t);return o}function tt(e,n,o){let t=[],r=[e];for(o.add(e);r.length>0;){let i=r.pop();t.push(i);for(let s of[...n.get(i)].sort())o.has(s)||(o.add(s),r.push(s))}return t.sort()}function Oe(e){let n=new Map;for(let o of e){let t=M(o?.id);t&&!n.has(t)&&n.set(t,o)}return n}function nt(e,n,o){let t=M(n.parent);if(!(!t||!o.has(t)))return{parent_id:t,child_id:e,source:"scalar_parent",kind:"parent",holder_id:e,child_cardinality:"one"}}function ot(e,n,o,t){let r=M(n?.id),i=t.resolve(n?.kind);if(!r||!o.has(r)||!i?.hierarchy)return;let s=i.hierarchyDirection==="source_parent";return{parent_id:s?e:r,child_id:s?r:e,source:"dependency",kind:i.kind,holder_id:e,target_id:r,child_cardinality:s?i.incoming:i.outgoing}}function De(e,n){let o=new Map;for(let[t,r]of e){let i=nt(t,r,e);i&&o.set(K(i),i);for(let s of r.dependencies??[]){let c=ot(t,s,e,n);c&&o.set(K(c),c)}}return[...o.values()].sort((t,r)=>K(t).localeCompare(K(r)))}function un(e,n=v()){return De(Oe(e),n)}function rt(e,n,o){let t=new Set(e.filter(r=>r.child_cardinality==="one").map(r=>r.child_id));return[...n].filter(([r,i])=>i.length>1&&t.has(r)).map(([r,i])=>({child_id:r,parent_ids:[...i],legacy_terminal:o.has(r)&&i.every(s=>o.has(s))})).sort((r,i)=>r.child_id.localeCompare(i.child_id))}function it(e,n,o){let t=new Map;for(let i of n){if(i.source!=="dependency")continue;let s=t.get(i.child_id)??new Set;s.add(i.parent_id),t.set(i.child_id,s)}let r=[];for(let[i,s]of e){let c=M(s.parent);if(!c||!e.has(c))continue;let d=[...t.get(i)??[]].filter(u=>u!==c).sort();d.length!==0&&r.push({child_id:i,scalar_parent_id:c,dependency_parent_ids:d,legacy_terminal:o.has(i)&&o.has(c)&&d.every(u=>o.has(u))})}return r.sort((i,s)=>i.child_id.localeCompare(s.child_id))}function H(e,n=t=>t==="closed"||t==="canceled",o=v()){let t=Oe(e),r=De(t,o),i=st(r),s=new Set([...t].filter(([,d])=>n(d.status)).map(([d])=>d)),c=Ze([...t.keys()],new Map([...i.children_by_parent].map(([d,u])=>[d,new Set(u)]))).map(d=>({item_ids:d,legacy_terminal:d.every(u=>s.has(u))}));return{relations:r,cycles:c,cardinality_violations:rt(r,i.parents_by_child,s),divergences:it(t,r,s)}}function ln(e){return e.source==="scalar_parent"?`${e.parent_id} -> ${e.child_id} (scalar parent on ${e.holder_id})`:`${e.parent_id} -> ${e.child_id} (${e.kind} dependency on ${e.holder_id})`}function st(e){let n=new Map,o=new Map;for(let t of e){let r=n.get(t.child_id)??new Set;r.add(t.parent_id),n.set(t.child_id,r);let i=o.get(t.parent_id)??new Set;i.add(t.child_id),o.set(t.parent_id,i)}return{parents_by_child:new Map([...n].map(([t,r])=>[t,[...r].sort()])),children_by_parent:new Map([...o].map(([t,r])=>[t,[...r].sort()]))}}function J(e,n){let o=new Set(n);return e.every(t=>o.has(t))}function pn(e,n,o,t,r){let i=M(o);if(!i)return;let s=H(e,t,r),c=H(n,t,r),d=c.divergences.find(a=>!s.divergences.some(p=>p.child_id===a.child_id&&p.scalar_parent_id===a.scalar_parent_id&&J(a.dependency_parent_ids,p.dependency_parent_ids)));if(d){let a=[d.scalar_parent_id,...d.dependency_parent_ids].sort();throw new w(`Hierarchy mutation would assign ${d.child_id} to multiple parents: ${a.join(", ")}.`,x.CONFLICT,{code:"hierarchy_parent_divergence_created",source_id:i,target_id:d.child_id,verification_errors:a})}let u=c.cardinality_violations.find(a=>(a.child_id===i||a.parent_ids.includes(i))&&!s.cardinality_violations.some(p=>p.child_id===a.child_id&&J(a.parent_ids,p.parent_ids)));if(u)throw new w(`Hierarchy mutation would assign ${u.child_id} to multiple parents: ${u.parent_ids.join(", ")}.`,x.CONFLICT,{code:"hierarchy_cardinality_created",source_id:i,target_id:u.child_id,verification_errors:u.parent_ids});let l=c.cycles.find(a=>a.item_ids.includes(i)&&!s.cycles.some(p=>J(a.item_ids,p.item_ids)));if(l)throw new w(`Hierarchy mutation would create a cycle: ${l.item_ids.join(" -> ")}.`,x.CONFLICT,{code:"hierarchy_cycle_created",source_id:i,verification_errors:l.item_ids})}var ct="global";function hn(e){let n=e?.trim();if(n)return R(n)?ct:n}function _n(e,n,o){return dt(e,n,o)}function dt(e,n,o){let t=e.trim();return R(o)||N(t)?t:Ee(t,n)}function L(e){if(typeof e!="string")return;let n=e.trim();if(!(!n||["none","null","n/a","na"].includes(n.toLowerCase())))return n}function $(e){let n=L(e);return n?.toLowerCase()==="no-active-blocker"?void 0:n}function B(e,n,o=!0){let t=L(e);return o&&(R(n)||t!==void 0&&N(t))}function Q(e,n){return B(e,n)?`external\0${e}`:`local\0${e.toLowerCase()}`}function Ae(e,n,o,t){return B(e,n)?t.get(e):o.get(e.toLowerCase())}function T(e,n){let o=e.toLowerCase(),t=n.toLowerCase();return o!==t?o<t?-1:1:e!==n?e<n?-1:1:0}function at(e){let n=new Map;for(let o of e.dependencies??[]){if(typeof o!="object"||o===null)continue;let t=o,r=L(t.id);if(!r)continue;let i=typeof t.kind=="string"?t.kind:"related",s=`${i}\0${Q(r,t.source_kind)}`,c=n.get(s);c?c.count+=1:n.set(s,{target_id:r,kind:i,count:1})}return n}function ut(e,n=o=>o==="closed"||o==="canceled"){let o=[];for(let t of e)if(!(typeof t?.id!="string"||t.id.trim().length===0))for(let r of at(t).values())r.count<2||o.push({holder_id:t.id.trim(),target_id:r.target_id,kind:r.kind,occurrences:r.count,holder_status:t.status,legacy_terminal:n(t.status)});return o.sort((t,r)=>{let i=T(t.holder_id,r.holder_id);if(i!==0)return i;let s=T(t.target_id,r.target_id);return s!==0?s:T(t.kind,r.kind)})}function lt(e,n,o,t,r){if(typeof o!="object"||o===null)return;let i=L(o.id);if(!i||Q(i,o.source_kind)!==Q(n))return;let s=r.resolve(typeof o.kind=="string"?o.kind:"related");if(!(s?.ordering!==!0||(s.precedence??"source_before_target")!=="source_before_target"))return{holder_id:e.id.trim(),target_id:i,dependency_kind:s.kind,holder_status:e.status,legacy_terminal:t(e.status)}}function pt(e,n=t=>t==="closed"||t==="canceled",o=v()){let t=new Map;for(let r of e){if(typeof r?.id!="string"||r.id.trim().length===0)continue;let i=L(r.blocked_by);if(i)for(let s of r.dependencies??[]){let c=lt(r,i,s,n,o);c&&t.set(`${c.holder_id.toLowerCase()}\0${c.target_id.toLowerCase()}\0${c.dependency_kind}`,c)}}return[...t.values()].sort((r,i)=>{let s=T(r.holder_id,i.holder_id);if(s!==0)return s;let c=T(r.target_id,i.target_id);return c!==0?c:T(r.dependency_kind,i.dependency_kind)})}function Z(e,n=o=>o==="closed"||o==="canceled"){let o=e.filter(d=>typeof d?.id=="string"&&d.id.trim().length>0),t=new Set(o.map(d=>d.id.trim().toLowerCase())),r=new Map,i=(d,u,l,a,p)=>{let m=L(u);if(!m||t.has(m.toLowerCase())||B(m,void 0,p))return;let f={holder_id:d.id.trim(),target_id:m,kind:l,source:a,holder_status:d.status,legacy_terminal:n(d.status),no_active_blocker_sentinel:m.toLowerCase()==="no-active-blocker"};r.set(`${f.holder_id}::${f.target_id}::${f.kind}::${f.source}`,f)};for(let d of o){i(d,d.parent,"parent","parent",!1),i(d,d.blocked_by,"blocked_by","blocked_by",!0);for(let u of d.dependencies??[]){if(typeof u!="object"||u===null)continue;let l=u;R(l.source_kind)||i(d,l.id,typeof l.kind=="string"?l.kind:"related","dependency",!0)}}let s=[...r.values()].sort((d,u)=>d.holder_id.localeCompare(u.holder_id)||d.target_id.localeCompare(u.target_id)||d.kind.localeCompare(u.kind)||d.source.localeCompare(u.source)),c=s.filter(d=>d.legacy_terminal);return{active:s.filter(d=>!d.legacy_terminal),legacy_terminal:c,no_active_blocker_sentinels:s.filter(d=>d.no_active_blocker_sentinel)}}function ft(e){let n=new Map;for(let o of[...e.active,...e.legacy_terminal]){if(o.no_active_blocker_sentinel)continue;let t=o.target_id.trim(),r=t.toLowerCase();n.has(r)||n.set(r,t)}return[...n.values()].sort((o,t)=>o.localeCompare(t))}function mt(e){let n=new Map;for(let o of e){let t=$(o.blocked_by);t&&B(t)&&!n.has(t)&&n.set(t,t);for(let r of o.dependencies??[]){if(typeof r!="object"||r===null||!B(r.id,r.source_kind))continue;let i=$(r.id);i&&!n.has(i)&&n.set(i,i)}}return[...n.values()].sort((o,t)=>o.localeCompare(t))}var Ne=new WeakMap;function En(e){return e.hierarchyIntegrity??Ne.get(e)}function gt(e,n=v()){let o={};for(let t of e)for(let r of t.dependencies??[]){if(typeof r!="object"||r===null)continue;let i=r.kind;if(typeof i!="string")continue;let s=i.trim().toLowerCase().replaceAll("-","_"),c=n.resolve(i);c&&s!==c.kind&&(o[s]=(o[s]??0)+1)}return Object.fromEntries(Object.entries(o).sort(([t],[r])=>t.localeCompare(r)))}function ee(e,n,o){let t=o??v(),r=e.filter(f=>typeof f?.id=="string"&&f.id.trim().length>0),i=new Map(r.map(f=>[f.id.trim().toLowerCase(),f.id.trim()])),s=Z(r,n),c=ft(s);for(let f of c)i.set(f.toLowerCase(),f);let d=mt(r),u=new Set(i.keys()),l=new Map;for(let f of d){let _=f;for(;u.has(_.toLowerCase());)_=`external:${_}`;l.set(f,_),u.add(_.toLowerCase())}let a=r.map(f=>{let _=$(f.parent),g=$(f.blocked_by),h=(f.dependencies??[]).flatMap(k=>{if(typeof k!="object"||k===null)return[];let y=k,C=$(y.id);return C?[{id:Ae(C,y.source_kind,i,l),kind:typeof y.kind=="string"?y.kind:"related"}]:[]});return{id:f.id.trim(),..._?{parent:i.get(_.toLowerCase())}:{},...g?{blocked_by:Ae(g,void 0,i,l)}:{},dependencies:h}}),p=H(r,n,t),m={graph:de.fromItems([...a,...c.map(f=>({id:f})),...d.map(f=>({id:l.get(f)}))],t),details:[...r.map(f=>({id:f.id.trim(),title:f.title,status:f.status,...typeof f.type=="string"&&f.type.trim().length>0?{type:f.type.trim()}:{}})),...c.map(f=>({id:f,title:`[missing] ${f}`,status:"missing"})),...d.map(f=>({id:l.get(f),title:`[external] ${f}`,status:"external"}))],missingIdSet:new Set(c.map(f=>f.toLowerCase())),dangling:s,duplicateRows:ut(r,n),orderingContradictions:pt(r,n,t),legacyAliasCounts:gt(r,t),hierarchyIntegrity:p};return Ne.set(m,p),m}import{createHash as ht}from"node:crypto";var _t=64,yt=8;function kt(e,n){let o=(e.dependencies??[]).map(t=>{if(typeof t!="object"||t===null)return"";let r=t;return`${typeof r.kind=="string"?r.kind:"related"}:${typeof r.id=="string"?r.id:""}`}).sort().join(",");return[e.id,e.title,e.status,n(e.status)?"1":"0",typeof e.type=="string"?e.type.trim():"",e.parent??"",e.blocked_by??"",o].join("\0")}function $e(e,n=t=>t==="closed"||t==="canceled",o=E()){let t=e.filter(i=>typeof i?.id=="string"&&i.id.trim().length>0).map(i=>kt(i,n)).sort(),r=o.list().map(i=>le(i)).sort();return ht("sha256").update(t.join("")).update("").update(r.join("")).digest("hex")}function Me(e,n,o){let t=n??o;if(!Number.isInteger(t)||t<1)throw new TypeError(`Invalid ${e} bound: ${String(n)}`);return t}var te=class{#e=new Map;#t;#n;constructor(n={}){this.#t=Me("maxResultsPerWorkspace",n.maxResultsPerWorkspace,_t),this.#n=Me("maxWorkspaces",n.maxWorkspaces,yt)}lookup(n,o,t){let r=this.#e.get(n),i=!0;(r===void 0||r.fingerprint!==o)&&(r={fingerprint:o,assembly:t(),results:new Map},i=!1,!this.#e.has(n)&&this.#e.size>=this.#n&&this.#e.delete(this.#e.keys().next().value)),this.#e.delete(n),this.#e.set(n,r);let s=r,c=this.#t;return{assembly:s.assembly,assemblyReused:i,fingerprint:o,memoize(d,u){let l=s.results.get(d);if(l!==void 0||s.results.has(d))return s.results.delete(d),s.results.set(d,l),{value:structuredClone(l),reused:!0};let a=u();return s.results.size>=c&&s.results.delete(s.results.keys().next().value),s.results.set(d,structuredClone(a)),{value:a,reused:!1}}}}clear(){this.#e.clear()}},Be=new te;function Pe(){return Be}function Sn(){Be.clear()}var U=1200,wt=["prerequisite","dependent","ancestor","descendant","provenance","related"],xt=new TextEncoder;function ne(e,n,o){let t=e??n;if(!Number.isInteger(t)||t<1)throw new TypeError(`Relationship context ${o} must be positive`);return t}function P(e){return Math.max(1,Math.ceil(xt.encode(JSON.stringify(e)).byteLength/4))}function W(e,n,o){let t=o.resolve(e.kind);if(t?.ordering){let i=(t.precedence??"source_before_target")==="source_before_target"?e.source:e.target;return n===i?"prerequisite":"dependent"}if(t?.hierarchy){let i=t.hierarchyDirection==="source_parent"?e.source:e.target;return n===i?"ancestor":"descendant"}return e.kind==="discovered_from"||e.kind==="incident_from"?"provenance":"related"}function vt(e,n,o,t){let r=e.filter(i=>i.source===n&&i.target===o||i.target===n&&i.source===o).map(i=>W(i,o,t));return[...new Set(r)].sort()}function Ct(e){return wt.find(n=>e.includes(n))}function Et(e,n,o,t){let r=t.direction??"both",i=t.maxDepth??3;if(!Number.isInteger(i)||i<0)throw new TypeError("Relationship context maxDepth must be non-negative");let s=new Set([n]),c=[{id:n,distance:0}],d=[],u=0,l=!1;for(let a=0;a<c.length;a+=1){t.signal?.throwIfAborted();let p=c[a];if(p.distance>=i&&l)continue;let m=e.neighborEdges(p.id,{direction:r,kinds:t.kinds,signal:t.signal});if(u+=m.meta.inspectedEdges,p.distance>=i){m.value.some(f=>!s.has(f.id))&&(l=!0);continue}for(let{id:f,edge:_}of m.value){if(s.has(f))continue;s.add(f);let g={id:f,distance:p.distance+1,via:p.id,role:W(_,f,o)};d.push(g),c.push(g)}}return{rows:d,visitedNodes:c.length,inspectedEdges:u,depthTruncated:l}}function bt(e,n,o,t){let r={prerequisite:0,dependent:0,ancestor:0,descendant:0,provenance:0,related:0},i=e.neighborEdges(n,{direction:t.direction??"both",kinds:t.kinds,signal:t.signal}).value;for(let{id:s,edge:c}of i)r[W(c,s,o)]+=1;return{directEdges:r,directTotal:i.length,rootEdges:i.map(({edge:s})=>s)}}function Rt(e,n,o,t){let r=new Set;for(let i of n){let s=i.source===o?i.target:i.source,c=W(i,s,t);(c==="prerequisite"||c==="ancestor")&&r.add(s)}return[...e].sort((i,s)=>Number(r.has(s.id))-Number(r.has(i.id))||i.distance-s.distance||i.id.localeCompare(s.id))}function It(e,n){let o=e.distance===1?vt(n.rootEdges,n.rootId,e.id,n.registry):[];return{...n.details.get(e.id)??{id:e.id},distance:e.distance,role:o.length>0?Ct(o):e.role,via:e.via,reasons:o.length>0?o:[`${e.role} via ${e.via} (depth ${e.distance})`]}}function Tt(e){let n=[],o=e.initialTokens,t=0;for(let r of e.candidates){if(n.length>=e.nodeLimit)break;let i=It(r,e),s=P(i);if(o+s>e.tokenBudget)break;let c=e.rootEdges.filter(d=>d.source===r.id||d.target===r.id).reduce((d,u)=>d+P(u),0);if(o+t+s+c>e.tokenBudget){if(n.length>0)break}else t+=c;n.push(i),o+=s}if(e.candidates.length>0&&n.length===0)throw new TypeError("Relationship context tokenBudget cannot fit one node");return{nodes:n,usedTokens:o}}function Lt(e){let n=e.options.kinds?new Set(e.options.kinds.map(i=>e.registry.require(i).kind)):void 0,o=e.graph.edges().filter(i=>{if(!e.included.has(i.source)||!e.included.has(i.target))return!1;if(n===void 0||n.has(i.kind))return!0;let s=e.registry.resolve(i.kind)?.inverse;return s!==void 0&&n.has(s)}).sort((i,s)=>+(s.source===e.rootId||s.target===e.rootId)-+(i.source===e.rootId||i.target===e.rootId)),t=[],r=e.initialTokens;for(let i of o){if(t.length>=e.edgeLimit)break;let s=P(i);r+s>e.tokenBudget||(t.push(i),r+=s)}return{edges:t,usedTokens:r,candidateCount:o.length}}function Ue(e,n,o,t={}){if(!e.nodes().includes(n))throw new TypeError(`Relationship node not found: ${n}`);let r=ne(t.nodeLimit,20,"nodeLimit"),i=ne(t.edgeLimit,40,"edgeLimit"),s=ne(t.tokenBudget,U,"tokenBudget"),c=t.registry??E(),d=new Map(o.map(I=>[I.id,I])),u=d.get(n)??{id:n},{evidence:l=[],...a}=u,p=[...l],m=Et(e,n,c,t),{rootEdges:f,..._}=bt(e,n,c,t),g=Rt(m.rows,f,n,c),h=ye("relationship-context",{rootId:n,direction:t.direction??"both",kinds:[...t.kinds??[]].sort(),maxDepth:t.maxDepth??3,ordering:"required-root-evidence-first-v1"}),k=we(g,t.cursor,h,({id:I})=>I,"--cursor"),y=g.slice(k),C=P(a)+P(p);if(C>s)throw new TypeError("Relationship context tokenBudget cannot fit root and evidence");let O=Tt({candidates:y,details:d,rootEdges:f,rootId:n,registry:c,nodeLimit:r,tokenBudget:s,initialTokens:C}),{nodes:D}=O,Ve=new Set([n,...D.map(({id:I})=>I)]),ie=Lt({graph:e,rootId:n,included:Ve,options:t,registry:c,edgeLimit:i,tokenBudget:s,initialTokens:O.usedTokens}),{edges:X,usedTokens:Ye}=ie,j=k+D.length,q=j<g.length,se=D.at(-1),V=ie.candidateCount-X.length,ce=m.depthTruncated||q||V>0,Je={rootId:n,...a.status===void 0?{}:{rootStatus:a.status},..._,discoveredNodes:g.length,returnedNodes:D.length,returnedEdges:X.length,omittedNodes:g.length-j,omittedEdges:V,evidenceCount:p.length,hasMore:q};return{root:a,summary:Je,nodes:D,edges:X,evidence:p,meta:{exact:!0,truncated:ce,completeness:ce?"truncated":"complete",nodeLimit:r,edgeLimit:i,tokenBudget:s,usedTokens:Ye,visitedNodes:m.visitedNodes,inspectedEdges:m.inspectedEdges,omittedNodes:g.length-j,omittedEdges:V,...q&&se?{nextCursor:ke(h,se.id,j-1)}:{}}}}var St=["tree","graph","context"],Ot=["none","repeated"],Dt=["outgoing","incoming","both"],At=32,Nt=200,Mt=400,$t=16e3;function Bt(e){let n=e?.trim().toLowerCase()??"tree";if(St.includes(n))return n;throw new w(`Invalid --format value "${e}". Use "tree", "graph", or "context".`,x.USAGE)}function S(e,n){if(e===void 0)return;let o=typeof e=="number"?e:Number(e.trim());if(!Number.isInteger(o)||o<1)throw new w(`Invalid --${n} value "${e}". Use a positive integer.`,x.USAGE);return o}function Fe(e){if(e===void 0)return;let n=typeof e=="number"?e:Number(e.trim());if(!Number.isInteger(n)||n<0)throw new w(`Invalid --max-depth value "${e}". Use a non-negative integer.`,x.USAGE);return n}function Pt(e){let n=e?.trim().toLowerCase()??"none";if(Ot.includes(n))return n;throw new w(`Invalid --collapse value "${e}". Use "none" or "repeated".`,x.USAGE)}function Ut(e){let n=e?.trim().toLowerCase()??"both";if(Dt.includes(n))return n;throw new w(`Invalid --direction value "${e}". Use "outgoing", "incoming", or "both".`,x.USAGE)}function jt(e,n=E()){if(e===void 0)return;let o=(Array.isArray(e)?e:[e]).flatMap(r=>r.split(",")).map(r=>r.trim()).filter(r=>r.length>0);if(o.length===0)return;let t=new Set;for(let r of o){let i=n.resolve(r);if(!i){let s=n.list().map(c=>c.kind).join(", ");throw new w(`Invalid --kind value "${r}". Registered kinds: ${s}.`,x.USAGE)}t.add(i.kind)}return[...t].sort()}function Ft(e){if(!e||e.length===0)return[];let n=e.map(({id:t,kind:r})=>({id:t.trim(),kind:r.trim().toLowerCase()})).sort((t,r)=>{let i=t.kind.localeCompare(r.kind);return i!==0?i:t.id.localeCompare(r.id)}),o=new Map;for(let t of n){let r=`${t.kind.toLowerCase()}::${t.id.toLowerCase()}`;o.has(r)||o.set(r,{id:t.id,kind:t.kind})}return[...o.values()]}function Gt(e){return{id:e.id,title:e.title,type:e.type,status:e.status,dependencies:Ft(e.dependencies)}}function zt(e){return A(new TextEncoder().encode(JSON.stringify({...e,dependencies:void 0})).byteLength)}function Kt(e,n,o,t,r,i,s,c,d){for(let u of n.dependencies){let l=Math.max(1,Math.ceil(JSON.stringify({from:e.id,to:u.id,kind:u.kind}).length/3));if(c.nodes>=c.nodeLimit){e.truncated=!0,c.reasons.add("node_limit");break}if(c.edges>=c.edgeLimit){e.truncated=!0,c.reasons.add("edge_limit");break}if(c.estimatedTokens+l>=c.tokenBudget){e.truncated=!0,c.reasons.add("token_budget");break}c.edges+=1,c.estimatedTokens+=l,e.dependencies.push(Ge(u.id,o,t,r,i,s,c,d+1,u.kind))}}function Ht(e,n,o,t,r,i,s,c){return s.estimatedTokens>=s.tokenBudget&&n?.dependencies.length?(e.truncated=!0,s.reasons.add("token_budget"),!0):!n||e.cycle?!0:t!==void 0&&c>=t?(n.dependencies.length>0&&(e.truncated=!0,s.reasons.add("max_depth")),!0):r==="repeated"&&i.has(o)?(e.collapsed=!0,!0):!1}function Ge(e,n,o,t,r,i,s,c=0,d){let u=e.trim().toLowerCase(),l=n.get(u),a={id:l?.id??e,title:l?.title,type:l?.type,status:l?.status,via:d,missing:!l,cycle:o.has(u),dependencies:[]};if(s.nodes+=1,s.estimatedTokens+=zt(a),Ht(a,l,u,t,r,i,s,c))return a;r==="repeated"&&i.add(u);let p=new Set(o);return p.add(u),Kt(a,l,n,p,t,r,i,s,c),a}function je(e,n){return!e||e.missing&&!n.missing?n:{...e,title:e.title??n.title,type:e.type??n.type,status:e.status??n.status}}function Wt(e){let n=new Map,o=new Map,t=[e];for(;t.length>0;){let c=t.pop();n.set(c.id,je(n.get(c.id),{id:c.id,title:c.title,type:c.type,status:c.status,missing:c.missing}));for(let d of c.dependencies){n.set(d.id,je(n.get(d.id),{id:d.id,title:d.title,type:d.type,status:d.status,missing:d.missing}));let u=d.via??"related",l=`${c.id}::${d.id}::${u}`;o.has(l)||o.set(l,{from:c.id,to:d.id,kind:u}),d.cycle||t.push(d)}}let r=[...n.values()].sort((c,d)=>c.id.localeCompare(d.id)),i=[...o.values()].sort((c,d)=>{let u=c.from.localeCompare(d.from);if(u!==0)return u;let l=c.to.localeCompare(d.to);return l!==0?l:c.kind.localeCompare(d.kind)}),s=r.filter(c=>c.missing).map(c=>c.id);return{root_id:e.id,nodes:r,edges:i,missing_ids:s}}function ze(e,n,o){let t=new Set,r=new Set,i=new Set,s=new Set,c=[{id:e,depth:0}],d=0;for(;d<c.length;){let u=c[d++],l=u.id.trim().toLowerCase();t.add(l);let a=n.get(l);if(!a){i.add(l);continue}if(!(o!==void 0&&u.depth>=o)&&!s.has(l)){s.add(l);for(let p of a.dependencies)r.add(`${l}::${p.id.trim().toLowerCase()}::${p.kind}`),c.push({id:p.id,depth:u.depth+1})}}return{node_count:t.size,edge_count:r.size,edge_basis:"deduplicated_directed",missing_count:i.size}}function Xt(e,n=E()){let o=Fe(e.maxDepth),t=S(e.nodeLimit,"node-limit"),r=S(e.edgeLimit,"edge-limit"),i=S(e.tokenBudget,"token-budget"),s=jt(e.kind,n);return{direction:Ut(e.direction),...s===void 0?{}:{kinds:s},...o===void 0?{}:{maxDepth:o},...t===void 0?{}:{nodeLimit:t},...r===void 0?{}:{edgeLimit:r},...i===void 0?{}:{tokenBudget:i},...e.cursor?.trim()?{cursor:e.cursor.trim()}:{}}}function qt(e,n,o,t){return Ue(e.graph,n,e.details.map(r=>r.id===n&&t.length>0?{...r,evidence:t}:r),o)}function oe(e,n,o,t){for(let r of o.slice(0,t)){let i=r?.trim();i&&e.push(`${n}:${i}`)}}async function Vt(e,n,o,t){let r=await Ie(e,n,o.id_prefix,o.item_format,t);if(!r)return[];let{document:i}=await Te(r,{schema:o.schema}),s=i.metadata,c=s.files??[],d=s.tests??[],u=s.docs??[],l=[["files",c.length],["tests",d.length],["docs",u.length],["comments",(s.comments??[]).length],["notes",(s.notes??[]).length],["learnings",(s.learnings??[]).length]];if(l.every(([,p])=>p===0))return[];let a=[`linked:${l.map(([p,m])=>`${p}=${m}`).join(",")}`];return oe(a,"file",c.map(p=>p.path),3),oe(a,"test",d.map(p=>p.command??p.path),2),oe(a,"doc",u.map(p=>p.path),2),a}function Yt(e){let{canonicalId:n,context:o,missingCount:t,missingReferences:r,referenceLimit:i,summaryOnly:s}=e;return{id:n,format:"context",node_count:o.nodes.length+1,edge_count:o.edges.length,edge_basis:"deduplicated_directed",missing_count:t,missing_scope:"traversal",missing_reference_count:r.length,...s?{}:{missing_references:r.slice(0,i),context:o}}}function Jt(e){let{row:n,missingReachableSet:o,packetIds:t,filteredKinds:r,registry:i}=e;if(n.no_active_blocker_sentinel||!o.has(n.target_id.trim().toLowerCase())||!t.has(n.holder_id))return!1;if(r===void 0)return!0;let s=i.resolve(n.kind);return s!==void 0&&(r.has(s.kind)||s.inverse!==void 0&&r.has(s.inverse))}function Ke(e,n){let o=fe(),t=n.commandOptionsOverride??(o?.command==="deps"?o.options:n.commandOptions);return xe("deps",{...t,...n.global,resolvedOutputFormat:n.format},e)}function re(e,n){let o=Ke(e,n),t=r=>Ce(r,n.format,n.global.lean===!0);return t(n.global.tokenAccounting===!0?ve(o,t):o)}function He(e,n,o){let t;for(;;){let r=A(new TextEncoder().encode(re(e,n)).byteLength);if(r===t)return r;o(r),t=r}}function We(e){return e instanceof TypeError&&e.message.startsWith("Relationship context tokenBudget cannot fit ")}function Xe(e){let{assembly:n,canonicalId:o,contextOptions:t,rootEvidence:r,summaryOnly:i,rendering:s,missingCount:c,missingReferences:d}=e,u=t.edgeLimit??40,l=Math.min(u,d.length),a=t.tokenBudget,p;for(;;){let m=qt(n,o,{...t,...a===void 0?{}:{tokenBudget:a}},r);p??=m.meta.tokenBudget,a??=p;let f=Yt({canonicalId:o,context:m,missingCount:c,missingReferences:d,referenceLimit:l,summaryOnly:i});if(i){if(A(new TextEncoder().encode(re(b(f,!0,s.legacyAliasCounts),s)).byteLength)>p)throw new TypeError("Relationship context tokenBudget cannot fit the rendered summary");return f}if(m.meta.tokenBudget=p,m.meta.usedTokens=He(b(f,!1,s.legacyAliasCounts),s,h=>{m.meta.usedTokens=h}),m.meta.usedTokens<=p)return f;if(l>0){l-=1;continue}let _=a,g=_*p/m.meta.usedTokens;a=Math.min(_-1,Math.max(1,Math.floor(g*.9)))}}function qe(e,n){let o=e.contextOptions,t={...e.rendering.global,outputFormat:e.rendering.format},r=["--pm-path",e.pmRoot,"item","deps",e.canonicalId,"--format","context","--output-format",e.rendering.format,"--token-budget"],i=r.length;r.push(String(n));let s=new Set(["--pm-path","--format","--output-format","--token-budget"]),c={format:"context",tokenBudget:n,kind:o.kinds},d=[["--max-depth","maxDepth",o.maxDepth],["--node-limit","nodeLimit",o.nodeLimit],["--edge-limit","edgeLimit",o.edgeLimit],["--direction","direction",o.direction],["--cursor","cursor",o.cursor],["--output-include","outputInclude",t.outputInclude],["--output-limit","outputLimit",t.outputLimit],["--output-budget","outputBudget",t.outputBudget],["--output-session","outputSession",t.outputSession],["--output-cursor","outputCursor",t.outputCursor]];for(let[a,p,m]of d)m!==void 0&&(r.push(a,String(m)),s.add(a),c[p]=m);for(let a of o.kinds??[])r.push("--kind",a),s.add("--kind");let u=[["--summary","summary",e.summaryOnly],["--full","full",e.rendering.commandOptions.full],["--json","json",t.json],["--lean","lean",t.lean],["--output-row-contract","outputRowContract",t.outputRowContract],["--token-accounting","tokenAccounting",t.tokenAccounting],["--no-extensions","noExtensions",t.noExtensions],["--no-pager","noPager",t.noPager]];for(let[a,p,m]of u)m===!0&&(r.push(a),s.add(a),c[p]=!0);let l=ge.find(a=>a.command==="deps");return Reflect.set(c,me,{canonical_include_modes:[],cli_invocation_observed:!0,explicit_legacy_aliases:Object.values(l.dimensions).flatMap(a=>a.legacy_aliases.flatMap(p=>s.has(p.flag)?[p.flag]:[]))}),he("deps",c),Y(c.summary===!0,c.full===!0,"--summary"),t.outputInclude=c.outputInclude,{args:r,budgetIndex:i,summaryOnly:c.summary===!0,rendering:{...e.rendering,global:t,commandOptionsOverride:c}}}function Qt(e,n,o){let t={...n.rendering,commandOptionsOverride:{...n.rendering.commandOptionsOverride,tokenBudget:o}},r;try{r=Xe({...e,contextOptions:{...e.contextOptions,tokenBudget:o},summaryOnly:n.summaryOnly,rootEvidence:n.summaryOnly?[]:e.rootEvidence,rendering:t})}catch(s){if(!We(s))throw s;return"native_floor"}let i=Ke(b(r,n.summaryOnly,t.legacyAliasCounts),t);return _e(i)?"output_constraints":"fits"}async function Zt(e,n){let o=e.contextOptions.tokenBudget??U,t=qe(e,o),i=(t.summaryOnly?1:1+Math.min(e.contextOptions.edgeLimit??40,e.missingReferences.length))*(e.assembly.details.reduce((p,m)=>p+m.id.length+m.title.length+m.status.length+(m.type?.length??0),e.assembly.graph.edges().length+e.missingReferences.length)+(t.summaryOnly?[]:e.rootEvidence).reduce((p,m)=>p+m.length,0)),{findContextBudgetRecovery:s}=await import("./context-budget-recovery-CSJV3TY3.js"),c=s({requested:o,initialBudget:U,workUnits:i,probe:p=>Qt(e,t,p)}),d=["--pm-path",e.pmRoot,"item","deps",e.canonicalId,"--format","tree","--summary"],u=F(d),l=c.feasible_tokens===null?d:[...t.args];c.feasible_tokens!==null&&(l[t.budgetIndex]=String(c.feasible_tokens));let a=F(l);return Se("Relationship context tokenBudget cannot fit the required rendered packet",{exitCode:x.USAGE,cause:n,context:{code:"invalid_argument_value",field:"tokenBudget",value:String(o),required:c.feasible_tokens===null?"Inspect the compact summary and review the output constraints.":"Retry the preserved context query with --token-budget "+c.feasible_tokens+".",why:"Budget advice is verified against the current query. A minimum is reported only after every smaller positive budget is checked.",examples:[a,u],nextSteps:[a],recovery:{recovery_mode:"compact",suggested_flags:["--token-budget"],token_budget:c,suggested_retry_args:l,suggested_retry:a,next_best_command:u,fallback_candidates:[{source:"relationship_summary",command:u,reason:"Inspect bounded counts separately from context rows."}]}}})}async function en(e){let{pmRoot:n,assembly:o,canonicalId:t,options:r,rootEvidence:i,summaryOnly:s,rendering:c}=e,d=Xt(r,o.graph.registry()),u=o.graph.closure(t,{direction:d.direction,...d.kinds===void 0?{}:{kinds:d.kinds},maxDepth:d.maxDepth??3}),l=u.value.filter(h=>o.missingIdSet.has(h.toLowerCase())),a=new Set(l.map(h=>h.toLowerCase())),p=o.graph.registry(),m=d.kinds?new Set(d.kinds.map(h=>p.require(h).kind)):void 0,f=new Set([t,...u.value]),_=[...o.dangling.active,...o.dangling.legacy_terminal].filter(h=>Jt({row:h,missingReachableSet:a,packetIds:f,filteredKinds:m,registry:p})),g={pmRoot:n,assembly:o,canonicalId:t,contextOptions:d,rootEvidence:i,summaryOnly:s,rendering:c,missingCount:l.length,missingReferences:_};try{return Xe(g)}catch(h){if(h instanceof w&&h.code==="invalid_query_cursor"){let k=qe({...g,contextOptions:{...d,cursor:void 0},rendering:{...c,global:{...c.global,outputCursor:void 0}}},d.tokenBudget??U),y=F(k.args);throw new w(h.message,h.exitCode,{...h.context,nextSteps:[...h.context.nextSteps,y],recovery:{suggested_retry:y,suggested_retry_args:k.args}})}throw We(h)?await Zt(g,h):h}}function tn(e){let n=[e],o;for(;n.length>0;){let t=n.pop();t.dependencies.length>0&&(o=t,n.push(...t.dependencies))}return o?(o.dependencies.pop(),o.truncated=!0,!0):!1}function nn(e,n,o,t,r,i,s){let c=r??At,d=S(o.nodeLimit,"node-limit")??Nt,u=S(o.edgeLimit,"edge-limit")??Mt,l=S(o.tokenBudget,"token-budget")??$t,a={nodeLimit:d,edgeLimit:u,tokenBudget:l,nodes:0,edges:0,estimatedTokens:0,reasons:new Set},p=Ge(e,t,new Set,c,n==="graph"?"repeated":i,new Set,a),m=ze(e,t,void 0),f;for(;;){let _=Wt(p),g=a.reasons.size===0?void 0:{reasons:[...a.reasons].sort(),limits:{max_depth:c,node_limit:d,edge_limit:u,token_budget:l},estimated_tokens:0,total_node_count:m.node_count,total_edge_count:m.edge_count,omitted_node_count:Math.max(0,m.node_count-_.nodes.length),omitted_edge_count:Math.max(0,m.edge_count-_.edges.length)},h={id:e,format:n,node_count:_.nodes.length,edge_count:_.edges.length,edge_basis:"deduplicated_directed",missing_count:_.missing_ids.length,...g?{truncation:g}:{}};if(f=n==="tree"?{...h,tree:p}:{...h,graph:_},(f.truncation===void 0?A(new TextEncoder().encode(re(b(f,!1,s.legacyAliasCounts),s)).byteLength):He(b(f,!1,s.legacyAliasCounts),s,y=>{f.truncation.estimated_tokens=y}))<=l)return f;if(!tn(p))return a.reasons.add("token_budget"),f;a.reasons.add("token_budget")}}function b(e,n,o={}){let t={name:e.format==="tree"?"dependency_tree":e.format==="graph"?"dependency_graph":"relationship_context",restore_with:"--full"},r=e.context?.meta.truncated?[{name:"relationship_context_bounds",restore_with:"--token-budget <n> --node-limit <n> --edge-limit <n> --max-depth <n>"}]:[];return{...e,legacy_alias_counts:o,projection:{mode:n?"summary":"full",declared_field_groups:[t,...r],included_field_groups:n?[]:[t.name]}}}async function ro(e,n,o){let t=ue(process.cwd(),o.path);await Re(t);let r=Bt(n.format),i=Fe(n.maxDepth),s=Pt(n.collapse);Y(n.summary===!0,n.full===!0,"--summary");let c=n.summary===!0,d=await be(t),u=ae(d,z()),l=await Le(t,d.item_format,u.type_to_folder,void 0,d.schema),a=pe(d.schema),p=new Map(l.map(g=>[g.id.trim().toLowerCase(),Gt(g)])),m=Z(l,g=>G(g,a));for(let g of[...m.active,...m.legacy_terminal]){let h=p.get(g.holder_id.trim().toLowerCase()),k=g.kind.trim().toLowerCase();h&&!h.dependencies.some(y=>y.id.trim().toLowerCase()===g.target_id.trim().toLowerCase()&&y.kind===k)&&h.dependencies.push({id:g.target_id,kind:k})}if(!p.has(e.trim().toLowerCase()))throw new w(`Item ${e} not found`,x.NOT_FOUND);let f=o.outputFormat??(o.json===!0||o.json===void 0&&o.defaultOutputFormat==="json"?"json":"toon");if(r==="context"){let g=p.get(e.trim().toLowerCase()).id,h=c?[]:await Vt(t,g,d,u.type_to_folder),k=O=>G(O,a),y=v(),C=Pe().lookup(t,$e(l,k,y),()=>ee(l,k,y));return b(await en({pmRoot:t,assembly:C.assembly,canonicalId:g,options:n,rootEvidence:h,summaryOnly:c,rendering:{format:f,global:o,commandOptions:n,legacyAliasCounts:C.assembly.legacyAliasCounts}}),c,C.assembly.legacyAliasCounts)}let _=Object.fromEntries(Object.entries(ee(l,g=>G(g,a)).legacyAliasCounts));return c?b({id:e,format:r,...ze(e,p,i)},!0,_):b(nn(e,r,n,p,i,s,{format:f,global:o,commandOptions:n,legacyAliasCounts:_}),!1,_)}export{hn as a,_n as b,dt as c,v as d,un as e,H as f,ln as g,st as h,pn as i,$ as j,ut as k,pt as l,Z as m,ft as n,En as o,ee as p,$e as q,te as r,Pe as s,Sn as t,U as u,Ue as v,S as w,Fe as x,Ut as y,jt as z,ro as A};
|
|
2
|
+
//# sourceMappingURL=chunk-YNRW2FWB.js.map
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{b as K}from"./chunk-4SX2BN4V.js";import{a as X,b as R,c as h,d as z}from"./chunk-AIDL2ZNT.js";import{n as H,s as $,u as V,y as q}from"./chunk-
|
|
1
|
+
import{b as K}from"./chunk-4SX2BN4V.js";import{a as X,b as R,c as h,d as z}from"./chunk-AIDL2ZNT.js";import{n as H,s as $,u as V,y as q}from"./chunk-WHHFPATO.js";import{Gc as U,Q as L,W as E,dc as P,y as B}from"./chunk-NSFS3VWP.js";import{u as W}from"./chunk-R6QFPHWW.js";import{A as v,C as S,E as F,F as G,I as N,z as _}from"./chunk-NGFDPEP7.js";import{access as ue,lstat as ee,readFile as T,realpath as w}from"node:fs/promises";import{constants as me}from"node:fs";import{execFile as pe}from"node:child_process";import c from"node:path";import{promisify as de}from"node:util";var ce="PM_SOURCE_CONTEXT_ACCESS",le="PM_ALLOW_SOURCE_CONTEXT_WRITES";function J(e){let n=e[ce],r=n===void 0||n.trim().toLowerCase()==="write"?"write":"read_only",t=r==="read_only"&&e[le]?.trim()==="1";return{access:r,write_override_applied:t,source_writes_allowed:r==="write"||t}}var k=de(pe),C="# pm-cli:merge-drivers:start",fe="# pm-cli:merge-drivers:end",x="# pm-cli:merge-drivers:v2:start",te="# pm-cli:merge-drivers:v2:end",ge="merge-fence",he="merge-attributes";function A(e){return`'${e.replaceAll("'",`'"'"'`)}'`}async function we(e,n){let r=await w(e);if(/(?:^|[\\/])bun-node-[^\\/]+[\\/]bun(?:\.exe)?$/iu.test(r))return;let{stdout:t}=await k(e,["--version"],{encoding:"utf8",windowsHide:!0,timeout:1e4});return t.trim()===n?r:void 0}async function ye(){let e=B(import.meta.url,["../../.."]),n=process.execPath,r=!1,t=await w(process.execPath),o=process.versions.bun,i=(process.env.PATH??"").split(c.delimiter).filter(s=>c.isAbsolute(s)).map(s=>c.join(s,o===void 0?c.basename(process.execPath):process.platform==="win32"?"bun.exe":"bun")),a=o===void 0?i:[process.env.npm_execpath??"",...i,t].filter(s=>c.isAbsolute(s)&&/^(?:bun|bun\.exe)$/iu.test(c.basename(s)));for(let s of a)try{if(await ue(s,me.X_OK),o!==void 0){let u=await we(s,o);if(u!==void 0){n=u,r=!0;break}continue}if(s!==t&&await w(s)===t){n=s;break}}catch{}if(o!==void 0&&!r)throw new v("Cannot install Bun merge drivers without a durable executable matching the current Bun version.",_.DEPENDENCY_FAILED,{code:"merge_bun_launcher_unavailable",why:"The current Bun process may be a temporary bunx launcher that Git cannot reuse after this command exits.",nextSteps:["Run with a durable version-matched Bun executable, expose one on an absolute PATH entry, or invoke pm through a Bun runner that publishes an absolute npm_execpath.","Retry pm merge install, then check pm health --strict-exit before merging branches."]});return`${A(n)} ${A(c.join(e,"dist","cli.js"))}`}var re=[{key:"pm-item-toon",name:"pm field-aware TOON item document merge",artifact:"item",itemPath:"%P"},{key:"pm-item-markdown",name:"pm field-aware JSON-markdown item document merge",artifact:"item",itemPath:"%P"},{key:"pm-history",name:"pm append-only history stream merge",artifact:"history",itemPath:void 0},{key:"pm-relationship",name:"pm append-only relationship event store merge",artifact:"relationship",itemPath:void 0},{key:"pm-json",name:"pm key-level JSON config merge",artifact:"json",itemPath:void 0}];function _e(e){let n=e.explicitPath?.trim(),r=e.environment.PM_SOURCE_WORKSPACE_ROOT?.trim(),t=e.environment.PM_SOURCE_PM_PATH?.trim(),o=J(e.environment),i=!!(r&&t),a=n===void 0&&i&&(e.dryRun||o.source_writes_allowed);if(n!==void 0){let s=E(e.cwd,n);return{pm_root:s,workspace_start:s,source_coordinates_available:i,source_context_selected:!1,source_policy:o}}return a?{pm_root:c.resolve(t),workspace_start:c.resolve(r),source_coordinates_available:!0,source_context_selected:!0,source_policy:o}:{pm_root:i?E(e.cwd,".agents/pm"):E(e.cwd),workspace_start:e.cwd,source_coordinates_available:i,source_context_selected:!1,source_policy:o}}async function O(e){try{let{stdout:n}=await k("git",["rev-parse","--show-toplevel"],{cwd:e,env:h(),encoding:"utf8",windowsHide:!0,timeout:1e4});return await w(R(n))}catch{return null}}async function ne(e){let n=await O(e);if(n===null)throw new v("pm merge install requires a git repository (merge drivers are git configuration).",_.USAGE);return n}function M(e,n){return c.relative(e,n).split(c.sep).join("/")}function Y(e){return e.replace(/[\\*?[\]!]/gu,"\\$&")}function g(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function Q(e,n){if(e[n]!=="'")return null;let r="";for(let t=n+1;t<e.length;t+=1){if(e.startsWith(`'"'"'`,t)){r+="'",t+=4;continue}if(e[t]==="'")return{value:r,nextOffset:t+1};r+=e[t]}return null}async function ve(e,n,r){if(V(n).filter(i=>i.constraint==="exact").some(i=>i.version!==r))return!1;let o=await O(e);if(o!==null&&o!==await w(n)){let i=await Promise.all([o,n].map(async a=>{let s=await k("git",["rev-parse","--path-format=absolute","--git-common-dir"],{cwd:a,env:h(),timeout:1e4});return w(s.stdout.trim())}));if(i[0]===i[1])return!1}return!0}async function be(e,n,r){let t=Q(e,0);if(t===null||e[t.nextOffset]!==" ")return!1;let o=Q(e,t.nextOffset+1);if(o===null||e.slice(o.nextOffset)!==n||!/^(?:node|bun)(?:\.exe)?$/iu.test(c.basename(t.value))||c.basename(o.value)!=="cli.js"||c.basename(c.dirname(o.value))!=="dist"||!await S(t.value)||!await S(o.value))return!1;try{let i=c.dirname(c.dirname(o.value)),a=JSON.parse(await T(c.join(i,"package.json"),"utf8")),s=typeof a.bin=="string"?a.bin:a.bin?.pm;return await ve(i,r,a.version)?a.name==="@unbrained/pm-cli"&&s==="dist/cli.js":!1}catch{return!1}}function I(e,n){let r=e.length>0?`${Y(e)}/`:"",t=[`${g(`${r}**/*.toon`)} merge=pm-item-toon`,`${g(`${r}**/*.md`)} merge=pm-item-markdown`];for(let o of n){let i=Y(o);t.push(`${g(`${r}${i}/*.toon`)} merge=pm-item-toon`),t.push(`${g(`${r}${i}/*.md`)} merge=pm-item-markdown`)}return t.push(`${g(`${r}**/*.jsonl`)} merge=pm-relationship`),t.push(`${g(`${r}history/*.jsonl`)} merge=pm-history`),t.push(`${g(`${r}settings.json`)} merge=pm-json`),t.push(`${g(`${r}**/*.json`)} merge=pm-json`),t.push(`${g(`${r}extensions/**`)} merge=text`),t.push(`${g(`${r}extensions/.managed-extensions.json`)} merge=pm-json`),t}function oe(e){let n=[],r=0;for(;r<e.length;){let t=e.indexOf(C,r),o=e.indexOf(x,r),i=t===-1?o:o===-1?t:Math.min(t,o);if(i===-1)break;let a=i===o,s=a?x:C,u=a?te:fe,p=e.indexOf(u,i+s.length),m=p===-1?e.length:p+u.length;n.push({start:i,end:m,closed:p!==-1,lines:e.slice(i+s.length,p===-1?m:p).split(`
|
|
2
2
|
`).map(l=>l.trim()).filter(Boolean)}),r=m}return n}function ie(e,n,r){let t=new Set(n),o=g(r.length>0?`${r}/`:"").slice(0,-1);return e.some(i=>t.has(i)||i.startsWith(o)&&/^[^/]+\/\*\.(?:toon|md)" merge=pm-item-(?:toon|markdown)$/u.test(i.slice(o.length)))}async function se(e,n,r,t){let o=c.join(e,".gitattributes"),i=t?null:R((await k("git",["rev-parse","--absolute-git-dir"],{cwd:e,env:h(),encoding:"utf8",windowsHide:!0,timeout:1e4})).stdout),a=i===null?null:await P(i,he,120,"merge-fence",!1,!0,5e3);try{let s=await G(o)??"",u=[x,...r,te].join(`
|
|
3
3
|
`),p=oe(s),m=p.filter(d=>ie(d.lines,r,n));m.length===0&&n===".agents/pm"&&p.length===1&&p[0].lines.every(d=>!d.includes("/"))&&m.push(p[0]);let l;if(m.length>0){let d=m[0];l=s;for(let b of m.slice(1).reverse())l=`${l.slice(0,b.start)}${l.slice(b.end)}`;l=`${l.slice(0,d.start)}${u}${l.slice(d.end)}`}else{let d=s.trimEnd();l=`${d.length>0?`${d}
|
|
4
4
|
|
|
5
5
|
`:""}${u}
|
|
6
6
|
`}return l===s&&!(await ee(o)).isSymbolicLink()?{path:o,changed:!1}:(t||await N(o,l),{path:o,changed:!0})}finally{await a?.()}}function ae(e){let n=L(e,null);return[...new Set(Object.values(n.type_to_folder))].sort((r,t)=>r.localeCompare(t))}async function Z(e){try{return await w(e)}catch{return null}}function ke(e,n){let r=c.relative(e,n);return r===""||!c.isAbsolute(r)&&r.split(c.sep)[0]!==".."}async function xe(e){try{return(await ee(e)).isFile()?await T(e,"utf8"):null}catch{return null}}async function Ee(e){try{return await T(e,"utf8")}catch{return null}}async function Pe(e,n){let r=n===void 0?await O(e):n;if(r===null)return{trackerRoot:e,topLevel:null};let[t,o]=await Promise.all([Z(e),Z(r)]);return t===null||o===null||!ke(o,t)?null:{trackerRoot:t,topLevel:o}}async function $e(e){let n=e.topLevel===null?Ee:xe,r=e.trackerRoot;for(let t=0;e.topLevel!==null||t<8;t+=1){let o=await n(c.join(r,".gitattributes"));if(o!==null&&(o.includes(x)||o.includes(C)))return{directory:r,content:o};let i=c.dirname(r);if(i===r||e.topLevel!==null&&c.relative(e.topLevel,r)==="")return null;r=i}return null}async function et(e,n,r={}){let t=await Pe(c.resolve(e),r.gitWorkspaceRoot),o=t===null?null:await $e(t);if(t===null||o===null)return{status:"not_installed",missing_patterns:[],stale_patterns:[],schema_scope:"project"};let i=o.directory,a=o.content,s=c.join(i,".gitattributes"),u=M(i,t.trackerRoot),p=oe(a),m=I(u,n),l=p.filter(y=>ie(y.lines,m,u)),d=l.flatMap(y=>y.closed?y.lines:[]),b=new Set(d),f=new Set(m),j=m.filter(y=>!b.has(y)),D=d.filter(y=>!f.has(y));return{status:l.length!==1||!l[0].closed||j.length>0||D.length>0?"drift":"ok",path:s,missing_patterns:j,stale_patterns:D,schema_scope:"project"}}async function tt(e){let n=[],r=[];for(let t of re){let o=`merge.${t.key}.driver`,i=` merge driver ${t.artifact} "%O" "%A" "%B"${t.itemPath===void 0?"":` --item-path ${t.itemPath}`}`;try{let{stdout:a}=await k("git",["config","--get",o],{cwd:e,env:h(),encoding:"utf8",windowsHide:!0,timeout:1e4}),s=a.trim();await be(s,i,e)||r.push(o)}catch{n.push(o)}}return{status:n.length>0?"missing":r.length>0?"drift":"ok",missing_keys:n,drifted_keys:r}}async function rt(e){let n;try{n=await ne(c.resolve(e))}catch{return{status:"no_git"}}let r=M(n,c.resolve(e)),t=await $(e),o=U(void 0,t.author_default),i=await P(e,ge,t.locks.ttl_seconds,o,!1,H(t).force_required_for_stale_lock,t.locks.wait_ms);try{let a=c.join(n,".gitattributes"),s;try{s=await T(a,"utf8")}catch(l){if(l instanceof Error&&"code"in l&&F(l))return{status:"not_installed",path:a};throw l}if(!s.includes(x)&&!s.includes(C))return{status:"not_installed",path:a};let u=await $(e),p=ae(u),m=await se(n,r,I(r,p),!1);return{status:m.changed?"refreshed":"unchanged",path:m.path}}finally{await i()}}async function nt(e,n){let r=_e({cwd:process.cwd(),explicitPath:n.path,dryRun:e.dryRun===!0,environment:process.env}),t=r.pm_root;await q(t);let o=await ne(r.workspace_start);return Te({pmRoot:t,workspaceRoot:o,dryRun:e.dryRun===!0,preCommitHook:e.preCommitHook===!0})}async function Ce(e,n){let r=(await k("git",["rev-parse","--path-format=absolute","--git-common-dir"],{cwd:e,env:h(),timeout:1e4})).stdout.trim(),t=await P(r,"merge-driver-config",120,"merge-install",!1,!0,5e3);try{let o=await z(e),i;try{i=(await k("git",["config",o,"--null","--get-regexp","."],{cwd:e,env:h(),timeout:1e4})).stdout}catch(s){if(typeof s!="object"||s===null||!("code"in s)||s.code!==1)throw s;i=""}let a=new Map(i.split("\0").filter(Boolean).map(s=>{let u=s.indexOf(`
|
|
7
7
|
`);return[s.slice(0,u),s.slice(u+1)]}));for(let s of n)a.get(s.key)!==s.value&&await X(e,[o,s.key,s.value])}finally{await t()}}async function Te(e){let n=c.resolve(e.pmRoot),r=c.resolve(e.workspaceRoot),t=e.dryRun===!0,o,i;try{[o,i]=await Promise.all([w(n),w(r)])}catch(f){throw new v(`Cannot resolve tracker root ${n} or workspace root ${r}: ${String(f)}`,_.NOT_FOUND,{code:"merge_root_not_found",nextSteps:["Initialize the tracker and ensure both paths are accessible.",'Retry "pm merge install" from the repository workspace.']})}let a=M(i,o);if(K(a))throw new v(`Tracker root ${n} is outside the git repository ${r}; there is nothing to configure for this repository.`,_.USAGE);let s=await $(o),u=ae(s),p=I(a,u),m=[],l=await ye(),d=e.preCommitHook===!0?await import("./settlement-hook-4MGRERCT.js").then(async f=>({plan:await f.prepareMergeSettlementHook(i,`${l} --pm-path ${A(a||".")}`),write:f.writeMergeSettlementHook})):void 0;for(let f of re)m.push({key:`merge.${f.key}.name`,value:f.name}),m.push({key:`merge.${f.key}.driver`,value:`${l} merge driver ${f.artifact} "%O" "%A" "%B"${f.itemPath===void 0?"":` --item-path ${f.itemPath}`}`});if(!t)try{await Ce(i,m)}catch{throw new v(`Cannot install repository-local merge drivers in ${i}. Ensure the repository Git config is writable and no other Git process holds its lock, then retry.`,_.DEPENDENCY_FAILED,{code:"merge_git_config_unwritable",why:"pm merge install must persist clone-local driver commands before publishing their shared .gitattributes mappings.",nextSteps:["Make the repository Git config writable or wait for the process holding its lock to finish.",'Retry "pm merge install"; the operation is idempotent.','Use "pm merge install --dry-run --json" when the workspace is intentionally read-only.']})}let b=await se(i,a,p,t);return d!==void 0&&!t&&await d.write(d.plan),{ok:!0,dry_run:t,workspace_root:i,pm_root:o,gitattributes:{path:b.path,changed:b.changed,patterns:p,schema_scope:"project"},git_config:m,...d===void 0?{}:{settlement_hook:{path:d.plan.path,changed:d.plan.changed}},guidance:["Commit .gitattributes so every branch and collaborator shares the merge mapping.",'git config is per-clone: each collaborator (and each fresh worktree/clone) runs "pm merge install" once.','After merging branches, run "pm merge reconcile --dry-run" to inspect the complete receipt and history repair, then apply "pm merge reconcile"; use --force only after explicitly accepting any discarded values.',"Custom item types registered later refresh this fence automatically (pm schema add-type/remove-type); rerun pm merge install only after out-of-band type-folder edits."],generated_at:W()}}import{execFile as Se}from"node:child_process";import{promisify as Re}from"node:util";var Ae=Re(Se);async function ut(e,n){if(n.length===0)return[];let r;try{let i=Ae("git",["check-ignore","--verbose","-z","--stdin"],{cwd:e,env:h(),timeout:1e4}),a=i.child.stdin;a!==null&&(a.on("error",()=>{i.child.kill()}),a.end(`${n.join("\0")}\0`)),{stdout:r}=await i}catch(i){if(typeof i=="object"&&i!==null&&"code"in i&&i.code===1)return[];throw new v("Git could not verify ignore rules for merge artifacts; no automatic settlement is safe until that check succeeds.",_.CONFLICT,{code:"merge_settlement_review_required",reason:"ignore_check_unavailable",nextSteps:["Check Git configuration and ignore-file readability, then retry pm merge reconcile --stage --dry-run."]})}let t=r.split("\0"),o=[];for(let i=0;i+3<t.length;i+=4){let[a,s,u,p]=t.slice(i,i+4);u.startsWith("!")||o.push({path:p,source:a,line:Number(s),pattern:u})}return o}export{ce as a,le as b,O as c,ae as d,et as e,tt as f,rt as g,nt as h,Te as i,ut as j};
|
|
8
|
-
//# sourceMappingURL=chunk-
|
|
8
|
+
//# sourceMappingURL=chunk-YSZZSV6M.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{f as a,g as b,h as c,i as d,j as e,k as f,l as g,m as h,n as i}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=field-option-collisions-
|
|
1
|
+
import{f as a,g as b,h as c,i as d,j as e,k as f,l as g,m as h,n as i}from"./chunk-RMJKVQYE.js";import"./chunk-GQBWI4KA.js";import"./chunk-BWOVFE5B.js";import"./chunk-R6QFPHWW.js";import"./chunk-OCKKIECS.js";import"./chunk-NGFDPEP7.js";export{i as assertFieldDefinitionOptionsAvailable,h as assertFieldOptionsAvailable,e as describeFieldFlagSpellingDefectLine,f as describeFieldOptionCollision,d as resolveAddFieldFlagSpellingDefects,b as resolveAddFieldOptionCollisions,c as resolveFieldFlagSpellingDefects,a as resolveFieldOptionCollisions,g as scanFieldOptionCollisions};
|
|
2
|
+
//# sourceMappingURL=field-option-collisions-WV6GPYYP.js.map
|
package/dist/cli-bundle/focused-chunks/{item-revision-KYMSQVZE.js → item-revision-RPTXN7WW.js}
RENAMED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as e,b as f,c as g,d as h,e as i,f as j,g as k,h as l,i as m,j as n,k as o,l as p,m as q,n as r,o as s,p as t,q as u,r as v,s as w,t as x,u as y}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=item-revision-
|
|
1
|
+
import{a as e,b as f,c as g,d as h,e as i,f as j,g as k,h as l,i as m,j as n,k as o,l as p,m as q,n as r,o as s,p as t,q as u,r as v,s as w,t as x,u as y}from"./chunk-IWEGGRRD.js";import"./chunk-FW5Q26HA.js";import"./chunk-RFJ3MEFP.js";import"./chunk-3BR5NWQI.js";import"./chunk-BKPUUW5O.js";import"./chunk-VV2QF5IE.js";import"./chunk-WHHFPATO.js";import"./chunk-X6CXWWNB.js";import{Dd as a,Ed as b,Fd as c,Gd as d}from"./chunk-NSFS3VWP.js";import"./chunk-R6QFPHWW.js";import"./chunk-OCKKIECS.js";import"./chunk-NGFDPEP7.js";export{f as ITEM_REVISION_CONFLICT_CHANGE_LIMIT,e as ITEM_REVISION_CONFLICT_CODE,w as assertExpectHashAdmissible,t as bindExpectedItemRevisions,c as bindItemRevisionScope,a as createItemRevisionScope,k as describeItemRevisionChanges,y as dispatchWithExpectedItemRevisions,q as enrichItemRevisionConflict,o as expectHashInvocationRewrittenError,x as expectHashRequiresMutationError,m as isItemRevisionConflict,u as isTrackerRevisionGuarded,l as itemRevisionConflictRowFields,d as itemRevisionScopeReceipt,v as itemRevisionUncheckedWarning,g as normalizeExpectedItemHash,h as parseExpectHashSpecs,i as readItemRevision,j as resolveExpectedItemRevisions,r as runWithBoundItemRevisionScope,b as runWithItemRevisionScope,p as scopeItemRevisionConflict,n as throwFirstItemRevisionConflict,s as withExpectedItemRevisions};
|
|
2
|
+
//# sourceMappingURL=item-revision-RPTXN7WW.js.map
|
package/dist/cli-bundle/focused-chunks/{item-transaction-I4HLVHEJ.js → item-transaction-A6MVNPT7.js}
RENAMED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{B as Le,C as Je,E as Z,H as We,J as Be,K as Ve,M as Ye,N as He,a as Pe,p as H}from"./chunk-C3FEDTSD.js";import"./chunk-PKX2EHE3.js";import"./chunk-IAOKVKWW.js";import{A as V,B as Ge,C as Y,D as qe,y as ze,z as j}from"./chunk-5RBC4WSE.js";import"./chunk-IIP6LZ5E.js";import"./chunk-TQIKDFOD.js";import"./chunk-4LQL4EO6.js";import"./chunk-4SX2BN4V.js";import"./chunk-AIDL2ZNT.js";import"./chunk-YYEWIKNI.js";import"./chunk-BOIMP2AR.js";import"./chunk-SXC2EO3E.js";import"./chunk-K53OIT5J.js";import"./chunk-X4EWD6TL.js";import{T as Ne,W as je}from"./chunk-UWWAVXG4.js";import"./chunk-TRL4JDWX.js";import"./chunk-ZLRRII55.js";import{Ha as Ke}from"./chunk-VMYVN36N.js";import"./chunk-WL2R7T5G.js";import"./chunk-BYQK5DGH.js";import{H as W}from"./chunk-3Y5PTQ2F.js";import{ra as _e,xa as Se}from"./chunk-A4R57E4K.js";import"./chunk-JOKRDFMQ.js";import"./chunk-VU2PH4PF.js";import"./chunk-BKPUUW5O.js";import{L as xe,R as De,b as ye,l as B}from"./chunk-7SSGTGZO.js";import{i as Ue,m as Fe,s as N}from"./chunk-MB56Y4M6.js";import"./chunk-BWOVFE5B.js";import"./chunk-X6CXWWNB.js";import{Cd as T,Hc as ke,Lc as M,Mb as ve,Q as K,Tb as Ae,Ub as $e,Vb as J,X as ge,fc as Te,ie as Ie,je as k,oe as Me,pe as Ce,sd as C,xd as Re}from"./chunk-XKLBTDJ7.js";import{c as E}from"./chunk-WVA5KOXF.js";import{F as Ee,J as L,K as Oe,N as be}from"./chunk-OCKKIECS.js";import{A as p,E as q,G as we,H as $,l as le,q as A,s as me,x as he,z as l}from"./chunk-NGFDPEP7.js";import oe from"node:crypto";import{constants as te,readFileSync as It}from"node:fs";import{cp as Mt,lstat as it,mkdir as Ct,mkdtemp as ot,open as Nt,readdir as jt,realpath as st,rm as at,stat as se,writeFile as ct}from"node:fs/promises";import{tmpdir as dt}from"node:os";import u from"node:path";var Et=new Set(["id","title","description","type","status","priority","tags","body","deadline","estimated_minutes","acceptance_criteria","definition_of_ready","order","rank","assignee",...le,"affected_version","fixed_version","component","regression","customer_impact","close_reason","completed_at","dependencies","comments","notes","learnings","files","tests","docs","reminders","events","type_options"]);function X(e,t,n){let r=e?.estimatedMinutes;if(!(r===void 0||typeof r=="string"))throw new p(`Mutation ${n+1} ${t} option "estimatedMinutes" must be a string.`,l.USAGE,{code:"mutation_option_value_invalid",required:'Pass estimatedMinutes as a string, for example "45", in raw mutation options.',why:"Raw options use the create/update command option types; item documents accept numeric estimated_minutes instead.",nextSteps:["Quote the estimatedMinutes value or use an item document with numeric estimated_minutes, then retry the transaction."]})}var Ot=["op","id","reason","options","unique","match"],bt=[...Ot,"ref"],xn=[...bt,"item"];var Xe="[a-z][a-z0-9._-]{0,63}",Dn=new RegExp(`^${Xe}$`,"u"),Pn=new RegExp(`(^|,)id=@(${Xe})(?=,|$)`,"gu"),Ze=e=>e.slice(2).replaceAll(/-([a-z])/gu,(t,n)=>n.toUpperCase());var vt=new Set(["created_at","updated_at","closed_at","version","format_version","path","author","collection_counts","notes_count","tests_count","pm_format_version","claim_principal","test_runs","deferred_fields"]),zn=new Set([...vt,"completed_at","id"]),Gn={create:Ne.map(e=>e.target),update:je.map(e=>e.target),close:_e.map(e=>Ze(e.flag)).filter(e=>e!=="reason"),release:Se.map(e=>Ze(e.flag))};function At(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function $t(e,t){return e<t?-1:+(e!==t)}function Q(e){return Array.isArray(e)?e.map(Q):At(e)?Object.fromEntries(Object.entries(e).sort(([t],[n])=>$t(t,n)).map(([t,n])=>[t,Q(n)])):e}function O(e){return typeof e=="string"?e.trim():JSON.stringify(Q(e))}var Tt=["id","updated_at","pm_format_version","type"],kt="import";function Qe(e,t){if(typeof e!="string"||!/^[A-Za-z][A-Za-z0-9_]*$/u.test(e)||e in Object.prototype)throw new TypeError(`${t} names an invalid field ${JSON.stringify(e)}; use a front-matter field name of letters, digits and underscores`);if(Tt.includes(e))throw new TypeError(`${t} cannot change "${e}"; the item writer derives it, or an update row owns it`)}function U(e){return Array.isArray(e)?`array of ${e.length}`:typeof e}var Rt=["__proto__","constructor","prototype"];function et(e){return e!==null&&typeof e=="object"&&Object.getPrototypeOf(e)===Object.prototype}function R(e){return e===null||typeof e=="string"||typeof e=="boolean"?!0:typeof e=="number"?Number.isFinite(e):Array.isArray(e)?Array.from(e).every(R):et(e)?Object.entries(e).every(([t,n])=>!Rt.includes(t)&&R(n)):!1}function ee(e,t){let{set:n,unset:r}=e;if(n!==void 0&&!et(n))throw new TypeError(`${t} set must be a plain object of front-matter fields`);if(r!==void 0&&!Array.isArray(r))throw new TypeError(`${t} unset must be an array of front-matter field names`);let i=Object.keys(n??{}),s=r??[];if(i.length+s.length===0)throw new TypeError(`${t} requires at least one field in set or unset`);for(let o of i)if(Qe(o,t),n[o]===null||!R(n[o]))throw new TypeError(`${t} set "${o}" must be a non-null JSON value (no undefined, non-finite number, sparse array, class instance, or __proto__/constructor/prototype key); remove a field with unset`);for(let o of s){if(Qe(o,t),o==="body"||o==="front_matter")throw new TypeError(`${t} cannot unset "${o}"; the item format reserves that name`);if(i.includes(o))throw new TypeError(`${t} both sets and unsets "${o}"`)}if(new Set(s).size!==s.length)throw new TypeError(`${t} unset repeats a field`)}async function tt(e){ee(e,`Finalization of ${e.id}`);let t=await N(e.pmRoot),n={schema:t.schema,extensionFieldNames:ye(k())},r=await De({pmRoot:e.pmRoot,settings:t,id:e.id,op:kt,author:e.author,message:e.message,force:e.force===!0,extensionFieldNames:n.extensionFieldNames,mutate:i=>{let s=structuredClone(i.metadata),o=i.metadata;for(let[c,f]of Object.entries(e.set??{}))o[c]=structuredClone(f);for(let c of e.unset??[])delete o[c];let a;try{ve(i.metadata);let c=J(i,n),f=J(Ae($e(c,n),n),n);if(E(f)!==E(c))throw new TypeError("the stored item reads back as a different document; a set field collides with a name the item format reserves");a=c.metadata;let h=Object.entries(e.set??{}).find(([m,w])=>U(a[m])!==U(w));if(h!==void 0)throw new TypeError(`set "${h[0]}" is not stored as declared (${U(h[1])} normalizes to ${a[h[0]]===void 0?"an absent field":U(a[h[0]])})`)}catch(c){throw new p(`Finalization of ${e.id} would not store a readable item with the declared fields: ${c.message}`,l.USAGE,{code:"finalization_invalid_document",item_id:e.id,required:"Declare set and unset fields that leave a valid item under the workspace schema, with each set value in the shape its field stores.",why:"A finalization writes front-matter fields exactly, so the patched document is read back through the item reader, and each declared value is checked against what would be stored, before anything is written.",nextSteps:[`Run pm get ${e.id} --json to compare the current fields with the finalization, then correct the patch and retry the transaction.`]})}return{changedFields:[...new Set([...Object.keys(s),...Object.keys(a)])].filter(c=>Object.hasOwn(s,c)!==Object.hasOwn(a,c)||E(s[c])!==E(a[c])).sort((c,f)=>c.localeCompare(f))}}});return{item:r.item,changedFields:r.changedFields}}async function Ut(e,t){if(!Fe(e))return{schema:L(t.schema),typeDefinitionsFromFile:[]};let n=await Ht(e,t.schema);return{schema:n.schema,typeDefinitionsFromFile:n.type_definitions_from_file??[]}}async function Ft(e,t,n,r){let i=K({...t,item_types:{...t.item_types,definitions:[...t.item_types?.definitions??[],...n.typeDefinitionsFromFile]}},k());return(await xe(e,t.item_format,i.type_to_folder,void 0,n.schema)).flatMap(o=>{let a=o[r];return a==null?[]:[{id:o.id,value:a}]})}function ae(e){let t=new Map,n=async r=>{let i=await N(e),s=await Ut(e,i),o=new Map;for(let a of await Ft(e,i,s,r)){let d=O(a.value);o.set(d,[...o.get(d)??[],a.id])}return o};return{lookup(r){let i=t.get(r)??n(r);return t.set(r,i),i},async recordCreate(r){for(let[i,s]of t){let o=r[i];if(o==null)continue;let a=await s,d=O(o);a.set(d,[...a.get(d)??[],String(r.id)])}},invalidate(){t.clear()}}}async function xt(e,t){let n=O(t.value),r=(await e.lookup(t.key)).get(n)??[];if(r.length!==0)throw new p(`Upsert key "${t.key}" value ${JSON.stringify(n)} now matches existing item ${r.join(", ")}; the plan was resolved before it existed.`,l.CONFLICT,{code:"upsert_key_conflict",required:"Re-plan the document so the row updates the existing item instead of creating a duplicate.",why:"Keyed upsert is resolved before the writer lock, so every remaining create is re-checked under the lock; concurrent imports therefore cannot create two items for one key value.",nextSteps:["Re-run pm item mutate with the same document and --upsert-key; the re-plan turns the row into an update of the existing item.","Inspect the existing item first when its content should win over the document row."]})}function ut(e,t,n){let r=e.metadata[n.key],i=O(n.value);if(O(r)!==i)throw new p(`Item ${t} no longer carries upsert key "${n.key}" value ${JSON.stringify(i)}; the plan selected it before the key changed.`,l.CONFLICT,{code:"upsert_match_changed",required:"Re-plan the document so the row is resolved against the current key values.",why:"Keyed upsert selects its target before the writer lock, so the update re-reads the key under the lock instead of updating a mismatched item blindly.",nextSteps:["Re-run pm item mutate with the same document and --upsert-key; the re-plan creates or re-targets the row from the current key values."]})}function nt(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.key=="string"&&t.key.trim().length>0&&t.value!==void 0&&t.value!==null}function P(e,t){let n={...e,...t};return e===void 0?n:W(e,n)}async function _(e,t){try{let r=(await H(t,{},{pmRoot:e})).item;return{id:r.id,closedAt:r.closed_at,updatedAt:r.updated_at,assignee:r.assignee,claimPrincipal:r.claim_principal}}catch(n){if(n instanceof p&&n.exitCode===l.NOT_FOUND)return;throw n}}function ce(e,t){let n=e.id.replaceAll(/[^a-zA-Z0-9._-]/gu,"_"),r=oe.createHash("sha256").update(E(e)).digest("hex").slice(0,12);return`${t+1}-${e.op}-${n}-${r}`}function Dt(e,t){let n=e.id.replaceAll(/[^a-zA-Z0-9._-]/gu,"_");return`${t+1}-${e.op}-${n}`}function y(e,t,n){return`bulk-item-transaction ${e} ${t} ${n}`}function de(e,t){return e===t||(e?.startsWith(`${t} | `)??!1)}async function v(e,t,n,r){let i=await M(u.join(e,"history",`${t}.jsonl`),t),s=y(n,r,"apply"),o=y(n,r,"compensate");for(let a=i.length-1;a>=0;a-=1){let d=i[a].message;if(de(d,s))return!0;if(d===o)return!1}return!1}async function z(e,t){let n=await _(e,t.id);if(n?.updatedAt===void 0)throw new p(`Bulk ${t.op} target ${t.id} does not exist or has no restorable version`,l.NOT_FOUND);let r=await M(u.join(e,"history",`${n.id}.jsonl`),n.id);if(r.length===0)throw new p(`Bulk ${t.op} target ${t.id} has no restorable history`,l.NOT_FOUND);return{target_updated_at:n.updatedAt,target_version:String(B(r)+r.length),target_history_hash:C(r),target_history_length:r.length}}function b(e,t,n){return new p(`Transaction ${e.transactionId} cannot safely compensate incomplete step ${n}; review item ${t} history before recovery.`,l.CONFLICT,{code:"transaction_partial_mutation",item_id:t,required:"Reconcile the item's partial or intervening changes before resuming this transaction.",why:"The retained history does not prove exclusive ownership of the changes to undo. The journal remains compensating instead of claiming a rollback or overwriting another writer.",nextSteps:[`Run pm history ${t} and inspect this transaction's retained compensation data before explicitly restoring or reconciling the item.`]})}function ft(e,t){let n=`bulk-item-transaction ${t} `;return[e.message,e.context?.item_transaction_step].some(r=>typeof r=="string"&&r.startsWith(n))}function Pt(e,t,n){let{expectedHistory:r,length:i,version:s}=t;if(C(e)===r)return!1;if(typeof i!="number"||!Number.isSafeInteger(i)||i<1||C(e.slice(0,i))!==r||s!==String(B(e)+i))throw b(n,n.itemId,n.stepId);let o=y(n.transactionId,n.stepId,"apply"),a=e.slice(i),d=m=>de(m.message,o)||m.context?.item_transaction_step===o,c=y(n.transactionId,n.stepId,"compensate");if(a.filter(m=>d(m)||m.message===c).at(-1)?.message===c)return!1;let f=a.filter(d);if(f.length===0)return!1;let h=e.at(-1).after_hash===f.at(-1).after_hash&&a.every(m=>ft(m,n.transactionId));if(f.length!==a.length&&!h)throw b(n,n.itemId,n.stepId);return!0}async function pt(e,t){let n=u.join(e,"history",`${t}.jsonl`),r=await ke(n,t);return{history:r.entries,assertOwnedUnderLock:(i,s)=>{let o;try{o=It(n).equals(r.raw_bytes)&&Re(i)===r.entries.at(-1).after_hash}catch(a){throw Object.assign(s(),{cause:a})}if(!o)throw s()}}}async function I(e,t,n,r){let i=r!==null&&typeof r=="object"&&!Array.isArray(r)?r:void 0;if(i===void 0||typeof i.target_updated_at!="string")return;let s=i.target_updated_at,o=await _(e.pmRoot,t);if(o===void 0)return;let{history:a,assertOwnedUnderLock:d}=await pt(e.pmRoot,o.id),c=i.target_history_hash,f=typeof c=="string";if(typeof c=="string"){if(!Pt(a,{expectedHistory:c,length:i.target_history_length,version:i.target_version},{...e,itemId:o.id,stepId:n}))return}else{if(o.updatedAt===s)return;if(!await v(e.pmRoot,o.id,e.transactionId,n))throw b(e,o.id,n)}let h=()=>Ve(t,typeof i.target_version=="string"?i.target_version:s,{force:!0,author:e.author,message:y(e.transactionId,n,"compensate")},{pmRoot:e.pmRoot});await T({pmRoot:e.pmRoot,id:o.id,validate:m=>{d(m,()=>b(e,o.id,n))},compensation:mt(e,t,n,"restore",f)},h)}var lt=new WeakMap;function mt(e,t,n,r,i){let s=i?ze(e.pmRoot,e.transactionId):void 0,o=s===void 0?void 0:lt.get(s);if(!(o?.stepId!==n||o.itemId!==t||o.operation!==r))return{transaction_id:e.transactionId,step_id:n,operations:[r],overrides:[]}}function ht(e,t,n){return{id:n,async inspect(){let r=await _(e.pmRoot,t.id);if(r===void 0)return{state:"pending"};if(r.closedAt!==void 0){let i=await M(u.join(e.pmRoot,"history",`${r.id}.jsonl`),r.id),s=`Compensated: interrupted bulk transaction ${e.transactionId}`;if(i.filter(d=>d.op==="close").at(-1)?.patch.some(d=>d.op==="add"||d.op==="replace"?d.path==="/metadata/close_reason"&&d.value===s:!1)??!1)throw new p(`Created item ${r.id} remains closed by transaction compensation; explicitly reopen or reconcile it before retrying.`,l.CONFLICT,{code:"transaction_create_compensated",item_id:r.id,required:"Review the compensated item and explicitly reopen it before retrying the same document.",why:"This item's latest closure belongs to transaction compensation. Automatically reopening it could overwrite later lifecycle decisions.",nextSteps:[`Run pm item reopen ${r.id} "Retry compensated creation" after reviewing its history, then retry the transaction.`]})}return{state:"applied",result:{id:r.id,op:"create"}}},async apply(){t.unique!==void 0&&await xt(e.uniqueIndex,t.unique);let r=await Le(P(t.options,{author:e.author,id:t.id,message:y(e.transactionId,n,"apply")}),{pmRoot:e.pmRoot}),i=r.item;return e.onCreateWarnings?.(String(i.id),r.warnings),await e.uniqueIndex.recordCreate(i),{id:String(i.id),op:"create"}},async compensate(){await zt(e,t.id,n)}}}async function zt(e,t,n){let r=await _(e.pmRoot,t);if(r===void 0||e.createCompensation==="close"&&r.closedAt!==void 0)return;let{history:i,assertOwnedUnderLock:s}=await pt(e.pmRoot,r.id),o=y(e.transactionId,n,"apply"),a=y(e.transactionId,n,"compensate"),d=i.filter(c=>de(c.message,o)||c.message===a).at(-1);if(d?.message!==a){if(d===void 0||!i.every(c=>ft(c,e.transactionId)))throw b(e,r.id,n);await T({pmRoot:e.pmRoot,id:r.id,validate:c=>{s(c,()=>b(e,r.id,n))},compensation:mt(e,t,n,e.createCompensation==="delete"?"delete":"close",!0)},async()=>{let c={force:!0,author:e.author,message:a};e.createCompensation==="delete"?await Be(t,c,{pmRoot:e.pmRoot}):await Z(t,`Compensated: interrupted bulk transaction ${e.transactionId}`,{...c,validateClose:"off"},{pmRoot:e.pmRoot})})}}function Gt(e,t,n){return{id:n,compensatePending:!0,async inspect(){let r=await _(e.pmRoot,t.id);return r===void 0?{state:"pending"}:await v(e.pmRoot,r.id,e.transactionId,n)?{state:"applied",result:{id:r.id,op:"update"}}:{state:"pending"}},async prepareCompensation(){return z(e.pmRoot,t)},async apply(){let r=()=>Je(t.id,P(t.options,{author:e.author,message:y(e.transactionId,n,"apply")}),{pmRoot:e.pmRoot}),i=t.match,s=i,a=(await T({pmRoot:e.pmRoot,id:await yt(e.pmRoot,t.id),validate:d=>{s!==void 0&&ut(d,t.id,s)},committed:d=>{i!==void 0&&(s={key:i.key,value:structuredClone(d.metadata[i.key])})},historyContext:{item_transaction_step:y(e.transactionId,n,"apply")}},r)).item;return e.uniqueIndex.invalidate(),{id:String(a.id),op:"update"}},async compensate(r){await I(e,t.id,n,r)}}}async function yt(e,t){return String((await H(t,{},{pmRoot:e})).item.id)}function qt(e,t,n){let r=y(e.transactionId,n,"apply");return{id:n,compensatePending:!0,async inspect(){let i=await _(e.pmRoot,t.id);return i===void 0||!await v(e.pmRoot,i.id,e.transactionId,n)?{state:"pending"}:{state:"applied",result:{id:i.id,op:t.op}}},async prepareCompensation(){return z(e.pmRoot,t)},async apply(){let i=await yt(e.pmRoot,t.id),{match:s}=t;return await He(e.pmRoot,()=>T({pmRoot:e.pmRoot,id:i,validate:o=>{s!==void 0&&ut(o,t.id,s)},historyContext:{item_transaction_step:r}},()=>tt({pmRoot:e.pmRoot,id:i,author:e.author,message:r,force:t.force,...t.set===void 0?{}:{set:t.set},...t.unset===void 0?{}:{unset:t.unset}}))),e.uniqueIndex.invalidate(),{id:i,op:t.op}},async compensate(i){await I(e,t.id,n,i)}}}function Kt(e,t,n){return{id:n,async inspect(){let r=await _(e.pmRoot,t.id);return r===void 0?{state:"pending"}:await v(e.pmRoot,r.id,e.transactionId,n)?{state:"applied",result:{id:r.id,op:"close"}}:r.closedAt===void 0?{state:"pending"}:{state:"applied",result:{id:r.id,op:"close"}}},async prepareCompensation(){return z(e.pmRoot,t)},async apply(){let i=(await Z(t.id,t.reason,P(t.options,{author:e.author,message:y(e.transactionId,n,"apply")}),{pmRoot:e.pmRoot})).item;return e.uniqueIndex.invalidate(),{id:String(i.id),op:"close"}},async compensate(r){await I(e,t.id,n,r)}}}function Lt(e,t,n){return{id:n,async inspect(){let r=await _(e.pmRoot,t.id);return r===void 0?{state:"pending"}:await v(e.pmRoot,r.id,e.transactionId,n)?{state:"applied",result:{id:r.id,op:"release"}}:r.assignee!==void 0||r.claimPrincipal!==void 0?{state:"pending"}:{state:"applied",result:{id:r.id,op:"release"}}},async prepareCompensation(){return z(e.pmRoot,t)},async apply(){let i=(await We(t.id,P(t.options,{author:e.author,message:y(e.transactionId,n,"apply")}),{pmRoot:e.pmRoot})).item;return e.uniqueIndex.invalidate(),{id:String(i.id),op:"release"}},async compensate(r){await I(e,t.id,n,r)}}}function ue(e,t,n){let r=ce(t,n),i=Jt(e,t,r);return lt.set(i,{transactionId:e.transactionId,stepId:r,itemId:t.id,operation:t.op!=="create"?"restore":e.createCompensation==="delete"?"delete":"close"}),i}function Jt(e,t,n){switch(t.op){case"create":return ht(e,t,n);case"update":return Gt(e,t,n);case"close":return Kt(e,t,n);case"release":return Lt(e,t,n);case"finalize":return qt(e,t,n)}}function Wt(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError(`Bulk mutation ${t+1} must be an object`);if(!["create","update","close","release","finalize"].includes(e.op))throw new TypeError(`Bulk mutation ${t+1} op must be create, update, close, release, or finalize`);if(typeof e.id!="string"||e.id.trim().length===0)throw new TypeError(`Bulk mutation ${t+1} requires a non-empty id`);if(e.op==="close"&&(typeof e.reason!="string"||e.reason.trim().length===0))throw new TypeError(`Bulk close mutation ${t+1} requires a non-empty reason`);if(Bt(e,t),e.op==="finalize"){Vt(e,t);return}X(e.options,e.op,t)}function Bt(e,t){if(e.op==="create"&&e.unique!==void 0&&!nt(e.unique))throw new TypeError(`Bulk create mutation ${t+1} unique must be an object with a non-empty key and a value`);if((e.op==="update"||e.op==="finalize")&&e.match!==void 0&&!nt(e.match))throw new TypeError(`Bulk ${e.op} mutation ${t+1} match must be an object with a non-empty key and a value`)}var rt=["op","id","set","unset","match","force"];function Vt(e,t){let n=`Bulk finalize mutation ${t+1}`,r=Object.keys(e).filter(i=>!rt.includes(i));if(r.length>0)throw new TypeError(`${n} has unsupported keys: ${r.join(", ")}; a finalization carries only ${rt.join(", ")}`);if(e.force!==void 0&&typeof e.force!="boolean")throw new TypeError(`${n} force must be a boolean`);if(e.match!==void 0&&!R(e.match))throw new TypeError(`${n} match must be a plain object with a JSON value`);ee(e,n)}function ie(e){if(e.length===0)throw new TypeError("Bulk item transaction requires at least one mutation");let t=new Map;for(let[n,r]of e.entries()){if(Wt(r,n),r.op!=="create"||r.unique===void 0)continue;let{key:i,value:s}=r.unique,o=t.get(i)??new Map,a=O(s),d=o.get(a);if(d!==void 0)throw new p(`Bulk create mutations ${d+1} and ${n+1} share the upsert key value ${JSON.stringify(a)} for "${i}".`,l.USAGE,{code:"upsert_key_duplicate",required:"Each create must carry a distinct unique key value within one batch.",why:"Direct SDK batches must preserve the same uniqueness invariant as planned document rows."});o.set(a,n),t.set(i,o)}}function wt(e){let t=[...e];ie(t);let n=t.map(r=>{let i=structuredClone(r);return r.op!=="finalize"&&i.op!=="finalize"&&r.options!==void 0&&i.options!==void 0&&W(r.options,i.options),i});return ie(n),n}function gt(e,t=""){return e===null||typeof e!="object"?[]:Object.entries(e).flatMap(([n,r])=>{let i=`${t}/${n.replaceAll("~","~0").replaceAll("/","~1")}`;return/^(created_at|updated_at|closed_at|completed_at|timestamp)$/u.test(n)?[i]:gt(r,i)})}async function ne(e,t,n){try{return await n()}catch(r){throw r instanceof p?new p(r.message,r.exitCode,{...r.context,transaction_operation:{index:t,op:e.op,id:e.id}}):r}}function _t(e,t,n,r){let i=u.relative(e,t),s=i.split(u.sep);return s[0]==="extensions"&&s[2]==="node_modules"&&!r.some(o=>i===o||i.startsWith(`${o}${u.sep}`)||o.startsWith(`${i}${u.sep}`))?!1:["locks","runtime","search"].includes(i.split(u.sep)[0])?r.some(o=>i===o||i.startsWith(`${o}${u.sep}`)||o.startsWith(`${i}${u.sep}`)):i===""||n===void 0||n.some(o=>i===o||i.startsWith(`${o}${u.sep}`)||o.startsWith(`${i}${u.sep}`))}async function x(e,t){let n=await it(t);if(n.isSymbolicLink())await se(t);else if(n.isDirectory()||n.isFile())return n;throw $(u.relative(e,t))}async function Yt(e,t){let n=await Nt(t,te.O_RDONLY|te.O_NOFOLLOW|te.O_NONBLOCK);try{let r=await n.stat();if(!r.isFile())throw $(u.relative(e,t));let i=oe.createHash("sha256");if(r.size>0)for await(let s of n.createReadStream({highWaterMark:64*1024,end:r.size-1,autoClose:!1}))i.update(s);return i.digest()}finally{await n.close()}}async function re(e,t,n){let r=oe.createHash("sha256");async function i(s){for(let o of(await jt(s)).sort()){let a=u.join(s,o);_t(e,a,t,n)&&((await x(e,a)).isDirectory()?await i(a):(r.update(JSON.stringify(u.relative(e,a))),r.update(await Yt(e,a))))}}return await i(e),r.digest("hex")}function F(){return new p("Tracker changed while preparing the transaction preview; retry against stable state.",l.CONFLICT,{code:"transaction_preview_snapshot_changed"})}async function fe(e){if(!q(e))return!1;let t=e.path;if(typeof t!="string")return!1;let n=u.resolve(t),r=n;for(;;)try{let i=await it(r);return r!==n&&i.isDirectory()}catch(i){if(!q(i))return!1;let s=u.dirname(r);if(s===r)return!1;r=s}}async function D(e,t){let n=u.join(e,t);try{let r=e;for(let i of t.split(u.sep).slice(0,-1))r=u.join(r,i),await x(e,r);if(!(await x(e,n)).isFile())throw $(t);return await we(n,$(t))}catch(r){if(await fe(r))return;throw r}}async function St(e,t,n,r){let i=L(n);for(let[s,o]of Object.entries(i.files)){let a=u.relative(e,Oe(e,o,Ee[s]));if(a===""||!u.resolve(e,a).startsWith(u.join(e,u.sep)))throw new p("Transaction preview requires schema files inside the selected tracker root; relocate the configured schema file before retrying.",l.USAGE,{code:"transaction_preview_external_schema",field:`schema.files.${s}`});i.files[s]=a;let d=await D(e,a);if(r?.set(a,d),d!==void 0){let c=u.join(t,a);await Ct(u.dirname(c),{recursive:!0}),await ct(c,d)}}return be(t,i)}async function Ht(e,t){await se(e);let n=await ot(u.join(dt(),"pm-schema-plan-"));try{let r=await st(e);return await St(r,u.join(n,"configuration"),t)}catch(r){throw await fe(r)?F():r}finally{await at(n,{recursive:!0,force:!0})}}async function Zt(e,t,n){let r=new Map,i=await D(e,A);r.set(A,i);let s;try{s=JSON.parse(i??"null")}catch{s=null}let o=Ue(s),a=o.success?o.data:void 0,d=await St(e,t,a?.schema,r),c=d.schema,f=u.relative(e,Te(e));r.set(f,await D(e,f));let h=K({...he,item_types:{definitions:[...a?.item_types?.definitions??[],...d.type_definitions_from_file??[]]}},n),m=ge(e)===e?[...me.filter(Boolean),A,Pe,"transactions",...h.folders,...r.keys()].map(g=>u.normalize(g)):void 0,w=a===void 0?void 0:JSON.stringify({...s,schema:{...a.schema,files:c.files}});return{configuration:r,ownedPaths:m,stagedSettings:w,registryFolders:h.folders}}async function Xt(e,t,n){await se(e);try{let r=await st(e),i=await Zt(r,u.join(u.dirname(t),"configuration"),n),s=[...i.configuration.keys(),...i.registryFolders].map(c=>u.normalize(c)),o=await re(r,i.ownedPaths,s);await Mt(r,t,{recursive:!0,dereference:!1,filter:async c=>_t(r,c,i.ownedPaths,s)?(await x(r,c),!0):!1});let[a,d]=await Promise.all([re(r,i.ownedPaths,s),re(t,i.ownedPaths,s)]);if(o!==a||o!==d)throw F();for(let[c,f]of i.configuration)if(await D(t,c)!==f)throw F();i.stagedSettings!==void 0&&await ct(u.join(t,A),i.stagedSettings)}catch(r){throw await fe(r)?F():r}}async function Ir(e){let t=j(e),n=wt(e.mutations),r=k(),i=Ce(),s=await ot(u.join(dt(),"pm-transaction-preview-")),o=u.join(s,"tracker");try{await Xt(t.pmRoot,o,r);let a=!1,d=[],c=[],f=new Set;return await Me(i,()=>Ye({path:o,noExtensions:!0},async()=>{Ie(r);let h={...t,pmRoot:o,createCompensation:"close",uniqueIndex:ae(o)},m=n.map((w,g)=>{let S=ue({...h,onCreateWarnings:(G,pe)=>{pe.length>0&&d.push({index:g,id:G,op:"create",warnings:pe})}},w,g);return{...S,inspect:()=>ne(w,g,()=>S.inspect()),prepareCompensation:()=>ne(w,g,async()=>S.prepareCompensation?.()),apply:()=>ne(w,g,async()=>{let G=await S.apply();return f.add(g),G})}});if(await V({...t,pmRoot:o,steps:m,onTransition:({transition:w})=>{w==="committed"&&(a=!0)}}),a)for(let[w,g]of n.entries()){let S=(await Ke(g.id,{path:o},{full:!0})).item;c.push({index:w,id:String(S.id),op:g.op,execution:f.has(w)?"applied":"adopted",item:S,commit_time_fields:gt(S)})}})),{records:c,validated:a,state:a?"staged_snapshot":"replayed_committed_plan",warnings:d,unresolved_commit_constraints:["concurrent_tracker_changes","extension_write_hooks","derived_extension_dependencies_excluded","generated_timestamps_and_provenance"]}}finally{await at(s,{recursive:!0,force:!0})}}async function Qt(e){let t=j(e),n=wt(e.mutations),r=e.createCompensation??"close";if(!["close","delete"].includes(r))throw new TypeError("Bulk item transaction createCompensation must be close or delete");let i={...t,createCompensation:r,uniqueIndex:ae(t.pmRoot)},s=await V({...t,steps:n.map((a,d)=>ue(i,a,d)),recoveryData:JSON.parse(JSON.stringify({kind:"item-mutations-v1",mutations:n,createCompensation:r})),...e.lockTtlSeconds===void 0?{}:{lockTtlSeconds:e.lockTtlSeconds},...e.lockWaitMs===void 0?{}:{lockWaitMs:e.lockWaitMs},...e.onTransition===void 0?{}:{onTransition:e.onTransition}}),o={};for(let[a,d]of n.entries()){let c=ce(d,a),f=s.results[c];o[Dt(d,a)]=f}return{transactionId:s.transactionId,status:"committed",recovered:s.recovered,results:o}}function en(e){let t=[];return e.evidence!==void 0&&Object.keys(e.evidence).length>0&&t.push({op:"update",id:e.id,options:e.evidence}),t.push({op:"close",id:e.id,reason:e.reason,...e.closeOptions===void 0?{}:{options:e.closeOptions}},{op:"release",id:e.id,...e.releaseOptions===void 0?{}:{options:e.releaseOptions}}),t}function Mr(e){return Qt({pmRoot:e.pmRoot,transactionId:e.transactionId,author:e.author,mutations:en(e),...e.lockTtlSeconds===void 0?{}:{lockTtlSeconds:e.lockTtlSeconds},...e.lockWaitMs===void 0?{}:{lockWaitMs:e.lockWaitMs},...e.onTransition===void 0?{}:{onTransition:e.onTransition}})}var Cr={buildCreateStep:ht,bulkHistoryMarker:y,compensateByRestore:I,deriveStepId:ce,isUpdateMarkerApplied:v,readItemSnapshot:_};async function Nr(e,t){let n=await Ge(e,t);return n===void 0?void 0:{journal:n,planDigest:Y(n)}}function tn(e,t){let n=t.recoveryData;if(n===null||typeof n!="object"||Array.isArray(n)||n.kind!=="item-mutations-v1"||!Array.isArray(n.mutations)||!["close","delete"].includes(String(n.createCompensation)))throw new p("Transaction has no supported item recovery plan",l.CONFLICT,{code:"transaction_recovery_plan_missing",required:"Resume with the original plan and its original adapter.",why:"Legacy or foreign journals cannot safely reconstruct item compensation."});let r=n.mutations;ie(r);let i={...e,createCompensation:n.createCompensation,uniqueIndex:ae(e.pmRoot)};return r.map((s,o)=>ue(i,s,o))}async function jr(e){let t=j(e),n=await qe({...e,...t,resolveSteps:r=>tn({...e,...t},r)});return{journal:n,planDigest:Y(n)}}export{Cr as _testOnlyItemTransaction,jr as abandonItemTransaction,en as buildItemCompletionMutations,Mr as commitItemCompletion,Qt as commitItemMutations,Ft as listUpsertKeyCandidates,Ht as loadGuardedRuntimeSchema,Ir as previewItemMutations,Nr as readItemTransaction,Ut as resolveTransactionSchema};
|
|
2
|
-
//# sourceMappingURL=item-transaction-
|
|
1
|
+
import{B as Le,C as Je,E as Z,H as We,J as Be,K as Ve,M as Ye,N as He,a as Pe,p as H}from"./chunk-AVLB4L7M.js";import"./chunk-RDELKGLS.js";import"./chunk-KEZ4VXYD.js";import{A as V,B as Ge,C as Y,D as qe,y as ze,z as j}from"./chunk-FQWKESMI.js";import"./chunk-IIP6LZ5E.js";import"./chunk-IWEGGRRD.js";import"./chunk-YSZZSV6M.js";import"./chunk-4SX2BN4V.js";import"./chunk-AIDL2ZNT.js";import"./chunk-QNWNUQSJ.js";import"./chunk-3GQRWIT5.js";import"./chunk-RMJKVQYE.js";import"./chunk-K53OIT5J.js";import"./chunk-AAB3ZR7Z.js";import{T as Ne,W as je}from"./chunk-TNVLDU7Z.js";import"./chunk-NXUFVQ33.js";import"./chunk-JUG3BAZZ.js";import{Ha as Ke}from"./chunk-QSRXF6XS.js";import"./chunk-UA2JNKMY.js";import"./chunk-FW5Q26HA.js";import{H as W}from"./chunk-RFJ3MEFP.js";import{sa as _e,ya as Se}from"./chunk-GQBWI4KA.js";import"./chunk-YNRW2FWB.js";import"./chunk-3BR5NWQI.js";import"./chunk-BKPUUW5O.js";import{L as xe,R as De,b as ye,l as B}from"./chunk-VV2QF5IE.js";import{i as Ue,m as Fe,s as N}from"./chunk-WHHFPATO.js";import"./chunk-BWOVFE5B.js";import"./chunk-X6CXWWNB.js";import{Cd as T,Hc as ke,Lc as M,Mb as ve,Q as K,Tb as Ae,Ub as $e,Vb as J,X as ge,fc as Te,ie as Ie,je as k,oe as Me,pe as Ce,sd as C,xd as Re}from"./chunk-NSFS3VWP.js";import{c as E}from"./chunk-R6QFPHWW.js";import{F as Ee,J as L,K as Oe,N as be}from"./chunk-OCKKIECS.js";import{A as p,E as q,G as we,H as $,l as le,q as A,s as me,x as he,z as l}from"./chunk-NGFDPEP7.js";import oe from"node:crypto";import{constants as te,readFileSync as It}from"node:fs";import{cp as Mt,lstat as it,mkdir as Ct,mkdtemp as ot,open as Nt,readdir as jt,realpath as st,rm as at,stat as se,writeFile as ct}from"node:fs/promises";import{tmpdir as dt}from"node:os";import u from"node:path";var Et=new Set(["id","title","description","type","status","priority","tags","body","deadline","estimated_minutes","acceptance_criteria","definition_of_ready","order","rank","assignee",...le,"affected_version","fixed_version","component","regression","customer_impact","close_reason","completed_at","dependencies","comments","notes","learnings","files","tests","docs","reminders","events","type_options"]);function X(e,t,n){let r=e?.estimatedMinutes;if(!(r===void 0||typeof r=="string"))throw new p(`Mutation ${n+1} ${t} option "estimatedMinutes" must be a string.`,l.USAGE,{code:"mutation_option_value_invalid",required:'Pass estimatedMinutes as a string, for example "45", in raw mutation options.',why:"Raw options use the create/update command option types; item documents accept numeric estimated_minutes instead.",nextSteps:["Quote the estimatedMinutes value or use an item document with numeric estimated_minutes, then retry the transaction."]})}var Ot=["op","id","reason","options","unique","match"],bt=[...Ot,"ref"],xn=[...bt,"item"];var Xe="[a-z][a-z0-9._-]{0,63}",Dn=new RegExp(`^${Xe}$`,"u"),Pn=new RegExp(`(^|,)id=@(${Xe})(?=,|$)`,"gu"),Ze=e=>e.slice(2).replaceAll(/-([a-z])/gu,(t,n)=>n.toUpperCase());var vt=new Set(["created_at","updated_at","closed_at","version","format_version","path","author","collection_counts","notes_count","tests_count","pm_format_version","claim_principal","test_runs","deferred_fields"]),zn=new Set([...vt,"completed_at","id"]),Gn={create:Ne.map(e=>e.target),update:je.map(e=>e.target),close:_e.map(e=>Ze(e.flag)).filter(e=>e!=="reason"),release:Se.map(e=>Ze(e.flag))};function At(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function $t(e,t){return e<t?-1:+(e!==t)}function Q(e){return Array.isArray(e)?e.map(Q):At(e)?Object.fromEntries(Object.entries(e).sort(([t],[n])=>$t(t,n)).map(([t,n])=>[t,Q(n)])):e}function O(e){return typeof e=="string"?e.trim():JSON.stringify(Q(e))}var Tt=["id","updated_at","pm_format_version","type"],kt="import";function Qe(e,t){if(typeof e!="string"||!/^[A-Za-z][A-Za-z0-9_]*$/u.test(e)||e in Object.prototype)throw new TypeError(`${t} names an invalid field ${JSON.stringify(e)}; use a front-matter field name of letters, digits and underscores`);if(Tt.includes(e))throw new TypeError(`${t} cannot change "${e}"; the item writer derives it, or an update row owns it`)}function U(e){return Array.isArray(e)?`array of ${e.length}`:typeof e}var Rt=["__proto__","constructor","prototype"];function et(e){return e!==null&&typeof e=="object"&&Object.getPrototypeOf(e)===Object.prototype}function R(e){return e===null||typeof e=="string"||typeof e=="boolean"?!0:typeof e=="number"?Number.isFinite(e):Array.isArray(e)?Array.from(e).every(R):et(e)?Object.entries(e).every(([t,n])=>!Rt.includes(t)&&R(n)):!1}function ee(e,t){let{set:n,unset:r}=e;if(n!==void 0&&!et(n))throw new TypeError(`${t} set must be a plain object of front-matter fields`);if(r!==void 0&&!Array.isArray(r))throw new TypeError(`${t} unset must be an array of front-matter field names`);let i=Object.keys(n??{}),s=r??[];if(i.length+s.length===0)throw new TypeError(`${t} requires at least one field in set or unset`);for(let o of i)if(Qe(o,t),n[o]===null||!R(n[o]))throw new TypeError(`${t} set "${o}" must be a non-null JSON value (no undefined, non-finite number, sparse array, class instance, or __proto__/constructor/prototype key); remove a field with unset`);for(let o of s){if(Qe(o,t),o==="body"||o==="front_matter")throw new TypeError(`${t} cannot unset "${o}"; the item format reserves that name`);if(i.includes(o))throw new TypeError(`${t} both sets and unsets "${o}"`)}if(new Set(s).size!==s.length)throw new TypeError(`${t} unset repeats a field`)}async function tt(e){ee(e,`Finalization of ${e.id}`);let t=await N(e.pmRoot),n={schema:t.schema,extensionFieldNames:ye(k())},r=await De({pmRoot:e.pmRoot,settings:t,id:e.id,op:kt,author:e.author,message:e.message,force:e.force===!0,extensionFieldNames:n.extensionFieldNames,mutate:i=>{let s=structuredClone(i.metadata),o=i.metadata;for(let[c,f]of Object.entries(e.set??{}))o[c]=structuredClone(f);for(let c of e.unset??[])delete o[c];let a;try{ve(i.metadata);let c=J(i,n),f=J(Ae($e(c,n),n),n);if(E(f)!==E(c))throw new TypeError("the stored item reads back as a different document; a set field collides with a name the item format reserves");a=c.metadata;let h=Object.entries(e.set??{}).find(([m,w])=>U(a[m])!==U(w));if(h!==void 0)throw new TypeError(`set "${h[0]}" is not stored as declared (${U(h[1])} normalizes to ${a[h[0]]===void 0?"an absent field":U(a[h[0]])})`)}catch(c){throw new p(`Finalization of ${e.id} would not store a readable item with the declared fields: ${c.message}`,l.USAGE,{code:"finalization_invalid_document",item_id:e.id,required:"Declare set and unset fields that leave a valid item under the workspace schema, with each set value in the shape its field stores.",why:"A finalization writes front-matter fields exactly, so the patched document is read back through the item reader, and each declared value is checked against what would be stored, before anything is written.",nextSteps:[`Run pm get ${e.id} --json to compare the current fields with the finalization, then correct the patch and retry the transaction.`]})}return{changedFields:[...new Set([...Object.keys(s),...Object.keys(a)])].filter(c=>Object.hasOwn(s,c)!==Object.hasOwn(a,c)||E(s[c])!==E(a[c])).sort((c,f)=>c.localeCompare(f))}}});return{item:r.item,changedFields:r.changedFields}}async function Ut(e,t){if(!Fe(e))return{schema:L(t.schema),typeDefinitionsFromFile:[]};let n=await Ht(e,t.schema);return{schema:n.schema,typeDefinitionsFromFile:n.type_definitions_from_file??[]}}async function Ft(e,t,n,r){let i=K({...t,item_types:{...t.item_types,definitions:[...t.item_types?.definitions??[],...n.typeDefinitionsFromFile]}},k());return(await xe(e,t.item_format,i.type_to_folder,void 0,n.schema)).flatMap(o=>{let a=o[r];return a==null?[]:[{id:o.id,value:a}]})}function ae(e){let t=new Map,n=async r=>{let i=await N(e),s=await Ut(e,i),o=new Map;for(let a of await Ft(e,i,s,r)){let d=O(a.value);o.set(d,[...o.get(d)??[],a.id])}return o};return{lookup(r){let i=t.get(r)??n(r);return t.set(r,i),i},async recordCreate(r){for(let[i,s]of t){let o=r[i];if(o==null)continue;let a=await s,d=O(o);a.set(d,[...a.get(d)??[],String(r.id)])}},invalidate(){t.clear()}}}async function xt(e,t){let n=O(t.value),r=(await e.lookup(t.key)).get(n)??[];if(r.length!==0)throw new p(`Upsert key "${t.key}" value ${JSON.stringify(n)} now matches existing item ${r.join(", ")}; the plan was resolved before it existed.`,l.CONFLICT,{code:"upsert_key_conflict",required:"Re-plan the document so the row updates the existing item instead of creating a duplicate.",why:"Keyed upsert is resolved before the writer lock, so every remaining create is re-checked under the lock; concurrent imports therefore cannot create two items for one key value.",nextSteps:["Re-run pm item mutate with the same document and --upsert-key; the re-plan turns the row into an update of the existing item.","Inspect the existing item first when its content should win over the document row."]})}function ut(e,t,n){let r=e.metadata[n.key],i=O(n.value);if(O(r)!==i)throw new p(`Item ${t} no longer carries upsert key "${n.key}" value ${JSON.stringify(i)}; the plan selected it before the key changed.`,l.CONFLICT,{code:"upsert_match_changed",required:"Re-plan the document so the row is resolved against the current key values.",why:"Keyed upsert selects its target before the writer lock, so the update re-reads the key under the lock instead of updating a mismatched item blindly.",nextSteps:["Re-run pm item mutate with the same document and --upsert-key; the re-plan creates or re-targets the row from the current key values."]})}function nt(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.key=="string"&&t.key.trim().length>0&&t.value!==void 0&&t.value!==null}function P(e,t){let n={...e,...t};return e===void 0?n:W(e,n)}async function _(e,t){try{let r=(await H(t,{},{pmRoot:e})).item;return{id:r.id,closedAt:r.closed_at,updatedAt:r.updated_at,assignee:r.assignee,claimPrincipal:r.claim_principal}}catch(n){if(n instanceof p&&n.exitCode===l.NOT_FOUND)return;throw n}}function ce(e,t){let n=e.id.replaceAll(/[^a-zA-Z0-9._-]/gu,"_"),r=oe.createHash("sha256").update(E(e)).digest("hex").slice(0,12);return`${t+1}-${e.op}-${n}-${r}`}function Dt(e,t){let n=e.id.replaceAll(/[^a-zA-Z0-9._-]/gu,"_");return`${t+1}-${e.op}-${n}`}function y(e,t,n){return`bulk-item-transaction ${e} ${t} ${n}`}function de(e,t){return e===t||(e?.startsWith(`${t} | `)??!1)}async function v(e,t,n,r){let i=await M(u.join(e,"history",`${t}.jsonl`),t),s=y(n,r,"apply"),o=y(n,r,"compensate");for(let a=i.length-1;a>=0;a-=1){let d=i[a].message;if(de(d,s))return!0;if(d===o)return!1}return!1}async function z(e,t){let n=await _(e,t.id);if(n?.updatedAt===void 0)throw new p(`Bulk ${t.op} target ${t.id} does not exist or has no restorable version`,l.NOT_FOUND);let r=await M(u.join(e,"history",`${n.id}.jsonl`),n.id);if(r.length===0)throw new p(`Bulk ${t.op} target ${t.id} has no restorable history`,l.NOT_FOUND);return{target_updated_at:n.updatedAt,target_version:String(B(r)+r.length),target_history_hash:C(r),target_history_length:r.length}}function b(e,t,n){return new p(`Transaction ${e.transactionId} cannot safely compensate incomplete step ${n}; review item ${t} history before recovery.`,l.CONFLICT,{code:"transaction_partial_mutation",item_id:t,required:"Reconcile the item's partial or intervening changes before resuming this transaction.",why:"The retained history does not prove exclusive ownership of the changes to undo. The journal remains compensating instead of claiming a rollback or overwriting another writer.",nextSteps:[`Run pm history ${t} and inspect this transaction's retained compensation data before explicitly restoring or reconciling the item.`]})}function ft(e,t){let n=`bulk-item-transaction ${t} `;return[e.message,e.context?.item_transaction_step].some(r=>typeof r=="string"&&r.startsWith(n))}function Pt(e,t,n){let{expectedHistory:r,length:i,version:s}=t;if(C(e)===r)return!1;if(typeof i!="number"||!Number.isSafeInteger(i)||i<1||C(e.slice(0,i))!==r||s!==String(B(e)+i))throw b(n,n.itemId,n.stepId);let o=y(n.transactionId,n.stepId,"apply"),a=e.slice(i),d=m=>de(m.message,o)||m.context?.item_transaction_step===o,c=y(n.transactionId,n.stepId,"compensate");if(a.filter(m=>d(m)||m.message===c).at(-1)?.message===c)return!1;let f=a.filter(d);if(f.length===0)return!1;let h=e.at(-1).after_hash===f.at(-1).after_hash&&a.every(m=>ft(m,n.transactionId));if(f.length!==a.length&&!h)throw b(n,n.itemId,n.stepId);return!0}async function pt(e,t){let n=u.join(e,"history",`${t}.jsonl`),r=await ke(n,t);return{history:r.entries,assertOwnedUnderLock:(i,s)=>{let o;try{o=It(n).equals(r.raw_bytes)&&Re(i)===r.entries.at(-1).after_hash}catch(a){throw Object.assign(s(),{cause:a})}if(!o)throw s()}}}async function I(e,t,n,r){let i=r!==null&&typeof r=="object"&&!Array.isArray(r)?r:void 0;if(i===void 0||typeof i.target_updated_at!="string")return;let s=i.target_updated_at,o=await _(e.pmRoot,t);if(o===void 0)return;let{history:a,assertOwnedUnderLock:d}=await pt(e.pmRoot,o.id),c=i.target_history_hash,f=typeof c=="string";if(typeof c=="string"){if(!Pt(a,{expectedHistory:c,length:i.target_history_length,version:i.target_version},{...e,itemId:o.id,stepId:n}))return}else{if(o.updatedAt===s)return;if(!await v(e.pmRoot,o.id,e.transactionId,n))throw b(e,o.id,n)}let h=()=>Ve(t,typeof i.target_version=="string"?i.target_version:s,{force:!0,author:e.author,message:y(e.transactionId,n,"compensate")},{pmRoot:e.pmRoot});await T({pmRoot:e.pmRoot,id:o.id,validate:m=>{d(m,()=>b(e,o.id,n))},compensation:mt(e,t,n,"restore",f)},h)}var lt=new WeakMap;function mt(e,t,n,r,i){let s=i?ze(e.pmRoot,e.transactionId):void 0,o=s===void 0?void 0:lt.get(s);if(!(o?.stepId!==n||o.itemId!==t||o.operation!==r))return{transaction_id:e.transactionId,step_id:n,operations:[r],overrides:[]}}function ht(e,t,n){return{id:n,async inspect(){let r=await _(e.pmRoot,t.id);if(r===void 0)return{state:"pending"};if(r.closedAt!==void 0){let i=await M(u.join(e.pmRoot,"history",`${r.id}.jsonl`),r.id),s=`Compensated: interrupted bulk transaction ${e.transactionId}`;if(i.filter(d=>d.op==="close").at(-1)?.patch.some(d=>d.op==="add"||d.op==="replace"?d.path==="/metadata/close_reason"&&d.value===s:!1)??!1)throw new p(`Created item ${r.id} remains closed by transaction compensation; explicitly reopen or reconcile it before retrying.`,l.CONFLICT,{code:"transaction_create_compensated",item_id:r.id,required:"Review the compensated item and explicitly reopen it before retrying the same document.",why:"This item's latest closure belongs to transaction compensation. Automatically reopening it could overwrite later lifecycle decisions.",nextSteps:[`Run pm item reopen ${r.id} "Retry compensated creation" after reviewing its history, then retry the transaction.`]})}return{state:"applied",result:{id:r.id,op:"create"}}},async apply(){t.unique!==void 0&&await xt(e.uniqueIndex,t.unique);let r=await Le(P(t.options,{author:e.author,id:t.id,message:y(e.transactionId,n,"apply")}),{pmRoot:e.pmRoot}),i=r.item;return e.onCreateWarnings?.(String(i.id),r.warnings),await e.uniqueIndex.recordCreate(i),{id:String(i.id),op:"create"}},async compensate(){await zt(e,t.id,n)}}}async function zt(e,t,n){let r=await _(e.pmRoot,t);if(r===void 0||e.createCompensation==="close"&&r.closedAt!==void 0)return;let{history:i,assertOwnedUnderLock:s}=await pt(e.pmRoot,r.id),o=y(e.transactionId,n,"apply"),a=y(e.transactionId,n,"compensate"),d=i.filter(c=>de(c.message,o)||c.message===a).at(-1);if(d?.message!==a){if(d===void 0||!i.every(c=>ft(c,e.transactionId)))throw b(e,r.id,n);await T({pmRoot:e.pmRoot,id:r.id,validate:c=>{s(c,()=>b(e,r.id,n))},compensation:mt(e,t,n,e.createCompensation==="delete"?"delete":"close",!0)},async()=>{let c={force:!0,author:e.author,message:a};e.createCompensation==="delete"?await Be(t,c,{pmRoot:e.pmRoot}):await Z(t,`Compensated: interrupted bulk transaction ${e.transactionId}`,{...c,validateClose:"off"},{pmRoot:e.pmRoot})})}}function Gt(e,t,n){return{id:n,compensatePending:!0,async inspect(){let r=await _(e.pmRoot,t.id);return r===void 0?{state:"pending"}:await v(e.pmRoot,r.id,e.transactionId,n)?{state:"applied",result:{id:r.id,op:"update"}}:{state:"pending"}},async prepareCompensation(){return z(e.pmRoot,t)},async apply(){let r=()=>Je(t.id,P(t.options,{author:e.author,message:y(e.transactionId,n,"apply")}),{pmRoot:e.pmRoot}),i=t.match,s=i,a=(await T({pmRoot:e.pmRoot,id:await yt(e.pmRoot,t.id),validate:d=>{s!==void 0&&ut(d,t.id,s)},committed:d=>{i!==void 0&&(s={key:i.key,value:structuredClone(d.metadata[i.key])})},historyContext:{item_transaction_step:y(e.transactionId,n,"apply")}},r)).item;return e.uniqueIndex.invalidate(),{id:String(a.id),op:"update"}},async compensate(r){await I(e,t.id,n,r)}}}async function yt(e,t){return String((await H(t,{},{pmRoot:e})).item.id)}function qt(e,t,n){let r=y(e.transactionId,n,"apply");return{id:n,compensatePending:!0,async inspect(){let i=await _(e.pmRoot,t.id);return i===void 0||!await v(e.pmRoot,i.id,e.transactionId,n)?{state:"pending"}:{state:"applied",result:{id:i.id,op:t.op}}},async prepareCompensation(){return z(e.pmRoot,t)},async apply(){let i=await yt(e.pmRoot,t.id),{match:s}=t;return await He(e.pmRoot,()=>T({pmRoot:e.pmRoot,id:i,validate:o=>{s!==void 0&&ut(o,t.id,s)},historyContext:{item_transaction_step:r}},()=>tt({pmRoot:e.pmRoot,id:i,author:e.author,message:r,force:t.force,...t.set===void 0?{}:{set:t.set},...t.unset===void 0?{}:{unset:t.unset}}))),e.uniqueIndex.invalidate(),{id:i,op:t.op}},async compensate(i){await I(e,t.id,n,i)}}}function Kt(e,t,n){return{id:n,async inspect(){let r=await _(e.pmRoot,t.id);return r===void 0?{state:"pending"}:await v(e.pmRoot,r.id,e.transactionId,n)?{state:"applied",result:{id:r.id,op:"close"}}:r.closedAt===void 0?{state:"pending"}:{state:"applied",result:{id:r.id,op:"close"}}},async prepareCompensation(){return z(e.pmRoot,t)},async apply(){let i=(await Z(t.id,t.reason,P(t.options,{author:e.author,message:y(e.transactionId,n,"apply")}),{pmRoot:e.pmRoot})).item;return e.uniqueIndex.invalidate(),{id:String(i.id),op:"close"}},async compensate(r){await I(e,t.id,n,r)}}}function Lt(e,t,n){return{id:n,async inspect(){let r=await _(e.pmRoot,t.id);return r===void 0?{state:"pending"}:await v(e.pmRoot,r.id,e.transactionId,n)?{state:"applied",result:{id:r.id,op:"release"}}:r.assignee!==void 0||r.claimPrincipal!==void 0?{state:"pending"}:{state:"applied",result:{id:r.id,op:"release"}}},async prepareCompensation(){return z(e.pmRoot,t)},async apply(){let i=(await We(t.id,P(t.options,{author:e.author,message:y(e.transactionId,n,"apply")}),{pmRoot:e.pmRoot})).item;return e.uniqueIndex.invalidate(),{id:String(i.id),op:"release"}},async compensate(r){await I(e,t.id,n,r)}}}function ue(e,t,n){let r=ce(t,n),i=Jt(e,t,r);return lt.set(i,{transactionId:e.transactionId,stepId:r,itemId:t.id,operation:t.op!=="create"?"restore":e.createCompensation==="delete"?"delete":"close"}),i}function Jt(e,t,n){switch(t.op){case"create":return ht(e,t,n);case"update":return Gt(e,t,n);case"close":return Kt(e,t,n);case"release":return Lt(e,t,n);case"finalize":return qt(e,t,n)}}function Wt(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError(`Bulk mutation ${t+1} must be an object`);if(!["create","update","close","release","finalize"].includes(e.op))throw new TypeError(`Bulk mutation ${t+1} op must be create, update, close, release, or finalize`);if(typeof e.id!="string"||e.id.trim().length===0)throw new TypeError(`Bulk mutation ${t+1} requires a non-empty id`);if(e.op==="close"&&(typeof e.reason!="string"||e.reason.trim().length===0))throw new TypeError(`Bulk close mutation ${t+1} requires a non-empty reason`);if(Bt(e,t),e.op==="finalize"){Vt(e,t);return}X(e.options,e.op,t)}function Bt(e,t){if(e.op==="create"&&e.unique!==void 0&&!nt(e.unique))throw new TypeError(`Bulk create mutation ${t+1} unique must be an object with a non-empty key and a value`);if((e.op==="update"||e.op==="finalize")&&e.match!==void 0&&!nt(e.match))throw new TypeError(`Bulk ${e.op} mutation ${t+1} match must be an object with a non-empty key and a value`)}var rt=["op","id","set","unset","match","force"];function Vt(e,t){let n=`Bulk finalize mutation ${t+1}`,r=Object.keys(e).filter(i=>!rt.includes(i));if(r.length>0)throw new TypeError(`${n} has unsupported keys: ${r.join(", ")}; a finalization carries only ${rt.join(", ")}`);if(e.force!==void 0&&typeof e.force!="boolean")throw new TypeError(`${n} force must be a boolean`);if(e.match!==void 0&&!R(e.match))throw new TypeError(`${n} match must be a plain object with a JSON value`);ee(e,n)}function ie(e){if(e.length===0)throw new TypeError("Bulk item transaction requires at least one mutation");let t=new Map;for(let[n,r]of e.entries()){if(Wt(r,n),r.op!=="create"||r.unique===void 0)continue;let{key:i,value:s}=r.unique,o=t.get(i)??new Map,a=O(s),d=o.get(a);if(d!==void 0)throw new p(`Bulk create mutations ${d+1} and ${n+1} share the upsert key value ${JSON.stringify(a)} for "${i}".`,l.USAGE,{code:"upsert_key_duplicate",required:"Each create must carry a distinct unique key value within one batch.",why:"Direct SDK batches must preserve the same uniqueness invariant as planned document rows."});o.set(a,n),t.set(i,o)}}function wt(e){let t=[...e];ie(t);let n=t.map(r=>{let i=structuredClone(r);return r.op!=="finalize"&&i.op!=="finalize"&&r.options!==void 0&&i.options!==void 0&&W(r.options,i.options),i});return ie(n),n}function gt(e,t=""){return e===null||typeof e!="object"?[]:Object.entries(e).flatMap(([n,r])=>{let i=`${t}/${n.replaceAll("~","~0").replaceAll("/","~1")}`;return/^(created_at|updated_at|closed_at|completed_at|timestamp)$/u.test(n)?[i]:gt(r,i)})}async function ne(e,t,n){try{return await n()}catch(r){throw r instanceof p?new p(r.message,r.exitCode,{...r.context,transaction_operation:{index:t,op:e.op,id:e.id}}):r}}function _t(e,t,n,r){let i=u.relative(e,t),s=i.split(u.sep);return s[0]==="extensions"&&s[2]==="node_modules"&&!r.some(o=>i===o||i.startsWith(`${o}${u.sep}`)||o.startsWith(`${i}${u.sep}`))?!1:["locks","runtime","search"].includes(i.split(u.sep)[0])?r.some(o=>i===o||i.startsWith(`${o}${u.sep}`)||o.startsWith(`${i}${u.sep}`)):i===""||n===void 0||n.some(o=>i===o||i.startsWith(`${o}${u.sep}`)||o.startsWith(`${i}${u.sep}`))}async function x(e,t){let n=await it(t);if(n.isSymbolicLink())await se(t);else if(n.isDirectory()||n.isFile())return n;throw $(u.relative(e,t))}async function Yt(e,t){let n=await Nt(t,te.O_RDONLY|te.O_NOFOLLOW|te.O_NONBLOCK);try{let r=await n.stat();if(!r.isFile())throw $(u.relative(e,t));let i=oe.createHash("sha256");if(r.size>0)for await(let s of n.createReadStream({highWaterMark:64*1024,end:r.size-1,autoClose:!1}))i.update(s);return i.digest()}finally{await n.close()}}async function re(e,t,n){let r=oe.createHash("sha256");async function i(s){for(let o of(await jt(s)).sort()){let a=u.join(s,o);_t(e,a,t,n)&&((await x(e,a)).isDirectory()?await i(a):(r.update(JSON.stringify(u.relative(e,a))),r.update(await Yt(e,a))))}}return await i(e),r.digest("hex")}function F(){return new p("Tracker changed while preparing the transaction preview; retry against stable state.",l.CONFLICT,{code:"transaction_preview_snapshot_changed"})}async function fe(e){if(!q(e))return!1;let t=e.path;if(typeof t!="string")return!1;let n=u.resolve(t),r=n;for(;;)try{let i=await it(r);return r!==n&&i.isDirectory()}catch(i){if(!q(i))return!1;let s=u.dirname(r);if(s===r)return!1;r=s}}async function D(e,t){let n=u.join(e,t);try{let r=e;for(let i of t.split(u.sep).slice(0,-1))r=u.join(r,i),await x(e,r);if(!(await x(e,n)).isFile())throw $(t);return await we(n,$(t))}catch(r){if(await fe(r))return;throw r}}async function St(e,t,n,r){let i=L(n);for(let[s,o]of Object.entries(i.files)){let a=u.relative(e,Oe(e,o,Ee[s]));if(a===""||!u.resolve(e,a).startsWith(u.join(e,u.sep)))throw new p("Transaction preview requires schema files inside the selected tracker root; relocate the configured schema file before retrying.",l.USAGE,{code:"transaction_preview_external_schema",field:`schema.files.${s}`});i.files[s]=a;let d=await D(e,a);if(r?.set(a,d),d!==void 0){let c=u.join(t,a);await Ct(u.dirname(c),{recursive:!0}),await ct(c,d)}}return be(t,i)}async function Ht(e,t){await se(e);let n=await ot(u.join(dt(),"pm-schema-plan-"));try{let r=await st(e);return await St(r,u.join(n,"configuration"),t)}catch(r){throw await fe(r)?F():r}finally{await at(n,{recursive:!0,force:!0})}}async function Zt(e,t,n){let r=new Map,i=await D(e,A);r.set(A,i);let s;try{s=JSON.parse(i??"null")}catch{s=null}let o=Ue(s),a=o.success?o.data:void 0,d=await St(e,t,a?.schema,r),c=d.schema,f=u.relative(e,Te(e));r.set(f,await D(e,f));let h=K({...he,item_types:{definitions:[...a?.item_types?.definitions??[],...d.type_definitions_from_file??[]]}},n),m=ge(e)===e?[...me.filter(Boolean),A,Pe,"transactions",...h.folders,...r.keys()].map(g=>u.normalize(g)):void 0,w=a===void 0?void 0:JSON.stringify({...s,schema:{...a.schema,files:c.files}});return{configuration:r,ownedPaths:m,stagedSettings:w,registryFolders:h.folders}}async function Xt(e,t,n){await se(e);try{let r=await st(e),i=await Zt(r,u.join(u.dirname(t),"configuration"),n),s=[...i.configuration.keys(),...i.registryFolders].map(c=>u.normalize(c)),o=await re(r,i.ownedPaths,s);await Mt(r,t,{recursive:!0,dereference:!1,filter:async c=>_t(r,c,i.ownedPaths,s)?(await x(r,c),!0):!1});let[a,d]=await Promise.all([re(r,i.ownedPaths,s),re(t,i.ownedPaths,s)]);if(o!==a||o!==d)throw F();for(let[c,f]of i.configuration)if(await D(t,c)!==f)throw F();i.stagedSettings!==void 0&&await ct(u.join(t,A),i.stagedSettings)}catch(r){throw await fe(r)?F():r}}async function Ir(e){let t=j(e),n=wt(e.mutations),r=k(),i=Ce(),s=await ot(u.join(dt(),"pm-transaction-preview-")),o=u.join(s,"tracker");try{await Xt(t.pmRoot,o,r);let a=!1,d=[],c=[],f=new Set;return await Me(i,()=>Ye({path:o,noExtensions:!0},async()=>{Ie(r);let h={...t,pmRoot:o,createCompensation:"close",uniqueIndex:ae(o)},m=n.map((w,g)=>{let S=ue({...h,onCreateWarnings:(G,pe)=>{pe.length>0&&d.push({index:g,id:G,op:"create",warnings:pe})}},w,g);return{...S,inspect:()=>ne(w,g,()=>S.inspect()),prepareCompensation:()=>ne(w,g,async()=>S.prepareCompensation?.()),apply:()=>ne(w,g,async()=>{let G=await S.apply();return f.add(g),G})}});if(await V({...t,pmRoot:o,steps:m,onTransition:({transition:w})=>{w==="committed"&&(a=!0)}}),a)for(let[w,g]of n.entries()){let S=(await Ke(g.id,{path:o},{full:!0})).item;c.push({index:w,id:String(S.id),op:g.op,execution:f.has(w)?"applied":"adopted",item:S,commit_time_fields:gt(S)})}})),{records:c,validated:a,state:a?"staged_snapshot":"replayed_committed_plan",warnings:d,unresolved_commit_constraints:["concurrent_tracker_changes","extension_write_hooks","derived_extension_dependencies_excluded","generated_timestamps_and_provenance"]}}finally{await at(s,{recursive:!0,force:!0})}}async function Qt(e){let t=j(e),n=wt(e.mutations),r=e.createCompensation??"close";if(!["close","delete"].includes(r))throw new TypeError("Bulk item transaction createCompensation must be close or delete");let i={...t,createCompensation:r,uniqueIndex:ae(t.pmRoot)},s=await V({...t,steps:n.map((a,d)=>ue(i,a,d)),recoveryData:JSON.parse(JSON.stringify({kind:"item-mutations-v1",mutations:n,createCompensation:r})),...e.lockTtlSeconds===void 0?{}:{lockTtlSeconds:e.lockTtlSeconds},...e.lockWaitMs===void 0?{}:{lockWaitMs:e.lockWaitMs},...e.onTransition===void 0?{}:{onTransition:e.onTransition}}),o={};for(let[a,d]of n.entries()){let c=ce(d,a),f=s.results[c];o[Dt(d,a)]=f}return{transactionId:s.transactionId,status:"committed",recovered:s.recovered,results:o}}function en(e){let t=[];return e.evidence!==void 0&&Object.keys(e.evidence).length>0&&t.push({op:"update",id:e.id,options:e.evidence}),t.push({op:"close",id:e.id,reason:e.reason,...e.closeOptions===void 0?{}:{options:e.closeOptions}},{op:"release",id:e.id,...e.releaseOptions===void 0?{}:{options:e.releaseOptions}}),t}function Mr(e){return Qt({pmRoot:e.pmRoot,transactionId:e.transactionId,author:e.author,mutations:en(e),...e.lockTtlSeconds===void 0?{}:{lockTtlSeconds:e.lockTtlSeconds},...e.lockWaitMs===void 0?{}:{lockWaitMs:e.lockWaitMs},...e.onTransition===void 0?{}:{onTransition:e.onTransition}})}var Cr={buildCreateStep:ht,bulkHistoryMarker:y,compensateByRestore:I,deriveStepId:ce,isUpdateMarkerApplied:v,readItemSnapshot:_};async function Nr(e,t){let n=await Ge(e,t);return n===void 0?void 0:{journal:n,planDigest:Y(n)}}function tn(e,t){let n=t.recoveryData;if(n===null||typeof n!="object"||Array.isArray(n)||n.kind!=="item-mutations-v1"||!Array.isArray(n.mutations)||!["close","delete"].includes(String(n.createCompensation)))throw new p("Transaction has no supported item recovery plan",l.CONFLICT,{code:"transaction_recovery_plan_missing",required:"Resume with the original plan and its original adapter.",why:"Legacy or foreign journals cannot safely reconstruct item compensation."});let r=n.mutations;ie(r);let i={...e,createCompensation:n.createCompensation,uniqueIndex:ae(e.pmRoot)};return r.map((s,o)=>ue(i,s,o))}async function jr(e){let t=j(e),n=await qe({...e,...t,resolveSteps:r=>tn({...e,...t},r)});return{journal:n,planDigest:Y(n)}}export{Cr as _testOnlyItemTransaction,jr as abandonItemTransaction,en as buildItemCompletionMutations,Mr as commitItemCompletion,Qt as commitItemMutations,Ft as listUpsertKeyCandidates,Ht as loadGuardedRuntimeSchema,Ir as previewItemMutations,Nr as readItemTransaction,Ut as resolveTransactionSchema};
|
|
2
|
+
//# sourceMappingURL=item-transaction-A6MVNPT7.js.map
|
package/dist/cli-bundle/focused-chunks/{mutation-actor-GGOQKAE6.js → mutation-actor-6ZVW6OME.js}
RENAMED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Dc as t,Ec as r,Fc as s}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=mutation-actor-
|
|
1
|
+
import{Dc as t,Ec as r,Fc as s}from"./chunk-NSFS3VWP.js";import"./chunk-R6QFPHWW.js";import"./chunk-OCKKIECS.js";import"./chunk-NGFDPEP7.js";function c(n){let e=r(n),o={...e.harness===void 0?{}:{harness:e.harness},...e.model===void 0?{}:{model:e.model},...e.model_source===void 0?{}:{model_source:e.model_source},...e.instance===void 0?{}:{instance:e.instance}};return Object.freeze({author:n,author_source:t(n),principal:s(n),...Object.keys(o).length===0?{}:{agent:Object.freeze(o)}})}export{c as resolveMutationActor};
|
|
2
|
+
//# sourceMappingURL=mutation-actor-6ZVW6OME.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Q as y,t as _,y as f}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=mutation-admission-
|
|
1
|
+
import{Q as y,t as _,y as f}from"./chunk-QNWNUQSJ.js";import"./chunk-AAB3ZR7Z.js";import{T as A,W as L,a as T}from"./chunk-TNVLDU7Z.js";import"./chunk-RFJ3MEFP.js";import{F as g,Pa as C,Va as E}from"./chunk-GQBWI4KA.js";import"./chunk-VV2QF5IE.js";import{s as M}from"./chunk-WHHFPATO.js";import"./chunk-BWOVFE5B.js";import"./chunk-X6CXWWNB.js";import{W as S,a as w}from"./chunk-NSFS3VWP.js";import{T as b}from"./chunk-R6QFPHWW.js";import{Q as R,R as N}from"./chunk-OCKKIECS.js";import{A as m}from"./chunk-NGFDPEP7.js";function l(e,t,n,i=!1){let s=[...n].map(o=>({candidate:o,distance:w(t,o,3)})).filter(o=>o.distance!==null).sort((o,d)=>o.distance-d.distance||o.candidate.localeCompare(d.candidate))[0]?.candidate,a=i?`Put mutation fields under options (options.${t}).`:s?`Did you mean "${s}"?`:"Use the declared command options or the field option for registered item fields.";throw new m(`Unknown ${e} ${i?"argument":"option"} "${t}". ${a} No changes were made.`,2,{code:"invalid_argument_value",reason:"unknown_mutation_option",changed:!1,field:t,required:a,nextSteps:[a]})}var p=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor"];function $(e){let t=e==="create"?A:L,i=(e==="create"?C:E).map(({flag:s})=>s.slice(2).replace(/-([a-z])/gu,(a,o)=>o.toUpperCase()));return new Set([...t.flatMap(s=>[s.target,...s.keys]),...i,"author","message","force","fullChangedFields","idOnly",...p])}function F(e){if(e!==void 0&&!f(e))throw new m("Mutation options must be an object. No changes were made.",2,{code:"invalid_argument_value",changed:!1})}async function v(e,t){let i=R((await M(S(process.cwd(),t))).schema).command_to_fields.get(e)??[];return{targets:i.map(s=>N(s)),reads:s=>i.some(a=>b({[s]:!0},a)===!0)}}async function h(e,t,n,i,s,a=(o,d)=>l(e,o,d)){let o=[...n].filter(r=>!i.has(r));if(o.length===0)return;let d=await v(t,s);for(let r of d.targets)i.add(r);for(let r of o)d.reads(r)||a(r,i)}async function ee(e,t,n,i,s){if(_(t))return;let a=$(e),o=new Set(["action","options","path","cwd","author","force","noExtensions","no_extensions","fullChangedFields","idOnly",...p,...s,...e==="update"?["id"]:[]]);for(let r of Object.keys(t))o.has(r)||l(e,r,a,a.has(r));let d=t.options;F(d),await h(e,e,new Set([...Object.keys(d??{}),...Object.keys(n)]),a,i)}var I=new Set([...y].filter(e=>e!=="filterStatus"&&(e.startsWith("filter")||e==="ids"||e==="limit"||e==="offset"))),k=e=>e.replace(/_([a-z])/gu,(t,n)=>n.toUpperCase()),O=new Map([["for","Bound the selection with list.limit."],["tokenBudget","Bound the selection with list.limit."],["token_budget","Bound the selection with list.limit."],["all",'State the status selection as filterStatus: "all" beside the list record.'],["status","State the status selection as filterStatus beside the list record."]]),K=["compact","brief","fields","includeBody","full"];async function U(e,t){let n=K.filter(s=>Object.hasOwn(e,s));if(n.length===0)return;let i=await v("list",t);for(let s of n)i.reads(s)&&c(`update-many "list.${s}" is not read beside this selection.`,`list.${s}`,"The bulk selection clears this list option, so the schema field's filter under that name is not applied; select the rows another way.")}var j=["excludeTerminal","lifecycleBucket","dependencyBlocked"];function P(){let e=g.map(({flag:n})=>n.replace(/^--(?:no-)?/u,"").replace(/-([a-z])/gu,(i,s)=>s.toUpperCase())),t=new Set([...e,...T.flatMap(n=>n.keys),"filterEstimateMissing",...j]);for(let n of O.keys())t.delete(n);return t}function c(e,t,n,i="unknown_mutation_option"){throw new m(`${e} ${n} No changes were made.`,2,{code:"invalid_argument_value",reason:i,changed:!1,field:t,required:n,nextSteps:[n]})}function D(){let e=$("update");e.delete("id");for(let t of e)/File$|^stdin/u.test(t)&&e.delete(t);return e.add("documentAnnotationSnapshot"),e}function B(e){for(let t of["list","update"]){let n=e[t];n!=null&&!f(n)&&c(`update-many "${t}" must be an object.`,t,`Pass ${t} as an object, or omit it.`,"invalid_mutation_option_value")}}async function x(e,t,n){Object.hasOwn(e,"id")&&l("update-many list","id",new Set(["ids"])),Object.hasOwn(e,"status")&&c('update-many "list.status" is not read beside this selection.',"list.status",O.get("status"));let i=[...t].find(s=>I.has(s));i!==void 0&&c(`update-many "${i}" is not read beside this selection.`,i,`Put the selection inside list, or drop the list record; a flat "${i}" beside it is not read.`),await U(e,n),await h("update-many list","list",Object.keys(e),P(),n,(s,a)=>{let o=O.get(s);o===void 0&&l("update-many list",s,a),c(`update-many "list.${s}" is not read beside this selection.`,`list.${s}`,o)})}function Y(e,t,n){for(let i of e)t.has(i)||(n.has(i)&&c(`Unknown update-many option "${i}".`,i,`Put update fields inside update (update.${i}); beside a nested update record an outer key selects rows or controls the run.`),l("update-many",i,t))}async function te(e,t,n){if(_(e))return;let i=e.options;F(i);let s=D(),a=new Set([...y,"author","message","force","fullChangedFields","idOnly",...p]),o=new Set([...s,...a]),d=new Set(["action","options","path","cwd","author","noExtensions","no_extensions","fullChangedFields","idOnly",...p]);for(let u of Object.keys(e))d.has(u)||l("update-many",u,o,o.has(u));let r=new Set([...Object.keys(i??{}),...Object.keys(t)].map(u=>p.includes(k(u))?k(u):u));if(B(t),f(t.list)&&await x(t.list,r,n),!f(t.update)){await h("update-many","update_many",r,o,n);return}Y(r,a,s),await h("update-many","update_many",Object.keys(t.update),s,n)}export{ee as assertNativeMutationOptions,te as assertNativeUpdateManyOptions};
|
|
2
|
+
//# sourceMappingURL=mutation-admission-2DA4CINP.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{c as w,j as y}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=stage-
|
|
1
|
+
import{c as w,j as y}from"./chunk-YSZZSV6M.js";import{b as u}from"./chunk-4SX2BN4V.js";import{c as g}from"./chunk-AIDL2ZNT.js";import"./chunk-BKPUUW5O.js";import"./chunk-WHHFPATO.js";import{W as h}from"./chunk-NSFS3VWP.js";import"./chunk-R6QFPHWW.js";import"./chunk-OCKKIECS.js";import{A as f,z as d}from"./chunk-NGFDPEP7.js";import{execFile as x}from"node:child_process";import{realpath as R}from"node:fs/promises";import p from"node:path";import{promisify as $}from"node:util";var b=$(x);function c(t){return new f(`Automatic merge settlement refused: ${t}`,d.CONFLICT,{code:"merge_settlement_review_required",recovery:{suggested_retry:"pm merge reconcile --dry-run"},nextSteps:["Inspect receipts, repair streams and Git changes. Resolve competing values or unrelated drift explicitly, then run pm merge reconcile and stage the reviewed artifacts manually."]})}async function G(t){let e=process.env.GIT_INDEX_FILE;if(e===void 0)return;let s=(await t(["rev-parse","--path-format=absolute","--git-path","index"])).stdout.trim();if(p.resolve(e)!==p.resolve(s))throw c("an alternate Git index requires explicit manual settlement")}async function k(t,e){if(e.length===0)return[];let s=e.map(n=>`:(literal)${n}`),a=new Set((await t(["ls-files","--cached","-z","--",...s])).stdout.split("\0")),i=e.filter(n=>!a.has(n)).map(n=>`:(literal)${n}`);if(i.length>0&&(await t(["diff","--cached","--name-only","--diff-filter=D","-z","--",...i])).stdout.length>0)throw c("a receipt has a staged deletion that requires explicit review");return i}async function I(t){let{git:e,preview:s,paths:a,newReceiptPathspecs:i}=t,n=!1;try{i.length>0&&(n=!0,await e(["add","--",...i]));let o=await t.apply();if(!o.ok||JSON.stringify(o.receipts.summaries)!==JSON.stringify(s.receipts.summaries)||o.repair.streams.some(m=>!s.repair.streams.some(l=>l.id===m.id)))throw c("reconciliation changed or did not finish; inspect the audit artifacts before staging");return a.length>0&&await e(["add","--",...a.map(m=>`:(literal)${m}`)]),{...o,staged_paths:a,guidance:["Lossless reconciliation artifacts are staged for the merge commit. Review git diff --cached before committing."]}}catch(o){throw n&&await e(["reset","--quiet","--",...i]),o}}function S(t){if(t.repair.totals.failed>0||t.receipts.missing_history_references_after>0||t.receipts.summaries.some(e=>e.conflict_fields.length>0)||t.repair.streams.some(e=>e.merge_receipt_proof?.trusted!==!0)||t.validation.checks.some(e=>e.name!=="history_drift"&&e.status!=="ok"))throw c("only fully authenticated receipt-backed repairs without discarded values can be staged")}async function q(t){try{return{...t,path:await R(h(process.cwd(),t.path))}}catch{throw c("the tracker root cannot be resolved")}}async function z(t){let{preview:e}=t;S(e);let{path:s}=await q(t.global),a=await w(s);if(a===null)throw c("a Git workspace is required");let i=r=>b("git",r,{cwd:a,env:g(),timeout:1e4});if(await G(i),(await i(["ls-files","--unmerged","-z"])).stdout.length>0)throw c("Git still has unresolved paths");let o=[...new Set([...[...new Set([...e.repair.streams.map(r=>r.id),...e.receipts.summaries.map(r=>r.item_id)])].map(r=>p.join(s,"history",`${r}.jsonl`)),...e.receipts.summaries.map(r=>p.join(s,"merge-receipts",`${r.receipt_id}.json`))])].map(r=>p.relative(a,r).replaceAll("\\","/"));if(o.some(u))throw c("reconciliation artifacts must belong to this Git workspace");let m=await y(a,o);if(m.length>0)throw new f(`Automatic merge settlement refused: required artifacts are ignored by Git: ${m.map(r=>`${r.path} (${r.source}:${r.line}: ${r.pattern})`).join(", ")}. Remove or narrow the owning ignore rules because merge receipts must travel with the commit.`,d.CONFLICT,{code:"merge_settlement_review_required",reason:"ignored_merge_artifacts",paths:m.map(r=>r.path),nextSteps:["Remove or narrow the named ignore rules, preserve receipt and history files, then retry pm merge reconcile --stage --dry-run before applying pm merge reconcile --stage. Do not force-add ignored proof as a substitute for fixing the shared policy."]});let l=o.map(r=>`:(literal)${r}`),v=e.receipts.summaries.map(r=>p.relative(a,p.join(s,"merge-receipts",`${r.receipt_id}.json`)).replaceAll("\\","/"));if(l.length>0)try{await i(["diff","--quiet","--",...l])}catch{throw c("reconciliation paths have unstaged edits or Git cannot verify their index state")}let _=await k(i,v);return t.dryRun?{...e,staged_paths:[]}:I({...t,git:i,paths:o,newReceiptPathspecs:_})}export{q as resolveMergeSettlementGlobal,z as stageLosslessMergeReconciliation};
|
|
2
|
+
//# sourceMappingURL=stage-RG3PKST7.js.map
|