@unbrained/pm-cli 2026.12.2 → 2026.12.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/dist/cli/commander-usage.js +4 -4
- package/dist/cli/expected-revisions.js +1 -1
- package/dist/cli/extension-command-help.js +4 -4
- package/dist/cli/main.js +5 -5
- package/dist/cli/runtime/invocation-rewrites.js +1 -1
- package/dist/cli/runtime-field-commands.js +2 -0
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/chunk-3ESBFEQC.js +2 -0
- package/dist/cli-bundle/chunks/chunk-46AZP5QW.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-OBPO6V7H.js → chunk-5WTBF4M4.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-3KEMIPKG.js → chunk-6TOZQ5BQ.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-4YYFY33T.js → chunk-AHVOEE7F.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-CQHB3ZZH.js +2 -0
- package/dist/cli-bundle/chunks/chunk-DZPOS3YT.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-ROTEELDL.js → chunk-E5ADC3HT.js} +65 -65
- package/dist/cli-bundle/chunks/{chunk-SY5C3U32.js → chunk-E5HO7HWP.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-3HKPVOAN.js → chunk-EDJ3KR2H.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-TKUG2X24.js → chunk-FWQNWPIV.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-7NAO7I75.js → chunk-H4U3LEOD.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-MZZ4ZJ5Z.js → chunk-HNMED75Y.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-SDXCJZKB.js → chunk-HPCMM74Q.js} +22 -22
- package/dist/cli-bundle/chunks/{chunk-WSEIEDEK.js → chunk-ITM4AMVM.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-Q6K7HWZ7.js → chunk-IW4A3I4N.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-7V65VACG.js → chunk-JJ73G5UT.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-L4HMFRHB.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-GOEQXVOI.js → chunk-LTQWPQ7H.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-UNBW2LF3.js → chunk-MRT3ADO4.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-ZL6J6JYT.js → chunk-PBMLIV74.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-G6TARHFK.js → chunk-PJMGWJKU.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-Q2HMDV56.js +9 -0
- package/dist/cli-bundle/chunks/{chunk-OXC5KBIQ.js → chunk-RRBNCL63.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-CBUC4X7Q.js → chunk-TDOF7BKO.js} +3 -3
- package/dist/cli-bundle/chunks/chunk-UXEZXGAD.js +113 -0
- package/dist/cli-bundle/chunks/{chunk-PCDTWL6V.js → chunk-W7HA65EO.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-I4SPJQQI.js → chunk-XGNUDSCG.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-AHV3CSQG.js → chunk-XKJ5NWQ7.js} +2 -2
- package/dist/cli-bundle/chunks/{field-option-collisions-BBGTV7AD.js → field-option-collisions-DXKTKW6J.js} +2 -2
- package/dist/cli-bundle/chunks/item-revision-DXEF4XBU.js +2 -0
- package/dist/cli-bundle/chunks/item-transaction-EANA7V4W.js +2 -0
- package/dist/cli-bundle/chunks/{linked-resource-value-list-ZBIY4H23.js → linked-resource-value-list-5JRGUDUB.js} +2 -2
- package/dist/cli-bundle/chunks/{mutation-actor-NHN33ITJ.js → mutation-actor-S5G7FMNG.js} +2 -2
- package/dist/cli-bundle/chunks/{mutation-admission-PGKJTCG6.js → mutation-admission-HQVNPOXV.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-7S5QWDTI.js → register-list-query-SQF5PSJ4.js} +2 -2
- package/dist/cli-bundle/chunks/{register-mutation-EK6DVIQK.js → register-mutation-4AQ4CEBL.js} +2 -2
- package/dist/cli-bundle/chunks/{register-operations-6MURXE4V.js → register-operations-76P7OM4P.js} +2 -2
- package/dist/cli-bundle/chunks/{register-setup-RW26X3GJ.js → register-setup-T6OEOZK3.js} +2 -2
- package/dist/cli-bundle/chunks/{stage-4ZCF74G4.js → stage-KUICZHSF.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-4SCFAWAW.js → chunk-3LHBKFPD.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-4DDXERKN.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-JPZGC3W4.js → chunk-4YU75CWI.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-TXTPAFHJ.js → chunk-5JQVPQMN.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-KNBGHCIP.js → chunk-5Z4DXYBZ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-7DOP5HEZ.js +44 -0
- package/dist/cli-bundle/focused-chunks/{chunk-TR22GU7M.js → chunk-AX4RBJ7B.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-7A6SEZEY.js → chunk-BEHQCHQV.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-BUIF6CMZ.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-E2IWEJL5.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-GBU7GKNJ.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-EQCQTYKO.js → chunk-K35KTBDZ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-VQIC3UZB.js → chunk-KNST4PGF.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-P2H3GTJK.js → chunk-L2XJB5PK.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-L6NOGC4N.js +100 -0
- package/dist/cli-bundle/focused-chunks/{chunk-VK3IE3TS.js → chunk-LWIIDPAV.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-6IY5CVGJ.js → chunk-M54BMYG4.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-6BKT6XQN.js → chunk-NEK7RX3N.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-BHNBPCHP.js → chunk-OKGWIW6C.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-2DGKVXFT.js → chunk-RFDSSOTZ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-SSX5YBDC.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-OG57ESZK.js → chunk-TIEQVIFN.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-3COWDIPX.js → chunk-VEUBDQDP.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-2UWKU2BQ.js → chunk-WDHNPNHX.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{field-option-collisions-2C6DLUC4.js → field-option-collisions-32X7FP3H.js} +2 -2
- package/dist/cli-bundle/focused-chunks/item-revision-GUYSVVQD.js +2 -0
- package/dist/cli-bundle/focused-chunks/{item-transaction-LQLQLZE7.js → item-transaction-MLKHZPL7.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{mutation-actor-DJMZUIZI.js → mutation-actor-RDZJTRW2.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{mutation-admission-SDWQVVHN.js → mutation-admission-IQB6XL75.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{stage-QBZIK3T5.js → stage-AA7LORZ2.js} +2 -2
- package/dist/cli-bundle/main.js +27 -27
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +1 -1
- package/dist/cli-bundle/sdk-core.js +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 +9 -9
- package/dist/core/extensions/loader.d.ts +8 -0
- package/dist/core/extensions/loader.js +1 -1
- package/dist/core/item/actionability.js +1 -1
- package/dist/core/output/output.js +16 -16
- package/dist/mcp/server.js +1 -1
- package/dist/sdk/cli-contracts/enum-contracts.d.ts +25 -1
- package/dist/sdk/cli-contracts/enum-contracts.js +1 -1
- package/dist/sdk/cli-contracts/flag-contracts.d.ts +1 -1
- package/dist/sdk/cli-contracts/flag-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.js +1 -1
- package/dist/sdk/context-intent-contracts.js +1 -1
- package/dist/sdk/lifecycle/expect-hash-admission.d.ts +27 -8
- package/dist/sdk/lifecycle/expect-hash-admission.js +1 -1
- package/dist/sdk/lifecycle/item-revision.d.ts +12 -4
- package/dist/sdk/lifecycle/item-revision.js +1 -1
- package/dist/sdk/output-projection.d.ts +1 -1
- package/dist/sdk/output-projection.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/read-output/surfaces.js +1 -1
- package/dist/sdk/runtime/schema.js +1 -1
- package/dist/sdk/runtime-input.d.ts +6 -0
- package/dist/sdk/runtime-input.js +1 -1
- package/dist/sdk/runtime-primitives.d.ts +1 -1
- package/dist/sdk/runtime-primitives.js +1 -1
- package/dist/sdk/runtime.js +1 -1
- package/docs/COMMANDS.md +23 -5
- package/docs/EXTENSIONS.md +1 -1
- package/docs/SDK.md +15 -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-A5ZEMOVR.js +0 -2
- package/dist/cli-bundle/chunks/chunk-C6WM6ZN4.js +0 -9
- package/dist/cli-bundle/chunks/chunk-HZZLSBIJ.js +0 -2
- package/dist/cli-bundle/chunks/chunk-L2ZSSMYY.js +0 -2
- package/dist/cli-bundle/chunks/chunk-NRQCBUYD.js +0 -113
- package/dist/cli-bundle/chunks/chunk-QDV7S2QS.js +0 -2
- package/dist/cli-bundle/chunks/chunk-V2S4XAX3.js +0 -2
- package/dist/cli-bundle/chunks/item-revision-3LENTXYF.js +0 -2
- package/dist/cli-bundle/chunks/item-transaction-56J5OCHA.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-HTDYNY4L.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-J72TRWR5.js +0 -44
- package/dist/cli-bundle/focused-chunks/chunk-N64AC5G6.js +0 -100
- package/dist/cli-bundle/focused-chunks/chunk-QZRYGYTI.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-SQMOF65W.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-T3ILWAEV.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-W4JMV7GF.js +0 -3
- package/dist/cli-bundle/focused-chunks/item-revision-723XCQPS.js +0 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Ea as yt,sa as wt}from"./chunk-7V65VACG.js";import{a as Wn}from"./chunk-6H36ZHMI.js";import{a as ge,b as Fn}from"./chunk-Q6K7HWZ7.js";import{c as Dn}from"./chunk-AA52P34H.js";import{ja as Gn}from"./chunk-C6WM6ZN4.js";import{t as Un}from"./chunk-QDV7S2QS.js";import{A as Oe,B as pe,D as ft,E as mt,F as z,G as _e,H as J,I as pt,J as In,kd as kt,mb as je,n as En,nb as $e,o as G,p as Sn,q as bn,r as me,vb as Nn,wb as ae}from"./chunk-CBUC4X7Q.js";import{H as ie,b as gt,g as xt,u as W}from"./chunk-OXC5KBIQ.js";import{Ib as $,Q as oe,Ra as Mn,Xg as se,lg as _t,of as ht}from"./chunk-NRQCBUYD.js";import{g as re,l as An,o as B,p as Pn,q as Rn,r as D,w as On}from"./chunk-GSLOAEY2.js";import{Q as V,R as jn,U as $n,a as vn,b as U,c as Tn,x as E}from"./chunk-I4SPJQQI.js";import{i as F}from"./chunk-TE6FBDHP.js";import{A as u,C as l,D as Cn,E as he,F as Ie,G as K,H as lt,L as Ln}from"./chunk-K672XXGQ.js";import ns from"node:fs/promises";import C from"node:path";import{readdir as Kn,realpath as Bn,stat as zn}from"node:fs/promises";import S from"node:path";var Oo=4096,Io=32,jo=1e3,$o=5e4,Mo={nodes:1e4,edges:4e4,stateIds:2e6},Y=47,ce=class extends Error{},No=new Map(Object.entries({alnum:[[48,57],[65,90],[97,122]],alpha:[[65,90],[97,122]],ascii:[[0,127]],blank:[[9,9],[32,32]],cntrl:[[0,31],[127,127]],digit:[[48,57]],graph:[[33,126]],lower:[[97,122]],print:[[32,126]],punct:[[33,47],[58,64],[91,96],[123,126]],space:[[9,13],[32,32]],upper:[[65,90]],word:[[48,57],[65,90],[95,95],[97,122]],xdigit:[[48,57],[65,70],[97,102]]}));function Jn(){return new l("--add-glob does not support negated patterns (a leading ! or !(...)); list the files or patterns to link instead",u.USAGE)}function Uo(e,t){let n=t+1;for((e[n]==="!"||e[n]==="^")&&(n+=1),e[n]==="]"&&(n+=1);n<e.length;){let r=e[n];if(r==="\\")n+=2;else if(r==="["&&e[n+1]===":"){let o=e.indexOf(":",n+2);o===-1||e[o+1]!=="]"?n+=1:n=o+2}else{if(r==="]")return n+1;n+=1}}return-1}function Go(e,t,n){let r=e[t];if(r==="{")return{index:t,kind:"{"};if(r!=="(")return;let o=e[t-1];return o!==void 0&&"@?*+!".includes(o)&&!Vn(e,t-1)?{index:t-1,kind:"("}:n.some(s=>s.kind==="(")?{index:t,kind:"plain"}:void 0}function Fo(e,t,n,r,o){let s=e[t],i=n.at(-1);if(s===")"&&i?.kind==="plain"){n.pop(),o.set(i.index,t);return}let a=s==="}"?"{":s===")"?"(":void 0;if(!(a===void 0||i?.kind!==a)&&(n.pop(),r.set(i.index,t),e[i.index]==="!"))throw Jn()}function Do(e){let t=new Map,n=new Map,r=new Map,o=[],s=0;for(;s<e.length;){if(e[s]==="\\"){s+=2;continue}let i=e[s]==="["?Uo(e,s):-1;if(i!==-1){n.set(s,i),s=i;continue}let a=Go(e,s,o);if(a!==void 0?o.push(a):Fo(e,s,o,t,r),o.length>Io)throw new ce;s+=1}return{closers:t,brackets:n,groups:r}}function Vn(e,t){let n=0;for(let r=t-1;r>=0&&e[r]==="\\";r-=1)n+=1;return n%2===1}function X(e){return Array.from(e,t=>({kind:"char",value:t.codePointAt(0)}))}function Wo(e){let t=/^(-?(?:0|[1-9]\d{0,8}))\.\.(-?(?:0|[1-9]\d{0,8}))$/u.exec(e),n=/^([A-Za-z])\.\.([A-Za-z])$/u.exec(e);if(t===null&&n===null)return;let[r,o]=t!==null?[Number(t[1]),Number(t[2])]:[n[1].codePointAt(0),n[2].codePointAt(0)];if(Math.abs(o-r)+1>jo)throw new ce;let s=r<=o?1:-1,i=[];for(let a=r;a!==o+s;a+=s)i.push(t!==null?String(a):String.fromCodePoint(a));return i}function qo(e,t){if(e[t]!=="["||e[t+1]!==":")return;let n=e.indexOf(":",t+2);if(!(n===-1||e[n+1]!=="]"))return{ranges:No.get(e.slice(t+2,n).join(""))??[],next:n+2}}function qn(e,t,n){let r=e[t]==="\\"&&t+1<n;return{codePoint:e[r?t+1:t].codePointAt(0),next:t+(r?2:1)}}function Ho(e,t,n){let r=[];for(let o=t;o<n;o+=1)e[o]==="\\"&&o+1<n&&(o+=1),r.push(e[o].codePointAt(0));return r}function Ko(e,t,n){let r=t+1,o=e[r]==="!"||e[r]==="^";o&&(r+=1);let s=[],i=n-1;for(;r<i;){let a=qo(e,r);if(a!==void 0){s.push(...a.ranges),r=a.next;continue}let c=qn(e,r,i);if(r=c.next,e[r]!=="-"||r+1>=i){s.push([c.codePoint,c.codePoint]);continue}let d=qn(e,r+1,i);r=d.next,c.codePoint<=d.codePoint&&s.push([c.codePoint,d.codePoint])}return{kind:"class",negated:o,ranges:s,literal:Ho(e,t,n)}}var vt=class{chars;closers;brackets;groups;constructor(t,n){this.chars=t,this.closers=n.closers,this.brackets=n.brackets,this.groups=n.groups}alternatives(t,n,r){let o=[],s=t;for(;;){let{nodes:i,stop:a}=this.sequence(s,n,r);if(o.push(i),a>=n)return o;s=a+1}}sequence(t,n,r){let o=[],s=t;for(;s<n;){if(this.chars[s]===r)return{nodes:o,stop:s};let i=this.token(s,n);o.push(...i.nodes),s=i.next}return{nodes:o,stop:n}}token(t,n){let r=this.chars[t];if(r==="\\")return{nodes:X(t+1<n?this.chars[t+1]:"\\"),next:t+2};let o=this.closers.get(t);if(o!==void 0)return{nodes:r==="{"?this.brace(t,o):this.extglob(r,t,o),next:o+1};let s=this.groups.get(t);if(s!==void 0)return{nodes:[...X("("),...this.sequence(t+1,s,void 0).nodes,...X(")")],next:s+1};let i=this.brackets.get(t);return i!==void 0?{nodes:[Ko(this.chars,t,i)],next:i}:r==="*"?this.stars(t,n):{nodes:r==="?"?[{kind:"any"}]:X(r),next:t+1}}extglob(t,n,r){let o=this.alternatives(n+2,r,"|");return[t==="@"?{kind:"alt",options:o}:{kind:"repeat",optional:t!=="+",many:t!=="?",options:o}]}brace(t,n){let r=this.alternatives(t+1,n,",");if(r.length>1)return[{kind:"alt",options:r}];let o=Wo(this.chars.slice(t+1,n).join(""));return o!==void 0?[{kind:"alt",options:o.map(X)}]:[...X("{"),...r[0],...X("}")]}stars(t,n){let r=1;for(;this.chars[t+r]==="*"&&t+r<n&&!this.closers.has(t+r);)r+=1;if(r!==2)return{nodes:[{kind:"star"}],next:t+r};let o=t+r<n&&this.chars[t+r]==="/";return{nodes:[{kind:"globstar",slash:o}],next:t+r+(o?1:0)}}},Tt=["segment","inside"],Me={kind:"any"};function Et(e){return Tt.flatMap(t=>e[t]===void 0?[]:[e[t]])}var St=class{states=[];add(){if(this.states.length>=$o)throw new ce;return this.states.push({epsilon:[],syntactic:[],edges:[]}),this.states.length-1}epsilon(t,n,r=!0){this.states[t].epsilon.push(n),r&&this.states[t].syntactic.push(n)}consume(t,n,r){let o=this.add();for(let s of Et(t))this.states[s].edges.push({test:n,to:o});return{[r]:o}}join(t){let n={};for(let r of Tt){let o=t.flatMap(s=>s[r]===void 0?[]:[s[r]]);if(o.length===1&&(n[r]=o[0]),o.length>1){let s=this.add();for(let i of o)this.epsilon(i,s);n[r]=s}}return n}feed(t,n){for(let r of Tt)t[r]!==void 0&&this.epsilon(t[r],n[r])}build(t,n){let r=n;for(let o of t)r=this.node(o,r);return r}alternation(t,n){return this.join(t.map(r=>this.build(r,n)))}star(t){let n=this.add();for(let r of Et(t))this.epsilon(r,n,!1);return this.states[n].edges.push({test:Me,to:n}),{inside:n}}segments(t){let n=this.add();this.epsilon(t,n,!1);let r=this.add();return this.states[n].edges.push({test:Me,to:r}),this.states[r].edges.push({test:Me,to:r},{test:{kind:"char",value:Y},to:n}),n}globstar(t,n){if(n){let o=[];return t.segment!==void 0&&o.push({segment:this.segments(t.segment)}),t.inside!==void 0&&o.push(this.consume(this.star({inside:t.inside}),{kind:"char",value:Y},"segment")),this.join(o)}let r=this.star(t);return t.segment!==void 0&&this.globstars.push({continuation:r.inside,entry:t.segment}),r}globstars=[];syntacticClosure(t){let n=new Set(t),r=[...t];for(;r.length>0;)for(let o of this.states[r.pop()].syntactic)n.has(o)||(n.add(o),r.push(o));return n}resolveGlobstars(t){for(let{continuation:n,entry:r}of this.globstars){let o=this.syntacticClosure([n]);if(o.has(t)){let a=this.add();this.epsilon(r,a,!1),this.states[a].edges.push({test:{kind:"all"},to:a}),this.epsilon(a,t,!1)}let s=new Set;for(let a of o)for(let{test:c,to:d}of this.states[a].edges)Xn(c,Y)&&s.add(d);if(s.size===0)continue;let i=this.segments(r);for(let a of s)this.epsilon(i,a,!1)}}repeat(t,n){if(!t.many)return this.join([n,this.alternation(t.options,n)]);let r={segment:this.add(),inside:this.add()};return this.feed(t.optional?n:this.alternation(t.options,n),r),this.feed(this.alternation(t.options,r),r),r}node(t,n){switch(t.kind){case"char":return this.consume(n,{kind:"char",value:t.value},t.value===Y?"segment":"inside");case"any":return this.consume(n,Me,"inside");case"star":return this.star(n);case"globstar":return this.globstar(n,t.slash);case"class":return this.join([this.consume(n,{kind:"class",negated:t.negated,ranges:t.ranges},"inside"),this.build(t.literal.map(r=>({kind:"char",value:r})),n)]);case"alt":return this.alternation(t.options,n);case"repeat":return this.repeat(t,n)}}};function Xn(e,t){switch(e.kind){case"char":return e.value===t;case"any":return t!==Y;case"all":return!0;case"class":return t!==Y&&e.ranges.some(([n,r])=>t>=n&&t<=r)!==e.negated}}var bt=class{generation=0;nextId=0;nodes=new Map;edges=new Map;stateIds=0;nfa;acceptState;limits;start;constructor(t,n,r,o){this.nfa=t,this.acceptState=r,this.limits=o,this.start=this.node(this.closure([n]))}retained(){return{nodes:this.nodes.size,edges:this.edges.size,stateIds:this.stateIds}}reset(){this.generation+=1,this.nodes=new Map,this.edges=new Map,this.stateIds=0}closure(t){let n=new Set(t),r=[...t];for(;r.length>0;)for(let o of this.nfa.states[r.pop()].epsilon)n.has(o)||(n.add(o),r.push(o));return[...n].sort((o,s)=>o-s)}node(t){let n=t.join(","),r=this.nodes.get(n);if(r!==void 0)return r;(this.nodes.size>=this.limits.nodes||this.stateIds+t.length>this.limits.stateIds)&&this.reset();let o={id:this.nextId,generation:this.generation,states:t,accepting:t.includes(this.acceptState)};return this.nextId+=1,this.nodes.set(n,o),this.stateIds+=t.length,o}step(t,n){let r=`${t.id}:${n}`,o=t.generation===this.generation?this.edges.get(r):void 0;if(o!==void 0)return o;let s=[];for(let a of t.states)for(let{test:c,to:d}of this.nfa.states[a].edges)Xn(c,n)&&s.push(d);let i=this.node(this.closure(s));return this.edges.size>=this.limits.edges&&this.reset(),t.generation===this.generation&&this.edges.set(r,i),i}advance(t,n){let r=t;for(let o of n){if(r.states.length===0)return r;r=this.step(r,o.codePointAt(0))}return r}};function Bo(e,t=Mo){let n=Array.from(e),r=new vt(n,Do(n)).sequence(0,n.length,void 0).nodes,o=new St,s=o.add(),i=o.add();for(let a of Et(o.build(r,{segment:s})))o.epsilon(a,i);return o.resolveGlobstars(i),new bt(o,s,i,t)}function zo(e){return!/[*?[\]{}()!@+\\]/u.test(e)}function Hn(e){return e.isFile()?"file":e.isDirectory()?"directory":"other"}async function Jo(e,t,n){if(!n.isSymbolicLink())return{kind:Hn(n),real:S.join(t,n.name)};try{let r=await Bn(S.join(e,n.name));return{kind:Hn(await zn(r)),real:r}}catch{return}}async function Yn(e,t,n,r,o,s,i){let a;try{a=await Kn(t,{withFileTypes:!0})}catch{return}for(let c of a){let d=e.advance(o,c.name);if(d.states.length===0)continue;let f=await Jo(t,n,c);if(f===void 0)continue;let m=S.posix.join(r,c.name);if(f.kind==="file"&&d.accepting&&i.push(m),f.kind!=="directory")continue;let p=e.step(d,Y);p.states.length===0||s.has(f.real)||(s.add(f.real),await Yn(e,S.join(t,c.name),f.real,m,p,s,i),s.delete(f.real))}}function Vo(e){let t=S.posix.normalize(e);return/^\/\/[^/]/u.test(e)?`/${t}`:t}function Xo(e){let t=e;for(;t.length>1&&t.endsWith("/")&&!Vn(t,t.length-1);)t=t.slice(0,-1);return t}async function Zn(e,t){return(await Kn(e).catch(()=>[])).includes(t)}async function Qn(e,t){let n=e,r=0;for(;t[r]==="..";)n=S.dirname(n),r+=1;for(;r<t.length;r+=1){if(!await Zn(n,t[r]))return!1;n=S.join(n,t[r])}return!0}function er(e,t=process.platform){return e.startsWith("/")||t==="win32"&&/^[A-Za-z]:\//u.test(e)}async function Yo(e,t){let n=S.resolve(t,e),r=await zn(n).catch(()=>{});if(r===void 0||!r.isFile())return[];let o=er(e);return(o?await Zn(S.dirname(n),S.basename(n)):await Qn(t,e.split("/")))?[o?n.replaceAll("\\","/"):S.posix.normalize(e)]:[]}function Zo(e,t){let n=e.split("/"),r=0;for(;r<n.length&&zo(n[r]);)r+=1;if(r===n.length)return;let o=r===0?"":`${n.slice(0,r).join("/")}/`,s=S.resolve(t,o),i=n.slice(r).join("/");if(er(e))return{root:s,base:s.replaceAll("\\","/"),rest:i,prefix:[]};let a=S.posix.normalize(o===""?".":o).replace(/\/$/u,"");return{root:s,base:a==="."?"":a,rest:i,prefix:n.slice(0,r)}}function Qo(e){try{return Bo(e)}catch(t){if(t instanceof ce)return;throw t}}async function tr(e,t){if(e.startsWith("!"))throw Jn();if(Array.from(e).length>Oo)return[];let n=Xo(Vo(e)),r=Zo(n,t);if(r===void 0)return Yo(n,t);let o=Qo(r.rest);if(o===void 0||!await Qn(t,r.prefix))return[];let s=await Bn(r.root).catch(()=>{});if(s===void 0)return[];let i=[];return await Yn(o,r.root,s,"",o.start,new Set([s]),i),i.map(a=>es(r.base,a))}function es(e,t){return e.startsWith("//")?`/${S.posix.join(e.slice(1),t)}`:S.posix.join(e,t)}var ts=/^[a-z][a-z0-9+.-]+:\/\//i;function Ct(e){return ts.test(e.trim())}var Lt=["refuse","replace","append"],Rt="; ";function rs(e,t){if(e===void 0)return"refuse";let n=e.trim().toLowerCase();if(!Lt.some(r=>r===n))throw new l(`--note-conflict must be one of ${Lt.join(", ")}; got "${e}"`,u.USAGE,{code:"invalid_argument_value",flag:"--note-conflict",value:e,required:`Pass --note-conflict ${Lt.join("|")}.`});if(!t)throw new l("--note-conflict requires --add or --add-glob in the same invocation (it decides how those links treat an existing note)",u.USAGE,{code:"missing_required_argument",flag:"--note-conflict",required:"Pass --add or --add-glob with --note-conflict."});return n}function os(e,t,n){if(t===void 0||t===e)return{note:e,outcome:"unchanged",conflict:!1};if(e===void 0)return{note:t,outcome:"note_added",conflict:!1};if(n==="replace")return{note:t,outcome:"note_replaced",conflict:!1};if(n==="append"){let r=Rt;return`${r}${e}${r}`.includes(`${r}${t}${r}`)?{note:e,outcome:"unchanged",conflict:!1}:{note:`${e}${Rt}${t}`,outcome:"note_appended",conflict:!1}}return{note:e,outcome:"unchanged",conflict:!0}}function ss(e){let t=e.conflicts[0],n=e.conflicts.length>1?` and ${e.conflicts.length-1} more`:"",r=e.retryArgs("append"),o=e.retryArgs("replace"),s=t.source==="stored"?`${e.itemId} already links ${e.noun} ${t.path} with the note "${t.existing_note}"${n}; the add was refused so that note is kept`:`The add names ${e.noun} ${t.path} on ${e.itemId} with two notes, "${t.existing_note}" and then "${t.requested_note}"${n}; the add was refused because they disagree`;return new l(s,u.CONFLICT,{code:"linked_artifact_note_conflict",item_id:e.itemId,why:"A different stored note is usually another agent's rationale, so --add never overwrites it silently.",required:"Re-run with --note-conflict append to keep both notes, or --note-conflict replace to overwrite the stored note.",...r===void 0||o===void 0?{}:{nextSteps:[e.render(r),e.render(o)],recovery:{suggested_retry:e.render(r),suggested_retry_args:r}},details:{conflicts:e.conflicts.map(i=>({...i}))}})}var Ot=["path","scope","note"],is=["pattern","glob","path","scope","note"],as=["path"],cs=["from","to"],ds=new Set(["note","scope"]);function nr(e){return JSON.parse(JSON.stringify(e))}function Mt(e,t){let n=e.map(nr);return t.filter(r=>{let o=nr(r),s=n.findIndex(i=>U(i,o));return s>=0&&n.splice(s,1),s<0})}function xe(e){let t=e.fullHistory?[...e.stored]:[...e.written],n=t.length<e.stored.length;return{entries:t,total_count:e.stored.length,returned_count:t.length,has_more:n,mutation_receipt:{changed_count:e.written.length,removed_count:e.removedCount,full_history_included:!n,...e.linkOutcomes&&e.linkOutcomes.length>0?{link_outcomes:[...e.linkOutcomes]}:{}},omission_receipt:{has_omissions:n,omitted_field_group_count:n?1:0,omitted_field_groups:n?[{name:`${e.collectionKey}_history`,restore_with:{selector:"full_history",cli_flag:"--full-history",sdk_option:"fullHistory",mcp_option:"full"}}]:[]}}}function rr(e){let t=e??"project";if(!F.includes(t))throw new l(`Invalid scope "${e}". Valid scopes: ${F.join(", ")} (default: project).`,u.USAGE);return t}function It(e){if(e.startsWith("```")||e.includes(`
|
|
1
|
+
import{Ea as yt,sa as wt}from"./chunk-JJ73G5UT.js";import{a as Wn}from"./chunk-6H36ZHMI.js";import{a as ge,b as Fn}from"./chunk-IW4A3I4N.js";import{c as Dn}from"./chunk-AA52P34H.js";import{ja as Gn}from"./chunk-Q2HMDV56.js";import{u as Un}from"./chunk-CQHB3ZZH.js";import{A as Oe,B as pe,D as ft,E as mt,F as z,G as _e,H as J,I as pt,J as In,kd as kt,mb as je,n as En,nb as $e,o as G,p as Sn,q as bn,r as me,vb as Nn,wb as ae}from"./chunk-TDOF7BKO.js";import{H as ie,b as gt,g as xt,u as W}from"./chunk-RRBNCL63.js";import{$g as se,Lb as $,T as oe,Ua as Mn,og as _t,rf as ht}from"./chunk-UXEZXGAD.js";import{g as re,l as An,o as B,p as Pn,q as Rn,r as D,w as On}from"./chunk-GSLOAEY2.js";import{Q as V,R as jn,U as $n,a as vn,b as U,c as Tn,x as E}from"./chunk-XGNUDSCG.js";import{i as F}from"./chunk-TE6FBDHP.js";import{A as u,C as l,D as Cn,E as he,F as Ie,G as K,H as lt,L as Ln}from"./chunk-K672XXGQ.js";import ns from"node:fs/promises";import C from"node:path";import{readdir as Kn,realpath as Bn,stat as zn}from"node:fs/promises";import S from"node:path";var Oo=4096,Io=32,jo=1e3,$o=5e4,Mo={nodes:1e4,edges:4e4,stateIds:2e6},Y=47,ce=class extends Error{},No=new Map(Object.entries({alnum:[[48,57],[65,90],[97,122]],alpha:[[65,90],[97,122]],ascii:[[0,127]],blank:[[9,9],[32,32]],cntrl:[[0,31],[127,127]],digit:[[48,57]],graph:[[33,126]],lower:[[97,122]],print:[[32,126]],punct:[[33,47],[58,64],[91,96],[123,126]],space:[[9,13],[32,32]],upper:[[65,90]],word:[[48,57],[65,90],[95,95],[97,122]],xdigit:[[48,57],[65,70],[97,102]]}));function Jn(){return new l("--add-glob does not support negated patterns (a leading ! or !(...)); list the files or patterns to link instead",u.USAGE)}function Uo(e,t){let n=t+1;for((e[n]==="!"||e[n]==="^")&&(n+=1),e[n]==="]"&&(n+=1);n<e.length;){let r=e[n];if(r==="\\")n+=2;else if(r==="["&&e[n+1]===":"){let o=e.indexOf(":",n+2);o===-1||e[o+1]!=="]"?n+=1:n=o+2}else{if(r==="]")return n+1;n+=1}}return-1}function Go(e,t,n){let r=e[t];if(r==="{")return{index:t,kind:"{"};if(r!=="(")return;let o=e[t-1];return o!==void 0&&"@?*+!".includes(o)&&!Vn(e,t-1)?{index:t-1,kind:"("}:n.some(s=>s.kind==="(")?{index:t,kind:"plain"}:void 0}function Fo(e,t,n,r,o){let s=e[t],i=n.at(-1);if(s===")"&&i?.kind==="plain"){n.pop(),o.set(i.index,t);return}let a=s==="}"?"{":s===")"?"(":void 0;if(!(a===void 0||i?.kind!==a)&&(n.pop(),r.set(i.index,t),e[i.index]==="!"))throw Jn()}function Do(e){let t=new Map,n=new Map,r=new Map,o=[],s=0;for(;s<e.length;){if(e[s]==="\\"){s+=2;continue}let i=e[s]==="["?Uo(e,s):-1;if(i!==-1){n.set(s,i),s=i;continue}let a=Go(e,s,o);if(a!==void 0?o.push(a):Fo(e,s,o,t,r),o.length>Io)throw new ce;s+=1}return{closers:t,brackets:n,groups:r}}function Vn(e,t){let n=0;for(let r=t-1;r>=0&&e[r]==="\\";r-=1)n+=1;return n%2===1}function X(e){return Array.from(e,t=>({kind:"char",value:t.codePointAt(0)}))}function Wo(e){let t=/^(-?(?:0|[1-9]\d{0,8}))\.\.(-?(?:0|[1-9]\d{0,8}))$/u.exec(e),n=/^([A-Za-z])\.\.([A-Za-z])$/u.exec(e);if(t===null&&n===null)return;let[r,o]=t!==null?[Number(t[1]),Number(t[2])]:[n[1].codePointAt(0),n[2].codePointAt(0)];if(Math.abs(o-r)+1>jo)throw new ce;let s=r<=o?1:-1,i=[];for(let a=r;a!==o+s;a+=s)i.push(t!==null?String(a):String.fromCodePoint(a));return i}function qo(e,t){if(e[t]!=="["||e[t+1]!==":")return;let n=e.indexOf(":",t+2);if(!(n===-1||e[n+1]!=="]"))return{ranges:No.get(e.slice(t+2,n).join(""))??[],next:n+2}}function qn(e,t,n){let r=e[t]==="\\"&&t+1<n;return{codePoint:e[r?t+1:t].codePointAt(0),next:t+(r?2:1)}}function Ho(e,t,n){let r=[];for(let o=t;o<n;o+=1)e[o]==="\\"&&o+1<n&&(o+=1),r.push(e[o].codePointAt(0));return r}function Ko(e,t,n){let r=t+1,o=e[r]==="!"||e[r]==="^";o&&(r+=1);let s=[],i=n-1;for(;r<i;){let a=qo(e,r);if(a!==void 0){s.push(...a.ranges),r=a.next;continue}let c=qn(e,r,i);if(r=c.next,e[r]!=="-"||r+1>=i){s.push([c.codePoint,c.codePoint]);continue}let d=qn(e,r+1,i);r=d.next,c.codePoint<=d.codePoint&&s.push([c.codePoint,d.codePoint])}return{kind:"class",negated:o,ranges:s,literal:Ho(e,t,n)}}var vt=class{chars;closers;brackets;groups;constructor(t,n){this.chars=t,this.closers=n.closers,this.brackets=n.brackets,this.groups=n.groups}alternatives(t,n,r){let o=[],s=t;for(;;){let{nodes:i,stop:a}=this.sequence(s,n,r);if(o.push(i),a>=n)return o;s=a+1}}sequence(t,n,r){let o=[],s=t;for(;s<n;){if(this.chars[s]===r)return{nodes:o,stop:s};let i=this.token(s,n);o.push(...i.nodes),s=i.next}return{nodes:o,stop:n}}token(t,n){let r=this.chars[t];if(r==="\\")return{nodes:X(t+1<n?this.chars[t+1]:"\\"),next:t+2};let o=this.closers.get(t);if(o!==void 0)return{nodes:r==="{"?this.brace(t,o):this.extglob(r,t,o),next:o+1};let s=this.groups.get(t);if(s!==void 0)return{nodes:[...X("("),...this.sequence(t+1,s,void 0).nodes,...X(")")],next:s+1};let i=this.brackets.get(t);return i!==void 0?{nodes:[Ko(this.chars,t,i)],next:i}:r==="*"?this.stars(t,n):{nodes:r==="?"?[{kind:"any"}]:X(r),next:t+1}}extglob(t,n,r){let o=this.alternatives(n+2,r,"|");return[t==="@"?{kind:"alt",options:o}:{kind:"repeat",optional:t!=="+",many:t!=="?",options:o}]}brace(t,n){let r=this.alternatives(t+1,n,",");if(r.length>1)return[{kind:"alt",options:r}];let o=Wo(this.chars.slice(t+1,n).join(""));return o!==void 0?[{kind:"alt",options:o.map(X)}]:[...X("{"),...r[0],...X("}")]}stars(t,n){let r=1;for(;this.chars[t+r]==="*"&&t+r<n&&!this.closers.has(t+r);)r+=1;if(r!==2)return{nodes:[{kind:"star"}],next:t+r};let o=t+r<n&&this.chars[t+r]==="/";return{nodes:[{kind:"globstar",slash:o}],next:t+r+(o?1:0)}}},Tt=["segment","inside"],Me={kind:"any"};function Et(e){return Tt.flatMap(t=>e[t]===void 0?[]:[e[t]])}var St=class{states=[];add(){if(this.states.length>=$o)throw new ce;return this.states.push({epsilon:[],syntactic:[],edges:[]}),this.states.length-1}epsilon(t,n,r=!0){this.states[t].epsilon.push(n),r&&this.states[t].syntactic.push(n)}consume(t,n,r){let o=this.add();for(let s of Et(t))this.states[s].edges.push({test:n,to:o});return{[r]:o}}join(t){let n={};for(let r of Tt){let o=t.flatMap(s=>s[r]===void 0?[]:[s[r]]);if(o.length===1&&(n[r]=o[0]),o.length>1){let s=this.add();for(let i of o)this.epsilon(i,s);n[r]=s}}return n}feed(t,n){for(let r of Tt)t[r]!==void 0&&this.epsilon(t[r],n[r])}build(t,n){let r=n;for(let o of t)r=this.node(o,r);return r}alternation(t,n){return this.join(t.map(r=>this.build(r,n)))}star(t){let n=this.add();for(let r of Et(t))this.epsilon(r,n,!1);return this.states[n].edges.push({test:Me,to:n}),{inside:n}}segments(t){let n=this.add();this.epsilon(t,n,!1);let r=this.add();return this.states[n].edges.push({test:Me,to:r}),this.states[r].edges.push({test:Me,to:r},{test:{kind:"char",value:Y},to:n}),n}globstar(t,n){if(n){let o=[];return t.segment!==void 0&&o.push({segment:this.segments(t.segment)}),t.inside!==void 0&&o.push(this.consume(this.star({inside:t.inside}),{kind:"char",value:Y},"segment")),this.join(o)}let r=this.star(t);return t.segment!==void 0&&this.globstars.push({continuation:r.inside,entry:t.segment}),r}globstars=[];syntacticClosure(t){let n=new Set(t),r=[...t];for(;r.length>0;)for(let o of this.states[r.pop()].syntactic)n.has(o)||(n.add(o),r.push(o));return n}resolveGlobstars(t){for(let{continuation:n,entry:r}of this.globstars){let o=this.syntacticClosure([n]);if(o.has(t)){let a=this.add();this.epsilon(r,a,!1),this.states[a].edges.push({test:{kind:"all"},to:a}),this.epsilon(a,t,!1)}let s=new Set;for(let a of o)for(let{test:c,to:d}of this.states[a].edges)Xn(c,Y)&&s.add(d);if(s.size===0)continue;let i=this.segments(r);for(let a of s)this.epsilon(i,a,!1)}}repeat(t,n){if(!t.many)return this.join([n,this.alternation(t.options,n)]);let r={segment:this.add(),inside:this.add()};return this.feed(t.optional?n:this.alternation(t.options,n),r),this.feed(this.alternation(t.options,r),r),r}node(t,n){switch(t.kind){case"char":return this.consume(n,{kind:"char",value:t.value},t.value===Y?"segment":"inside");case"any":return this.consume(n,Me,"inside");case"star":return this.star(n);case"globstar":return this.globstar(n,t.slash);case"class":return this.join([this.consume(n,{kind:"class",negated:t.negated,ranges:t.ranges},"inside"),this.build(t.literal.map(r=>({kind:"char",value:r})),n)]);case"alt":return this.alternation(t.options,n);case"repeat":return this.repeat(t,n)}}};function Xn(e,t){switch(e.kind){case"char":return e.value===t;case"any":return t!==Y;case"all":return!0;case"class":return t!==Y&&e.ranges.some(([n,r])=>t>=n&&t<=r)!==e.negated}}var bt=class{generation=0;nextId=0;nodes=new Map;edges=new Map;stateIds=0;nfa;acceptState;limits;start;constructor(t,n,r,o){this.nfa=t,this.acceptState=r,this.limits=o,this.start=this.node(this.closure([n]))}retained(){return{nodes:this.nodes.size,edges:this.edges.size,stateIds:this.stateIds}}reset(){this.generation+=1,this.nodes=new Map,this.edges=new Map,this.stateIds=0}closure(t){let n=new Set(t),r=[...t];for(;r.length>0;)for(let o of this.nfa.states[r.pop()].epsilon)n.has(o)||(n.add(o),r.push(o));return[...n].sort((o,s)=>o-s)}node(t){let n=t.join(","),r=this.nodes.get(n);if(r!==void 0)return r;(this.nodes.size>=this.limits.nodes||this.stateIds+t.length>this.limits.stateIds)&&this.reset();let o={id:this.nextId,generation:this.generation,states:t,accepting:t.includes(this.acceptState)};return this.nextId+=1,this.nodes.set(n,o),this.stateIds+=t.length,o}step(t,n){let r=`${t.id}:${n}`,o=t.generation===this.generation?this.edges.get(r):void 0;if(o!==void 0)return o;let s=[];for(let a of t.states)for(let{test:c,to:d}of this.nfa.states[a].edges)Xn(c,n)&&s.push(d);let i=this.node(this.closure(s));return this.edges.size>=this.limits.edges&&this.reset(),t.generation===this.generation&&this.edges.set(r,i),i}advance(t,n){let r=t;for(let o of n){if(r.states.length===0)return r;r=this.step(r,o.codePointAt(0))}return r}};function Bo(e,t=Mo){let n=Array.from(e),r=new vt(n,Do(n)).sequence(0,n.length,void 0).nodes,o=new St,s=o.add(),i=o.add();for(let a of Et(o.build(r,{segment:s})))o.epsilon(a,i);return o.resolveGlobstars(i),new bt(o,s,i,t)}function zo(e){return!/[*?[\]{}()!@+\\]/u.test(e)}function Hn(e){return e.isFile()?"file":e.isDirectory()?"directory":"other"}async function Jo(e,t,n){if(!n.isSymbolicLink())return{kind:Hn(n),real:S.join(t,n.name)};try{let r=await Bn(S.join(e,n.name));return{kind:Hn(await zn(r)),real:r}}catch{return}}async function Yn(e,t,n,r,o,s,i){let a;try{a=await Kn(t,{withFileTypes:!0})}catch{return}for(let c of a){let d=e.advance(o,c.name);if(d.states.length===0)continue;let f=await Jo(t,n,c);if(f===void 0)continue;let m=S.posix.join(r,c.name);if(f.kind==="file"&&d.accepting&&i.push(m),f.kind!=="directory")continue;let p=e.step(d,Y);p.states.length===0||s.has(f.real)||(s.add(f.real),await Yn(e,S.join(t,c.name),f.real,m,p,s,i),s.delete(f.real))}}function Vo(e){let t=S.posix.normalize(e);return/^\/\/[^/]/u.test(e)?`/${t}`:t}function Xo(e){let t=e;for(;t.length>1&&t.endsWith("/")&&!Vn(t,t.length-1);)t=t.slice(0,-1);return t}async function Zn(e,t){return(await Kn(e).catch(()=>[])).includes(t)}async function Qn(e,t){let n=e,r=0;for(;t[r]==="..";)n=S.dirname(n),r+=1;for(;r<t.length;r+=1){if(!await Zn(n,t[r]))return!1;n=S.join(n,t[r])}return!0}function er(e,t=process.platform){return e.startsWith("/")||t==="win32"&&/^[A-Za-z]:\//u.test(e)}async function Yo(e,t){let n=S.resolve(t,e),r=await zn(n).catch(()=>{});if(r===void 0||!r.isFile())return[];let o=er(e);return(o?await Zn(S.dirname(n),S.basename(n)):await Qn(t,e.split("/")))?[o?n.replaceAll("\\","/"):S.posix.normalize(e)]:[]}function Zo(e,t){let n=e.split("/"),r=0;for(;r<n.length&&zo(n[r]);)r+=1;if(r===n.length)return;let o=r===0?"":`${n.slice(0,r).join("/")}/`,s=S.resolve(t,o),i=n.slice(r).join("/");if(er(e))return{root:s,base:s.replaceAll("\\","/"),rest:i,prefix:[]};let a=S.posix.normalize(o===""?".":o).replace(/\/$/u,"");return{root:s,base:a==="."?"":a,rest:i,prefix:n.slice(0,r)}}function Qo(e){try{return Bo(e)}catch(t){if(t instanceof ce)return;throw t}}async function tr(e,t){if(e.startsWith("!"))throw Jn();if(Array.from(e).length>Oo)return[];let n=Xo(Vo(e)),r=Zo(n,t);if(r===void 0)return Yo(n,t);let o=Qo(r.rest);if(o===void 0||!await Qn(t,r.prefix))return[];let s=await Bn(r.root).catch(()=>{});if(s===void 0)return[];let i=[];return await Yn(o,r.root,s,"",o.start,new Set([s]),i),i.map(a=>es(r.base,a))}function es(e,t){return e.startsWith("//")?`/${S.posix.join(e.slice(1),t)}`:S.posix.join(e,t)}var ts=/^[a-z][a-z0-9+.-]+:\/\//i;function Ct(e){return ts.test(e.trim())}var Lt=["refuse","replace","append"],Rt="; ";function rs(e,t){if(e===void 0)return"refuse";let n=e.trim().toLowerCase();if(!Lt.some(r=>r===n))throw new l(`--note-conflict must be one of ${Lt.join(", ")}; got "${e}"`,u.USAGE,{code:"invalid_argument_value",flag:"--note-conflict",value:e,required:`Pass --note-conflict ${Lt.join("|")}.`});if(!t)throw new l("--note-conflict requires --add or --add-glob in the same invocation (it decides how those links treat an existing note)",u.USAGE,{code:"missing_required_argument",flag:"--note-conflict",required:"Pass --add or --add-glob with --note-conflict."});return n}function os(e,t,n){if(t===void 0||t===e)return{note:e,outcome:"unchanged",conflict:!1};if(e===void 0)return{note:t,outcome:"note_added",conflict:!1};if(n==="replace")return{note:t,outcome:"note_replaced",conflict:!1};if(n==="append"){let r=Rt;return`${r}${e}${r}`.includes(`${r}${t}${r}`)?{note:e,outcome:"unchanged",conflict:!1}:{note:`${e}${Rt}${t}`,outcome:"note_appended",conflict:!1}}return{note:e,outcome:"unchanged",conflict:!0}}function ss(e){let t=e.conflicts[0],n=e.conflicts.length>1?` and ${e.conflicts.length-1} more`:"",r=e.retryArgs("append"),o=e.retryArgs("replace"),s=t.source==="stored"?`${e.itemId} already links ${e.noun} ${t.path} with the note "${t.existing_note}"${n}; the add was refused so that note is kept`:`The add names ${e.noun} ${t.path} on ${e.itemId} with two notes, "${t.existing_note}" and then "${t.requested_note}"${n}; the add was refused because they disagree`;return new l(s,u.CONFLICT,{code:"linked_artifact_note_conflict",item_id:e.itemId,why:"A different stored note is usually another agent's rationale, so --add never overwrites it silently.",required:"Re-run with --note-conflict append to keep both notes, or --note-conflict replace to overwrite the stored note.",...r===void 0||o===void 0?{}:{nextSteps:[e.render(r),e.render(o)],recovery:{suggested_retry:e.render(r),suggested_retry_args:r}},details:{conflicts:e.conflicts.map(i=>({...i}))}})}var Ot=["path","scope","note"],is=["pattern","glob","path","scope","note"],as=["path"],cs=["from","to"],ds=new Set(["note","scope"]);function nr(e){return JSON.parse(JSON.stringify(e))}function Mt(e,t){let n=e.map(nr);return t.filter(r=>{let o=nr(r),s=n.findIndex(i=>U(i,o));return s>=0&&n.splice(s,1),s<0})}function xe(e){let t=e.fullHistory?[...e.stored]:[...e.written],n=t.length<e.stored.length;return{entries:t,total_count:e.stored.length,returned_count:t.length,has_more:n,mutation_receipt:{changed_count:e.written.length,removed_count:e.removedCount,full_history_included:!n,...e.linkOutcomes&&e.linkOutcomes.length>0?{link_outcomes:[...e.linkOutcomes]}:{}},omission_receipt:{has_omissions:n,omitted_field_group_count:n?1:0,omitted_field_groups:n?[{name:`${e.collectionKey}_history`,restore_with:{selector:"full_history",cli_flag:"--full-history",sdk_option:"fullHistory",mcp_option:"full"}}]:[]}}}function rr(e){let t=e??"project";if(!F.includes(t))throw new l(`Invalid scope "${e}". Valid scopes: ${F.join(", ")} (default: project).`,u.USAGE);return t}function It(e){if(e.startsWith("```")||e.includes(`
|
|
2
2
|
`)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(e))return!0;let t=e.indexOf(","),n=e.slice(0,t>=0?t:e.length),r=n.indexOf("=");return r>=0&&!/\s/u.test(e)&&(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)||/^(?:[A-Za-z]:[\\/]|[\\/]{1,2}|\.\.?(?:[\\/]))/u.test(e)||[e.indexOf("/"),e.indexOf("\\")].some(o=>o>=0&&o<r))?!1:n.includes("=")||Sn(e)}function us(e){let t=0;for(let n of e)if(n==="("&&(t+=1),n===")"&&(t-=1),t<0)return!1;return t===0}function ls(e){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)&&!It(e))return{path:e,scope:"project",note:void 0};let t=e.indexOf("](");if(e.startsWith("[")&&t>0&&e.endsWith(")")){let s=e.slice(t+2,-1).trim();if(s.length>0&&us(s))return{path:s,scope:"project",note:e.slice(1,t).trim()||void 0}}let n=e.indexOf(",");if(n<0)return;let r=e.slice(0,n).trim(),o=e.slice(n+1).trim();if(!(r.length===0||!/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(o)))return{path:o,scope:"project",note:r}}function Nt(e,t){return e?e.flatMap(n=>{let r=n.trim();if(t==="doc"){let s=ls(r);if(s!==void 0)return[s]}bn(r,"--add",`${t} path`,It(r));let o=It(r)?G(n,"--add"):{path:r};if(me(o,"--add",Ot),!o.path)throw new l(`--add requires path=<value> or a bare ${t} path`,u.USAGE);return[{path:o.path,scope:rr(o.scope),note:o.note?.trim()||void 0}]}):[]}function fs(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new l("--add-glob requires a glob pattern value",u.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(n)||n.startsWith("```")){let r=G(n,"--add-glob");me(r,"--add-glob",is);let o=r.pattern?.trim()||r.glob?.trim()||r.path?.trim();if(!o)throw new l("--add-glob key/value form requires pattern=<glob>",u.USAGE);return{pattern:o,scope:rr(r.scope),note:r.note?.trim()||void 0}}return{pattern:n,scope:"project"}}):[]}function ms(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new l("--remove requires a path value",u.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(n)||n.startsWith("```")){let r=G(n,"--remove"),o=Object.keys(r).filter(s=>ds.has(s.toLowerCase()));if(o.length>0)throw new l(`--remove identifies a linked artifact by path only and does not accept ${o.map(s=>`"${s}"`).join(", ")}. Pass just the path (path=<value>, path:<value>, or a bare path); record removal context with --message "<why removed>".`,u.USAGE);if(me(r,"--remove",as),!r.path)throw new l("--remove key/value form requires path=<value>",u.USAGE);return r.path}return n}):[]}function ps(e){return e?e.map(t=>{let n=G(t,"--migrate");me(n,"--migrate",cs);let r=n.from?.trim(),o=n.to?.trim();if(!r||!o)throw new l("--migrate requires from=<value> and to=<value>",u.USAGE);return{from:r,to:o}}):[]}function de(e,t){let n=e;for(let r of t)n.startsWith(r.from)&&(n=`${r.to}${n.slice(r.from.length)}`);return n}function hs(e,t,n=[]){if(e.length===0||t.length===0)return;let r=new Set(e.map(s=>q(de(s.path,n)))),o=[...new Set(t.map(s=>q(de(s,n))).filter(s=>r.has(s)))].sort((s,i)=>s.localeCompare(i));if(o.length!==0)throw new l(`Linked artifact mutation cannot add and remove the same normalized path in one transaction: ${o.join(", ")}. Split the replacement into separate commands so each history event has one unambiguous intent.`,u.USAGE,{code:"linked_artifact_mutation_conflict",reason:"same_path_added_and_removed",required:"Use distinct normalized paths for --add and --remove in one invocation.",why:"Conflicting batch intent cannot be applied deterministically without silently discarding metadata or a removal.",nextSteps:["Run the removal and addition as separate commands with a --message describing each intent."]})}function At(e){return e.split(C.sep).join("/")}function jt(e,t,n=process.cwd()){let r=e.trim();if(Ct(r))return r;if(C.isAbsolute(r)||/^[A-Za-z]:[\\/]/.test(r))return At(r.replaceAll("\\",C.sep));let o=C.relative(t,n);return o.startsWith(`..${C.sep}`)||o===".."||C.isAbsolute(o)?At(C.normalize(r)):At(C.relative(t,C.resolve(n,r)))}async function _s(e,t=process.cwd(),n=process.cwd()){let r=[];for(let o of e){if(C.resolve(n,o.pattern)===C.resolve(n))continue;let s=await tr(o.pattern,n),i=[...new Set(s.map(a=>jt(a,t,n)))].sort((a,c)=>a.localeCompare(c));for(let a of i)r.push({path:a,scope:o.scope,note:o.note})}return r}function gs(e,t,n){if(t===void 0)return e;if(!n)throw new l("--note requires --add or --add-glob in the same invocation (the note annotates the links being added)",u.USAGE);let r=t.trim();return r.length===0?e:e.map(o=>o.note===void 0?{...o,note:r}:o)}function $t(e){return`${e.path}::${e.scope}`}function xs(e){return[...e].sort((t,n)=>{let r=t.path.localeCompare(n.path);return r!==0?r:t.scope.localeCompare(n.scope)})}function ks(e){return[...new Map(e.map(t=>[$t(t),t])).values()].map(t=>({...t,note:t.note?.trim()||void 0}))}async function ws(e,t=process.cwd()){let n=[...new Set(e)].sort((a,c)=>a.localeCompare(c)),r=[],o=[],s=[],i=[];for(let a of n){if(Ct(a)){i.push(a.trim());continue}let c=C.isAbsolute(a)?a:C.resolve(t,a);try{(await ns.stat(c)).isFile()?r.push(a):s.push(a)}catch(d){if(typeof d=="object"&&d!==null&&"code"in d&&Ie(d)){o.push(a);continue}s.push(a)}}return{checked:n.length,existing_files:r,missing_paths:o,non_file_paths:s,remote_references:i}}function ys(e,t,n,r){let o=0;for(let i=0;i<e.length;i+=1){let a=de(e[i].path,r);a!==e[i].path&&(o+=1);let c=q(a);c!==e[i].path&&(e[i]={...e[i],path:c})}return{adds:t.map(i=>{let a=de(i.path,r);return a!==i.path&&(o+=1),{...i,path:q(a)}}),removes:n.map(i=>q(de(i,r))),count:o}}function q(e){return e.replaceAll("\\","/")}function Pt(e){return`${e.scope}\0${q(e.path)}`}function vs(e,t,n){let r=new Map(e.map(i=>[Pt(i),i.note])),o=new Map(t.map(i=>[Pt(i),i.note])),s=new Map;for(let i of n){let a=Pt(i);s.has(a)||s.set(a,{path:q(i.path),scope:i.scope,outcome:Ts(r.has(a),r.get(a),o.get(a))})}return[...s.values()]}function Ts(e,t,n){return e?n===t?"unchanged":t===void 0?"note_added":n?.startsWith(`${t}${Rt}`)?"note_appended":"note_replaced":"added"}function Es(e,t,n){let r=e.merged.findIndex(i=>i.path===t.path&&i.scope===t.scope),o=e.merged[r];if(o===void 0){e.merged.push(t),t.note!==void 0&&e.notedHere.add(t);return}let s=os(o.note,t.note,n);if(s.conflict)e.conflicts.push({path:t.path,scope:t.scope,existing_note:o.note,requested_note:t.note,source:e.notedHere.has(o)?"this_write":"stored"});else if(s.note!==o.note){let i={...o,note:s.note};e.merged[r]=i,e.notedHere.add(i)}}function Ss(e,t,n,r,o){let s=ks(e),i={merged:[...s],notedHere:new Set,conflicts:[]};for(let d of t)Es(i,d,o);let{merged:a}=i,c=vs(s,a,t);if(n.length>0)for(let d=a.length-1;d>=0;d-=1)n.includes(a[d].path)&&a.splice(d,1);return{entries:r?a:xs(a),outcomes:c,conflicts:i.conflicts}}async function or(e){let t=e.mutation?.entries??e.artifacts,n=e.options.validatePaths?e.artifacts:t,{counts:r,receipts:o}=Ue(e.mutation);return{id:e.id,artifacts:t,changed:e.changed,count:t.length,...r,migrations_applied:e.migrationsApplied&&e.migrationsApplied>0?e.migrationsApplied:void 0,validation:e.options.validatePaths||e.changed&&n.length>0?await ws(n.map(s=>s.path),e.workspaceRoot):void 0,...o}}function bs(e,t,n){let r=new Map;for(let s of t){let i=$t(s);r.set(i,(r.get(i)??0)+1)}let o=0;for(let s of e){let i=$t({...s,path:q(de(s.path,n))}),a=r.get(i)??0;a>0?r.set(i,a-1):o+=1}return o}function Cs(e,t){let n=/[\n\r]|^\s*[-*+`]/u.test(e)?[]:En(e),r=n.findIndex(f=>f.key?.toLowerCase()==="note");if(r<0)return;let o=n.slice(0,r).map(f=>f.raw.trim()),s=new Set(n.slice(0,r).map(f=>f.key?.toLowerCase())),i=[n[r].value],a;for(let f of n.slice(r+1)){let m=f.key?.toLowerCase();if((m==="path"||m==="scope")&&!s.has(m)){o.push(f.raw.trim()),s.add(m);continue}a??=f.key===void 0?void 0:{segment:f.text.trim(),key:f.key},i.push(f.text)}if(a===void 0)return;let c=i.join(",").trim(),d=[...o,`note=${JSON.stringify(c)}`].join(",");try{Nt([d],t)}catch{return}return{entry:d,note:c,...a}}function Ls(e,t){return e.findIndex(n=>{try{return Nt([n],t),!1}catch{return!0}})+1}function Ne(e,t,n){return(t??[]).flatMap(r=>[e,n!==void 0&&r.trim()==="-"?`${n}=-`:r])}function sr(e){let{options:t}=e,n=e.noteConflict??t.noteConflict;return[...oe(e.global),...e.guards.map(r=>`--expect-hash=${r}`),e.config.metadataKey,e.id,...Ne("--add",e.entries.map((r,o)=>o===e.position-1?e.rewritten:r),"path"),...Ne("--add-glob",e.resolved.addGlob,"pattern"),...Ne("--remove",e.resolved.remove,"path"),...Ne("--migrate",e.resolved.migrate),...t.note===void 0?[]:["--note",t.note],...n===void 0?[]:["--note-conflict",n],...e.config.supportsAppendStable&&t.appendStable===!0?["--append-stable"]:[],...t.validatePaths===!0?["--validate-paths"]:[],...t.fullHistory===!0?["--full-history"]:[],...t.author?["--author",t.author]:[],...t.message?["--message",t.message]:[],...t.force===!0?["--force"]:[]]}function As(e){return Ot.some(t=>t===e.toLowerCase())?`If "${e}" was meant as a key, give it once per entry.`:`If "${e}" was meant as a key, it is not one of: ${Ot.join(", ")}.`}function Ps(e){try{return Nt(e.entries,e.config.bareNoun)}catch(t){let n=e.entries,r=t,o=Ls(n,e.config.bareNoun),s=Cs(n[o-1],e.config.bareNoun);if(s===void 0)throw t;let i=ht(e.pmRoot),a=i===void 0?void 0:sr({...e,entries:n,position:o,rewritten:s.entry,guards:i});throw new l(`--add read the note segment "${s.segment}" as a new key "${s.key}", so the ${e.config.bareNoun} link was refused (${r.message})`,u.USAGE,{code:"linked_artifact_note_key_misread",flag:"--add",value:n[o-1],required:`Retry with the note quoted so its commas stay prose (${a===void 0?`as ${s.entry}; its revision guards cannot be replayed as typed, so no executable retry is offered`:"recovery.suggested_retry_args replays the whole invocation that way"}), or pass the prose through --note in a single-entry call. ${As(s.key)}`,why:"After a comma, an identifier followed by = or : opens a new key, so that a typo such as lable=main is refused instead of being stored as note text (GH-258).",...a===void 0?{}:{nextSteps:[E(a)]},details:{entry_index:o,misread_segment:s.segment,misread_key:s.key,note:s.note,rewritten_entry:s.entry,cause:r.context.code??"invalid_argument_value"},...a===void 0?{}:{recovery:{suggested_retry:E(a),suggested_retry_args:a}}})}}function Ue(e){return e===void 0?{counts:{},receipts:{}}:{counts:{total_count:e.total_count,returned_count:e.returned_count,has_more:e.has_more},receipts:{mutation_receipt:e.mutation_receipt,omission_receipt:e.omission_receipt}}}async function Rs(e){let{settings:t,config:n}=e,r=await je(e.pmRoot,e.id,t.id_prefix,t.item_format,e.typeToFolder);if(!r)throw new l(`Item ${e.id} not found`,u.NOT_FOUND);let s=(await $e(r,{schema:t.schema})).document.metadata[n.metadataKey]??[],i=e.writeRequested?xe({collectionKey:n.metadataKey,stored:s,written:[],removedCount:0,fullHistory:e.options.fullHistory===!0}):void 0;return or({id:r.id,artifacts:s,changed:!1,options:e.options,workspaceRoot:e.workspaceRoot,mutation:i})}async function Vc(e,t,n,r){let{metadataKey:o}=r,s=Oe(),i=B(process.cwd(),n.path),a=Pn(i),c=process.cwd();await ie(i);let d=await W(i),f=re(d,se()),m=await s.resolveList(t.add,"--add"),p=await s.resolveList(t.addGlob,"--add-glob"),g=await s.resolveList(t.remove,"--remove"),x=await s.resolveList(t.migrate,"--migrate"),h=Ps({id:e,pmRoot:i,entries:m,resolved:{addGlob:p,remove:g,migrate:x},options:t,global:n,config:r}).map(j=>({...j,path:jt(j.path,a,c)})),w=fs(p),L=await _s(w,a,c),R=h.length>0||w.length>0,b=gs([...h,...L],t.note,R),N=rs(t.noteConflict,R),k=ms(g).map(j=>jt(j,a,c)),v=ps(x);if(hs(b,k,v),!(b.length>0||k.length>0||v.length>0))return Rs({id:e,pmRoot:i,settings:d,typeToFolder:f.type_to_folder,options:t,workspaceRoot:a,config:r,writeRequested:w.length>0});let M=$(t.author,d.author_default),A=[],I=0,ct=[],Ce=await ae({pmRoot:i,settings:d,id:e,op:r.op,author:M,message:t.message,force:t.force,skipNoop:!0,mutate(j){let ut=j.metadata,Le=ut[o]??[],kn=[...Le],Ae=ys(kn,b,k,v),Pe=Ss(kn,Ae.adds,Ae.removes,r.supportsAppendStable&&t.appendStable===!0,N);if(Pe.conflicts.length>0){let yn=ht(i);throw ss({itemId:j.metadata.id,noun:r.bareNoun,conflicts:Pe.conflicts,retryArgs:Ro=>yn===void 0?void 0:sr({id:j.metadata.id,entries:m??[],position:0,rewritten:"",resolved:{addGlob:p,remove:g,migrate:x},options:t,global:n,config:r,guards:yn,noteConflict:Ro}),render:E})}let Re=Pe.entries;ct=Pe.outcomes,Re.length>0?ut[o]=Re:delete ut[o];let wn=!U(Le,Re);return A=Le,I=bs(Le,Re,v),{changedFields:wn?[o]:[],warnings:wn&&Ae.count>0?[`path_migrations_applied:${Ae.count}`]:[]}}}),dt=Ce.item[o]??[],xn=Ce.warnings.find(j=>j.startsWith("path_migrations_applied:")),Po=xn?Number(xn.slice(24)):0;return or({id:Ce.item.id,artifacts:dt,changed:Ce.changedFields.includes(o),migrationsApplied:Po,options:t,workspaceRoot:a,mutation:xe({collectionKey:o,stored:dt,written:Mt(A,dt),removedCount:I,fullHistory:t.fullHistory===!0,linkOutcomes:ct})})}function Xc(e,t){let n={};for(let[r,o]of Object.entries(e))n[r==="artifacts"?t:r]=o;return n}import{readFileSync as Os}from"node:fs";import Ge from"node:path";var Is=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),Ft=new Set(["--pm-path","--path","--author","--expect-hash"]),js={get:new Set(["--depth","--fields","--tree-depth","--tree_depth","--at","--format"]),history:new Set(["--limit","--field","--format"]),restore:new Set(["--message"]),update:new Set(["--title","-t","--description","-d","--body","-b","--status","-s","--close-reason","--close_reason","--priority","-p","--type","--tags","--add-tags","--add_tags","--remove-tags","--remove_tags","--deadline","--estimated-minutes","--estimate","--estimated_minutes","--acceptance-criteria","--ac","--acceptance_criteria","--definition-of-ready","--definition_of_ready","--order","--rank","--goal","--objective","--value","--impact","--outcome","--why-now","--why_now","--message","--assignee","--parent","--reviewer","--risk","--confidence","--sprint","--release","--blocked-by","--blocked_by","--blocked-reason","--blocked_reason","--unblock-note","--unblock_note","--reporter","--severity","--environment","--repro-steps","--repro_steps","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual","--affected-version","--affected_version","--fixed-version","--fixed_version","--component","--regression","--customer-impact","--customer_impact","--dep","--dep-remove","--dep_remove","--comment","--note","--learning","--file","--test","--doc","--reminder","--event","--type-option","--type_option","--field","--unset","--body-file"]),close:new Set(["--reason","-r","--close-reason","--duplicate-of","-d","--message","-m","--validate-close","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual"]),delete:new Set(["--message"]),append:new Set(["--body","--text","--message"]),claim:new Set(["--assignee","--message","--type","--tag","--priority","--assignee-filter","--parent","--sprint","--release","--max-attempts"]),release:new Set(["--assignee","--message"]),comments:new Set(["--add","--body","--comment","--file","--edit","--delete","--limit","--message"]),notes:new Set(["--add","--file","--edit","--delete","--limit","--message"]),learnings:new Set(["--add","--file","--edit","--delete","--limit","--message"]),files:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),docs:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),deps:new Set(["--format","--max-depth","--collapse","--node-limit","--edge-limit","--token-budget","--cursor","--direction","--kind"]),test:new Set(["--add","--add-json","--remove","--match","--only-index","--timeout","--env-set","--env-clear","--pm-context","--message"])},$s=new Set(["-p","--package"]),Ms=new Set(["-c","--call"]),Dt=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),Wt=new Set(["-C","--prefix","--userconfig","--cache"]),ir=new Set(["--cwd"]),ar=new Set(["--cwd"]),Ns=new Set(["exec","x"]),cr=new Set(["run","run-script"]),dr=new Set(["-C","--dir","--cwd","-w","--workspace","--filter"]);function Z(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function We(e,t=process.cwd()){let n=qe(e.split(" ").filter(i=>i.length>0));if(n.length===0)return null;let[r,...o]=n;if(Fe(r)||De(r,t))return o;if(r==="node"&&o[0]&&De(o[0],t))return o.slice(1);let s=r==="npx"||r==="bunx"?Q(o):r==="pnpm"?He(o):r==="npm"?Ke(o):null;return s&&(Fe(s.command)||ur(s.command))?s.args:null}var Us=(e,t="pm")=>{let n=t.trim().toLowerCase(),r=n.length;for(;r>0&&n[r-1]==="-";)r-=1;let o=n.slice(0,r);if(o.length===0)return[];let s=e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase(),i=new Set;for(let a of Z(s)){let c=We(a),d=c?qt(c):null,f=d&&Is.has(d.subcommand)?Fs(d.remaining,js[d.subcommand]):void 0,m=f?.trim().toLowerCase();m?.startsWith(`${o}-`)===!0&&m.length>o.length+1&&i.add(f)}return[...i].sort((a,c)=>a.localeCompare(c))};function qe(e){let t=0;for(e[t]==="env"&&(t+=1);t<e.length;){let n=e[t];if(/^(?:[a-z_][a-z0-9_]*|\$env:[a-z_][a-z0-9_]*)=.*/.test(n)){t+=1;continue}break}return e.slice(t)}function Gt(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(Ft.has(n)){t+=2;continue}t+=1;continue}return n}}function Fe(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function Gs(e){let t=e.trim();if(!t.startsWith("@")){let o=t.indexOf("@");return o===-1?t:t.slice(0,o)}let n=t.indexOf("/");if(n===-1)return t;let r=t.indexOf("@",n+1);return r===-1?t:t.slice(0,r)}function ur(e){let t=Gs(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function De(e,t=process.cwd()){let n=e.replaceAll("\\","/");if(n!=="dist/cli.js"&&n!=="./dist/cli.js"&&!n.endsWith("/dist/cli.js"))return!1;let r=Ge.resolve(t,e);try{return JSON.parse(Os(Ge.join(Ge.dirname(Ge.dirname(r)),"package.json"),"utf8")).name==="@unbrained/pm-cli"}catch{return!1}}function Q(e){let t=0;for(;t<e.length;){let r=e[t];if(r==="--"){t+=1;break}if(!r.startsWith("-"))break;let o=/^(?:-c|--call)=(.*)$/.exec(r);if(o){let s=o[1];return s?{command:s,args:e.slice(t+1)}:null}if(Ms.has(r)){t+=1;break}t+=$s.has(r)&&!r.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function H(e,t){let n=0;for(;n<e.length;){let r=e[n];if(r==="--"){n+=1;continue}if(r.startsWith("-")){if(r.includes("=")){n+=1;continue}if(t.has(r)){n+=2;continue}n+=1;continue}return{subcommand:r,args:e.slice(n+1)}}return null}function He(e){let t=H(e,Dt);return t?.subcommand!=="dlx"?null:Q(t.args)}function Ke(e){let t=H(e,Wt);return!t||!Ns.has(t.subcommand)?null:Q(t.args)}function qt(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(Ft.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function Fs(e,t=new Set){for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="--")return e[n+1];if(!r.startsWith("-"))return r;!r.includes("=")&&(Ft.has(r)||t.has(r))&&(n+=1)}}function Ut(e){return!e||!Fe(e.command)&&!ur(e.command)?!1:Gt(e.args)==="test-all"}var Ht=new Map([...["sh","bash","dash","zsh"].map(e=>[e,/^(?:-c|-[a-z]*c[a-z]*)$/u]),...["cmd","cmd.exe"].map(e=>[e,/^\/[ck]$/u]),...["powershell","powershell.exe","pwsh","pwsh.exe"].map(e=>[e,/^-(?:c|command)$/u])]),Ds=new Set(["npx","bunx"]);function Kt(e){let t=e.split(" ").filter(i=>i.length>0),n=qe(t);if(n.length===0)return!1;let[r,...o]=n,s=Ht.get(r);if(s){let i=o.findIndex(a=>s.test(a));return i>=0?Kt(o.slice(i+1).join(" ")):!1}return Fe(r)||De(r)?Gt(o)==="test-all":r==="node"&&o.length>0&&De(o[0])?Gt(o.slice(1))==="test-all":Ds.has(r)?Ut(Q(o)):r==="pnpm"?Ut(He(o)):r==="npm"?Ut(Ke(o)):!1}function Bt(e){let t=ue(e);return Z(t).some(n=>Kt(n))}function ke(e){if(Bt(e))throw new l('Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.',u.USAGE)}function ue(e){return e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase()}import{execFile as Ws}from"node:child_process";import{readFile as qs}from"node:fs/promises";import fr from"node:path";import{promisify as Hs}from"node:util";var Ks=Hs(Ws),zt=1,Bs="linked-test-trust.json";function Jt(e){return fr.join(On(e),Bs)}function lr(){return{version:zt,acknowledged:{}}}async function Vt(e){try{let t=JSON.parse(await qs(Jt(e),"utf8"));return t.version!==zt||typeof t.acknowledged!="object"||t.acknowledged===null||Array.isArray(t.acknowledged)?lr():{version:zt,acknowledged:t.acknowledged}}catch{return lr()}}async function Xt(e=process.cwd()){let t=process.env.GITHUB_HEAD_REF?.trim()||process.env.GITHUB_REF_NAME?.trim();if(t&&t!=="merge")return t;try{let{stdout:n}=await Ks("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),r=n.trim();return r.length===0?void 0:r}catch{return}}function Yt(e=process.cwd()){return process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||e}function zs(e){return e===null||typeof e!="object"?!1:typeof e.author=="string"&&e.author.trim().length>0&&typeof e.created_at=="string"&&jn(e.created_at)&&(e.source_kind==="local_mutation"||e.source_kind==="merge_union")}function we(e,t){return{...e?{source_ref:e}:{},...t?{current_source_ref:t}:{}}}function Js(e,t,n,r){return e?.map(o=>o.command&&!o.provenance?{...o,provenance:{author:t,created_at:n,source_kind:"local_mutation",...r?{source_ref:r}:{}}}:o)}async function mr(e,t,n){if(!e||e.length===0)return e;for(let o of e)z(o);let r=Yt();return Js(e,t,n,await Xt(r))}function pr(e){return Tn(vn({command:e.command??null,path:e.path??null,scope:e.scope,pm_context_mode:e.pm_context_mode??null,workspace_context_mode:e.workspace_context_mode??null,env_set:e.env_set??null,env_clear:e.env_clear??null,shared_host_safe:e.shared_host_safe??null,provenance:e.provenance??null,provenance_invalid:e.provenance_invalid??null}))}async function Zt(e,t,n){let r=await Vt(e);return hr(t,n,r)}function hr(e,t,n){let r=pr(e),o=e.provenance?.source_ref;if(e.provenance===void 0&&e.provenance_invalid!==!0)return{fingerprint:r,trusted:!0,reason:"legacy"};let s=Object.hasOwn(n.acknowledged,r);return e.provenance_invalid===!0||!zs(e.provenance)?s?{fingerprint:r,trusted:!0,reason:"acknowledged",...we(void 0,t)}:{fingerprint:r,trusted:!1,reason:"invalid_provenance",...we(void 0,t)}:e.provenance.source_kind==="local_mutation"&&o===void 0?{fingerprint:r,trusted:!0,reason:"local_mutation",...we(void 0,t)}:e.provenance.source_kind==="local_mutation"&&o!==void 0&&o===t?{fingerprint:r,trusted:!0,reason:"local_source_ref",source_ref:o,current_source_ref:t}:s?{fingerprint:r,trusted:!0,reason:"acknowledged",...we(o,t)}:{fingerprint:r,trusted:!1,reason:"foreign_source_ref",...we(o,t)}}async function fd(e,t,n){let r=await Vt(e);return t.map(o=>hr(o,n,r))}async function _r(e,t,n){let r=await Vt(e),o=t.filter(s=>typeof s.command=="string"&&s.command.length>0).map(pr);for(let s of o)r.acknowledged[s]={acknowledged_at:n};return await Cn(fr.dirname(Jt(e))),await Ln(Jt(e),`${JSON.stringify(r,null,2)}
|
|
3
3
|
`),{acknowledged:o.length,fingerprints:o}}var Vs=["setup","test"];function P(e){return e.phase==="setup"}function Be(e,t){if(e===void 0)return;let n=typeof e=="string"?e.trim().toLowerCase():e;if(n==="setup")return"setup";if(!(n==="test"||n===""))throw new l(`${t} field "phase" must be one of: ${Vs.join(", ")}`,u.USAGE,{code:"invalid_argument_value",required:"Use phase=setup for a step that runs before the linked commands, or omit phase for a regular linked test.",examples:['pm test <id> --add "command=npm run build,phase=setup"']})}function gr(e){return[...e.filter(P),...e.filter(t=>!P(t))]}function xr(e,t){if(!e.selected.some(s=>!P(s)))return e;let n=t.flatMap((s,i)=>P(s)?[i+1]:[]);if(n.length===0)return e;let r=e.selected_indexes.filter(s=>!P(t[s-1])),o=n.filter(s=>!e.selected_indexes.includes(s));return{...e,selected:[...n,...r].map(s=>t[s-1]),selected_indexes:[...n,...r],selected_count:n.length+r.length,skipped_count:t.length-n.length-r.length,...o.length>0?{setup_indexes:o}:{}}}function kr(e,t,n){if(!P(e))return;let r=[...n].filter(o=>o!==t).sort();if(r.length!==0)return{command:e.command,path:e.path,status:"refused",exit_code:null,failure_category:"config_refusal",error:`Setup entry runs in the ${t} workspace, but linked commands it prepares run in ${r.join(", ")}, so its output would not reach them. Set workspace_context_mode on the setup entry and the linked commands to one mode.`}}function wr(){let e;return{blocked(t){if(e!==void 0)return{command:t.command,path:t.path,status:"skipped",...P(t)?{phase:"setup"}:{},error:`Skipped because setup entry "${e.label}" did not pass (${e.outcome}); no later linked command ran.`}},options(t,n){return!P(t)||n===void 0?n:{...n,failOnEmptyTestRun:!1,requireAssertionsForPm:!1}},record(t,n){if(!P(t))return n;if(n.status==="passed")return{...n,phase:"setup"};let o=n.status==="refused"||n.failure_category==="trust_refusal"||n.failure_category==="setup_failed"?{...n,phase:"setup"}:{...n,status:"failed",phase:"setup",failure_category:"setup_failed",...n.failure_category===void 0?{}:{setup_failure_cause:n.failure_category}};return e={label:t.command??t.path??"<no command>",outcome:o.failure_category??o.status},o}}}function Xs(){return{infra_collision:0,trust_refusal:0,config_refusal:0,assertion_failure:0,empty_run:0,timeout:0,max_buffer:0,spawn_error:0,signal:0,setup_failed:0}}function Qt(e){let t=Xs();for(let n of e)n.status!=="failed"&&n.status!=="refused"||!n.failure_category||(t[n.failure_category]+=1);return t}var ne=new Set(["PM_PATH","PM_GLOBAL_PATH","PM_SOURCE_PM_PATH","PM_SOURCE_WORKSPACE_ROOT","PM_BUILD_CONSUMER_LEASE","PM_BUILD_CONSUMER_LEASE_ROOT",ge,Fn,"FORCE_COLOR"]),Ve=/^[A-Za-z_][A-Za-z0-9_]*$/,te=["schema","tracker","auto","none"],yr=["source","isolated","snapshot"];function en(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new l(`${t} env_set must include at least one KEY=VALUE assignment`,u.USAGE);let r=Object.create(null);for(let o of n){let s=o.indexOf("=");if(s<=0)throw new l(`${t} env_set entries must use KEY=VALUE and be separated by semicolons. Example: env_set=PORT=0;PLAYWRIGHT_BASE_URL=http://127.0.0.1:4173`,u.USAGE);let i=o.slice(0,s).trim(),a=o.slice(s+1);if(!Ve.test(i))throw new l(`${t} env_set key "${i}" is invalid`,u.USAGE);if(ne.has(i.toUpperCase()))throw new l(`${t} env_set key "${i}" is reserved for sandbox safety`,u.USAGE);r[i]=a}return Object.keys(r).length>0?r:void 0}function tn(e,t){if(!e)return;let n=kt(e,{separators:/[;,\n]/});if(n.length===0)throw new l(`${t} env_clear must include at least one environment variable name`,u.USAGE);for(let r of n){if(!Ve.test(r))throw new l(`${t} env_clear key "${r}" is invalid`,u.USAGE);if(ne.has(r.toUpperCase()))throw new l(`${t} env_clear key "${r}" is reserved for sandbox safety`,u.USAGE)}return n}function Tr(e,t,n){if(!e)return;let r=e.trim().toLowerCase();if(r==="true"||r==="1"||r==="yes")return!0;if(r==="false"||r==="0"||r==="no")return!1;throw new l(`${t} ${n} must be one of true|false|1|0|yes|no`,u.USAGE)}function Er(e,t){if(!e)return;let n=e.trim().toLowerCase();if(te.includes(n))return n;throw new l(`${t} pm_context_mode must be one of: ${te.join(", ")}`,u.USAGE)}function ye(e,t){if(!e)return;let n=e.trim().toLowerCase();if(yr.includes(n))return n;throw new l(`${t} workspace_context_mode must be one of: ${yr.join(", ")}`,u.USAGE)}function Xe(e){if(!e)return;let t=kt(e,{separators:/[;\n]/});return t.length>0?t:void 0}function nn(e,t,n){let r=Xe(e);if(!(!r||r.length===0)){for(let o of r)try{new RegExp(o,"m")}catch(s){throw new l(`${t} ${n} includes invalid regex "${o}": ${s instanceof Error?s.message:String(s)}`,u.USAGE)}return r}}function Sr(e,t){if(!e)return;let n=pe(e,"assert_stdout_min_lines");if(!Number.isInteger(n)||n<0)throw new l(`${t} assert_stdout_min_lines must be an integer >= 0`,u.USAGE);return n}function br(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new l(`${t} assert_json_field_equals must include at least one path=value assignment`,u.USAGE);let r=Object.create(null);for(let o of n){let s=o.indexOf("=");if(s<=0)throw new l(`${t} assert_json_field_equals entries must use path=value and be separated by semicolons`,u.USAGE);let i=o.slice(0,s).trim(),a=o.slice(s+1).trim();if(i.length===0||a.length===0)throw new l(`${t} assert_json_field_equals entries must include non-empty path and value`,u.USAGE);r[i]=a}return Object.keys(r).length>0?r:void 0}function Cr(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new l(`${t} assert_json_field_gte must include at least one path=value assignment`,u.USAGE);let r=Object.create(null);for(let o of n){let s=o.indexOf("=");if(s<=0)throw new l(`${t} assert_json_field_gte entries must use path=value and be separated by semicolons`,u.USAGE);let i=o.slice(0,s).trim(),a=o.slice(s+1).trim();if(i.length===0||a.length===0)throw new l(`${t} assert_json_field_gte entries must include non-empty path and value`,u.USAGE);let c=Number(a);if(!Number.isFinite(c))throw new l(`${t} assert_json_field_gte value for "${i}" must be numeric`,u.USAGE);r[i]=c}return Object.keys(r).length>0?r:void 0}var Ys=new Set(J);function Ye(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Zs(e,t){let n={},r=[];for(let[o,s]of Object.entries(e)){let i=o.toLowerCase();if(!Ys.has(i)){r.push(o);continue}if(Object.hasOwn(n,i))throw t(`provides key "${o}" more than once after case normalization`);n[i]=s}if(r.length>0)throw t(`does not recognize key${r.length>1?"s":""} ${r.map(o=>`"${o}"`).join(", ")}. Allowed keys: ${J.join(", ")}.`);return n}function ee(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r!==void 0){if(typeof r!="string")throw n(`field "${t}" must be a JSON string`);return r}}function ze(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r===void 0)return;let o=typeof r=="string"?[r]:r;if(!Array.isArray(o)||o.some(i=>typeof i!="string"))throw n(`field "${t}" must be a string or an array of strings`);let s=o.filter(i=>i.length>0);return s.length>0?s:void 0}function vr(e,t,n){let r=ze(e,t,n);if(r){for(let o of r)try{new RegExp(o,"m")}catch(s){throw n(`field "${t}" includes invalid regex "${o}": ${s instanceof Error?s.message:String(s)}`)}return r}}function Je(e,t,n){let r=typeof e=="number"?e:typeof e=="string"&&e.trim().length>0?Number(e.trim()):Number.NaN;if(typeof e=="boolean"||!Number.isFinite(r))throw n(`field "${t}" must be a finite number (or numeric string)`);return r}function Qs(e,t){let n=e.timeout_seconds,r=e.timeout;if(n===void 0&&r===void 0)return;let o=n===void 0?void 0:Je(n,"timeout_seconds",t),s=r===void 0?void 0:Je(r,"timeout",t);if(o!==void 0&&s!==void 0&&o!==s)throw t("timeout and timeout_seconds must match when both are provided");let i=o??s;if(!Number.isInteger(i)||i<=0)throw t("timeout_seconds must be a positive integer");return i}function ei(e,t){let n=ee(e,"scope",t);if(n===void 0)return"project";if(!F.includes(n))throw t(`field "scope" must be one of: ${F.join(", ")}`);return n}function ti(e,t){if(!Object.hasOwn(e,"env_set"))return;let n=e.env_set;if(n===void 0)return;if(!Ye(n))throw t('field "env_set" must be a JSON object mapping environment names to string values');let r=Object.create(null);for(let[o,s]of Object.entries(n)){if(typeof s!="string")throw t(`field "env_set" value for "${o}" must be a string`);if(!Ve.test(o))throw t(`field "env_set" key "${o}" is invalid`);if(ne.has(o.toUpperCase()))throw t(`field "env_set" key "${o}" is reserved for sandbox safety`);r[o]=s}return Object.keys(r).length>0?r:void 0}function ni(e,t){let n=ze(e,"env_clear",t);if(n){for(let r of n){if(!Ve.test(r))throw t(`field "env_clear" key "${r}" is invalid`);if(ne.has(r.toUpperCase()))throw t(`field "env_clear" key "${r}" is reserved for sandbox safety`)}return n}}function ri(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r!==void 0){if(typeof r!="boolean")throw n(`field "${t}" must be a JSON boolean (true or false)`);return r}}function oi(e,t){if(!Object.hasOwn(e,"assert_stdout_min_lines"))return;let n=e.assert_stdout_min_lines;if(n===void 0)return;let r=Je(n,"assert_stdout_min_lines",t);if(!Number.isInteger(r)||r<0)throw t('field "assert_stdout_min_lines" must be an integer >= 0');return r}function si(e,t){if(!Object.hasOwn(e,"assert_json_field_equals"))return;let n=e.assert_json_field_equals;if(n===void 0)return;if(!Ye(n))throw t('field "assert_json_field_equals" must be a JSON object mapping field paths to expected values');let r=Object.create(null);for(let[o,s]of Object.entries(n)){if(o.trim().length===0)throw t('field "assert_json_field_equals" keys must be non-empty field paths');if(typeof s!="string"&&typeof s!="number"&&typeof s!="boolean")throw t(`field "assert_json_field_equals" value for "${o}" must be a string, number, or boolean`);r[o]=String(s)}return Object.keys(r).length>0?r:void 0}function ii(e,t){if(!Object.hasOwn(e,"assert_json_field_gte"))return;let n=e.assert_json_field_gte;if(n===void 0)return;if(!Ye(n))throw t('field "assert_json_field_gte" must be a JSON object mapping field paths to numeric minimums');let r=Object.create(null);for(let[o,s]of Object.entries(n)){if(o.trim().length===0)throw t('field "assert_json_field_gte" keys must be non-empty field paths');r[o]=Je(s,`assert_json_field_gte.${o}`,t)}return Object.keys(r).length>0?r:void 0}function ai(e,t,n){let r=p=>new l(`${n} ${t} ${p}`,u.USAGE);if(!Ye(e))throw r(`must be a JSON object with linked-test fields. Allowed keys: ${J.join(", ")}.`);let o=Zs(e,r),s=ee(o,"command",r),i=ee(o,"cmd",r);if(s!==void 0&&i!==void 0&&s!==i)throw r("command and cmd must match when both are provided");let a=s??i;if(a===void 0||a.trim().length===0)throw r('requires a non-empty "command" string');let c=ee(o,"path",r),d=ee(o,"pm_context_mode",r);if(d!==void 0&&!te.includes(d))throw r(`field "pm_context_mode" must be one of: ${te.join(", ")}`);let f=ye(ee(o,"workspace_context_mode",r),`${n} ${t}`),m=ee(o,"note",r);return{command:a,path:c!==void 0&&c.length>0?c:void 0,scope:ei(o,r),timeout_seconds:Qs(o,r),pm_context_mode:d,workspace_context_mode:f,env_set:ti(o,r),env_clear:ni(o,r),shared_host_safe:ri(o,"shared_host_safe",r),assert_stdout_contains:ze(o,"assert_stdout_contains",r),assert_stdout_regex:vr(o,"assert_stdout_regex",r),assert_stderr_contains:ze(o,"assert_stderr_contains",r),assert_stderr_regex:vr(o,"assert_stderr_regex",r),assert_stdout_min_lines:oi(o,r),assert_json_field_equals:si(o,r),assert_json_field_gte:ii(o,r),note:m!==void 0&&m.trim().length>0?m.trim():void 0,phase:Be(o.phase,`${n} ${t}`)}}function ve(e,t){let n=e.trim();if(n.length===0)throw new l(`${t} requires a JSON object or array of objects describing linked-test entries`,u.USAGE);let r;try{r=JSON.parse(n)}catch(s){throw new l(`${t} value is not valid JSON: ${s instanceof Error?s.message:String(s)}. Provide a JSON object or array of objects, e.g. '{"command":"node scripts/check.js --flag value, with commas","timeout_seconds":120}'.`,u.USAGE)}let o=Array.isArray(r)?r:[r];if(o.length===0)throw new l(`${t} array must include at least one linked-test entry object`,u.USAGE);return o.map((s,i)=>ai(s,o.length>1?`entry ${i+1}`:"entry",t))}var ci=32;function di(e){let t=[];for(let n of e??[]){let r=[];for(let o of n.split(",")){let s=o.slice(0,o.indexOf("=")).trim();r.length>0&&s!=="unit"&&s!=="threshold"&&(t.push(r.join(",")),r=[]),r.push(o)}t.push(r.join(","))}return t}function rn(e,t){let n=di(e).map(o=>{let[s,...i]=o.split(","),a=s.indexOf("="),c=s.slice(0,a).trim(),d=s.slice(a+1).trim(),f=Number(d);if(a<=0||c.length===0||d.length===0||!Number.isFinite(f))throw new l(`Invalid --measure "${o}"; expected name=value[,unit=...][,threshold=...]`,u.USAGE);let m,p;for(let g of i){let x=g.indexOf("="),h=g.slice(0,x).trim(),w=g.slice(x+1).trim();if(h==="unit"&&w.length>0)m=w;else if(h==="threshold"&&w.length>0&&Number.isFinite(Number(w)))p=Number(w);else throw new l(`Invalid --measure attribute "${g}"`,u.USAGE)}return{name:c,value:f,unit:m,threshold:p,recorded_at:t}});return[...new Map(n.map(o=>[o.name,o])).values()].sort((o,s)=>o.name.localeCompare(s.name)).slice(0,ci)}function Lr(e,t,n){return e.flatMap(r=>(r.measurements??[]).filter(o=>o.name===t&&o.value<n).map(o=>({...o,run_id:r.run_id})))}function Ar(e,t){let n=e.flatMap(s=>s.measurements??[]).filter(s=>s.name===t).sort((s,i)=>i.recorded_at.localeCompare(s.recorded_at)),r=n[0],o=n[1];return{name:t,latest:r?.value??null,previous:o?.value??null,delta:r!==void 0&&o!==void 0?r.value-o.value:null,unit:r?.unit}}var Pr=100;function le(e,t="--only-index"){let n=typeof e=="number"?e:Number(String(e).trim());if(!Number.isInteger(n)||n<1)throw new l(`${t} requires a 1-based integer index into the linked-test list (got "${e}"). Use pm test <id> --list to inspect positions.`,u.USAGE);return n}function ui(e){let n=(e.command??e.path??"<no command>").replaceAll(/\s+/g," ").trim()||"<no command>";return n.length<=Pr?n:`${n.slice(0,Pr-3)}...`}function Rr(e){return e.map((t,n)=>`${n+1}. ${ui(t)}`).join("; ")}function li(e){let t=[];return e.match!==void 0&&t.push("match"),e.onlyIndex!==void 0&&t.push("only-index"),e.onlyLast===!0&&t.push("only-last"),t}function fi(e,t){let n=e.command?.toLowerCase()??"",r=e.path?.toLowerCase()??"";return n.includes(t)||r.includes(t)}function Or(e,t){let n=li(t);if(n.length===0)return{selector:null,requested:null,selected:e,selected_indexes:e.map((o,s)=>s+1),selected_count:e.length,skipped_count:0};if(n.length>1)throw new l(`Combine at most one linked-test selector per run: ${n.map(o=>`--${o}`).join(" and ")} were provided. Pick one of --match, --only-index, --only-last.`,u.USAGE);let r=n[0];if(e.length===0)throw new l(`--${r} matched no linked tests because this item has none. Add one first with --add, --command, or --add-json.`,u.USAGE);if(r==="match"){let o=t.match.trim().toLowerCase();if(o.length===0)throw new l("--match requires a non-empty substring to match against linked-test command/path values",u.USAGE);let s=[],i=[];for(let a=0;a<e.length;a+=1)fi(e[a],o)&&(i.push(e[a]),s.push(a+1));if(i.length===0)throw new l(`--match "${t.match}" matched none of the ${e.length} linked test(s). Available entries: ${Rr(e)}`,u.USAGE);return{selector:"match",requested:t.match,selected:i,selected_indexes:s,selected_count:i.length,skipped_count:e.length-i.length}}if(r==="only-index"){let o=le(t.onlyIndex);if(o>e.length)throw new l(`--only-index ${o} is out of range: this item has ${e.length} linked test(s). Available entries: ${Rr(e)}`,u.USAGE);return{selector:"only-index",requested:String(o),selected:[e[o-1]],selected_indexes:[o],selected_count:1,skipped_count:e.length-1}}return{selector:"only-last",requested:"last",selected:[e[e.length-1]],selected_indexes:[e.length],selected_count:1,skipped_count:e.length-1}}var on=["command","cmd"],Te=Object.freeze(J.filter(e=>!["command","cmd","timeout"].includes(e)));function Ir(e){if(e.update===void 0&&e.updateIndex===void 0&&e.setJson===void 0)return;if(e.update===void 0==(e.updateIndex===void 0)||e.setJson===void 0)throw new l("Use exactly one --update or --update-index with --set-json",u.USAGE);let t;try{t=JSON.parse(e.setJson)}catch{throw new l("--set-json must contain a JSON object with explicit linked-test metadata fields",u.USAGE)}if(e.updateIndex!==void 0)return{selector:{index:le(e.updateIndex,"--update-index")},patch:t};let n=e.update,r=/^(command|path)=/u.exec(n);return{selector:r?.[1]==="path"?{path:n.slice(r[0].length)}:{command:r?n.slice(r[0].length):n},patch:t}}function jr(e){if([e.list,e.run,e.progress,e.timeout!==void 0,e.acknowledgeLinkedTests,e.metricBelow!==void 0,e.metricDiff!==void 0,(e.add?.length??0)>0,(e.addJson?.length??0)>0,(e.remove?.length??0)>0,(e.removeIndex?.length??0)>0].some(Boolean))throw new l("Edit linked-test metadata separately from listing, additions, removals, execution options, metric filters and trust acknowledgement",u.USAGE)}function mi(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new l("Select one linked test by index, command, or path",u.USAGE);let n=Object.keys(t);if(n.length!==1||!["index","command","path"].includes(n[0]))throw new l("Select one linked test by index, command, or path",u.USAGE);if("index"in t){let r=le(t.index,"--update-index");if(r<=e.length)return r-1}else{let r="command"in t?"command":"path",o="command"in t?t.command:t.path;if(typeof o!="string"||o.trim().length===0)throw new l("Linked-test selector must be a non-empty command or path",u.USAGE);let s=e.flatMap((i,a)=>i[r]===o?[a]:[]);if(s.length===1)return s[0];if(s.length>1)throw new l(`Linked-test selector is ambiguous; matching indexes: ${s.map(i=>i+1).join(", ")}`,u.USAGE,{code:"linked_test_update_ambiguous",required:"List linked tests and select one current --update-index."})}throw new l("No linked test matched the update selector",u.NOT_FOUND,{code:"linked_test_update_no_match",required:"List linked tests and select a current command, path, or --update-index."})}function $r(e,t){let n=Object.keys(e),r=n.filter(o=>!Te.includes(o));if(n.length===0&&!t||r.length>0)throw new l("Patch explicit linked-test metadata fields; command, aliases and provenance cannot be edited",u.USAGE,{code:"linked_test_patch_fields_unsupported",changed:!1,...r.length>0?{field:r[0]}:{},required:`Patch at least one editable field: ${Te.join(", ")}.`,recovery:{allowed_values:[...Te]},...r.length>0?{nextSteps:[`Remove unsupported field(s) from --set-json: ${r.join(", ")}.`]}:{}});if(e.scope===null)throw new l("scope is required and cannot be cleared",u.USAGE)}function pi(e,t,n){let r={};for(let o of Te){let s=t[o]!==void 0?t[o]:e[o];s!=null&&(r[o]=s)}return{command:n,...r}}function Ze(e){return{field:e,changed:!1,required:"Replace the entry instead: remove the selected linked test and add the new command in one pm test invocation, which records fresh provenance."}}function hi(e,t,n){let r=on.filter(s=>Object.hasOwn(e,s)).map(s=>e[s]),o=typeof e[t]=="string"?e[t].trim():"";if(r.length>1&&r.some(s=>typeof s!="string"||s.trim()!==o))throw new l("--set-json sets command and cmd to different values; send one command",u.USAGE,{code:"linked_test_command_immutable",...Ze(t),nextSteps:["Send the replacement command once, as command."]});if(o.length===0||o===n.command)throw new l(o.length===0?`--set-json cannot set ${t}: a linked test's command is its immutable identity`:`--set-json ${t} repeats the selected entry's command; omit it to edit only metadata`,u.USAGE,{code:"linked_test_command_immutable",...Ze(t),nextSteps:[`Patch only editable fields: ${Te.join(", ")}.`]});return ke(o),o}function _i(e){let{id:t,tests:n,index:r,identityKey:o,otherFields:s,requested:i,global:a}=e;$r(s,!0);let c=pi(n[r],s,i),d=ve(JSON.stringify(c),"--add-json")[0];z(d);let f=n.findIndex((m,p)=>p!==r&&_e(m,d));if(f>=0)throw new l(`--set-json cannot change ${o}: linked test ${f+1} already has the requested identity, so a replacement would merge into it`,u.USAGE,{code:"linked_test_command_immutable",...Ze(o),nextSteps:[`Edit linked test ${f+1} instead: ${E([...oe(a),"test",t,"--update-index",String(f+1),"--set-json","<editable fields>"])}`,`Or drop the selected entry: ${E([...oe(a),"test",t,"--remove-index",String(r+1)])}`]});return c}function gi(e){return[...e.author!==void 0?["--author",e.author]:[],...e.message!==void 0?["--message",e.message]:[],...e.force===!0?["--force"]:[]]}function xi(e){let{id:t,tests:n,index:r,patch:o,global:s,controls:i}=e;if(typeof o!="object"||o===null||Array.isArray(o))return;let a=o,c=on.find(h=>Object.hasOwn(a,h));if(c===void 0)return;let d=n[r],f=hi(a,c,d),m=Object.fromEntries(Object.entries(a).filter(([h])=>!on.includes(h))),p=_i({id:t,tests:n,index:r,identityKey:c,otherFields:m,requested:f,global:s}),g=d.command!==void 0&&n.filter(h=>h.command===d.command).length===1?["--remove",`command=${d.command}`]:["--remove-index",String(r+1)],x=[...oe(s),"test",t,...g,"--add-json",JSON.stringify(p),...gi(i)];throw new l(`--set-json cannot change ${c}: a linked test's command is its immutable identity; replace the entry instead`,u.USAGE,{code:"linked_test_command_immutable",...Ze(c),recovery:{suggested_retry:E(x),suggested_retry_args:x},nextSteps:["Run the suggested retry: it removes the selected entry and adds the new command in one history-recorded write. It selects the entry by its current command or list position, so list the linked tests again first if another writer may have changed them.",`SDK: runTest(${JSON.stringify(t)}, { ${g[0]==="--remove"?"remove":"removeIndex"}: [...], addJson: [...] }, { path: <the same tracker root> }) with the same values.`]})}function ki(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new l("Linked-test metadata patch must be a JSON object",u.USAGE);let n=Object.keys(t);$r(t,!1);let r=Object.fromEntries(Object.entries(e).filter(([a])=>J.includes(a))),o=Mn(ve(JSON.stringify({...r,command:e.command??"legacy-path-only",...Object.fromEntries(Object.entries(t).map(([a,c])=>[a,c===null?void 0:c]))}),"--set-json")[0]);z(o);let s=n.filter(a=>!U(e[a],o[a])),i={...e};for(let a of s){let c=o[a];Object.assign(i,{[a]:c}),c===void 0&&delete i[a]}if(!i.command?.trim()&&!i.path?.trim())throw new l("Linked-test entry must retain a command or path",u.USAGE);return{test:i,fields:s}}async function Mr(e,t,n={}){let r=B(process.cwd(),n.path);await ie(r);let o=await W(r),s=$(t.author,o.author_default),i=re(o,se()),a=0,c=[],d=await Nn({pmRoot:r,settings:o,id:e,author:s,op:"tests_update",message:t.message,force:t.force,skipNoop:!0,typeToFolder:i.type_to_folder,resolveHistoryContext:()=>({linked_test_update:{index:a,fields:c}}),mutate(m){let p=m.metadata.tests??[],g=mi(p,t.selector);xi({id:m.metadata.id,tests:p,index:g,patch:t.patch,global:n,controls:t});let x=ki(p[g],t.patch);return a=g+1,c=x.fields,x.fields.length===0?{changedFields:[]}:(m.metadata.tests=p.map((h,w)=>w===g?{...x.test,updated_by:s,updated_at:V()}:h),{changedFields:["tests"]})}}),f=d.item.tests;return{ok:!0,id:d.item.id,tests:f,count:f.length,changed:d.changedFields.length>0,updated_index:a,updated_fields:c}}var wi=[{code:"no_projects_matched_filters",regex:/\bNo projects matched the filters\b/i},{code:"no_test_files_found",regex:/\bNo test files found\b/i},{code:"no_tests_found",regex:/\bNo tests found\b/i},{code:"no_matching_tests",regex:/\bNo matching tests?\b/i},{code:"collected_zero_items",regex:/\bcollected 0 items?\b/i},{code:"reported_zero_tests",regex:/^\s*Ran 0 tests? across \d+ files?\./imu},{code:"reported_zero_passes",regex:/(?:^\s*(?:#|ℹ)?\s*tests\s+0\s*$[\s\S]*^\s*(?:#|ℹ)?\s*pass\s+0\s*$|^\s*(?:#|ℹ)?\s*pass\s+0\s*$[\s\S]*^\s*(?:#|ℹ)?\s*tests\s+0\s*$)/imu},{code:"reported_zero_tests",regex:/^\s*(?:#|ℹ)?\s*tests\s+0\s*$/imu}],yi=[{receiptCode:"reported_tests",regex:/^\s*(?:#|ℹ)?\s*tests\s+[1-9]\d*\s*$/imu},{receiptCode:"reported_passes",regex:/^\s*(?:#|ℹ)?\s*pass\s+[1-9]\d*\s*$/imu},{receiptCode:"tests_passed",regex:/\bTests?\s+[1-9]\d*\s+passed\b/iu},{receiptCode:"passed_count",regex:/\b[1-9]\d*\s+passed\b/iu},{receiptCode:"tests_summary",regex:/\bTests:\s+(?:.*\b)?[1-9]\d*\s+passed\b/iu},{receiptCode:"bun_pass_count",regex:/^\s*[1-9]\d* pass\s*$/imu},{receiptCode:"bun_executed_tests",regex:/^\s*Ran [1-9]\d* tests? across \d+ files?\./imu}];function Qe(e,t){let n=`${e}
|
|
4
4
|
${t}`;for(let r of wi)if(r.regex.test(n))return{code:r.code};return null}function Nr(e,t){for(let[n,r]of[["stdout",e],["stderr",t]]){let o=yi.find(s=>s.regex.test(r));if(o)return{code:o.receiptCode,stream:n}}}function Ur(e,t){return{trackerPath:e.path?.trim()||(process.env.PM_PATH?.trim()?t:void 0),noExtensions:e.noExtensions}}function Gr(e,t={}){let n=t.trackerPath?.trim();return E(["test",e,"--list",...t.noExtensions===!0?["--no-extensions"]:[],...n?["--pm-path",n]:[]],t.platform)}function Fr(e,t,n,r,o){if((t.measure?.length??0)===0||o.some(i=>i.phase!=="setup"&&typeof i.stdout=="string"&&i.failure_category!=="spawn_error"&&i.failure_category!=="empty_run"&&Qe(i.stdout,i.stderr??"")===null))return;let s=["--pm-path",r,...n.noExtensions?["--no-extensions"]:[],...n.author?["--author",n.author]:[],"test",e,"--list","--json"];throw new l("--measure requires an executed linked test",u.USAGE,{code:"test_measure_requires_execution",required:"Execute at least one linked command before recording measurement evidence.",why:"Empty, skipped and pre-execution refused runs cannot support measured evidence.",nextSteps:["Inspect the linked commands, adjust empty selections or missing commands, and resolve any trust refusal before retrying the measurement."],recovery:{suggested_retry:E(s),suggested_retry_args:s}})}function sn(e,t,n,r,o=!1){if((t.measure?.length??0)===0||t.run===!0)return;let s=["--pm-path",r,...n.noExtensions?["--no-extensions"]:[],...n.author?["--author",n.author]:[]],i=[...s,...Gn(e,t),...t.list?["--list"]:[],...o?["--background"]:[]],a=t.acknowledgeLinkedTests?[...s,"test",e,"--help"]:i,c=[...s,"test",e,"--acknowledge-linked-tests",...t.author?["--author",t.author]:[]];throw new l("--measure requires --run",u.USAGE,{code:"test_measure_requires_run",flag:"--measure",required:"Run the linked tests with --run to record measurement evidence.",why:"Measurements describe an executed linked-test run; recording them without execution would fabricate evidence.",...t.acknowledgeLinkedTests?{nextSteps:[`Review the linked commands and apply any requested link updates separately before acknowledging trust: ${E([...s,"test",e,"--list"])}`,`After review, acknowledge trust as a separate non-executing operation: ${E(c)}`,`Then run the measurement without --acknowledge-linked-tests: ${E(i)}`]}:{},recovery:{missing:["--run"],suggested_retry:E(a),suggested_retry_args:a}})}function Dr(e){if(!/^(?:[^.[\]]+|\[\d+\])(?:\.[^.[\]]+|\[\d+\])*$/u.test(e))return[];let t=[],n=e.matchAll(/[^.[\]]+|\[\d+\]/g);for(let[r]of n){if(r.startsWith("[")&&r.endsWith("]")){let o=Number.parseInt(r.slice(1,-1),10);if(!Number.isSafeInteger(o))return[];t.push(o);continue}t.push(r)}return t}function an(e,t){let n=t.trim();if(n.length===0)return{found:!1,value:void 0};let r=Dr(n);if(r.length===0)return{found:!1,value:void 0};let o=e;for(let s of r){if(typeof o!="object"||o===null)return{found:!1,value:void 0};if(typeof s=="number"&&(!Array.isArray(o)||s>=o.length))return{found:!1,value:void 0};let i=Object.getOwnPropertyDescriptor(o,s);if(!i||!Object.hasOwn(i,"value"))return{found:!1,value:void 0};o=i.value}return{found:!0,value:o}}import{cp as Ci,lstat as Li,mkdir as Ai,readlink as Pi,realpath as un,stat as Ri,symlink as Hr}from"node:fs/promises";import{execFile as Oi}from"node:child_process";import _ from"node:path";import{promisify as Ii}from"node:util";import{execFile as vi}from"node:child_process";import{readdir as Ti,realpath as Ei}from"node:fs/promises";import Si from"node:path";import{promisify as bi}from"node:util";var cn=bi(vi),Wr=".agents/pm/merge-receipts";async function qr(e,t,n){let r=Si.join(n,"merge-receipts"),o=(await Ti(r).catch(c=>{if(K(c))return[];throw c})).filter(c=>c.endsWith(".json")),{readIndexedReceiptBlobs:s}=await import("./indexed-receipt-blobs-DR3FDHND.js"),i=o.length===0?new Map:await s(e,r,o,Wn,await Ei(r),{failOnReadError:!0}),a={cwd:t,env:Dn(),timeout:1e4,maxBuffer:1024*1024,windowsHide:!0};await cn("git",["rm","-q","-r","--cached","--ignore-unmatch","--",Wr],a);for(let[c,d]of i){let f=cn("git",["hash-object","-w","--stdin"],a),m=f.child.stdin;m!==null&&(m.on("error",()=>{f.child.kill()}),m.end(d));let p=(await f).stdout.trim();if(!/^(?:[a-f\d]{40}|[a-f\d]{64})$/u.test(p))throw new Error("Invalid snapshot receipt object identity.");await cn("git",["update-index","--add","--cacheinfo","100644",p,`${Wr}/${c}`],a)}}var ji=new Set([".agents",".git",".nyc_output",".turbo","coverage"]),et=Ii(Oi);async function $i(e,t){let n=await tt(_.join(e,".git"));if(!n||n.isDirectory()&&!await tt(_.join(e,".git/HEAD")))return!1;let r=Object.fromEntries(Object.entries(process.env).filter(([o])=>!o.toUpperCase().startsWith("GIT_")));await et("git",["clone","--no-local","--no-checkout","--template=","--origin=origin","--",e,t],{env:r,timeout:12e4,maxBuffer:1024*1024,windowsHide:!0}),await et("git",["-C",t,"remote","remove","origin"],{env:r,timeout:1e4,windowsHide:!0});try{await et("git",["-C",t,"rev-parse","--verify","--quiet","HEAD"],{env:r,timeout:1e4,windowsHide:!0})}catch(o){if(o.code===1)return!0;throw o}return await et("git",["-C",t,"read-tree","HEAD"],{env:r,timeout:1e4,windowsHide:!0}),!0}async function Mi(e,t,n,r){await $i(e,t)&&n&&r!==!1&&await qr(e,t,n)}function dn(e){return e.split(_.sep).some(t=>ji.has(t.toLowerCase()))}function Ee(e){return e===".."||e.startsWith(`..${_.sep}`)||_.isAbsolute(e)}async function tt(e){try{return await Ri(e)}catch(t){if(!K(t))throw t;return}}async function nt(e){let t=[],n=e;for(;_.dirname(n)!==n;)try{return _.join(await un(n),...t)}catch(r){if(!K(r))throw r;t.unshift(_.basename(n)),n=_.dirname(n)}return _.join(await un(n),...t)}async function Ni(e,t,n){let r=_.relative(t,await nt(e));if(!Ee(r))return r;let o=[],s=e;for(;_.dirname(s)!==s;){let i=await nt(s),a=n.find(([,c])=>c===i);if(a)return _.join(a[0],...o);o.unshift(_.basename(s)),s=_.dirname(s)}return r}async function Kr(e,t,n,r){let o=[],s=[],i=await un(e),a=await nt(_.resolve(t));if(![_.relative(i,a),_.relative(a,i)].every(Ee))throw new Error("Snapshot destination must be disjoint from the source workspace; choose a temporary root outside the checkout.");await Ai(_.dirname(t),{recursive:!0}),await Mi(i,t,n,r),await Ci(i,t,{recursive:!0,force:!0,async filter(c){let d=_.relative(i,c);if(!d)return!0;if(dn(d))return!1;if(_.basename(c).toLowerCase()==="node_modules"){if((await tt(c))?.isDirectory()){let f=await nt(c),m=_.relative(i,f);if(!Ee(_.relative(f,i))||!Ee(m)&&(dn(m)||!m.split(_.sep).some(p=>p.toLowerCase()==="node_modules")))throw new Error(`Dependency symlink must target an included dependency directory or external installation: ${d}`);o.push([d,f])}return!1}return(await Li(c)).isSymbolicLink()?(s.push([d,_.resolve(_.dirname(c),await Pi(c)),(await tt(c))?.isDirectory()?"junction":"file"]),!1):!0}});for(let[c]of o)await Hr(_.resolve(i,c),_.join(t,c),"junction");for(let[c,d,f]of s){let m=await Ni(d,i,o);if(Ee(m)||dn(m))throw new Error(`Source symlink must target included workspace source: ${c}`);await Hr(_.resolve(t,m),_.join(t,c),f)}}import{execFile as Ui}from"node:child_process";import{constants as Br}from"node:fs";import{access as Gi,open as Fi}from"node:fs/promises";import zr from"node:path";import{promisify as Di}from"node:util";var Wi=Di(Ui);function qi(e){let t=e.match(/^\s*(?:"([^"\r\n]+)"|'([^'\r\n]+)'|([\w./\\:-]+))(?=\s|$)/u),n=t?.[1]??t?.[2]??t?.[3];return n&&!/[$`%&|<>^;]/u.test(n)?n:void 0}function Hi(e,t,n){return process.platform==="win32"?(t===1||t===9009)&&n.split(/\r?\n/u).some(r=>r.trim()===`'${e}' is not recognized as an internal or external command,`):t!==126&&t!==127?!1:n.split(/\r?\n/u).some(r=>t===127&&(r.endsWith(`: ${e}: not found`)||r.endsWith(`: ${e}: command not found`))||t===126&&r.includes(`: ${e}: `)&&r.endsWith(": bad interpreter: No such file or directory"))}async function Ki(e,t){let n=e.trim();if(!n||/[\r\n]/u.test(n))return!1;try{let r=await Fi(zr.resolve(t,n),Br.O_RDONLY|Br.O_NONBLOCK),o;try{let i=Buffer.alloc(256),{bytesRead:a}=await r.read(i,0,i.length,0);if(o=i.toString("utf8",0,a),a===i.length&&!o.includes(`
|
|
@@ -7,4 +7,4 @@ ${t}`;for(let r of wi)if(r.regex.test(n))return{code:r.code};return null}functio
|
|
|
7
7
|
[pm linked-test output truncated at ${st} bytes per stream; the child process continued to completion]
|
|
8
8
|
`:"";!x&&await Jr(e,{exitCode:R,stderr:k.text},n,s)&&(x="Linked test executable was not found. Install the tool or update the linked command before retrying.");let M={stdout:`${N.text}${O}`,stderr:k.text,exitCode:R,signal:b,timedOut:L,maxBufferExceeded:!1,outputTruncated:v,spawnError:x};return Ta(r,M,i,o),M}finally{await be(a,{recursive:!0,force:!0})}}function Aa(e,t){let n=[];e.maxBufferExceeded&&n.push(`Linked test output exceeded maxBuffer=${st} bytes. Reduce output volume or split the command.`),e.timedOut&&t>0&&n.push(`Linked test timed out after ${t}ms.`);let r=e.signal?`Linked test command terminated by signal ${e.signal}.`:void 0,o=e.spawnError?.trim()||r||"Linked test command failed.";return n.length===0?o:`${o} ${n.join(" ")}`}function Pa(e){let t=[e.spawnError??"",e.stderr,e.stdout].join(`
|
|
9
9
|
`);return ea.some(n=>n.test(t))||t.split(/\r?\n/u).some(n=>ta.test(n)&&na.test(n))}function Ra(e){return Pa(e)?"infra_collision":e.timedOut?"timeout":e.maxBufferExceeded?"max_buffer":e.spawnError?"spawn_error":e.signal?"signal":"assertion_failure"}function oo(e,t){for(let[n,r]of Object.entries(t.env_set))ne.has(n.toUpperCase())||(e[n]=r);for(let n of t.env_clear)ne.has(n.toUpperCase())||delete e[n]}function Oa(e){e.PORT===void 0&&(e.PORT="0"),e.HOST===void 0&&(e.HOST="127.0.0.1"),e.PM_SHARED_HOST_SAFE===void 0&&(e.PM_SHARED_HOST_SAFE="1"),e.PLAYWRIGHT_HTML_OPEN===void 0&&(e.PLAYWRIGHT_HTML_OPEN="never"),e.PW_TEST_HTML_REPORT_OPEN===void 0&&(e.PW_TEST_HTML_REPORT_OPEN="never")}function Ia(e,t){let n={...e.env_set,...t.env_set},r=[...new Set([...e.env_clear,...t.env_clear??[]])],o=t.shared_host_safe??e.shared_host_safe;return{env_set:n,env_clear:r,shared_host_safe:o}}function Co(e,t,n){return{env_set:ma(e,"--env-set"),env_clear:pa(t,"--env-clear"),shared_host_safe:n===!0}}async function Se(e,t,n=!1,r=hn){if(await he(e))try{await _t("seed_linked_test",async()=>{if(await r(y.dirname(t),{recursive:!0}),n){await Zr(e,t,{recursive:!0,force:!0});return}await Zr(e,t,{force:!0})},{why:"Linked tests need an isolated PM context without mutating the source tracker.",nextSteps:["Reclaim capacity on the filesystem that hosts the linked-test temporary directory."]})}catch(o){if(typeof o=="object"&&o!==null&&"code"in o&&K(o))return;throw o}}async function so(e,t,n,r=!1){for(let[o,s]of[[n.projectPmRoot,e],[n.globalPmRoot,t]])if(r){let i=await lt(D(o));if(i!==null){let a=await W(s);await xt({pmRoot:s,filePath:D(s),raw:i,op:"settings:write",author:$(void 0,a.author_default),lockTtlSeconds:a.locks.ttl_seconds,lockWaitMs:a.locks.wait_ms,recordCreation:!0,message:"Seed linked-test schema settings history"})}}else await Se(D(o),D(s));await Se(y.join(n.projectPmRoot,"extensions"),y.join(e,"extensions"),!0),await Se(y.join(n.globalPmRoot,"extensions"),y.join(t,"extensions"),!0)}async function io(e,t){if(!await he(e))return;let n=await mn(e,{withFileTypes:!0});for(let r of n){if(Zi.has(r.name))continue;let o=y.join(e,r.name),s=y.join(t,r.name);if(r.isDirectory()){await Se(o,s,!0);continue}r.isFile()&&await Se(o,s)}}async function ao(e,t){let n=await lt(D(e));if(n===null||await he(gt(e)))return;let r=await W(t);await be(gt(t),{force:!0}),await be(D(t),{force:!0}),await xt({pmRoot:t,filePath:D(t),raw:n,op:"settings:write",author:$(void 0,r.author_default),lockTtlSeconds:r.locks.ttl_seconds,lockWaitMs:r.locks.wait_ms,recordCreation:!0,message:"Seed linked-test tracker settings history"})}async function fe(e){if(!await he(e))return 0;let t=0,n=await mn(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||Qi.has(r.name))continue;let o=y.join(e,r.name),s;try{s=await mn(o,{withFileTypes:!0})}catch{continue}for(let i of s)i.isFile()&&An.some(a=>i.name.toLowerCase().endsWith(a))&&(t+=1)}return t}function ja(e){let t=typeof e.exitCode=="number"?e.exitCode:1;return(e.timedOut||e.maxBufferExceeded)&&t===0?1:t}function $a(e){let t=e.trim();if(t==="true")return!0;if(t==="false")return!1;if(t==="null")return null;let n=Number(t);if(t.length>0&&Number.isFinite(n))return n;if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch{}return t}function Ma(e,t){return typeof e=="object"&&e!==null&&typeof t=="object"&&t!==null?U(e,t):Object.is(e,t)}function Na(e,t,n){let r=[];r.push(...co("stdout",t,e.assert_stdout_contains)),r.push(...uo("stdout",t,e.assert_stdout_regex)),r.push(...co("stderr",n,e.assert_stderr_contains)),r.push(...uo("stderr",n,e.assert_stderr_regex)),r.push(...Ua(t,e.assert_stdout_min_lines));let o=e.assert_json_field_equals??{},s=e.assert_json_field_gte??{};if(!(Object.keys(o).length>0||Object.keys(s).length>0))return r;let a;try{a=JSON.parse(t)}catch(c){return r.push(`stdout is not valid JSON for assert_json_field_* checks: ${c instanceof Error?c.message:String(c)}`),r}for(let[c,d]of Object.entries(o)){let f=an(a,c);if(!f.found){r.push(`assert_json_field_equals missing path "${c}"`);continue}let m=$a(d);Ma(f.value,m)||r.push(`assert_json_field_equals mismatch at "${c}" (expected=${JSON.stringify(m)} actual=${JSON.stringify(f.value)})`)}for(let[c,d]of Object.entries(s)){let f=an(a,c);if(!f.found){r.push(`assert_json_field_gte missing path "${c}"`);continue}if(typeof f.value!="number"||!Number.isFinite(f.value)){r.push(`assert_json_field_gte path "${c}" resolved to non-numeric value`);continue}f.value<d&&r.push(`assert_json_field_gte failed at "${c}" (expected >= ${d}, actual ${f.value})`)}return r}function co(e,t,n){let r=[];for(let o of n??[])t.includes(o)||r.push(`${e} missing required text: "${o}"`);return r}function uo(e,t,n){let r=[];for(let o of n??[])try{new RegExp(o,"m").test(t)||r.push(`${e} failed regex assertion: /${o}/m`)}catch(s){r.push(`${e} regex assertion is invalid: /${o}/ (${s instanceof Error?s.message:String(s)})`)}return r}function Ua(e,t){if(typeof t!="number")return[];let n=e.split(/\r?\n/).map(r=>r.trim()).filter(r=>r.length>0).length;return n<t?[`stdout line count ${n} is below required minimum ${t}`]:[]}function Ga(e){let t=ue(e);return/(?:^|\s)(?:--test-name-pattern|--testnamepattern)(?:=|\s)/u.test(t)?!0:Z(t).some(n=>/(?:^|\s)-t(?:=|\s)/u.test(n)&&gn(n))}function Fa(e){return{root:e,schemaProjectPmPath:y.join(e,"schema","project",".agents","pm"),schemaGlobalPmPath:y.join(e,"schema","global"),trackerProjectPmPath:y.join(e,"tracker","project",".agents","pm"),trackerGlobalPmPath:y.join(e,"tracker","global"),workspaceSnapshotRoot:y.join(e,"workspace","project"),workspaceIsolatedRoot:y.join(e,"workspace","isolated")}}function Da(e,t,n){return e.some(r=>go(r,t,n)==="snapshot")}async function Wa(e,t){let n=y.join(e,".agents"),r=y.join(n,"pm");await hn(n,{recursive:!0}),await be(r,{recursive:!0,force:!0}),await Ji(t,r,process.platform==="win32"?"junction":"dir")}async function qa(e,t=yt,n=!0){let r={defaults:!0,agentGuidance:"skip"};await t(void 0,{path:e.schemaProjectPmPath},r),await t(void 0,{path:e.schemaGlobalPmPath},r),n&&(await t(void 0,{path:e.trackerProjectPmPath},r),await t(void 0,{path:e.trackerGlobalPmPath},r))}async function Ha(e,t,n){t&&(await so(e.schemaProjectPmPath,e.schemaGlobalPmPath,t,!0),n&&(await so(e.trackerProjectPmPath,e.trackerGlobalPmPath,t),await io(t.projectPmRoot,e.trackerProjectPmPath),await io(t.globalPmRoot,e.trackerGlobalPmPath),await ao(t.projectPmRoot,e.trackerProjectPmPath),await ao(t.globalPmRoot,e.trackerGlobalPmPath)))}function Ka(e,t,n){return e.some(r=>{let o=r.command??"",s=o.length>0&&wo(o),i=n?.autoPmContext===!0&&s?"auto":xo(r,t,n?.overrideLinkedPmContext===!0);return ko(i,s)==="tracker"})}async function Ba(e,t){return{sourceProjectItemCount:t?await fe(t.projectPmRoot):0,sourceGlobalItemCount:t?await fe(t.globalPmRoot):0,schemaProjectItemCount:await fe(e.schemaProjectPmPath),schemaGlobalItemCount:await fe(e.schemaGlobalPmPath),trackerProjectItemCount:await fe(e.trackerProjectPmPath),trackerGlobalItemCount:await fe(e.trackerGlobalPmPath)}}function za(e){let t=e.effectivePmContextMode==="tracker",n=t?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath,r=t?e.layout.trackerGlobalPmPath:e.layout.schemaGlobalPmPath,o=t?e.counts.trackerProjectItemCount:e.counts.schemaProjectItemCount,s=t?e.counts.trackerGlobalItemCount:e.counts.schemaGlobalItemCount,i=e.workspaceContextMode==="snapshot"?e.layout.workspaceSnapshotRoot:e.workspaceContextMode==="isolated"?e.layout.workspaceIsolatedRoot:e.sourceWorkspaceRoot,a=e.workspaceContextMode==="isolated"?"":i;return{requested_pm_context_mode:e.requestedPmContextMode,pm_context_mode:e.effectivePmContextMode,auto_pm_context_applied:e.autoPmContextApplied,is_pm_command:e.isPmCommand,is_pm_tracker_read_command:e.isPmTrackerReadCommand,source_project_pm_path:e.sourceRoots?.projectPmRoot??"",sandbox_project_pm_path:n,source_global_pm_path:e.sourceRoots?.globalPmRoot??"",sandbox_global_pm_path:r,source_project_item_count:e.counts.sourceProjectItemCount,sandbox_project_item_count:o,source_global_item_count:e.counts.sourceGlobalItemCount,sandbox_global_item_count:s,mismatch_detected:e.isPmCommand&&(e.counts.sourceProjectItemCount!==o||e.counts.sourceGlobalItemCount!==s),project_extensions_seeded:!!e.sourceRoots,global_extensions_seeded:!!e.sourceRoots,requested_workspace_context_mode:e.requestedWorkspaceContextMode,workspace_context_mode:e.workspaceContextMode,working_directory:i,source_workspace_root:a,trust:e.trust}}async function Ja(e){let t=typeof e.linkedTest.pm_context_mode=="string"&&e.linkedTest.pm_context_mode.trim().length>0?at(e.linkedTest.pm_context_mode):void 0,n=typeof e.linkedTest.command=="string"&&e.linkedTest.command.length>0?e.linkedTest.command:void 0,r=n?ha(n):!1,o=r&&n?wo(n):!1,s=e.options?.autoPmContext===!0&&o,i=s?"auto":xo(e.linkedTest,e.runLevelPmContextMode,e.options?.overrideLinkedPmContext===!0),a=ko(i,o),c=a==="tracker"?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath;e.workspaceContextMode==="snapshot"&&await Wa(e.layout.workspaceSnapshotRoot,c);let d=e.options?.pmRoot?await Zt(e.options.pmRoot,e.linkedTest,e.currentSourceRef):await Zt(e.layout.root,e.linkedTest,e.currentSourceRef);return{linkedOverridePmContextMode:t,executionContext:za({layout:e.layout,counts:e.counts,sourceRoots:e.sourceRoots,isPmCommand:r,isPmTrackerReadCommand:o,requestedPmContextMode:i,effectivePmContextMode:a,autoPmContextApplied:s,requestedWorkspaceContextMode:e.requestedWorkspaceContextMode,workspaceContextMode:e.workspaceContextMode,sourceWorkspaceRoot:e.sourceWorkspaceRoot,trust:d})}}function lo(e,t,n){return{command:e.command,path:e.path,status:"skipped",execution_context:t,error:n}}function Va(e,t,n,r){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"assertion_failure",execution_context:t,...r?{stdout:r.stdout,stderr:r.stderr}:{},error:n}}function Xa(e,t,n){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"trust_refusal",execution_context:t,error:n}}function Ya(e){if(e.executionContext.trust.trusted)return null;let t=e.options?.allowUntrustedLinkedTests===!0,n=e.options?.untrustedLinkedTestsPolicyEnabled===!0;if(t&&n)return null;let r=n?"Retry with --allow-untrusted-linked-tests for this invocation, or acknowledge the current commands with --acknowledge-linked-tests.":"Set testing.allow_untrusted_linked_tests=true, then retry with --allow-untrusted-linked-tests; alternatively acknowledge the current commands with --acknowledge-linked-tests.";return Xa(e.linkedTest,e.executionContext,`Linked test command is not trusted by this clone (source_ref=${e.executionContext.trust.source_ref??"unknown"}, current_ref=${e.executionContext.trust.current_source_ref??"unknown"}). ${r}`)}function Za(e){if(!e.linkedTest.command)return lo(e.linkedTest,e.executionContext,"No command configured for this linked test.");let t=xa(e.linkedTest.command);return t?lo(e.linkedTest,e.executionContext,t):null}function Qa(e){return e.executionContext.pm_context_mode!=="none"?null:e.executionContext.workspace_context_mode==="source"?it(e.linkedTest,e.executionContext,"pm_context_mode=none requires workspace_context_mode=isolated or snapshot so implicit tracker discovery cannot reach the source workspace."):e.executionContext.is_pm_command?it(e.linkedTest,e.executionContext,"pm_context_mode=none is for self-isolating SDK tests; direct PM commands require schema, tracker, or auto context."):null}function it(e,t,n){return{command:e.command,path:e.path,status:"refused",exit_code:null,failure_category:"config_refusal",execution_context:t,error:n}}function ec(e){let t=e.executionContext.pm_context_mode==="schema"&&e.executionContext.is_pm_tracker_read_command&&e.executionContext.mismatch_detected,n=e.options?.failOnContextMismatch===!0&&e.executionContext.is_pm_command&&e.executionContext.mismatch_detected;if(!t&&!n)return null;let r=fa({executionContext:e.executionContext,runLevelPmContextMode:e.runLevelPmContextMode,linkedOverridePmContextMode:e.linkedOverridePmContextMode}),o=e.options?.checkContext===!0?"Linked test preflight PM context mismatch detected":"Linked test PM context mismatch detected";return it(e.linkedTest,e.executionContext,`${o} (source_project_items=${e.executionContext.source_project_item_count}, sandbox_project_items=${e.executionContext.sandbox_project_item_count}).${r}`)}function tc(e){let t=Za(e);if(t)return t;let n=Ya(e);if(n)return n;let r=Qa(e);if(r)return r;let o=ec(e);return o||(e.options?.requireAssertionsForPm===!0&&e.executionContext.is_pm_command&&!la(e.linkedTest)?it(e.linkedTest,e.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled."):null)}function nc(e){let t=Ia(e.runtimeDirectives,e.linkedTest),n={...process.env,SENTRY_ENVIRONMENT:"test"};return oo(n,e.runtimeDirectives),oo(n,{env_set:e.linkedTest.env_set??{},env_clear:e.linkedTest.env_clear??[]}),t.shared_host_safe&&Oa(n),n.FORCE_COLOR="0",e.executionContext.pm_context_mode==="none"?delete n.PM_PATH:n.PM_PATH=e.executionContext.sandbox_project_pm_path,n.PM_GLOBAL_PATH=e.executionContext.sandbox_global_pm_path,e.executionContext.workspace_context_mode!=="source"&&(delete n.PM_BUILD_CONSUMER_LEASE,delete n.PM_BUILD_CONSUMER_LEASE_ROOT),e.executionContext.workspace_context_mode==="isolated"?(delete n.PM_SOURCE_WORKSPACE_ROOT,delete n.PM_SOURCE_PM_PATH,delete n[ge]):(n.PM_SOURCE_WORKSPACE_ROOT=e.executionContext.source_workspace_root,n.PM_SOURCE_PM_PATH=e.executionContext.workspace_context_mode==="snapshot"?e.executionContext.sandbox_project_pm_path:e.executionContext.source_project_pm_path,n[ge]="read_only"),n}function rc(e,t,n,r){return{command:e.command,path:e.path,status:"passed",exit_code:0,execution_context:t,stdout:n.stdout,stderr:n.stderr,...r?{execution_receipt:r}:{}}}function fo(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:1,failure_category:"empty_run",execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:`Linked test reported an empty test run (${e.emptyRunSignal.code}). Update the test selection so at least one test executes; unfiltered commands may opt out by omitting --fail-on-empty-test-run.`}}function oc(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:ja(e.execution),failure_category:Ra(e.execution),execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:Aa(e.execution,e.timeoutMs)}}function sc(e){let t=Nr(e.execution.stdout,e.execution.stderr),n=e.linkedTest.phase!=="setup"&&Ga(e.linkedTest.command??"");if(e.options?.failOnEmptyTestRun===!0||n){let o=Qe(e.execution.stdout,e.execution.stderr);if(o)return fo({...e,emptyRunSignal:o});if(n&&!t)return fo({...e,emptyRunSignal:{code:"missing_positive_execution_receipt"}})}let r=Na(e.linkedTest,e.execution.stdout,e.execution.stderr);return r.length>0?Va(e.linkedTest,e.executionContext,`Linked test assertion(s) failed: ${r.join("; ")}`,e.execution):rc(e.linkedTest,e.executionContext,e.execution,t)}async function ic(e){let t=e.linkedTest.command??"",n=(e.linkedTest.timeout_seconds??e.defaultTimeoutSeconds??120)*1e3,r=await La(t,n,nc(e),{index:e.index+1,total:e.total,timeoutMs:n,command:t},e.progressMode,e.executionContext.working_directory);return r.exitCode===0&&!r.timedOut&&!r.maxBufferExceeded?sc({...e,execution:r}):oc({...e,execution:r,timeoutMs:n})}async function ac(e,t,n){let r=gr(e);for(let w of r)mt(w.command);let o=[],s=await po(y.join(ho(),"pm-linked-test-")),i=Fa(s),a=at(n?.pmContext),c=_o(n?.workspaceContext),d=n?.progress===!0?"always":"auto",f=Co(n?.envSet,n?.envClear,n?.sharedHostSafe),m=n?.sourceRoots,p=Yt(),g=Ka(r,a,n),x=Da(r,c,n?.overrideLinkedWorkspaceContext===!0),h=await Xt(p);try{await qa(i,yt,g),await hn(i.workspaceIsolatedRoot,{recursive:!0}),await Ha(i,m,g),x&&await Kr(p,i.workspaceSnapshotRoot,m?.projectPmRoot,g);let w=await Ba(i,m),L=wr(),R=k=>go(k,c,n?.overrideLinkedWorkspaceContext===!0),b=new Set(r.filter(k=>!P(k)).map(R)),N=async(k,v)=>{let O=L.options(k,n),M=R(k),A=kr(k,M,b);if(A)return A;let I=await Ja({linkedTest:k,layout:i,counts:w,sourceRoots:m,runLevelPmContextMode:a,options:n,requestedWorkspaceContextMode:c,workspaceContextMode:M,currentSourceRef:h,sourceWorkspaceRoot:p});return tc({linkedTest:k,executionContext:I.executionContext,runLevelPmContextMode:a,linkedOverridePmContextMode:I.linkedOverridePmContextMode,options:O})??await ic({linkedTest:k,index:v,total:r.length,defaultTimeoutSeconds:t,runtimeDirectives:f,progressMode:d,executionContext:I.executionContext,options:O})};for(let k=0;k<r.length;k+=1){let v=r[k];o.push(L.blocked(v)??L.record(v,await N(v,k)))}}finally{await be(i.root,{recursive:!0,force:!0,maxRetries:3,retryDelay:100})}return o}function cc(e,t){let n=[...t];return e.filter(r=>{let o=n.findIndex(s=>_e(s,r));return o>=0&&n.splice(o,1),o<0}).length}async function dc(e){let{id:t,pmRoot:n,settings:r,typeToFolder:o}=e,s=await je(n,t,r.id_prefix,r.item_format,o);if(!s)throw new l(`Item ${t} not found`,u.NOT_FOUND);let i=await $e(s,{schema:r.schema});return{itemId:s.id,tests:i.document.metadata.tests??[],testRuns:i.document.metadata.test_runs??[],changed:!1,removed:0}}function uc(e,t){let n=[...e];for(let r of t)n.some(o=>_e(o,r))||n.push(r);return n}function lc(e,t,n){if(t.length===0&&n.length===0)return{tests:e,removed:0};let r=new Set(n),o=e.filter((s,i)=>r.has(i+1)?!1:!t.some(a=>a.kind==="command"?s.command===a.value:a.kind==="path"?s.path===a.value:s.command===a.value||s.path===a.value));return{tests:o,removed:e.length-o.length}}function fc(e,t,n,r){return lc(uc(e,t),n,r)}function mc(e){return[e.timeout!==void 0,e.progress===!0,(e.envSet?.length??0)>0,(e.envClear?.length??0)>0,e.sharedHostSafe===!0,e.pmContext!==void 0,e.overrideLinkedPmContext===!0,e.failOnContextMismatch===!0,e.failOnSkipped===!0,e.failOnEmptyTestRun===!0,e.requireAssertionsForPm===!0,e.checkContext===!0,e.fullOutput===!0,e.autoPmContext===!0,e.workspaceContext!==void 0,e.overrideLinkedWorkspaceContext===!0,e.allowUntrustedLinkedTests===!0].some(Boolean)}function Lo(e){if(mc(e)&&e.run!==!0)throw new l("--timeout, --progress, --env-set, --env-clear, --shared-host-safe, --pm-context, --override-linked-pm-context, --workspace-context, --override-linked-workspace-context, --allow-untrusted-linked-tests, --fail-on-context-mismatch, --fail-on-skipped, --fail-on-empty-test-run, --require-assertions-for-pm, --check-context, --full-output, and --auto-pm-context require --run",u.USAGE);if(e.acknowledgeLinkedTests===!0&&e.run===!0)throw new l("--acknowledge-linked-tests records trust without executing commands; run it separately before --run",u.USAGE);if((e.match!==void 0||e.onlyIndex!==void 0||e.onlyLast===!0)&&e.run!==!0)throw new l("--match, --only-index, and --only-last require --run",u.USAGE)}async function pc(e){let{id:t,options:n,pmRoot:r,settings:o,typeToFolder:s,adds:i,removes:a,removeIndexes:c}=e;if(i.length===0&&a.length===0&&c.length===0)return dc({id:t,pmRoot:r,settings:o,typeToFolder:s});let d=0,f=[],m=await ae({pmRoot:r,settings:o,id:t,op:i.length>0?"tests_add":"tests_remove",author:$(n.author,o.author_default),message:n.message,force:n.force,skipNoop:!0,mutate(g){let x=g.metadata.tests??[],h=fc(x,i,a,c);if(ft(()=>Ao(n,h.tests)),d=h.removed,(a.length>0||c.length>0)&&d===0)throw new l("No linked tests matched the requested removal selector",u.NOT_FOUND,{code:"linked_test_remove_no_match",unmatched:[...a.map(w=>`${w.kind}=${w.value}`),...c.map(w=>`index=${w}`)],required:"List linked tests and retry with an exact command/path or a current 1-based --remove-index.",examples:[`pm test ${t} --list`,`pm test ${t} --remove-index 1`]});return g.metadata.tests=h.tests,f=x,{changedFields:U(x,h.tests)?[]:["tests"]}}}),p=m.item.tests??[];return{itemId:m.item.id,tests:p,testRuns:m.item.test_runs??[],changed:m.changedFields.length>0,removed:d,written:m.changedFields.length>0?Mt(f,p):[],storedRemoved:cc(f,p)}}function Ao(e,t){let n=at(e.pmContext);_o(e.workspaceContext),Co(e.envSet,e.envClear,e.sharedHostSafe);let r={match:e.match,onlyIndex:e.onlyIndex===void 0?void 0:le(e.onlyIndex),onlyLast:e.onlyLast},o=e.timeout===void 0?void 0:pe(e.timeout,"--timeout");if(o!==void 0&&o<=0)throw new l(`--timeout must be a positive number (got "${e.timeout}")`,u.USAGE);Lo(e);let s=e.run===!0?xr(Or(t,r),t):void 0;if(s)for(let i of s.selected)mt(i.command);return{defaultTimeoutSeconds:o,pmContextMode:n,runSelection:s,testsToRun:s?.selected??t}}async function hc(e){let{options:t,runOptions:n,pmRoot:r}=e;return t.run!==!0?[]:await ac(n.testsToRun,n.defaultTimeoutSeconds,{progress:t.progress,envSet:t.envSet,envClear:t.envClear,sharedHostSafe:t.sharedHostSafe,pmContext:n.pmContextMode,overrideLinkedPmContext:t.overrideLinkedPmContext,failOnContextMismatch:t.failOnContextMismatch,failOnEmptyTestRun:t.failOnEmptyTestRun===!0||(t.measure?.length??0)>0,requireAssertionsForPm:t.requireAssertionsForPm,checkContext:t.checkContext,autoPmContext:t.autoPmContext,workspaceContext:t.workspaceContext,overrideLinkedWorkspaceContext:t.overrideLinkedWorkspaceContext,pmRoot:r,allowUntrustedLinkedTests:t.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:e.untrustedLinkedTestsPolicyEnabled,sourceRoots:{projectPmRoot:r,globalPmRoot:Rn(process.cwd())}})}function _c(e,t){let n=[];if(e.run===!0&&e.checkContext===!0){let r=da(t);n.push(`context_preflight:checked_pm_commands=${r.checked_pm_commands};tracker_read_commands=${r.tracker_read_commands};mismatches=${r.mismatches};auto_remediated=${r.auto_remediated}`)}return n}function gc(e){let t=ca(e.runResults),n=Number.parseInt(process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim()??"",10),r=process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM?.trim(),o=V(),s=rn(e.options.measure,o);return{run_id:aa("test"),kind:"test",status:t.failed>0||e.failOnSkippedTriggered?"failed":"passed",started_at:e.runStartedAt,finished_at:o,recorded_at:o,attempt:Number.isFinite(n)&&n>=1?n:void 0,resumed_from:r&&r.length>0?r:void 0,passed:t.passed,failed:t.failed,skipped:t.skipped,fail_on_skipped_triggered:e.failOnSkippedTriggered?!0:void 0,measurements:s.length>0?s:void 0,executions:e.runResults.filter(i=>i.command?.trim()).slice(0,32).map(i=>({command:i.command.trim(),requested_pm_context_mode:i.execution_context?.requested_pm_context_mode,pm_context_mode:i.execution_context?.pm_context_mode,workspace_context_mode:i.execution_context?.workspace_context_mode,trust_reason:i.execution_context?.trust.reason}))}}async function xc(e){let{options:t,pmRoot:n,settings:r,itemId:o,runStartedAt:s,runResults:i,failOnSkippedTriggered:a,warnings:c}=e;if(t.run!==!0||!s)return;let d=gc({options:t,runStartedAt:s,runResults:i,failOnSkippedTriggered:a});if(r.testing.record_results_to_items!==!0)return{entry:d,receipt:{recorded:!1,reason:"tracking_disabled",run_id:d.run_id,recovery_command:"pm config project set test-result-tracking --policy enabled"}};try{return await Xr({pmRoot:n,settings:r,itemId:o,author:$(t.author,r.author_default),message:`Track test run summary (${d.run_id})`,entry:d}),{entry:d,receipt:{recorded:!0,reason:"recorded",run_id:d.run_id}}}catch(f){if(Un(f))throw f;return c.push(`test_result_tracking_failed:${o}:${f instanceof Error?f.message:String(f)}`),{entry:d,receipt:{recorded:!1,reason:"write_failed",run_id:d.run_id}}}}function mo(e,t,n){let r;if(e.metricBelow!==void 0){let o=e.metricBelow.indexOf("="),s=e.metricBelow.slice(0,o).trim(),i=e.metricBelow.slice(o+1).trim(),a=Number(i);if(o<=0||s.length===0||i.length===0||!Number.isFinite(a))throw new l("--metric-below must use name=value",u.USAGE);r=Lr(t,s,a)}return{measurements:n?.measurements,metric_below:r,metric_diff:e.metricDiff===void 0?void 0:Ar(t,e.metricDiff)}}async function kc(e,t,n){if(e.acknowledgeLinkedTests===!0)return _r(t,n,V())}function wc(e){let{item:t,runResults:n,failureCategories:r,runSelection:o,failOnSkippedTriggered:s,warnings:i,recording:a,measurementProjection:c,restoreScope:d}=e,f=vc(t,e.fullHistory),m=yc(t,o,f,d),{counts:p,receipts:g}=Ue(f);return{ok:n.every(x=>x.status!=="failed"&&x.status!=="refused")&&s!==!0,id:t.itemId,tests:m.tests,...m.omitted,run_results:n,...e.ran?{failure_categories:r}:{},selection:o?{selector:o.selector,requested:o.requested,selected_indexes:o.selected_indexes,selected_count:o.selected_count,skipped_count:o.skipped_count,...o.setup_indexes?{setup_indexes:o.setup_indexes}:{}}:void 0,fail_on_skipped_triggered:s?!0:void 0,warnings:i.length>0?i:void 0,changed:t.changed||a?.receipt.recorded===!0,...a?{evidence_recording:a.receipt}:{},count:m.count,...t.removed>0?{removed:t.removed}:{},...p,...c,...g}}function yc(e,t,n,r){return n!==void 0?{tests:n.entries,count:n.returned_count,omitted:{}}:t!==void 0&&t.selector!==null&&t.skipped_count>0?{tests:t.selected,count:e.tests.length,omitted:{tests_omitted:{count:e.tests.length-t.selected.length,restore_with:Gr(e.itemId,r)}}}:{tests:e.tests,count:e.tests.length,omitted:{}}}function vc(e,t){if(e.written!==void 0)return xe({collectionKey:"tests",stored:e.tests,written:e.written,removedCount:e.storedRemoved,fullHistory:t})}function Tc(e,t){let n=e.tests[e.updated_index-1],r=xe({collectionKey:"tests",stored:e.tests,written:e.changed&&n!==void 0?[n]:[],removedCount:0,fullHistory:t}),{counts:o,receipts:s}=Ue(r);return{...e,tests:r.entries,run_results:[],count:r.returned_count,...o,...s}}async function yl(e,t,n){let r=Ir(t);if(r){jr(t),Lo(t),sn(e,t,n,B(process.cwd(),n.path));let I=await Mr(e,{...r,author:t.author,message:t.message,force:t.force},n);return Tc(I,t.fullHistory===!0)}let o=Oe(),s=B(process.cwd(),n.path);await ie(s);let i=await W(s);sn(e,t,n,s),rn(t.measure,"validation"),mo(t,[],void 0);let a=re(i,se()),c=await o.resolveList(t.add,"--add"),d=await o.resolveList(t.addJson,"--add-json"),f=await o.resolveList(t.remove,"--remove"),m=[...yo(c),...vo(d)],p=await mr(m,$(t.author,i.author_default),V())??[],g=To(f),x=Eo(t.removeIndex),h=await pc({id:e,options:t,pmRoot:s,settings:i,typeToFolder:a.type_to_folder,adds:p,removes:g,removeIndexes:x}),w=ft(()=>Ao(t,h.tests)),L=await kc(t,s,h.tests),R=t.run===!0?V():void 0,b=await hc({options:t,runOptions:w,pmRoot:s,untrustedLinkedTestsPolicyEnabled:i.testing.allow_untrusted_linked_tests});Fr(e,t,n,s,b);let N=Qt(b),k=t.run===!0&&t.failOnSkipped===!0&&b.some(I=>I.status==="skipped"),v=_c(t,b);L&&v.push(`linked_test_trust_acknowledged:${L.acknowledged}`);let O=await xc({options:t,pmRoot:s,settings:i,itemId:h.itemId,runStartedAt:R,runResults:b,failOnSkippedTriggered:k,warnings:v}),M=O?.receipt.recorded?ln([...h.testRuns,O.entry]):h.testRuns,A=mo(t,M,O?.entry);return wc({item:h,runResults:b,failureCategories:N,runSelection:w.runSelection,failOnSkippedTriggered:k,warnings:v,recording:O,measurementProjection:A,restoreScope:Ur(n,s),ran:t.run===!0,fullHistory:t.fullHistory===!0})}export{Ct as a,Lt as b,os as c,Mt as d,xe as e,rr as f,Nt as g,fs as h,ms as i,ps as j,de as k,hs as l,At as m,_s as n,gs as o,$t as p,xs as q,ks as r,ws as s,Vc as t,Xc as u,Us as v,Xt as w,Yt as x,Js as y,mr as z,pr as A,Zt as B,fd as C,_r as D,P as E,Be as F,gr as G,wr as H,Qt as I,ne as J,Ve as K,te as L,yr as M,en as N,tn as O,Tr as P,Er as Q,ye as R,Xe as S,nn as T,Sr as U,br as V,Cr as W,ve as X,ci as Y,rn as Z,Lr as _,Ar as $,Xr as aa,Mr as ba,sn as ca,da,kl as ea,wl as fa,Ra as ga,ja as ha,ac as ia,yl as ja};
|
|
10
|
-
//# sourceMappingURL=chunk-
|
|
10
|
+
//# sourceMappingURL=chunk-LTQWPQ7H.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{$a as ae,Ub as ut,Vb as ft,Xb as ce,_b as pt,a as rt,ac as lt,bc as mt,xc as ht,yc as yt}from"./chunk-ROTEELDL.js";import{u as dt}from"./chunk-SY5C3U32.js";import{Xb as ct}from"./chunk-SDXCJZKB.js";import{m as at}from"./chunk-L2ZSSMYY.js";import{a as it,c as P,d as oe,e as ot,f as se,g as st}from"./chunk-7V65VACG.js";import{j as z,m as G}from"./chunk-C6WM6ZN4.js";import{Ra as ie,d as Re,ea as Ye,ga as x,qb as Xe,qc as et,t as Ie,u as Me,v as X,wb as Qe}from"./chunk-CBUC4X7Q.js";import{m as Ze,u as D}from"./chunk-OXC5KBIQ.js";import{b as He}from"./chunk-3AZOATC2.js";import{Ha as De,Jb as Ke,Ma as Pe,Nb as U,Ua as ze,Va as Ge,Wa as re,Wg as We,Xg as C,Ze as F,cg as Je,df as Le,hb as qe,hh as Be,ih as Ve,ja as je,jf as M}from"./chunk-NRQCBUYD.js";import{g as ee,p as Ne}from"./chunk-GSLOAEY2.js";import{Aa as tt,Ga as nt}from"./chunk-A5ZEMOVR.js";import{a as b,da as ne}from"./chunk-I4SPJQQI.js";import{P as Ue,V as te,Z as Fe,aa as xe,ea as v}from"./chunk-TE6FBDHP.js";import{A as f,C as u,G as Q,J as Ce,K as I,l as $e,q as R,t as Te,y as ke}from"./chunk-K672XXGQ.js";import ge from"node:crypto";import{constants as me,readFileSync as Jn}from"node:fs";import{cp as Wn,lstat as qt,mkdir as Bn,mkdtemp as Kt,open as Vn,readdir as Yn,realpath as Lt,rm as Jt,stat as _e,writeFile as Wt}from"node:fs/promises";import{tmpdir as Bt}from"node:os";import m from"node:path";import Tt from"node:crypto";var A=new Set(["id","title","description","type","status","priority","tags","body","deadline","estimated_minutes","acceptance_criteria","definition_of_ready","order","rank","assignee",...$e,"affected_version","fixed_version","component","regression","customer_impact","close_reason","completed_at","dependencies","comments","notes","learnings","files","tests","docs","reminders","events","type_options"]);function wt(e){if(e===void 0)return;let t=e.replace(/[A-Z]/gu,n=>`_${n.toLowerCase()}`);return A.has(t)?t:e}function q(e,t,n){let r=e?.estimatedMinutes;if(!(r===void 0||typeof r=="string"))throw new u(`Mutation ${n+1} ${t} option "estimatedMinutes" must be a string.`,f.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 de=["op","id","reason","options","unique","match"],sn=[...de,"ref"],gt=[...sn,"item"],an="mutate-",_t="row-",St=["schema_version","mutations"],kt="[a-z][a-z0-9._-]{0,63}",Et=new RegExp(`^${kt}$`,"u"),Rt=new RegExp(`(^|,)id=@(${kt})(?=,|$)`,"gu"),Ot=e=>e.slice(2).replaceAll(/-([a-z])/gu,(t,n)=>n.toUpperCase()),K=["item","item_hash","linked","schedule","claim_state","children","omission_receipt","row_contract","context_intent"],It=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"]),cn=new Set([...It,"completed_at","id"]),Mt={create:z.map(e=>e.target),update:G.map(e=>e.target),close:tt.map(e=>Ot(e.flag)).filter(e=>e!=="reason"),release:nt.map(e=>Ot(e.flag))};function Pr(e){let t=Tt.createHash("sha256").update(e).digest("hex");return`${an}${t.slice(0,24)}`}function zr(e){let t={},n=e.createCompensation;if(n!==void 0){if(n!=="close"&&n!=="delete")throw new u("createCompensation must be close or delete.",f.USAGE);t.createCompensation=n}for(let r of["lockTtlSeconds","lockWaitMs"]){let i=e[r];if(i===void 0)continue;let s=typeof i=="number"||typeof i=="string"&&i.trim().length>0?Number(i):Number.NaN;if(!Number.isSafeInteger(s)||s<=0)throw new u(`${r} must be a positive safe integer.`,f.USAGE);t[r]=s}return t}function w(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function L(e,t){let n=Math.max(1,Math.min(3,Math.floor(e.length/4)+1)),r;for(let i of t){let s=je(e,i,n);s!==null&&(r===void 0||s<r.distance)&&(r={key:i,distance:s})}return r?.key}function $(e,t,n){let r=L(t,n);return new u(r===void 0?`${e} does not recognize key "${t}". Allowed keys: ${n.join(", ")}.`:`${e} does not recognize key "${t}". Did you mean "${r}"?`,f.USAGE,{code:"stdin_json_unknown_key",required:`Use documented ${e} keys only.`,why:"Strict structured input prevents silent typos from creating incomplete or unintended mutations.",nextSteps:[r===void 0?`Remove or correct "${t}".`:`Replace "${t}" with "${r}".`]})}function pe(e,t){try{return JSON.parse(e)}catch(n){let r=n instanceof Error?n.message:String(n);throw new u(`${t} must be valid JSON: ${r}`,f.USAGE,{code:"stdin_json_invalid",required:`Pipe one valid JSON ${t.toLowerCase()} into stdin.`,why:"Structured mutation input must parse deterministically before any tracker write begins."})}}function dn(e,t){if(!w(e))throw new u(`Mutation ${t+1} must be an object.`,f.USAGE);for(let n of Object.keys(e))if(!de.includes(n))throw $(`mutation ${t+1}`,n,de);return e}function un(e,t,n,r){if(e===void 0)return;if(!w(e))throw new u(`Mutation ${n+1} options must be an object.`,f.USAGE);let i=[...Mt[t],...jt(t,r)];for(let s of Object.keys(e))if(!i.includes(s))throw $(`mutation ${n+1} ${t} options`,s,i);return q(e,t,n),e}function bt(e,t,n,r){if(e===void 0)return;let i=r==="unique"?"create":"update";if(t!==i)throw new u(`Mutation ${n+1} ${r} is only valid for ${i} operations.`,f.USAGE);let s=w(e)&&typeof e.key=="string"?e.key.trim():"";if(!w(e)||s.length===0||e.value===void 0||e.value===null)throw new u(`Mutation ${n+1} ${r} must be an object with a non-empty key and a value.`,f.USAGE);return{key:s,value:e.value}}function fn(e,t,n){let r=dn(e,t),{op:i,id:s,reason:o}=r;if(i!=="create"&&i!=="update"&&i!=="close"&&i!=="release")throw new u(`Mutation ${t+1} op must be create, update, close, or release.`,f.USAGE);let a=un(r.options,i,t,n),d=bt(r.unique,i,t,"unique"),c=bt(r.match,i,t,"match");if(typeof s!="string"||s.trim().length===0)throw new u(`Mutation ${t+1} requires a non-empty id.`,f.USAGE);let p=s.trim();if(i==="close"){if(typeof o!="string"||o.trim().length===0)throw new u(`Mutation ${t+1} close requires a non-empty reason.`,f.USAGE);return{op:i,id:p,reason:o.trim(),...a===void 0?{}:{options:a}}}if(i==="release")return{op:i,id:p,...a===void 0?{}:{options:a}};if(!w(a))throw new u(`Mutation ${t+1} ${i} requires an options object.`,f.USAGE);return{op:i,id:p,options:a,...d===void 0?{}:{unique:d},...c===void 0?{}:{match:c}}}function Ct(e,t={}){let n=pe(e,"Mutation batch"),r=Array.isArray(n)?n:w(n)&&Array.isArray(n.mutations)?n.mutations:void 0;if(r===void 0||r.length===0)throw new u("Mutation batch must be a non-empty JSON array or an object with a non-empty mutations array.",f.USAGE);let i=t.runtimeFields??[];return r.map((s,o)=>{let a=fn(s,o,i);return a.options!==void 0&&Ie(a.options),a})}function pn(e,t,n){let r=Tt.createHash("sha256").update(e).update("\0").update(t).digest("hex"),i=BigInt(`0x${r.slice(0,16)}`).toString(36).padStart(13,"0").slice(-12);return`${Ye(n)}${i}`}function vt(e,t){if(typeof e!="string"||!e.startsWith("@"))return e;let n=e.slice(1),r=t[n];if(r===void 0)throw new u(`Unknown mutation reference "${e}".`,f.USAGE);return r}function At(e,t){if(typeof e!="string")return e;let n=e.replace(Rt,(r,i,s)=>{let o=t[s];if(o===void 0)throw new u(`Unknown mutation reference "@${s}".`,f.USAGE);return`${i}id=${o}`});if(/(^|,)id=@/u.test(n))throw new u(`Malformed mutation reference in dependency "${e}".`,f.USAGE);return n}function ln(e){return typeof e!="string"?[]:e.startsWith("@")?[e.slice(1)]:[...e.matchAll(Rt)].map(t=>t[1]).filter(t=>t!==void 0)}function mn(e,t){let n=new Map;for(let[o,a]of e.entries()){let d=t[o];if(d===void 0)continue;let c=w(a.options)?a.options:{},p=Array.isArray(c.dep)?c.dep:c.dep===void 0?[]:[c.dep];n.set(d,[c.parent,c.blockedBy,...p].flatMap(ln))}let r=new Set,i=new Set,s=o=>{if(r.has(o))throw new u(`Mutation reference cycle includes "@${o}".`,f.USAGE);if(!i.has(o)){r.add(o);for(let a of n.get(o))n.has(a)&&s(a);r.delete(o),i.add(o)}};for(let o of n.keys())s(o)}function hn(e){let n=e.split(/\r?\n/u).map((o,a)=>({line:o.trim(),number:a+1})).filter(o=>o.line.length>0);if(n.length<2)return null;let r=n.map(o=>{try{return{...o,ok:!0,value:JSON.parse(o.line)}}catch(a){return{...o,ok:!1,error:a}}}),i=r[0];if(!i.ok&&(i.line.startsWith("[")||i.line==="{"||r.at(-1).line==="}")||!r.some(o=>o.ok&&w(o.value)))return null;let s=[];for(let o of r){if(!o.ok)throw new u(`Mutation document line ${o.number} must be one valid JSON object: ${et(o.error)}`,f.USAGE,{code:"stdin_json_invalid",required:"Provide one JSON object per line (JSON Lines), a JSON array, or a {schema_version, mutations} document.",why:"Structured mutation input must parse deterministically before any tracker write begins."});if(!w(o.value))throw new u(`Mutation document line ${o.number} must be a JSON object.`,f.USAGE);s.push(o.value)}return s}function yn(e){return Object.hasOwn(e,"mutations")||Object.hasOwn(e,"schema_version")}function wn(e){let t;try{t=pe(e,"Mutation document")}catch(n){let r=hn(e);if(r===null)throw n;return{schema_version:1,mutations:r}}return Array.isArray(t)?{schema_version:1,mutations:t}:w(t)&&!yn(t)?{schema_version:1,mutations:[t]}:t}function gn(e,t){let n=Object.hasOwn(e,"op")?_n(e,t):Sn(e,t);if(n.op==="create"&&n.id===void 0&&w(n.item)&&n.item.id!==void 0){if(typeof n.item.id!="string")throw new u(`Mutation ${t+1} item id must be a string.`,f.USAGE);n.id=n.item.id}return n}function _n(e,t){for(let n of Object.keys(e))if(!gt.includes(n))throw $(`mutation ${t+1}`,n,gt);if(e.item!==void 0&&e.op!=="create")throw new u(`Mutation ${t+1} item documents are only valid for create operations.`,f.USAGE);if(e.item!==void 0&&e.options!==void 0)throw new u(`Mutation ${t+1} must declare either item or options, not both.`,f.USAGE);return{...e}}function Sn(e,t){let{ref:n,id:r,item:i,...s}=e,o=i!==void 0?i:s;if(i!==void 0&&Object.keys(s).length>0)throw new u(`Mutation ${t+1} must not mix item document keys with top-level fields.`,f.USAGE);if(!w(o))throw new u(`Mutation ${t+1} item document must be an object.`,f.USAGE);return{op:"create",...n===void 0?{}:{ref:n},...r===void 0?{}:{id:r},item:o}}function En(e){let t=wn(e);if(!w(t))throw new u("Mutation document must be a JSON array or object.",f.USAGE);for(let n of Object.keys(t))if(!St.includes(n))throw $("mutation document",n,St);if(t.schema_version!==void 0&&t.schema_version!==1)throw new u("Mutation document schema_version must be 1.",f.USAGE);if(!Array.isArray(t.mutations)||t.mutations.length===0)throw new u("Mutation document requires a non-empty mutations array.",f.USAGE);return t.mutations.map((n,r)=>{if(!w(n))throw new u(`Mutation ${r+1} must be an object.`,f.USAGE);return gn(n,r)})}function On(e,t,n){let r=new Set(Object.values(Ft(t,n,Object.create(null))));for(let i of t)i.op==="create"&&typeof i.id=="string"&&i.id.trim().length>0&&r.add(x(i.id,n.idPrefix));return{...e,existing:e.existing.filter(i=>!r.has(i.id))}}function bn(e){let t=new Set(e.map(n=>n.ref).filter(n=>typeof n=="string"));for(let[n,r]of e.entries()){if(r.op!=="create"||r.ref!==void 0||typeof r.id=="string"&&r.id.trim().length>0)continue;let i=`${_t}${n+1}`;if(t.has(i))throw new u(`Mutation ${n+1} receives the synthesized ref "${i}", but another row declares that ref. Rename it or give mutation ${n+1} its own ref; ${_t}<n> aliases are reserved for rows without one.`,f.USAGE);r.ref=i}}function Nt(e,t,n){let r=Gn(JSON.stringify(e),t,{},n);return delete r.stdinJson,delete r.documentAnnotationSnapshot,r}function jt(e,t){return e!=="create"&&e!=="update"?[]:t.filter(n=>n.commands.includes(e)).map(n=>v(n))}function vn(e,t){for(let n of e)w(n.item)&&(n.options=Nt(n.item,"create",t),delete n.item)}function Ut(e,t){return t.some(n=>n.metadata_key===e)?e:wt(e)}function ue(e,t,n){let r=t.replaceAll(/_([a-z])/gu,(d,c)=>c.toUpperCase());if(w(e.item)){if(e.item[t]!==void 0)return e.item[t];if(Ut(r,n)===t&&e.item[r]!==void 0)return e.item[r]}let i=w(e.options)?e.options:{},s=n.find(d=>d.metadata_key===t);return s!==void 0&&i[v(s)]!==void 0?i[v(s)]:i[t]!==void 0?i[t]:i[r]!==void 0?i[r]:(Array.isArray(i.field)?i.field:[]).map(String).find(d=>d.startsWith(`${t}=`))?.slice(t.length+1)}function An(e,t){return e<t?-1:+(e!==t)}function fe(e){return Array.isArray(e)?e.map(fe):w(e)?Object.fromEntries(Object.entries(e).sort(([t],[n])=>An(t,n)).map(([t,n])=>[t,fe(n)])):e}function S(e){return typeof e=="string"?e.trim():JSON.stringify(fe(e))}function $n(e,t,n,r,i){let s=t.key.trim();if(s.length===0)throw new u("Upsert key must be a non-empty field name.",f.USAGE);let o=Tn(t.existing),a=new Map,d=new Set;for(let[c,p]of e.entries()){if(p.op!=="create")continue;let l=kn(p,s,c,a,r),y=Rn(o.get(l)??[],s,l);if(y===void 0){p.unique={key:s,value:ue(p,s,r)};continue}let h=x(y,n);typeof p.ref=="string"&&(i[p.ref]=h),In(p,h,r,{key:s,value:ue(p,s,r)}),d.add(c)}return d}function Tn(e){let t=new Map;for(let n of e){if(n.value===void 0||n.value===null)continue;let r=S(n.value);t.set(r,[...t.get(r)??[],n.id])}return t}function kn(e,t,n,r,i){let s=ue(e,t,i);if(s==null||s==="")throw new u(`Mutation ${n+1} is missing the upsert key "${t}".`,f.USAGE,{code:"upsert_key_missing",required:`Every create record must carry a non-empty "${t}" value when --upsert-key ${t} is set.`,why:"Keyed upsert identifies existing items by that field; a record without it cannot be matched or safely created."});let o=S(s),a=r.get(o);if(a!==void 0)throw new u(`Mutations ${a+1} and ${n+1} share the upsert key value ${JSON.stringify(o)} for "${t}".`,f.USAGE,{code:"upsert_key_duplicate",required:"Each record must carry a distinct upsert key value within one batch.",why:"Two records with the same key would race for the same existing item."});return r.set(o,n),o}function Rn(e,t,n){if(e.length>1)throw new u(`Upsert key "${t}" value ${JSON.stringify(n)} matches ${e.length} existing items: ${e.join(", ")}.`,f.CONFLICT,{code:"upsert_key_ambiguous",required:"Resolve the duplicate existing items or choose a key that is unique per item.",why:"An ambiguous key cannot select one item to update without guessing."});return e[0]}function In(e,t,n,r){let i=new Set([...Mt.update,...jt("update",n)]),s=w(e.item)?Nt(e.item,"update",n):Object.fromEntries(Object.entries(e.options).filter(([o])=>i.has(o)));delete e.item,delete e.ref,e.op="update",e.id=t,e.options=s,e.match=r}function Ft(e,t,n){for(let[r,i]of e.entries())if(i.ref!==void 0){if(i.op!=="create")throw new u(`Mutation ${r+1} ref is only valid for create operations.`,f.USAGE);if(typeof i.ref!="string"||!Et.test(i.ref))throw new u(`Mutation ${r+1} ref must match ${Et.source}.`,f.USAGE);if(n[i.ref]!==void 0)throw new u(`Duplicate mutation ref "${i.ref}".`,f.USAGE);n[i.ref]=typeof i.id=="string"&&i.id.trim().length>0?x(i.id,t.idPrefix):pn(t.transactionId,i.ref,t.idPrefix)}return n}function Gr(e,t){let n=En(e);bn(n);let r=n.map(p=>typeof p.ref=="string"?p.ref:void 0),i=Object.create(null),s=t.upsert===void 0?new Set:$n(n,On(t.upsert,n,t),t.idPrefix,t.runtimeFields??[],i);vn(n,t.runtimeFields??[]),Ft(n,t,i),mn(n,r);let o=n.map(p=>{let l={...p},y=typeof l.ref=="string"?l.ref:void 0;if(delete l.ref,y!==void 0?l.id=i[y]:l.id=vt(l.id,i),w(l.options)){let h={...l.options};for(let g of["parent","blockedBy"])h[g]!==void 0&&(h[g]=vt(h[g],i));Array.isArray(h.dep)?h.dep=h.dep.map(g=>At(g,i)):h.dep!==void 0&&(h.dep=At(h.dep,i)),l.options=h}return l}),a=Ct(JSON.stringify(o),{runtimeFields:t.runtimeFields??[]}),d=a.filter(p=>p.op==="create").map(p=>p.id);if(new Set(d).size!==d.length)throw new u("Duplicate resolved create id in mutation document.",f.USAGE);let c=a.map((p,l)=>{let y=r[l];return{index:l,...typeof y=="string"?{ref:y}:{},id:p.id,op:p.op,...s.has(l)?{upserted:!0}:{}}});return{schema_version:1,mutations:a,references:i,rows:c}}function Mn(e,t){return t.filter(n=>e[n]!==void 0&&e[n]!==null).map(n=>{let r=String(e[n]);return`${n}=${/[",\n\r\\]/u.test(r)?JSON.stringify(r):r}`}).join(",")}function Cn(e,t,n){if(e!==void 0){if(!Array.isArray(e)||!e.every(w))throw new u(`${n} must be an array of objects.`,f.USAGE);return e.map(r=>Mn(r,t))}}function Nn(e,t){return e==="tags"&&Array.isArray(t)&&t.every(n=>typeof n=="string")?JSON.stringify(t):typeof t=="number"||typeof t=="boolean"?String(t):t}function $t(e,t,n=!1){for(let[r,i,s]of ct){let o=t[r],a=Cn(n&&["comments","notes","learnings"].includes(r)&&Array.isArray(o)?o.filter(d=>!w(d)||d.created_at===void 0):o,s,r);a!==void 0&&a.length>0&&(e[i]=a)}}function jn(e,t){for(let n of Object.keys(e)){if(t){if(!K.includes(n))throw $("item envelope",n,K);continue}if(!A.has(n)&&L(n,[...A])===void 0&&L(n,K)==="item")throw $("item envelope",n,K)}}function Un(e){let t=Object.hasOwn(e,"item");jn(e,t);let n=t?e.item:e;if(!w(n))throw new u("Item document item must be an object.",f.USAGE);return{item:n,...t&&w(e.linked)?{linked:e.linked}:{}}}function Fn(e,t,n,r,i,s){if((r==="update"?cn:It).has(t))return;let a=i.find(d=>d.metadata_key===t&&d.commands.includes(r));if(a!==void 0){let d=ne(s,a);e[v(a)]=d!==void 0?d:a.type==="array"||a.type==="object"?JSON.stringify(n):n;return}if(!A.has(t)){if(L(t,[...A])!==void 0)throw $("item document",t,[...A]);let c=Array.isArray(e.field)?e.field:[];c.push(`${t}=${typeof n=="string"?n:JSON.stringify(n)}`),e.field=c;return}["dependencies","comments","notes","learnings","files","tests","docs","reminders","events","type_options"].includes(t)||(e[t.replaceAll(/_([a-z])/gu,(d,c)=>c.toUpperCase())]=Nn(t,n))}function xn(e){return{command_to_fields:new Map([["create",e.filter(t=>t.commands.includes("create"))]])}}function Dn(e,t,n,r){let i=r.filter(c=>c.commands.includes("create")),s=new Set([...De.filter(c=>t.has(c.option)).map(c=>c.field),...i.filter(c=>t.has(v(c))).map(c=>c.metadata_key),...at(Array.isArray(n)?n.map(String):[],xn(i)).metadataKeys]),o=(Array.isArray(e)?e:[]).filter(w).filter(c=>typeof c.field=="string"&&!s.has(c.field));if(o.length===0)return{};let a=o.map(c=>typeof c.reason=="string"?c.reason.trim():""),d=o.map(c=>c.field);return t.has("deferReason")?{defer:d}:a.every(c=>c.length>0)?{defer:d,deferReason:[...new Set(a)].join("; ")}:{defer:d}}function Pn(e,t,n){let r=new Set(Object.entries(e).filter(([,s])=>s!==void 0).map(([s])=>s)),i=t==="create"?z:G;for(let{target:s,keys:o}of i)o.some(a=>r.has(a))&&r.add(s);for(let s of n.filter(o=>o.commands.includes(t)))ne(e,s)!==void 0&&r.add(v(s));return r}function zn(e,t,n){let r=t==="create"?z:G;for(let{target:i}of r)i!=="field"&&n.has(i)&&delete e[i]}function Gn(e,t,n={},r=[]){let i=pe(e,"Item document");if(!w(i))throw new u("Item document must be a JSON object.",f.USAGE);let{item:s,linked:o}=Un(i),a={};for(let[l,y]of Object.entries(s)){let h=Ut(l,r);h!==l&&Object.hasOwn(s,h)||Fn(a,h,y,t,r,n)}$t(a,s,t==="update"),o!==void 0&&$t(a,o);let d=Pn(n,t,r);if(zn(a,t,d),t==="create"&&!d.has("defer")&&Object.assign(a,Dn(s.deferred_fields,d,n.unset,r)),t==="update"){let l=Object.fromEntries(["comments","notes","learnings"].filter(y=>Object.hasOwn(s,y)&&!d.has(y.slice(0,-1))).map(y=>[y,s[y].filter(h=>w(h)&&h.created_at!==void 0)]));Object.keys(l).length>0&&(a.documentAnnotationSnapshot=l)}let c={...a,...Object.fromEntries(Object.entries(n).filter(([,l])=>l!==void 0)),...Array.isArray(a.field)&&Array.isArray(n.field)?{field:[...a.field,...n.field]}:{},stdinJson:void 0},p=Object.keys(a).filter(l=>!d.has(l));return Me(Re(c,p),p)}function qr(e){return Ct(JSON.stringify(e))}var qn=["id","updated_at","pm_format_version","type"],Kn="import";function xt(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(qn.includes(e))throw new TypeError(`${t} cannot change "${e}"; the item writer derives it, or an update row owns it`)}function J(e){return Array.isArray(e)?`array of ${e.length}`:typeof e}var Ln=["__proto__","constructor","prototype"];function Dt(e){return e!==null&&typeof e=="object"&&Object.getPrototypeOf(e)===Object.prototype}function N(e){return e===null||typeof e=="string"||typeof e=="boolean"?!0:typeof e=="number"?Number.isFinite(e):Array.isArray(e)?Array.from(e).every(N):Dt(e)?Object.entries(e).every(([t,n])=>!Ln.includes(t)&&N(n)):!1}function le(e,t){let{set:n,unset:r}=e;if(n!==void 0&&!Dt(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(xt(o,t),n[o]===null||!N(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(xt(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 Pt(e){le(e,`Finalization of ${e.id}`);let t=await D(e.pmRoot),n={schema:t.schema,extensionFieldNames:Je(C())},r=await Qe({pmRoot:e.pmRoot,settings:t,id:e.id,op:Kn,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,p]of Object.entries(e.set??{}))o[c]=structuredClone(p);for(let c of e.unset??[])delete o[c];let a;try{Pe(i.metadata);let c=re(i,n),p=re(ze(Ge(c,n),n),n);if(b(p)!==b(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 l=Object.entries(e.set??{}).find(([y,h])=>J(a[y])!==J(h));if(l!==void 0)throw new TypeError(`set "${l[0]}" is not stored as declared (${J(l[1])} normalizes to ${a[l[0]]===void 0?"an absent field":J(a[l[0]])})`)}catch(c){throw new u(`Finalization of ${e.id} would not store a readable item with the declared fields: ${c.message}`,f.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)||b(s[c])!==b(a[c])).sort((c,p)=>c.localeCompare(p))}}});return{item:r.item,changedFields:r.changedFields}}async function Hn(e,t){if(!Ze(e))return{schema:te(t.schema),typeDefinitionsFromFile:[]};let n=await fr(e,t.schema);return{schema:n.schema,typeDefinitionsFromFile:n.type_definitions_from_file??[]}}async function Zn(e,t,n,r){let i=ee({...t,item_types:{...t.item_types,definitions:[...t.item_types?.definitions??[],...n.typeDefinitionsFromFile]}},C());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 Se(e){let t=new Map,n=async r=>{let i=await D(e),s=await Hn(e,i),o=new Map;for(let a of await Zn(e,i,s,r)){let d=S(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=S(o);a.set(d,[...a.get(d)??[],String(r.id)])}},invalidate(){t.clear()}}}async function Xn(e,t){let n=S(t.value),r=(await e.lookup(t.key)).get(n)??[];if(r.length!==0)throw new u(`Upsert key "${t.key}" value ${JSON.stringify(n)} now matches existing item ${r.join(", ")}; the plan was resolved before it existed.`,f.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 Vt(e,t,n){let r=e.metadata[n.key],i=S(n.value);if(S(r)!==i)throw new u(`Item ${t} no longer carries upsert key "${n.key}" value ${JSON.stringify(i)}; the plan selected it before the key changed.`,f.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 zt(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 Y(e,t){let n={...e,...t};return e===void 0?n:X(e,n)}async function E(e,t){try{let r=(await ae(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 u&&n.exitCode===f.NOT_FOUND)return;throw n}}function Ee(e,t){let n=e.id.replaceAll(/[^a-zA-Z0-9._-]/gu,"_"),r=ge.createHash("sha256").update(b(e)).digest("hex").slice(0,12);return`${t+1}-${e.op}-${n}-${r}`}function Qn(e,t){let n=e.id.replaceAll(/[^a-zA-Z0-9._-]/gu,"_");return`${t+1}-${e.op}-${n}`}function _(e,t,n){return`bulk-item-transaction ${e} ${t} ${n}`}function Oe(e,t){return e===t||(e?.startsWith(`${t} | `)??!1)}async function k(e,t,n,r){let i=await U(m.join(e,"history",`${t}.jsonl`),t),s=_(n,r,"apply"),o=_(n,r,"compensate");for(let a=i.length-1;a>=0;a-=1){let d=i[a].message;if(Oe(d,s))return!0;if(d===o)return!1}return!1}async function H(e,t){let n=await E(e,t.id);if(n?.updatedAt===void 0)throw new u(`Bulk ${t.op} target ${t.id} does not exist or has no restorable version`,f.NOT_FOUND);let r=await U(m.join(e,"history",`${n.id}.jsonl`),n.id);if(r.length===0)throw new u(`Bulk ${t.op} target ${t.id} has no restorable history`,f.NOT_FOUND);return{target_updated_at:n.updatedAt,target_version:String(ie(r)+r.length),target_history_hash:F(r),target_history_length:r.length}}function T(e,t,n){return new u(`Transaction ${e.transactionId} cannot safely compensate incomplete step ${n}; review item ${t} history before recovery.`,f.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 Yt(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 er(e,t,n){let{expectedHistory:r,length:i,version:s}=t;if(F(e)===r)return!1;if(typeof i!="number"||!Number.isSafeInteger(i)||i<1||F(e.slice(0,i))!==r||s!==String(ie(e)+i))throw T(n,n.itemId,n.stepId);let o=_(n.transactionId,n.stepId,"apply"),a=e.slice(i),d=y=>Oe(y.message,o)||y.context?.item_transaction_step===o,c=_(n.transactionId,n.stepId,"compensate");if(a.filter(y=>d(y)||y.message===c).at(-1)?.message===c)return!1;let p=a.filter(d);if(p.length===0)return!1;let l=e.at(-1).after_hash===p.at(-1).after_hash&&a.every(y=>Yt(y,n.transactionId));if(p.length!==a.length&&!l)throw T(n,n.itemId,n.stepId);return!0}async function Ht(e,t){let n=m.join(e,"history",`${t}.jsonl`),r=await Ke(n,t);return{history:r.entries,assertOwnedUnderLock:(i,s)=>{let o;try{o=Jn(n).equals(r.raw_bytes)&&Le(i)===r.entries.at(-1).after_hash}catch(a){throw Object.assign(s(),{cause:a})}if(!o)throw s()}}}async function j(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(e.pmRoot,t);if(o===void 0)return;let{history:a,assertOwnedUnderLock:d}=await Ht(e.pmRoot,o.id),c=i.target_history_hash,p=typeof c=="string";if(typeof c=="string"){if(!er(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 k(e.pmRoot,o.id,e.transactionId,n))throw T(e,o.id,n)}let l=()=>mt(t,typeof i.target_version=="string"?i.target_version:s,{force:!0,author:e.author,message:_(e.transactionId,n,"compensate")},{pmRoot:e.pmRoot});await M({pmRoot:e.pmRoot,id:o.id,validate:y=>{d(y,()=>T(e,o.id,n))},compensation:Xt(e,t,n,"restore",p)},l)}var Zt=new WeakMap;function Xt(e,t,n,r,i){let s=i?it(e.pmRoot,e.transactionId):void 0,o=s===void 0?void 0:Zt.get(s);if(!(o?.stepId!==n||o.itemId!==t||o.operation!==r))return{transaction_id:e.transactionId,step_id:n,operations:[r],overrides:[]}}function Qt(e,t,n){return{id:n,async inspect(){let r=await E(e.pmRoot,t.id);if(r===void 0)return{state:"pending"};if(r.closedAt!==void 0){let i=await U(m.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 u(`Created item ${r.id} remains closed by transaction compensation; explicitly reopen or reconcile it before retrying.`,f.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 Xn(e.uniqueIndex,t.unique);let r=await ut(Y(t.options,{author:e.author,id:t.id,message:_(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 tr(e,t.id,n)}}}async function tr(e,t,n){let r=await E(e.pmRoot,t);if(r===void 0||e.createCompensation==="close"&&r.closedAt!==void 0)return;let{history:i,assertOwnedUnderLock:s}=await Ht(e.pmRoot,r.id),o=_(e.transactionId,n,"apply"),a=_(e.transactionId,n,"compensate"),d=i.filter(c=>Oe(c.message,o)||c.message===a).at(-1);if(d?.message!==a){if(d===void 0||!i.every(c=>Yt(c,e.transactionId)))throw T(e,r.id,n);await M({pmRoot:e.pmRoot,id:r.id,validate:c=>{s(c,()=>T(e,r.id,n))},compensation:Xt(e,t,n,e.createCompensation==="delete"?"delete":"close",!0)},async()=>{let c={force:!0,author:e.author,message:a};e.createCompensation==="delete"?await lt(t,c,{pmRoot:e.pmRoot}):await ce(t,`Compensated: interrupted bulk transaction ${e.transactionId}`,{...c,validateClose:"off"},{pmRoot:e.pmRoot})})}}function nr(e,t,n){return{id:n,compensatePending:!0,async inspect(){let r=await E(e.pmRoot,t.id);return r===void 0?{state:"pending"}:await k(e.pmRoot,r.id,e.transactionId,n)?{state:"applied",result:{id:r.id,op:"update"}}:{state:"pending"}},async prepareCompensation(){return H(e.pmRoot,t)},async apply(){let r=()=>ft(t.id,Y(t.options,{author:e.author,message:_(e.transactionId,n,"apply")}),{pmRoot:e.pmRoot}),i=t.match,s=i,a=(await M({pmRoot:e.pmRoot,id:await en(e.pmRoot,t.id),validate:d=>{s!==void 0&&Vt(d,t.id,s)},committed:d=>{i!==void 0&&(s={key:i.key,value:structuredClone(d.metadata[i.key])})},historyContext:{item_transaction_step:_(e.transactionId,n,"apply")}},r)).item;return e.uniqueIndex.invalidate(),{id:String(a.id),op:"update"}},async compensate(r){await j(e,t.id,n,r)}}}async function en(e,t){return String((await ae(t,{},{pmRoot:e})).item.id)}function rr(e,t,n){let r=_(e.transactionId,n,"apply");return{id:n,compensatePending:!0,async inspect(){let i=await E(e.pmRoot,t.id);return i===void 0||!await k(e.pmRoot,i.id,e.transactionId,n)?{state:"pending"}:{state:"applied",result:{id:i.id,op:t.op}}},async prepareCompensation(){return H(e.pmRoot,t)},async apply(){let i=await en(e.pmRoot,t.id),{match:s}=t;return await yt(e.pmRoot,()=>M({pmRoot:e.pmRoot,id:i,validate:o=>{s!==void 0&&Vt(o,t.id,s)},historyContext:{item_transaction_step:r}},()=>Pt({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 j(e,t.id,n,i)}}}function ir(e,t,n){return{id:n,async inspect(){let r=await E(e.pmRoot,t.id);return r===void 0?{state:"pending"}:await k(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 H(e.pmRoot,t)},async apply(){let i=(await ce(t.id,t.reason,Y(t.options,{author:e.author,message:_(e.transactionId,n,"apply")}),{pmRoot:e.pmRoot})).item;return e.uniqueIndex.invalidate(),{id:String(i.id),op:"close"}},async compensate(r){await j(e,t.id,n,r)}}}function or(e,t,n){return{id:n,async inspect(){let r=await E(e.pmRoot,t.id);return r===void 0?{state:"pending"}:await k(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 H(e.pmRoot,t)},async apply(){let i=(await pt(t.id,Y(t.options,{author:e.author,message:_(e.transactionId,n,"apply")}),{pmRoot:e.pmRoot})).item;return e.uniqueIndex.invalidate(),{id:String(i.id),op:"release"}},async compensate(r){await j(e,t.id,n,r)}}}function be(e,t,n){let r=Ee(t,n),i=sr(e,t,r);return Zt.set(i,{transactionId:e.transactionId,stepId:r,itemId:t.id,operation:t.op!=="create"?"restore":e.createCompensation==="delete"?"delete":"close"}),i}function sr(e,t,n){switch(t.op){case"create":return Qt(e,t,n);case"update":return nr(e,t,n);case"close":return ir(e,t,n);case"release":return or(e,t,n);case"finalize":return rr(e,t,n)}}function ar(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(cr(e,t),e.op==="finalize"){dr(e,t);return}q(e.options,e.op,t)}function cr(e,t){if(e.op==="create"&&e.unique!==void 0&&!zt(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&&!zt(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 Gt=["op","id","set","unset","match","force"];function dr(e,t){let n=`Bulk finalize mutation ${t+1}`,r=Object.keys(e).filter(i=>!Gt.includes(i));if(r.length>0)throw new TypeError(`${n} has unsupported keys: ${r.join(", ")}; a finalization carries only ${Gt.join(", ")}`);if(e.force!==void 0&&typeof e.force!="boolean")throw new TypeError(`${n} force must be a boolean`);if(e.match!==void 0&&!N(e.match))throw new TypeError(`${n} match must be a plain object with a JSON value`);le(e,n)}function we(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(ar(r,n),r.op!=="create"||r.unique===void 0)continue;let{key:i,value:s}=r.unique,o=t.get(i)??new Map,a=S(s),d=o.get(a);if(d!==void 0)throw new u(`Bulk create mutations ${d+1} and ${n+1} share the upsert key value ${JSON.stringify(a)} for "${i}".`,f.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 tn(e){let t=[...e];we(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&&X(r.options,i.options),i});return we(n),n}function nn(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]:nn(r,i)})}async function he(e,t,n){try{return await n()}catch(r){throw r instanceof u?new u(r.message,r.exitCode,{...r.context,transaction_operation:{index:t,op:e.op,id:e.id}}):r}}function rn(e,t,n,r){let i=m.relative(e,t),s=i.split(m.sep);return s[0]==="extensions"&&s[2]==="node_modules"&&!r.some(o=>i===o||i.startsWith(`${o}${m.sep}`)||o.startsWith(`${i}${m.sep}`))?!1:["locks","runtime","search"].includes(i.split(m.sep)[0])?r.some(o=>i===o||i.startsWith(`${o}${m.sep}`)||o.startsWith(`${i}${m.sep}`)):i===""||n===void 0||n.some(o=>i===o||i.startsWith(`${o}${m.sep}`)||o.startsWith(`${i}${m.sep}`))}async function B(e,t){let n=await qt(t);if(n.isSymbolicLink())await _e(t);else if(n.isDirectory()||n.isFile())return n;throw I(m.relative(e,t))}async function ur(e,t){let n=await Vn(t,me.O_RDONLY|me.O_NOFOLLOW|me.O_NONBLOCK);try{let r=await n.stat();if(!r.isFile())throw I(m.relative(e,t));let i=ge.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 ye(e,t,n){let r=ge.createHash("sha256");async function i(s){for(let o of(await Yn(s)).sort()){let a=m.join(s,o);rn(e,a,t,n)&&((await B(e,a)).isDirectory()?await i(a):(r.update(JSON.stringify(m.relative(e,a))),r.update(await ur(e,a))))}}return await i(e),r.digest("hex")}function W(){return new u("Tracker changed while preparing the transaction preview; retry against stable state.",f.CONFLICT,{code:"transaction_preview_snapshot_changed"})}async function ve(e){if(!Q(e))return!1;let t=e.path;if(typeof t!="string")return!1;let n=m.resolve(t),r=n;for(;;)try{let i=await qt(r);return r!==n&&i.isDirectory()}catch(i){if(!Q(i))return!1;let s=m.dirname(r);if(s===r)return!1;r=s}}async function V(e,t){let n=m.join(e,t);try{let r=e;for(let i of t.split(m.sep).slice(0,-1))r=m.join(r,i),await B(e,r);if(!(await B(e,n)).isFile())throw I(t);return await Ce(n,I(t))}catch(r){if(await ve(r))return;throw r}}async function on(e,t,n,r){let i=te(n);for(let[s,o]of Object.entries(i.files)){let a=m.relative(e,Fe(e,o,Ue[s]));if(a===""||!m.resolve(e,a).startsWith(m.join(e,m.sep)))throw new u("Transaction preview requires schema files inside the selected tracker root; relocate the configured schema file before retrying.",f.USAGE,{code:"transaction_preview_external_schema",field:`schema.files.${s}`});i.files[s]=a;let d=await V(e,a);if(r?.set(a,d),d!==void 0){let c=m.join(t,a);await Bn(m.dirname(c),{recursive:!0}),await Wt(c,d)}}return xe(t,i)}async function fr(e,t){await _e(e);let n=await Kt(m.join(Bt(),"pm-schema-plan-"));try{let r=await Lt(e);return await on(r,m.join(n,"configuration"),t)}catch(r){throw await ve(r)?W():r}finally{await Jt(n,{recursive:!0,force:!0})}}async function pr(e,t,n){let r=new Map,i=await V(e,R);r.set(R,i);let s;try{s=JSON.parse(i??"null")}catch{s=null}let o=He(s),a=o.success?o.data:void 0,d=await on(e,t,a?.schema,r),c=d.schema,p=m.relative(e,qe(e));r.set(p,await V(e,p));let l=ee({...ke,item_types:{definitions:[...a?.item_types?.definitions??[],...d.type_definitions_from_file??[]]}},n),y=Ne(e)===e?[...Te.filter(Boolean),R,rt,"transactions",...l.folders,...r.keys()].map(g=>m.normalize(g)):void 0,h=a===void 0?void 0:JSON.stringify({...s,schema:{...a.schema,files:c.files}});return{configuration:r,ownedPaths:y,stagedSettings:h,registryFolders:l.folders}}async function lr(e,t,n){await _e(e);try{let r=await Lt(e),i=await pr(r,m.join(m.dirname(t),"configuration"),n),s=[...i.configuration.keys(),...i.registryFolders].map(c=>m.normalize(c)),o=await ye(r,i.ownedPaths,s);await Wn(r,t,{recursive:!0,dereference:!1,filter:async c=>rn(r,c,i.ownedPaths,s)?(await B(r,c),!0):!1});let[a,d]=await Promise.all([ye(r,i.ownedPaths,s),ye(t,i.ownedPaths,s)]);if(o!==a||o!==d)throw W();for(let[c,p]of i.configuration)if(await V(t,c)!==p)throw W();i.stagedSettings!==void 0&&await Wt(m.join(t,R),i.stagedSettings)}catch(r){throw await ve(r)?W():r}}async function Mi(e){let t=P(e),n=tn(e.mutations),r=C(),i=Ve(),s=await Kt(m.join(Bt(),"pm-transaction-preview-")),o=m.join(s,"tracker");try{await lr(t.pmRoot,o,r);let a=!1,d=[],c=[],p=new Set;return await Be(i,()=>ht({path:o,noExtensions:!0},async()=>{We(r);let l={...t,pmRoot:o,createCompensation:"close",uniqueIndex:Se(o)},y=n.map((h,g)=>{let O=be({...l,onCreateWarnings:(Z,Ae)=>{Ae.length>0&&d.push({index:g,id:Z,op:"create",warnings:Ae})}},h,g);return{...O,inspect:()=>he(h,g,()=>O.inspect()),prepareCompensation:()=>he(h,g,async()=>O.prepareCompensation?.()),apply:()=>he(h,g,async()=>{let Z=await O.apply();return p.add(g),Z})}});if(await oe({...t,pmRoot:o,steps:y,onTransition:({transition:h})=>{h==="committed"&&(a=!0)}}),a)for(let[h,g]of n.entries()){let O=(await dt(g.id,{path:o},{full:!0})).item;c.push({index:h,id:String(O.id),op:g.op,execution:p.has(h)?"applied":"adopted",item:O,commit_time_fields:nn(O)})}})),{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 Jt(s,{recursive:!0,force:!0})}}async function mr(e){let t=P(e),n=tn(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:Se(t.pmRoot)},s=await oe({...t,steps:n.map((a,d)=>be(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=Ee(d,a),p=s.results[c];o[Qn(d,a)]=p}return{transactionId:s.transactionId,status:"committed",recovered:s.recovered,results:o}}function hr(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 Ci(e){return mr({pmRoot:e.pmRoot,transactionId:e.transactionId,author:e.author,mutations:hr(e),...e.lockTtlSeconds===void 0?{}:{lockTtlSeconds:e.lockTtlSeconds},...e.lockWaitMs===void 0?{}:{lockWaitMs:e.lockWaitMs},...e.onTransition===void 0?{}:{onTransition:e.onTransition}})}var Ni={buildCreateStep:Qt,bulkHistoryMarker:_,compensateByRestore:j,deriveStepId:Ee,isUpdateMarkerApplied:k,readItemSnapshot:E};async function ji(e,t){let n=await ot(e,t);return n===void 0?void 0:{journal:n,planDigest:se(n)}}function yr(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 u("Transaction has no supported item recovery plan",f.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;we(r);let i={...e,createCompensation:n.createCompensation,uniqueIndex:Se(e.pmRoot)};return r.map((s,o)=>be(i,s,o))}async function Ui(e){let t=P(e),n=await st({...e,...t,resolveSteps:r=>yr({...e,...t},r)});return{journal:n,planDigest:se(n)}}export{wt as a,Pr as b,zr as c,Ct as d,S as e,Gr as f,Gn as g,qr as h,Hn as i,Zn as j,fr as k,Mi as l,mr as m,hr as n,Ci as o,Ni as p,ji as q,Ui as r};
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{$a as ae,Ub as ut,Vb as ft,Xb as ce,_b as pt,a as rt,ac as lt,bc as mt,xc as ht,yc as yt}from"./chunk-E5ADC3HT.js";import{u as dt}from"./chunk-E5HO7HWP.js";import{Xb as ct}from"./chunk-HPCMM74Q.js";import{m as at}from"./chunk-L4HMFRHB.js";import{a as it,c as P,d as oe,e as ot,f as se,g as st}from"./chunk-JJ73G5UT.js";import{j as z,m as G}from"./chunk-Q2HMDV56.js";import{Ra as ie,d as Re,ea as Ye,ga as x,qb as Xe,qc as et,t as Ie,u as Me,v as X,wb as Qe}from"./chunk-TDOF7BKO.js";import{m as Ze,u as D}from"./chunk-RRBNCL63.js";import{b as He}from"./chunk-3AZOATC2.js";import{$g as C,Ka as De,Mb as Ke,Pa as Pe,Qb as U,Xa as ze,Ya as Ge,Za as re,_g as We,af as F,fg as Je,gf as Le,kb as qe,lh as Be,ma as je,mf as M,mh as Ve}from"./chunk-UXEZXGAD.js";import{g as ee,p as Ne}from"./chunk-GSLOAEY2.js";import{Aa as tt,Ga as nt}from"./chunk-3ESBFEQC.js";import{a as b,da as ne}from"./chunk-XGNUDSCG.js";import{P as Ue,V as te,Z as Fe,aa as xe,ea as v}from"./chunk-TE6FBDHP.js";import{A as f,C as u,G as Q,J as Ce,K as I,l as $e,q as R,t as Te,y as ke}from"./chunk-K672XXGQ.js";import ge from"node:crypto";import{constants as me,readFileSync as Jn}from"node:fs";import{cp as Wn,lstat as qt,mkdir as Bn,mkdtemp as Kt,open as Vn,readdir as Yn,realpath as Lt,rm as Jt,stat as _e,writeFile as Wt}from"node:fs/promises";import{tmpdir as Bt}from"node:os";import m from"node:path";import Tt from"node:crypto";var A=new Set(["id","title","description","type","status","priority","tags","body","deadline","estimated_minutes","acceptance_criteria","definition_of_ready","order","rank","assignee",...$e,"affected_version","fixed_version","component","regression","customer_impact","close_reason","completed_at","dependencies","comments","notes","learnings","files","tests","docs","reminders","events","type_options"]);function wt(e){if(e===void 0)return;let t=e.replace(/[A-Z]/gu,n=>`_${n.toLowerCase()}`);return A.has(t)?t:e}function q(e,t,n){let r=e?.estimatedMinutes;if(!(r===void 0||typeof r=="string"))throw new u(`Mutation ${n+1} ${t} option "estimatedMinutes" must be a string.`,f.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 de=["op","id","reason","options","unique","match"],sn=[...de,"ref"],gt=[...sn,"item"],an="mutate-",_t="row-",St=["schema_version","mutations"],kt="[a-z][a-z0-9._-]{0,63}",Et=new RegExp(`^${kt}$`,"u"),Rt=new RegExp(`(^|,)id=@(${kt})(?=,|$)`,"gu"),Ot=e=>e.slice(2).replaceAll(/-([a-z])/gu,(t,n)=>n.toUpperCase()),K=["item","item_hash","linked","schedule","claim_state","children","omission_receipt","row_contract","context_intent"],It=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"]),cn=new Set([...It,"completed_at","id"]),Mt={create:z.map(e=>e.target),update:G.map(e=>e.target),close:tt.map(e=>Ot(e.flag)).filter(e=>e!=="reason"),release:nt.map(e=>Ot(e.flag))};function Pr(e){let t=Tt.createHash("sha256").update(e).digest("hex");return`${an}${t.slice(0,24)}`}function zr(e){let t={},n=e.createCompensation;if(n!==void 0){if(n!=="close"&&n!=="delete")throw new u("createCompensation must be close or delete.",f.USAGE);t.createCompensation=n}for(let r of["lockTtlSeconds","lockWaitMs"]){let i=e[r];if(i===void 0)continue;let s=typeof i=="number"||typeof i=="string"&&i.trim().length>0?Number(i):Number.NaN;if(!Number.isSafeInteger(s)||s<=0)throw new u(`${r} must be a positive safe integer.`,f.USAGE);t[r]=s}return t}function w(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function L(e,t){let n=Math.max(1,Math.min(3,Math.floor(e.length/4)+1)),r;for(let i of t){let s=je(e,i,n);s!==null&&(r===void 0||s<r.distance)&&(r={key:i,distance:s})}return r?.key}function $(e,t,n){let r=L(t,n);return new u(r===void 0?`${e} does not recognize key "${t}". Allowed keys: ${n.join(", ")}.`:`${e} does not recognize key "${t}". Did you mean "${r}"?`,f.USAGE,{code:"stdin_json_unknown_key",required:`Use documented ${e} keys only.`,why:"Strict structured input prevents silent typos from creating incomplete or unintended mutations.",nextSteps:[r===void 0?`Remove or correct "${t}".`:`Replace "${t}" with "${r}".`]})}function pe(e,t){try{return JSON.parse(e)}catch(n){let r=n instanceof Error?n.message:String(n);throw new u(`${t} must be valid JSON: ${r}`,f.USAGE,{code:"stdin_json_invalid",required:`Pipe one valid JSON ${t.toLowerCase()} into stdin.`,why:"Structured mutation input must parse deterministically before any tracker write begins."})}}function dn(e,t){if(!w(e))throw new u(`Mutation ${t+1} must be an object.`,f.USAGE);for(let n of Object.keys(e))if(!de.includes(n))throw $(`mutation ${t+1}`,n,de);return e}function un(e,t,n,r){if(e===void 0)return;if(!w(e))throw new u(`Mutation ${n+1} options must be an object.`,f.USAGE);let i=[...Mt[t],...jt(t,r)];for(let s of Object.keys(e))if(!i.includes(s))throw $(`mutation ${n+1} ${t} options`,s,i);return q(e,t,n),e}function bt(e,t,n,r){if(e===void 0)return;let i=r==="unique"?"create":"update";if(t!==i)throw new u(`Mutation ${n+1} ${r} is only valid for ${i} operations.`,f.USAGE);let s=w(e)&&typeof e.key=="string"?e.key.trim():"";if(!w(e)||s.length===0||e.value===void 0||e.value===null)throw new u(`Mutation ${n+1} ${r} must be an object with a non-empty key and a value.`,f.USAGE);return{key:s,value:e.value}}function fn(e,t,n){let r=dn(e,t),{op:i,id:s,reason:o}=r;if(i!=="create"&&i!=="update"&&i!=="close"&&i!=="release")throw new u(`Mutation ${t+1} op must be create, update, close, or release.`,f.USAGE);let a=un(r.options,i,t,n),d=bt(r.unique,i,t,"unique"),c=bt(r.match,i,t,"match");if(typeof s!="string"||s.trim().length===0)throw new u(`Mutation ${t+1} requires a non-empty id.`,f.USAGE);let p=s.trim();if(i==="close"){if(typeof o!="string"||o.trim().length===0)throw new u(`Mutation ${t+1} close requires a non-empty reason.`,f.USAGE);return{op:i,id:p,reason:o.trim(),...a===void 0?{}:{options:a}}}if(i==="release")return{op:i,id:p,...a===void 0?{}:{options:a}};if(!w(a))throw new u(`Mutation ${t+1} ${i} requires an options object.`,f.USAGE);return{op:i,id:p,options:a,...d===void 0?{}:{unique:d},...c===void 0?{}:{match:c}}}function Ct(e,t={}){let n=pe(e,"Mutation batch"),r=Array.isArray(n)?n:w(n)&&Array.isArray(n.mutations)?n.mutations:void 0;if(r===void 0||r.length===0)throw new u("Mutation batch must be a non-empty JSON array or an object with a non-empty mutations array.",f.USAGE);let i=t.runtimeFields??[];return r.map((s,o)=>{let a=fn(s,o,i);return a.options!==void 0&&Ie(a.options),a})}function pn(e,t,n){let r=Tt.createHash("sha256").update(e).update("\0").update(t).digest("hex"),i=BigInt(`0x${r.slice(0,16)}`).toString(36).padStart(13,"0").slice(-12);return`${Ye(n)}${i}`}function vt(e,t){if(typeof e!="string"||!e.startsWith("@"))return e;let n=e.slice(1),r=t[n];if(r===void 0)throw new u(`Unknown mutation reference "${e}".`,f.USAGE);return r}function At(e,t){if(typeof e!="string")return e;let n=e.replace(Rt,(r,i,s)=>{let o=t[s];if(o===void 0)throw new u(`Unknown mutation reference "@${s}".`,f.USAGE);return`${i}id=${o}`});if(/(^|,)id=@/u.test(n))throw new u(`Malformed mutation reference in dependency "${e}".`,f.USAGE);return n}function ln(e){return typeof e!="string"?[]:e.startsWith("@")?[e.slice(1)]:[...e.matchAll(Rt)].map(t=>t[1]).filter(t=>t!==void 0)}function mn(e,t){let n=new Map;for(let[o,a]of e.entries()){let d=t[o];if(d===void 0)continue;let c=w(a.options)?a.options:{},p=Array.isArray(c.dep)?c.dep:c.dep===void 0?[]:[c.dep];n.set(d,[c.parent,c.blockedBy,...p].flatMap(ln))}let r=new Set,i=new Set,s=o=>{if(r.has(o))throw new u(`Mutation reference cycle includes "@${o}".`,f.USAGE);if(!i.has(o)){r.add(o);for(let a of n.get(o))n.has(a)&&s(a);r.delete(o),i.add(o)}};for(let o of n.keys())s(o)}function hn(e){let n=e.split(/\r?\n/u).map((o,a)=>({line:o.trim(),number:a+1})).filter(o=>o.line.length>0);if(n.length<2)return null;let r=n.map(o=>{try{return{...o,ok:!0,value:JSON.parse(o.line)}}catch(a){return{...o,ok:!1,error:a}}}),i=r[0];if(!i.ok&&(i.line.startsWith("[")||i.line==="{"||r.at(-1).line==="}")||!r.some(o=>o.ok&&w(o.value)))return null;let s=[];for(let o of r){if(!o.ok)throw new u(`Mutation document line ${o.number} must be one valid JSON object: ${et(o.error)}`,f.USAGE,{code:"stdin_json_invalid",required:"Provide one JSON object per line (JSON Lines), a JSON array, or a {schema_version, mutations} document.",why:"Structured mutation input must parse deterministically before any tracker write begins."});if(!w(o.value))throw new u(`Mutation document line ${o.number} must be a JSON object.`,f.USAGE);s.push(o.value)}return s}function yn(e){return Object.hasOwn(e,"mutations")||Object.hasOwn(e,"schema_version")}function wn(e){let t;try{t=pe(e,"Mutation document")}catch(n){let r=hn(e);if(r===null)throw n;return{schema_version:1,mutations:r}}return Array.isArray(t)?{schema_version:1,mutations:t}:w(t)&&!yn(t)?{schema_version:1,mutations:[t]}:t}function gn(e,t){let n=Object.hasOwn(e,"op")?_n(e,t):Sn(e,t);if(n.op==="create"&&n.id===void 0&&w(n.item)&&n.item.id!==void 0){if(typeof n.item.id!="string")throw new u(`Mutation ${t+1} item id must be a string.`,f.USAGE);n.id=n.item.id}return n}function _n(e,t){for(let n of Object.keys(e))if(!gt.includes(n))throw $(`mutation ${t+1}`,n,gt);if(e.item!==void 0&&e.op!=="create")throw new u(`Mutation ${t+1} item documents are only valid for create operations.`,f.USAGE);if(e.item!==void 0&&e.options!==void 0)throw new u(`Mutation ${t+1} must declare either item or options, not both.`,f.USAGE);return{...e}}function Sn(e,t){let{ref:n,id:r,item:i,...s}=e,o=i!==void 0?i:s;if(i!==void 0&&Object.keys(s).length>0)throw new u(`Mutation ${t+1} must not mix item document keys with top-level fields.`,f.USAGE);if(!w(o))throw new u(`Mutation ${t+1} item document must be an object.`,f.USAGE);return{op:"create",...n===void 0?{}:{ref:n},...r===void 0?{}:{id:r},item:o}}function En(e){let t=wn(e);if(!w(t))throw new u("Mutation document must be a JSON array or object.",f.USAGE);for(let n of Object.keys(t))if(!St.includes(n))throw $("mutation document",n,St);if(t.schema_version!==void 0&&t.schema_version!==1)throw new u("Mutation document schema_version must be 1.",f.USAGE);if(!Array.isArray(t.mutations)||t.mutations.length===0)throw new u("Mutation document requires a non-empty mutations array.",f.USAGE);return t.mutations.map((n,r)=>{if(!w(n))throw new u(`Mutation ${r+1} must be an object.`,f.USAGE);return gn(n,r)})}function On(e,t,n){let r=new Set(Object.values(Ft(t,n,Object.create(null))));for(let i of t)i.op==="create"&&typeof i.id=="string"&&i.id.trim().length>0&&r.add(x(i.id,n.idPrefix));return{...e,existing:e.existing.filter(i=>!r.has(i.id))}}function bn(e){let t=new Set(e.map(n=>n.ref).filter(n=>typeof n=="string"));for(let[n,r]of e.entries()){if(r.op!=="create"||r.ref!==void 0||typeof r.id=="string"&&r.id.trim().length>0)continue;let i=`${_t}${n+1}`;if(t.has(i))throw new u(`Mutation ${n+1} receives the synthesized ref "${i}", but another row declares that ref. Rename it or give mutation ${n+1} its own ref; ${_t}<n> aliases are reserved for rows without one.`,f.USAGE);r.ref=i}}function Nt(e,t,n){let r=Gn(JSON.stringify(e),t,{},n);return delete r.stdinJson,delete r.documentAnnotationSnapshot,r}function jt(e,t){return e!=="create"&&e!=="update"?[]:t.filter(n=>n.commands.includes(e)).map(n=>v(n))}function vn(e,t){for(let n of e)w(n.item)&&(n.options=Nt(n.item,"create",t),delete n.item)}function Ut(e,t){return t.some(n=>n.metadata_key===e)?e:wt(e)}function ue(e,t,n){let r=t.replaceAll(/_([a-z])/gu,(d,c)=>c.toUpperCase());if(w(e.item)){if(e.item[t]!==void 0)return e.item[t];if(Ut(r,n)===t&&e.item[r]!==void 0)return e.item[r]}let i=w(e.options)?e.options:{},s=n.find(d=>d.metadata_key===t);return s!==void 0&&i[v(s)]!==void 0?i[v(s)]:i[t]!==void 0?i[t]:i[r]!==void 0?i[r]:(Array.isArray(i.field)?i.field:[]).map(String).find(d=>d.startsWith(`${t}=`))?.slice(t.length+1)}function An(e,t){return e<t?-1:+(e!==t)}function fe(e){return Array.isArray(e)?e.map(fe):w(e)?Object.fromEntries(Object.entries(e).sort(([t],[n])=>An(t,n)).map(([t,n])=>[t,fe(n)])):e}function S(e){return typeof e=="string"?e.trim():JSON.stringify(fe(e))}function $n(e,t,n,r,i){let s=t.key.trim();if(s.length===0)throw new u("Upsert key must be a non-empty field name.",f.USAGE);let o=Tn(t.existing),a=new Map,d=new Set;for(let[c,p]of e.entries()){if(p.op!=="create")continue;let l=kn(p,s,c,a,r),y=Rn(o.get(l)??[],s,l);if(y===void 0){p.unique={key:s,value:ue(p,s,r)};continue}let h=x(y,n);typeof p.ref=="string"&&(i[p.ref]=h),In(p,h,r,{key:s,value:ue(p,s,r)}),d.add(c)}return d}function Tn(e){let t=new Map;for(let n of e){if(n.value===void 0||n.value===null)continue;let r=S(n.value);t.set(r,[...t.get(r)??[],n.id])}return t}function kn(e,t,n,r,i){let s=ue(e,t,i);if(s==null||s==="")throw new u(`Mutation ${n+1} is missing the upsert key "${t}".`,f.USAGE,{code:"upsert_key_missing",required:`Every create record must carry a non-empty "${t}" value when --upsert-key ${t} is set.`,why:"Keyed upsert identifies existing items by that field; a record without it cannot be matched or safely created."});let o=S(s),a=r.get(o);if(a!==void 0)throw new u(`Mutations ${a+1} and ${n+1} share the upsert key value ${JSON.stringify(o)} for "${t}".`,f.USAGE,{code:"upsert_key_duplicate",required:"Each record must carry a distinct upsert key value within one batch.",why:"Two records with the same key would race for the same existing item."});return r.set(o,n),o}function Rn(e,t,n){if(e.length>1)throw new u(`Upsert key "${t}" value ${JSON.stringify(n)} matches ${e.length} existing items: ${e.join(", ")}.`,f.CONFLICT,{code:"upsert_key_ambiguous",required:"Resolve the duplicate existing items or choose a key that is unique per item.",why:"An ambiguous key cannot select one item to update without guessing."});return e[0]}function In(e,t,n,r){let i=new Set([...Mt.update,...jt("update",n)]),s=w(e.item)?Nt(e.item,"update",n):Object.fromEntries(Object.entries(e.options).filter(([o])=>i.has(o)));delete e.item,delete e.ref,e.op="update",e.id=t,e.options=s,e.match=r}function Ft(e,t,n){for(let[r,i]of e.entries())if(i.ref!==void 0){if(i.op!=="create")throw new u(`Mutation ${r+1} ref is only valid for create operations.`,f.USAGE);if(typeof i.ref!="string"||!Et.test(i.ref))throw new u(`Mutation ${r+1} ref must match ${Et.source}.`,f.USAGE);if(n[i.ref]!==void 0)throw new u(`Duplicate mutation ref "${i.ref}".`,f.USAGE);n[i.ref]=typeof i.id=="string"&&i.id.trim().length>0?x(i.id,t.idPrefix):pn(t.transactionId,i.ref,t.idPrefix)}return n}function Gr(e,t){let n=En(e);bn(n);let r=n.map(p=>typeof p.ref=="string"?p.ref:void 0),i=Object.create(null),s=t.upsert===void 0?new Set:$n(n,On(t.upsert,n,t),t.idPrefix,t.runtimeFields??[],i);vn(n,t.runtimeFields??[]),Ft(n,t,i),mn(n,r);let o=n.map(p=>{let l={...p},y=typeof l.ref=="string"?l.ref:void 0;if(delete l.ref,y!==void 0?l.id=i[y]:l.id=vt(l.id,i),w(l.options)){let h={...l.options};for(let g of["parent","blockedBy"])h[g]!==void 0&&(h[g]=vt(h[g],i));Array.isArray(h.dep)?h.dep=h.dep.map(g=>At(g,i)):h.dep!==void 0&&(h.dep=At(h.dep,i)),l.options=h}return l}),a=Ct(JSON.stringify(o),{runtimeFields:t.runtimeFields??[]}),d=a.filter(p=>p.op==="create").map(p=>p.id);if(new Set(d).size!==d.length)throw new u("Duplicate resolved create id in mutation document.",f.USAGE);let c=a.map((p,l)=>{let y=r[l];return{index:l,...typeof y=="string"?{ref:y}:{},id:p.id,op:p.op,...s.has(l)?{upserted:!0}:{}}});return{schema_version:1,mutations:a,references:i,rows:c}}function Mn(e,t){return t.filter(n=>e[n]!==void 0&&e[n]!==null).map(n=>{let r=String(e[n]);return`${n}=${/[",\n\r\\]/u.test(r)?JSON.stringify(r):r}`}).join(",")}function Cn(e,t,n){if(e!==void 0){if(!Array.isArray(e)||!e.every(w))throw new u(`${n} must be an array of objects.`,f.USAGE);return e.map(r=>Mn(r,t))}}function Nn(e,t){return e==="tags"&&Array.isArray(t)&&t.every(n=>typeof n=="string")?JSON.stringify(t):typeof t=="number"||typeof t=="boolean"?String(t):t}function $t(e,t,n=!1){for(let[r,i,s]of ct){let o=t[r],a=Cn(n&&["comments","notes","learnings"].includes(r)&&Array.isArray(o)?o.filter(d=>!w(d)||d.created_at===void 0):o,s,r);a!==void 0&&a.length>0&&(e[i]=a)}}function jn(e,t){for(let n of Object.keys(e)){if(t){if(!K.includes(n))throw $("item envelope",n,K);continue}if(!A.has(n)&&L(n,[...A])===void 0&&L(n,K)==="item")throw $("item envelope",n,K)}}function Un(e){let t=Object.hasOwn(e,"item");jn(e,t);let n=t?e.item:e;if(!w(n))throw new u("Item document item must be an object.",f.USAGE);return{item:n,...t&&w(e.linked)?{linked:e.linked}:{}}}function Fn(e,t,n,r,i,s){if((r==="update"?cn:It).has(t))return;let a=i.find(d=>d.metadata_key===t&&d.commands.includes(r));if(a!==void 0){let d=ne(s,a);e[v(a)]=d!==void 0?d:a.type==="array"||a.type==="object"?JSON.stringify(n):n;return}if(!A.has(t)){if(L(t,[...A])!==void 0)throw $("item document",t,[...A]);let c=Array.isArray(e.field)?e.field:[];c.push(`${t}=${typeof n=="string"?n:JSON.stringify(n)}`),e.field=c;return}["dependencies","comments","notes","learnings","files","tests","docs","reminders","events","type_options"].includes(t)||(e[t.replaceAll(/_([a-z])/gu,(d,c)=>c.toUpperCase())]=Nn(t,n))}function xn(e){return{command_to_fields:new Map([["create",e.filter(t=>t.commands.includes("create"))]])}}function Dn(e,t,n,r){let i=r.filter(c=>c.commands.includes("create")),s=new Set([...De.filter(c=>t.has(c.option)).map(c=>c.field),...i.filter(c=>t.has(v(c))).map(c=>c.metadata_key),...at(Array.isArray(n)?n.map(String):[],xn(i)).metadataKeys]),o=(Array.isArray(e)?e:[]).filter(w).filter(c=>typeof c.field=="string"&&!s.has(c.field));if(o.length===0)return{};let a=o.map(c=>typeof c.reason=="string"?c.reason.trim():""),d=o.map(c=>c.field);return t.has("deferReason")?{defer:d}:a.every(c=>c.length>0)?{defer:d,deferReason:[...new Set(a)].join("; ")}:{defer:d}}function Pn(e,t,n){let r=new Set(Object.entries(e).filter(([,s])=>s!==void 0).map(([s])=>s)),i=t==="create"?z:G;for(let{target:s,keys:o}of i)o.some(a=>r.has(a))&&r.add(s);for(let s of n.filter(o=>o.commands.includes(t)))ne(e,s)!==void 0&&r.add(v(s));return r}function zn(e,t,n){let r=t==="create"?z:G;for(let{target:i}of r)i!=="field"&&n.has(i)&&delete e[i]}function Gn(e,t,n={},r=[]){let i=pe(e,"Item document");if(!w(i))throw new u("Item document must be a JSON object.",f.USAGE);let{item:s,linked:o}=Un(i),a={};for(let[l,y]of Object.entries(s)){let h=Ut(l,r);h!==l&&Object.hasOwn(s,h)||Fn(a,h,y,t,r,n)}$t(a,s,t==="update"),o!==void 0&&$t(a,o);let d=Pn(n,t,r);if(zn(a,t,d),t==="create"&&!d.has("defer")&&Object.assign(a,Dn(s.deferred_fields,d,n.unset,r)),t==="update"){let l=Object.fromEntries(["comments","notes","learnings"].filter(y=>Object.hasOwn(s,y)&&!d.has(y.slice(0,-1))).map(y=>[y,s[y].filter(h=>w(h)&&h.created_at!==void 0)]));Object.keys(l).length>0&&(a.documentAnnotationSnapshot=l)}let c={...a,...Object.fromEntries(Object.entries(n).filter(([,l])=>l!==void 0)),...Array.isArray(a.field)&&Array.isArray(n.field)?{field:[...a.field,...n.field]}:{},stdinJson:void 0},p=Object.keys(a).filter(l=>!d.has(l));return Me(Re(c,p),p)}function qr(e){return Ct(JSON.stringify(e))}var qn=["id","updated_at","pm_format_version","type"],Kn="import";function xt(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(qn.includes(e))throw new TypeError(`${t} cannot change "${e}"; the item writer derives it, or an update row owns it`)}function J(e){return Array.isArray(e)?`array of ${e.length}`:typeof e}var Ln=["__proto__","constructor","prototype"];function Dt(e){return e!==null&&typeof e=="object"&&Object.getPrototypeOf(e)===Object.prototype}function N(e){return e===null||typeof e=="string"||typeof e=="boolean"?!0:typeof e=="number"?Number.isFinite(e):Array.isArray(e)?Array.from(e).every(N):Dt(e)?Object.entries(e).every(([t,n])=>!Ln.includes(t)&&N(n)):!1}function le(e,t){let{set:n,unset:r}=e;if(n!==void 0&&!Dt(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(xt(o,t),n[o]===null||!N(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(xt(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 Pt(e){le(e,`Finalization of ${e.id}`);let t=await D(e.pmRoot),n={schema:t.schema,extensionFieldNames:Je(C())},r=await Qe({pmRoot:e.pmRoot,settings:t,id:e.id,op:Kn,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,p]of Object.entries(e.set??{}))o[c]=structuredClone(p);for(let c of e.unset??[])delete o[c];let a;try{Pe(i.metadata);let c=re(i,n),p=re(ze(Ge(c,n),n),n);if(b(p)!==b(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 l=Object.entries(e.set??{}).find(([y,h])=>J(a[y])!==J(h));if(l!==void 0)throw new TypeError(`set "${l[0]}" is not stored as declared (${J(l[1])} normalizes to ${a[l[0]]===void 0?"an absent field":J(a[l[0]])})`)}catch(c){throw new u(`Finalization of ${e.id} would not store a readable item with the declared fields: ${c.message}`,f.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)||b(s[c])!==b(a[c])).sort((c,p)=>c.localeCompare(p))}}});return{item:r.item,changedFields:r.changedFields}}async function Hn(e,t){if(!Ze(e))return{schema:te(t.schema),typeDefinitionsFromFile:[]};let n=await fr(e,t.schema);return{schema:n.schema,typeDefinitionsFromFile:n.type_definitions_from_file??[]}}async function Zn(e,t,n,r){let i=ee({...t,item_types:{...t.item_types,definitions:[...t.item_types?.definitions??[],...n.typeDefinitionsFromFile]}},C());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 Se(e){let t=new Map,n=async r=>{let i=await D(e),s=await Hn(e,i),o=new Map;for(let a of await Zn(e,i,s,r)){let d=S(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=S(o);a.set(d,[...a.get(d)??[],String(r.id)])}},invalidate(){t.clear()}}}async function Xn(e,t){let n=S(t.value),r=(await e.lookup(t.key)).get(n)??[];if(r.length!==0)throw new u(`Upsert key "${t.key}" value ${JSON.stringify(n)} now matches existing item ${r.join(", ")}; the plan was resolved before it existed.`,f.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 Vt(e,t,n){let r=e.metadata[n.key],i=S(n.value);if(S(r)!==i)throw new u(`Item ${t} no longer carries upsert key "${n.key}" value ${JSON.stringify(i)}; the plan selected it before the key changed.`,f.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 zt(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 Y(e,t){let n={...e,...t};return e===void 0?n:X(e,n)}async function E(e,t){try{let r=(await ae(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 u&&n.exitCode===f.NOT_FOUND)return;throw n}}function Ee(e,t){let n=e.id.replaceAll(/[^a-zA-Z0-9._-]/gu,"_"),r=ge.createHash("sha256").update(b(e)).digest("hex").slice(0,12);return`${t+1}-${e.op}-${n}-${r}`}function Qn(e,t){let n=e.id.replaceAll(/[^a-zA-Z0-9._-]/gu,"_");return`${t+1}-${e.op}-${n}`}function _(e,t,n){return`bulk-item-transaction ${e} ${t} ${n}`}function Oe(e,t){return e===t||(e?.startsWith(`${t} | `)??!1)}async function k(e,t,n,r){let i=await U(m.join(e,"history",`${t}.jsonl`),t),s=_(n,r,"apply"),o=_(n,r,"compensate");for(let a=i.length-1;a>=0;a-=1){let d=i[a].message;if(Oe(d,s))return!0;if(d===o)return!1}return!1}async function H(e,t){let n=await E(e,t.id);if(n?.updatedAt===void 0)throw new u(`Bulk ${t.op} target ${t.id} does not exist or has no restorable version`,f.NOT_FOUND);let r=await U(m.join(e,"history",`${n.id}.jsonl`),n.id);if(r.length===0)throw new u(`Bulk ${t.op} target ${t.id} has no restorable history`,f.NOT_FOUND);return{target_updated_at:n.updatedAt,target_version:String(ie(r)+r.length),target_history_hash:F(r),target_history_length:r.length}}function T(e,t,n){return new u(`Transaction ${e.transactionId} cannot safely compensate incomplete step ${n}; review item ${t} history before recovery.`,f.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 Yt(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 er(e,t,n){let{expectedHistory:r,length:i,version:s}=t;if(F(e)===r)return!1;if(typeof i!="number"||!Number.isSafeInteger(i)||i<1||F(e.slice(0,i))!==r||s!==String(ie(e)+i))throw T(n,n.itemId,n.stepId);let o=_(n.transactionId,n.stepId,"apply"),a=e.slice(i),d=y=>Oe(y.message,o)||y.context?.item_transaction_step===o,c=_(n.transactionId,n.stepId,"compensate");if(a.filter(y=>d(y)||y.message===c).at(-1)?.message===c)return!1;let p=a.filter(d);if(p.length===0)return!1;let l=e.at(-1).after_hash===p.at(-1).after_hash&&a.every(y=>Yt(y,n.transactionId));if(p.length!==a.length&&!l)throw T(n,n.itemId,n.stepId);return!0}async function Ht(e,t){let n=m.join(e,"history",`${t}.jsonl`),r=await Ke(n,t);return{history:r.entries,assertOwnedUnderLock:(i,s)=>{let o;try{o=Jn(n).equals(r.raw_bytes)&&Le(i)===r.entries.at(-1).after_hash}catch(a){throw Object.assign(s(),{cause:a})}if(!o)throw s()}}}async function j(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(e.pmRoot,t);if(o===void 0)return;let{history:a,assertOwnedUnderLock:d}=await Ht(e.pmRoot,o.id),c=i.target_history_hash,p=typeof c=="string";if(typeof c=="string"){if(!er(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 k(e.pmRoot,o.id,e.transactionId,n))throw T(e,o.id,n)}let l=()=>mt(t,typeof i.target_version=="string"?i.target_version:s,{force:!0,author:e.author,message:_(e.transactionId,n,"compensate")},{pmRoot:e.pmRoot});await M({pmRoot:e.pmRoot,id:o.id,validate:y=>{d(y,()=>T(e,o.id,n))},compensation:Xt(e,t,n,"restore",p)},l)}var Zt=new WeakMap;function Xt(e,t,n,r,i){let s=i?it(e.pmRoot,e.transactionId):void 0,o=s===void 0?void 0:Zt.get(s);if(!(o?.stepId!==n||o.itemId!==t||o.operation!==r))return{transaction_id:e.transactionId,step_id:n,operations:[r],overrides:[]}}function Qt(e,t,n){return{id:n,async inspect(){let r=await E(e.pmRoot,t.id);if(r===void 0)return{state:"pending"};if(r.closedAt!==void 0){let i=await U(m.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 u(`Created item ${r.id} remains closed by transaction compensation; explicitly reopen or reconcile it before retrying.`,f.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 Xn(e.uniqueIndex,t.unique);let r=await ut(Y(t.options,{author:e.author,id:t.id,message:_(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 tr(e,t.id,n)}}}async function tr(e,t,n){let r=await E(e.pmRoot,t);if(r===void 0||e.createCompensation==="close"&&r.closedAt!==void 0)return;let{history:i,assertOwnedUnderLock:s}=await Ht(e.pmRoot,r.id),o=_(e.transactionId,n,"apply"),a=_(e.transactionId,n,"compensate"),d=i.filter(c=>Oe(c.message,o)||c.message===a).at(-1);if(d?.message!==a){if(d===void 0||!i.every(c=>Yt(c,e.transactionId)))throw T(e,r.id,n);await M({pmRoot:e.pmRoot,id:r.id,validate:c=>{s(c,()=>T(e,r.id,n))},compensation:Xt(e,t,n,e.createCompensation==="delete"?"delete":"close",!0)},async()=>{let c={force:!0,author:e.author,message:a};e.createCompensation==="delete"?await lt(t,c,{pmRoot:e.pmRoot}):await ce(t,`Compensated: interrupted bulk transaction ${e.transactionId}`,{...c,validateClose:"off"},{pmRoot:e.pmRoot})})}}function nr(e,t,n){return{id:n,compensatePending:!0,async inspect(){let r=await E(e.pmRoot,t.id);return r===void 0?{state:"pending"}:await k(e.pmRoot,r.id,e.transactionId,n)?{state:"applied",result:{id:r.id,op:"update"}}:{state:"pending"}},async prepareCompensation(){return H(e.pmRoot,t)},async apply(){let r=()=>ft(t.id,Y(t.options,{author:e.author,message:_(e.transactionId,n,"apply")}),{pmRoot:e.pmRoot}),i=t.match,s=i,a=(await M({pmRoot:e.pmRoot,id:await en(e.pmRoot,t.id),validate:d=>{s!==void 0&&Vt(d,t.id,s)},committed:d=>{i!==void 0&&(s={key:i.key,value:structuredClone(d.metadata[i.key])})},historyContext:{item_transaction_step:_(e.transactionId,n,"apply")}},r)).item;return e.uniqueIndex.invalidate(),{id:String(a.id),op:"update"}},async compensate(r){await j(e,t.id,n,r)}}}async function en(e,t){return String((await ae(t,{},{pmRoot:e})).item.id)}function rr(e,t,n){let r=_(e.transactionId,n,"apply");return{id:n,compensatePending:!0,async inspect(){let i=await E(e.pmRoot,t.id);return i===void 0||!await k(e.pmRoot,i.id,e.transactionId,n)?{state:"pending"}:{state:"applied",result:{id:i.id,op:t.op}}},async prepareCompensation(){return H(e.pmRoot,t)},async apply(){let i=await en(e.pmRoot,t.id),{match:s}=t;return await yt(e.pmRoot,()=>M({pmRoot:e.pmRoot,id:i,validate:o=>{s!==void 0&&Vt(o,t.id,s)},historyContext:{item_transaction_step:r}},()=>Pt({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 j(e,t.id,n,i)}}}function ir(e,t,n){return{id:n,async inspect(){let r=await E(e.pmRoot,t.id);return r===void 0?{state:"pending"}:await k(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 H(e.pmRoot,t)},async apply(){let i=(await ce(t.id,t.reason,Y(t.options,{author:e.author,message:_(e.transactionId,n,"apply")}),{pmRoot:e.pmRoot})).item;return e.uniqueIndex.invalidate(),{id:String(i.id),op:"close"}},async compensate(r){await j(e,t.id,n,r)}}}function or(e,t,n){return{id:n,async inspect(){let r=await E(e.pmRoot,t.id);return r===void 0?{state:"pending"}:await k(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 H(e.pmRoot,t)},async apply(){let i=(await pt(t.id,Y(t.options,{author:e.author,message:_(e.transactionId,n,"apply")}),{pmRoot:e.pmRoot})).item;return e.uniqueIndex.invalidate(),{id:String(i.id),op:"release"}},async compensate(r){await j(e,t.id,n,r)}}}function be(e,t,n){let r=Ee(t,n),i=sr(e,t,r);return Zt.set(i,{transactionId:e.transactionId,stepId:r,itemId:t.id,operation:t.op!=="create"?"restore":e.createCompensation==="delete"?"delete":"close"}),i}function sr(e,t,n){switch(t.op){case"create":return Qt(e,t,n);case"update":return nr(e,t,n);case"close":return ir(e,t,n);case"release":return or(e,t,n);case"finalize":return rr(e,t,n)}}function ar(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(cr(e,t),e.op==="finalize"){dr(e,t);return}q(e.options,e.op,t)}function cr(e,t){if(e.op==="create"&&e.unique!==void 0&&!zt(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&&!zt(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 Gt=["op","id","set","unset","match","force"];function dr(e,t){let n=`Bulk finalize mutation ${t+1}`,r=Object.keys(e).filter(i=>!Gt.includes(i));if(r.length>0)throw new TypeError(`${n} has unsupported keys: ${r.join(", ")}; a finalization carries only ${Gt.join(", ")}`);if(e.force!==void 0&&typeof e.force!="boolean")throw new TypeError(`${n} force must be a boolean`);if(e.match!==void 0&&!N(e.match))throw new TypeError(`${n} match must be a plain object with a JSON value`);le(e,n)}function we(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(ar(r,n),r.op!=="create"||r.unique===void 0)continue;let{key:i,value:s}=r.unique,o=t.get(i)??new Map,a=S(s),d=o.get(a);if(d!==void 0)throw new u(`Bulk create mutations ${d+1} and ${n+1} share the upsert key value ${JSON.stringify(a)} for "${i}".`,f.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 tn(e){let t=[...e];we(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&&X(r.options,i.options),i});return we(n),n}function nn(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]:nn(r,i)})}async function he(e,t,n){try{return await n()}catch(r){throw r instanceof u?new u(r.message,r.exitCode,{...r.context,transaction_operation:{index:t,op:e.op,id:e.id}}):r}}function rn(e,t,n,r){let i=m.relative(e,t),s=i.split(m.sep);return s[0]==="extensions"&&s[2]==="node_modules"&&!r.some(o=>i===o||i.startsWith(`${o}${m.sep}`)||o.startsWith(`${i}${m.sep}`))?!1:["locks","runtime","search"].includes(i.split(m.sep)[0])?r.some(o=>i===o||i.startsWith(`${o}${m.sep}`)||o.startsWith(`${i}${m.sep}`)):i===""||n===void 0||n.some(o=>i===o||i.startsWith(`${o}${m.sep}`)||o.startsWith(`${i}${m.sep}`))}async function B(e,t){let n=await qt(t);if(n.isSymbolicLink())await _e(t);else if(n.isDirectory()||n.isFile())return n;throw I(m.relative(e,t))}async function ur(e,t){let n=await Vn(t,me.O_RDONLY|me.O_NOFOLLOW|me.O_NONBLOCK);try{let r=await n.stat();if(!r.isFile())throw I(m.relative(e,t));let i=ge.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 ye(e,t,n){let r=ge.createHash("sha256");async function i(s){for(let o of(await Yn(s)).sort()){let a=m.join(s,o);rn(e,a,t,n)&&((await B(e,a)).isDirectory()?await i(a):(r.update(JSON.stringify(m.relative(e,a))),r.update(await ur(e,a))))}}return await i(e),r.digest("hex")}function W(){return new u("Tracker changed while preparing the transaction preview; retry against stable state.",f.CONFLICT,{code:"transaction_preview_snapshot_changed"})}async function ve(e){if(!Q(e))return!1;let t=e.path;if(typeof t!="string")return!1;let n=m.resolve(t),r=n;for(;;)try{let i=await qt(r);return r!==n&&i.isDirectory()}catch(i){if(!Q(i))return!1;let s=m.dirname(r);if(s===r)return!1;r=s}}async function V(e,t){let n=m.join(e,t);try{let r=e;for(let i of t.split(m.sep).slice(0,-1))r=m.join(r,i),await B(e,r);if(!(await B(e,n)).isFile())throw I(t);return await Ce(n,I(t))}catch(r){if(await ve(r))return;throw r}}async function on(e,t,n,r){let i=te(n);for(let[s,o]of Object.entries(i.files)){let a=m.relative(e,Fe(e,o,Ue[s]));if(a===""||!m.resolve(e,a).startsWith(m.join(e,m.sep)))throw new u("Transaction preview requires schema files inside the selected tracker root; relocate the configured schema file before retrying.",f.USAGE,{code:"transaction_preview_external_schema",field:`schema.files.${s}`});i.files[s]=a;let d=await V(e,a);if(r?.set(a,d),d!==void 0){let c=m.join(t,a);await Bn(m.dirname(c),{recursive:!0}),await Wt(c,d)}}return xe(t,i)}async function fr(e,t){await _e(e);let n=await Kt(m.join(Bt(),"pm-schema-plan-"));try{let r=await Lt(e);return await on(r,m.join(n,"configuration"),t)}catch(r){throw await ve(r)?W():r}finally{await Jt(n,{recursive:!0,force:!0})}}async function pr(e,t,n){let r=new Map,i=await V(e,R);r.set(R,i);let s;try{s=JSON.parse(i??"null")}catch{s=null}let o=He(s),a=o.success?o.data:void 0,d=await on(e,t,a?.schema,r),c=d.schema,p=m.relative(e,qe(e));r.set(p,await V(e,p));let l=ee({...ke,item_types:{definitions:[...a?.item_types?.definitions??[],...d.type_definitions_from_file??[]]}},n),y=Ne(e)===e?[...Te.filter(Boolean),R,rt,"transactions",...l.folders,...r.keys()].map(g=>m.normalize(g)):void 0,h=a===void 0?void 0:JSON.stringify({...s,schema:{...a.schema,files:c.files}});return{configuration:r,ownedPaths:y,stagedSettings:h,registryFolders:l.folders}}async function lr(e,t,n){await _e(e);try{let r=await Lt(e),i=await pr(r,m.join(m.dirname(t),"configuration"),n),s=[...i.configuration.keys(),...i.registryFolders].map(c=>m.normalize(c)),o=await ye(r,i.ownedPaths,s);await Wn(r,t,{recursive:!0,dereference:!1,filter:async c=>rn(r,c,i.ownedPaths,s)?(await B(r,c),!0):!1});let[a,d]=await Promise.all([ye(r,i.ownedPaths,s),ye(t,i.ownedPaths,s)]);if(o!==a||o!==d)throw W();for(let[c,p]of i.configuration)if(await V(t,c)!==p)throw W();i.stagedSettings!==void 0&&await Wt(m.join(t,R),i.stagedSettings)}catch(r){throw await ve(r)?W():r}}async function Mi(e){let t=P(e),n=tn(e.mutations),r=C(),i=Ve(),s=await Kt(m.join(Bt(),"pm-transaction-preview-")),o=m.join(s,"tracker");try{await lr(t.pmRoot,o,r);let a=!1,d=[],c=[],p=new Set;return await Be(i,()=>ht({path:o,noExtensions:!0},async()=>{We(r);let l={...t,pmRoot:o,createCompensation:"close",uniqueIndex:Se(o)},y=n.map((h,g)=>{let O=be({...l,onCreateWarnings:(Z,Ae)=>{Ae.length>0&&d.push({index:g,id:Z,op:"create",warnings:Ae})}},h,g);return{...O,inspect:()=>he(h,g,()=>O.inspect()),prepareCompensation:()=>he(h,g,async()=>O.prepareCompensation?.()),apply:()=>he(h,g,async()=>{let Z=await O.apply();return p.add(g),Z})}});if(await oe({...t,pmRoot:o,steps:y,onTransition:({transition:h})=>{h==="committed"&&(a=!0)}}),a)for(let[h,g]of n.entries()){let O=(await dt(g.id,{path:o},{full:!0})).item;c.push({index:h,id:String(O.id),op:g.op,execution:p.has(h)?"applied":"adopted",item:O,commit_time_fields:nn(O)})}})),{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 Jt(s,{recursive:!0,force:!0})}}async function mr(e){let t=P(e),n=tn(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:Se(t.pmRoot)},s=await oe({...t,steps:n.map((a,d)=>be(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=Ee(d,a),p=s.results[c];o[Qn(d,a)]=p}return{transactionId:s.transactionId,status:"committed",recovered:s.recovered,results:o}}function hr(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 Ci(e){return mr({pmRoot:e.pmRoot,transactionId:e.transactionId,author:e.author,mutations:hr(e),...e.lockTtlSeconds===void 0?{}:{lockTtlSeconds:e.lockTtlSeconds},...e.lockWaitMs===void 0?{}:{lockWaitMs:e.lockWaitMs},...e.onTransition===void 0?{}:{onTransition:e.onTransition}})}var Ni={buildCreateStep:Qt,bulkHistoryMarker:_,compensateByRestore:j,deriveStepId:Ee,isUpdateMarkerApplied:k,readItemSnapshot:E};async function ji(e,t){let n=await ot(e,t);return n===void 0?void 0:{journal:n,planDigest:se(n)}}function yr(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 u("Transaction has no supported item recovery plan",f.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;we(r);let i={...e,createCompensation:n.createCompensation,uniqueIndex:Se(e.pmRoot)};return r.map((s,o)=>be(i,s,o))}async function Ui(e){let t=P(e),n=await st({...e,...t,resolveSteps:r=>yr({...e,...t},r)});return{journal:n,planDigest:se(n)}}export{wt as a,Pr as b,zr as c,Ct as d,S as e,Gr as f,Gn as g,qr as h,Hn as i,Zn as j,fr as k,Mi as l,mr as m,hr as n,Ci as o,Ni as p,ji as q,Ui as r};
|
|
2
|
+
//# sourceMappingURL=chunk-MRT3ADO4.js.map
|