@unbrained/pm-cli 2026.11.29 → 2026.11.30
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-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/{chunk-Q6GIFUCW.js → chunk-2SBTXR6C.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-PY6A7ULK.js → chunk-3TXEWHQX.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-K3MVVDLN.js → chunk-47ZS6RPL.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-WLZ5KVM2.js → chunk-5PNOVDVO.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-3TK2YOVB.js → chunk-AOTI76Q6.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-CV2B4JUB.js → chunk-CCKM5YQM.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-JQHLOSSS.js → chunk-DCWGM7CY.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-LQEB6GSY.js → chunk-FECZV72T.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-FRYNDVLN.js → chunk-FR7ULTM4.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-NLHNB2L3.js → chunk-HXQ3OHQR.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-JFPCL45G.js → chunk-IGEFPHV7.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-NRCGGNOE.js → chunk-JPJNJHQW.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-R6M5OGJH.js → chunk-KCVSSONY.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-3E53F7QY.js → chunk-KXTKLDKD.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-DBASKWBO.js → chunk-NHBG5ET3.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-CNZOC6JD.js → chunk-NVYDPNQP.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-3US5T6B2.js → chunk-NZSXWIX7.js} +5 -5
- package/dist/cli-bundle/chunks/{chunk-VI3A7UZ2.js → chunk-Q4VZSMUL.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-RWHS77ME.js → chunk-SJWIPGZW.js} +39 -39
- package/dist/cli-bundle/chunks/{chunk-EYEQC3L2.js → chunk-TX74QJ4W.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-WNB62BGK.js → chunk-TY55UX6M.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-4EBHZBM2.js → chunk-USBTXMKS.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-VCXQ6A35.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-L7HON3BE.js → chunk-WFYE34TO.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-YPMNXG2C.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-ZK4CY24V.js → chunk-YVTALIN3.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-ZSBPE36C.js → chunk-Z7YL2SUM.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-KCR4NF2A.js → chunk-ZA5NS3PL.js} +2 -2
- package/dist/cli-bundle/chunks/{field-option-collisions-OZE43TOH.js → field-option-collisions-2F2Z7R7B.js} +2 -2
- package/dist/cli-bundle/chunks/{item-revision-3WXNNFLP.js → item-revision-UAF6L47R.js} +2 -2
- package/dist/cli-bundle/chunks/item-transaction-RJECL53Y.js +2 -0
- package/dist/cli-bundle/chunks/{linked-resource-value-list-2655COY2.js → linked-resource-value-list-WXPPYUVQ.js} +2 -2
- package/dist/cli-bundle/chunks/{mutation-actor-QOKPDYM4.js → mutation-actor-UK3QNEEB.js} +2 -2
- package/dist/cli-bundle/chunks/{mutation-admission-JNJHB3E6.js → mutation-admission-UTDYPFWP.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-YGVUE4YZ.js → register-list-query-DRA3CWHI.js} +2 -2
- package/dist/cli-bundle/chunks/{register-mutation-3JVZQDHH.js → register-mutation-WO74VLEQ.js} +2 -2
- package/dist/cli-bundle/chunks/{register-operations-LCHUHKRA.js → register-operations-CRBKH7WN.js} +2 -2
- package/dist/cli-bundle/chunks/{register-setup-IJ7M3VUK.js → register-setup-6V6NQB5C.js} +2 -2
- package/dist/cli-bundle/chunks/{stage-7BD7U2BX.js → stage-DYEHGASU.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-WJAUHPXD.js → chunk-2UUBS4BG.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-KLOHZNJ4.js → chunk-4ER3VMST.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-BZ3PUUPG.js → chunk-4YBMHMBJ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-ACTBMSCH.js → chunk-62AMZMR4.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-LSVRZ4KQ.js → chunk-7G7JIXLL.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-BPOU2S44.js → chunk-A3DORTXS.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-NNLENKU7.js → chunk-FM5WQ6ZU.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-BPBKHY6H.js → chunk-HXM7K6VH.js} +35 -35
- package/dist/cli-bundle/focused-chunks/{chunk-EUDAUT6T.js → chunk-IIVDBAJM.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-LKTRICZR.js → chunk-IJ3T3W4U.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-S5VG7RFY.js → chunk-L357ZAES.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-PPCBCPIZ.js → chunk-LWBZ7UGG.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-TSZVCALS.js → chunk-M57KDG7I.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-2CQFGJQ6.js → chunk-MZNV26XE.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-NGHT2LNG.js +3 -0
- package/dist/cli-bundle/focused-chunks/{chunk-GTUPHXKR.js → chunk-NJTKGBSK.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-5NSWNLFE.js → chunk-P55AZPFN.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-NO5MUY4I.js → chunk-RQYVX2T6.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-KWKPX36T.js → chunk-SXC3NVZI.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-QTV6UE2Q.js → chunk-TQQO42C2.js} +5 -5
- package/dist/cli-bundle/focused-chunks/{chunk-S4AC7OMI.js → chunk-U35K7FSE.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-42SU4LK3.js → chunk-UQJ4PY2Y.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-NZA2LP4Y.js → chunk-WAP3DF4B.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-MYWUMVCZ.js → chunk-XR745UGE.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{field-option-collisions-HABQYZMQ.js → field-option-collisions-7TG7STO7.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{item-revision-YH5R7YPW.js → item-revision-J7EUGCHR.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{item-transaction-YZ2PUPGM.js → item-transaction-2IC2MLML.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{mutation-actor-DJ2VRLKG.js → mutation-actor-LJVF2HVD.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{mutation-admission-3SECKVKY.js → mutation-admission-SLFAUONA.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{stage-FEJT2UCG.js → stage-MWR73LTZ.js} +2 -2
- package/dist/cli-bundle/main.js +3 -3
- 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 +61 -61
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +1 -1
- package/dist/core/shared/url-credentials.d.ts +4 -2
- package/dist/core/shared/url-credentials.js +1 -1
- package/dist/sdk/context-intent-contracts.js +1 -1
- package/docs/CONFIGURATION.md +22 -3
- package/docs/READ_OUTPUT_CONTRACTS.md +5 -0
- package/docs/SDK.md +19 -3
- 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-JV7LREUF.js +0 -3
- package/dist/cli-bundle/chunks/chunk-SV27NNXQ.js +0 -2
- package/dist/cli-bundle/chunks/item-transaction-DJ5GAITL.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-TX24L7RQ.js +0 -3
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{$a as ae,Ub as ut,Vb as ft,Xb as ce,_b as pt,a as tt,ac as lt,bc as mt,xc as ht,yc as yt}from"./chunk-3US5T6B2.js";import{u as dt}from"./chunk-Q6GIFUCW.js";import{Xb as ct}from"./chunk-L7HON3BE.js";import{m as at}from"./chunk-VI3A7UZ2.js";import{a as nt,c as P,d as oe,e as rt,f as se,g as it}from"./chunk-JFPCL45G.js";import{j as z,m as G}from"./chunk-R6M5OGJH.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-PY6A7ULK.js";import{m as Ze,u as D}from"./chunk-3E53F7QY.js";import{b as He}from"./chunk-3AZOATC2.js";import{$g as We,Ha as De,Jb as Ke,Ma as Pe,Nb as U,Ua as ze,Va as Ge,Wa as re,ah as C,cf as F,hb as qe,hg as Je,if as Le,ja as je,mh as Be,nh as Ve,of as M}from"./chunk-RWHS77ME.js";import{g as ee,p as Ne}from"./chunk-GSLOAEY2.js";import{ta as ot,za as st}from"./chunk-NRCGGNOE.js";import{a as b,da as ne}from"./chunk-JV7LREUF.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:ot.map(e=>Ot(e.flag)).filter(e=>e!=="reason"),release:st.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?nt(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,tt,"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 rt(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 it({...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 tt,ac as lt,bc as mt,xc as ht,yc as yt}from"./chunk-NZSXWIX7.js";import{u as dt}from"./chunk-2SBTXR6C.js";import{Xb as ct}from"./chunk-WFYE34TO.js";import{m as at}from"./chunk-Q4VZSMUL.js";import{a as nt,c as P,d as oe,e as rt,f as se,g as it}from"./chunk-IGEFPHV7.js";import{j as z,m as G}from"./chunk-KCVSSONY.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-3TXEWHQX.js";import{m as Ze,u as D}from"./chunk-KXTKLDKD.js";import{b as He}from"./chunk-3AZOATC2.js";import{$g as We,Ha as De,Jb as Ke,Ma as Pe,Nb as U,Ua as ze,Va as Ge,Wa as re,ah as C,cf as F,hb as qe,hg as Je,if as Le,ja as je,mh as Be,nh as Ve,of as M}from"./chunk-SJWIPGZW.js";import{g as ee,p as Ne}from"./chunk-GSLOAEY2.js";import{ta as ot,za as st}from"./chunk-JPJNJHQW.js";import{a as b,da as ne}from"./chunk-VCXQ6A35.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:ot.map(e=>Ot(e.flag)).filter(e=>e!=="reason"),release:st.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?nt(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,tt,"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 rt(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 it({...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-FECZV72T.js.map
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{O as Fe,Wa as Pe,k as Ce,l as Ae}from"./chunk-3US5T6B2.js";import{w as Re,x as P,y as Oe,z as Se}from"./chunk-L7HON3BE.js";import{la as Ne,n as T}from"./chunk-JFPCL45G.js";import{V as _e,W as $e,X as ke}from"./chunk-PY6A7ULK.js";import{$g as F,Ag as ce,Bg as fe,Cg as le,Dg as ue,Eg as pe,Kg as ge,Lg as he,Od as W,Pd as Y,Rg as ve,Se as X,Te as J,Tg as N,U as V,Uf as h,Ug as ye,V as G,Wg as xe,Xf as $,Yf as Z,Zg as Ee,_g as be,ca as b,ch as we,da as z,gg as Q,ng as ee,rg as re,sg as te,tg as ne,ug as oe,vg as ie,wg as se,xg as ae,yg as de,zg as me}from"./chunk-RWHS77ME.js";import{A,C as U,k as S}from"./chunk-K672XXGQ.js";function pt(r){return r}function gt(r){return r}function Xe(r,e){for(let t of e.commands??[])r.registerCommand(t);for(let[t,n]of Object.entries(e.commandOverrides??{}))r.registerCommand(t,n);for(let[t,n]of Object.entries(e.flags??{}))r.registerFlags(t,n);for(let[t,n]of Object.entries(e.parsers??{}))r.registerParser(t,n);for(let[t,n]of Object.entries(e.renderers??{}))if(typeof n=="function")r.registerRenderer(t,n);else{let{run:s,...o}=n;r.registerRenderer(t,s,o)}for(let[t,n]of Object.entries(e.services??{}))r.registerService(t,n)}function Je(r,e){for(let o of e.preflights??[])r.registerPreflight(o);let t=e.itemTypes??[];t.length>0&&r.registerItemTypes(t);let n=e.itemFields??[];n.length>0&&r.registerItemFields(n);let s=e.relationshipKinds??[];s.length>0&&r.registerRelationshipKinds(s);for(let o of e.migrations??[])r.registerMigration(o);for(let o of e.profiles??[])r.registerProfile(o)}function Ze(r,e){for(let t of e.searchProviders??[])r.registerSearchProvider(t);for(let t of e.vectorStoreAdapters??[])r.registerVectorStoreAdapter(t);for(let t of e.assuranceProviders??[])r.registerAssuranceMeasurementProvider(t);for(let t of e.importers??[])r.registerImporter(t.name,t.importer,t.options);for(let t of e.exporters??[])r.registerExporter(t.name,t.exporter,t.options)}function Qe(r,e){for(let t of e.beforeCommand??[])r.hooks.beforeCommand(t);for(let t of e.beforeMutation??[])r.hooks.beforeMutation(t);for(let t of e.afterCommand??[])r.hooks.afterCommand(t);for(let t of e.onWrite??[])r.hooks.onWrite(t);for(let t of e.onRead??[])r.hooks.onRead(t);for(let t of e.onIndex??[])r.hooks.onIndex(t)}function er(r){let t={activate:async n=>{Xe(n,r),Je(n,r),Ze(n,r),Qe(n,r.hooks??{}),await r.activate?.(n)}};return r.manifest&&(t.manifest=r.manifest),r.deactivate&&(t.deactivate=r.deactivate),t}function v(r){let e=r.flatMap(t=>t??[]);return e.length>0?e:void 0}function k(r){let e=Object.assign({},...r.map(t=>t??{}));return Object.keys(e).length>0?e:void 0}function rr(r){let e={};for(let t of r)for(let[n,s]of Object.entries(t??{}))e[n]=[...e[n]??[],...s];return Object.keys(e).length>0?e:void 0}var tr=["beforeCommand","beforeMutation","afterCommand","onWrite","onRead","onIndex"];function nr(r,e,t){let n=e.map(o=>o?.[t]),s=v(n);if(s!==void 0){let o=r;o[t]=s}}function or(r){let e={};for(let t of tr)nr(e,r,t);return Object.keys(e).length>0?e:void 0}function ht(...r){let e={},t=(i,a)=>{a!==void 0&&(e[i]=a)};t("commands",v(r.map(i=>i.commands))),t("commandOverrides",k(r.map(i=>i.commandOverrides))),t("flags",rr(r.map(i=>i.flags))),t("parsers",k(r.map(i=>i.parsers))),t("renderers",k(r.map(i=>i.renderers))),t("services",k(r.map(i=>i.services))),t("preflights",v(r.map(i=>i.preflights))),t("itemTypes",v(r.map(i=>i.itemTypes))),t("itemFields",v(r.map(i=>i.itemFields))),t("relationshipKinds",v(r.map(i=>i.relationshipKinds))),t("migrations",v(r.map(i=>i.migrations))),t("profiles",v(r.map(i=>i.profiles))),t("searchProviders",v(r.map(i=>i.searchProviders))),t("vectorStoreAdapters",v(r.map(i=>i.vectorStoreAdapters))),t("assuranceProviders",v(r.map(i=>i.assuranceProviders))),t("importers",v(r.map(i=>i.importers))),t("exporters",v(r.map(i=>i.exporters))),t("hooks",or(r.map(i=>i.hooks)));let n;for(let i of r)i.manifest&&(n=i.manifest);t("manifest",n);let s=r.some(i=>i.activate);t("activate",s?async i=>{for(let a of r)a.activate&&await a.activate(i)}:void 0);let o=r.some(i=>i.deactivate);return t("deactivate",o?async()=>{let i=[];for(let a of[...r].reverse())if(a.deactivate)try{await a.deactivate()}catch(d){i.push(d)}if(i.length>0)throw i.length>1?new AggregateError(i,"Multiple extension blueprint deactivate hooks failed."):i[0]}:void 0),e}var ir=[["commands","commands"],["commandOverrides","commands"],["flags","schema"],["itemTypes","schema"],["itemFields","schema"],["relationshipKinds","schema"],["migrations","schema"],["profiles","schema"],["parsers","parser"],["renderers","renderers"],["services","services"],["preflights","preflight"],["searchProviders","search"],["vectorStoreAdapters","search"],["assuranceProviders","services"],["importers","importers"],["exporters","importers"]];function C(r){return r?Array.isArray(r)?r.length>0:Object.keys(r).length>0:!1}function M(r){let e=new Set;for(let[s,o]of ir)C(r[s])&&e.add(o);(r.commands??[]).filter(w).some(s=>s.flags!==void 0)&&e.add("schema");let t=[...r.importers??[],...r.exporters??[]].filter(w);t.some(s=>s?.options?.flags!==void 0)&&e.add("schema"),t.some(s=>typeof s=="object")&&e.add("commands");let n=r.hooks??{};return[n.beforeCommand,n.beforeMutation,n.afterCommand,n.onWrite,n.onRead,n.onIndex].some(C)&&e.add("hooks"),[...e].sort((s,o)=>s.localeCompare(o))}var sr=[["beforeCommand","before_command"],["beforeMutation","before_mutation"],["afterCommand","after_command"],["onWrite","on_write"],["onRead","on_read"],["onIndex","on_index"]];function l(r){return[...new Set(r)].sort((e,t)=>e.localeCompare(t))}function w(r){return r!=null}function I(r){return h(`${r.name} import`)}function j(r){return h(`${r.name} export`)}function ar(r,e,t){return[...r.map(n=>h(n.name)),...e.filter(n=>n.options!==void 0).map(I),...t.filter(n=>n.options!==void 0).map(j)]}function dr(r,e,t,n){return[...Object.keys(r.flags??{}).map(s=>h(s)),...e.filter(s=>s.flags!==void 0).map(s=>h(s.name)),...t.filter(s=>s.options?.flags!==void 0).map(I),...n.filter(s=>s.options?.flags!==void 0).map(j)]}function mr(r){return sr.filter(([e])=>(r[e]?.length??0)>0).map(([,e])=>e)}function cr(r){let e=Object.entries(r??{}).filter(([,t])=>typeof t!="function"&&((t.commands?.length??0)>0||t.resultDiscriminator!==void 0)).map(([t,n])=>{let s=n;return{format:t,commands:l((s.commands??[]).map(o=>h(o))),result_discriminator:s.resultDiscriminator!==void 0}}).sort((t,n)=>t.format.localeCompare(n.format));return e.length>0?{renderer_ownership:e}:{}}function fr(r){return!r||r.length===0?{}:{assurance_providers:l(r.map(e=>e.id))}}function lr(r,e,t){return{item_types:l((r.itemTypes??[]).map(n=>n.name)),item_fields:l((r.itemFields??[]).map(n=>n.name)),...(r.relationshipKinds?.length??0)>0?{relationship_kinds:l(r.relationshipKinds.map(n=>n.kind))}:{},migrations:l((r.migrations??[]).flatMap(n=>typeof n.id=="string"?[n.id]:[])),profiles:l((r.profiles??[]).map(n=>n.name)),importers:l(e.map(n=>h(n.name))),exporters:l(t.map(n=>h(n.name))),search_providers:l((r.searchProviders??[]).map(n=>n.name)),vector_store_adapters:l((r.vectorStoreAdapters??[]).map(n=>n.name)),...fr(r.assuranceProviders),parser_overrides:l(Object.keys(r.parsers??{}).map(n=>h(n))),service_overrides:l(Object.keys(r.services??{}).map(n=>String(n).trim().toLowerCase())),renderer_overrides:l(Object.keys(r.renderers??{}).map(n=>String(n).trim().toLowerCase())),...cr(r.renderers),preflight_overrides:(r.preflights??[]).length,preflight_ownership:(r.preflights??[]).map(n=>({commands:[...n.commands??[]]}))}}function ur(r){let e=(r.commands??[]).filter(w),t=(r.importers??[]).filter(w),n=(r.exporters??[]).filter(w),s=t.map(I),o=n.map(j),i=ar(e,t,n),a=dr(r,e,t,n),d=r.hooks??{},c=lr(r,t,n);return{capabilities:M(r),commands:l(i),command_overrides:l(Object.keys(r.commandOverrides??{}).map(y=>h(y))),command_handlers:l([...i,...s,...o]),hooks:mr(d),flag_commands:l(a),...c}}var pr=["commands","commandOverrides","flags","parsers","renderers","services","preflights","itemTypes","itemFields","relationshipKinds","migrations","profiles","searchProviders","vectorStoreAdapters","assuranceProviders","importers","exporters"];function gr(r){return(r.itemFields??[]).filter(e=>typeof e?.name=="string"&&Q.has(e.name.trim())).map(e=>({code:"reserved_item_field",severity:"error",message:`Item field "${e.name}" collides with reserved item metadata; rename it with an extension-specific prefix before publishing.`,field:e.name}))}function hr(r){return[...Object.values(r.flags??{}).flat(),...(r.commands??[]).flatMap(t=>t.flags??[]),...(r.importers??[]).flatMap(t=>t.options?.flags??[]),...(r.exporters??[]).flatMap(t=>t.options?.flags??[])].flatMap(t=>{if(typeof t?.long!="string"&&typeof t?.short!="string")return[];let n=V(t.long,t.short);if(n===null)return[];let{token:s,failure:o}=n;return[{code:o,severity:"error",message:`Flag "${s}" ${G(s,o)}.`,field:s}]})}function Me(r){let e=new Set;for(let t of r){let n=Z(t)??$(t);n!==null&&e.add(n)}return[...e].sort((t,n)=>t.localeCompare(n))}function vr(r,e){let t=[];if(e===null)return r.length>0&&t.push({code:"manifest_capabilities_absent",severity:"warning",message:`Blueprint exercises ${r.length===1?"capability":"capabilities"} [${r.join(", ")}] but declares none; set capabilities to deriveExtensionCapabilities(blueprint) so the manifest grant matches.`}),t;let n=new Set(e),s=new Set(r);for(let o of r)n.has(o)||t.push({code:"capability_undeclared",severity:"error",message:`Blueprint exercises capability "${o}" but it is absent from the declared capabilities; activation throws extension_capability_missing \u2014 add "${o}" to the manifest capabilities.`,capability:o});for(let o of e)s.has(o)||t.push({code:"capability_unused",severity:"warning",message:`Capability "${o}" is declared but no blueprint surface exercises it; drop it to keep the manifest least-privilege (pm package doctor reports this as extension_capability_unused).`,capability:o});return t}function yr(r){let e=[],t=new Map;for(let s of r.commands??[]){let o=h(s.name);t.set(o,(t.get(o)??0)+1)}for(let[s,o]of t)o>1&&e.push({code:"duplicate_command",severity:"warning",message:`Command "${s}" is declared ${o} times in commands; the later registration shadows the earlier one at dispatch.`,command:s});let n=new Set(Object.keys(r.commandOverrides??{}).map(s=>h(s)));for(let s of t.keys())n.has(s)&&e.push({code:"command_override_conflict",severity:"warning",message:`Command "${s}" is declared both as a new command definition and as a command override; register one or the other.`,command:s});return e}function xr(r){let e=[];for(let t of pr)t in r&&!C(r[t])&&e.push({code:"empty_surface",severity:"warning",message:`Blueprint field "${t}" is present but empty; remove it or populate it.`,field:t});if("hooks"in r){let t=r.hooks??{};[t.beforeCommand,t.beforeMutation,t.afterCommand,t.onWrite,t.onRead,t.onIndex].some(C)||e.push({code:"empty_surface",severity:"warning",message:'Blueprint field "hooks" is present but registers no lifecycle hooks; remove it or populate it.',field:"hooks"})}return e}function R(r,e={}){let t=M(r),n=e.declaredCapabilities??r.manifest?.capabilities,s=Array.isArray(n)?Me(n):null,o=[...vr(t,s),...yr(r),...hr(r),...gr(r),...xr(r)];return{ok:o.every(i=>i.severity!=="error"),findings:o,used:t,declared:s}}function Ie(r,e){let{additionalCapabilities:t,...n}=e,s=Array.isArray(t)?Me(t):[],o=[...new Set([...M(r),...s])].sort((i,a)=>i.localeCompare(a));return{...n,capabilities:o}}function vt(r,e){let t=Ie(r,e);return{module:er({...r,manifest:t}),manifest:t}}function Te(r,e){if(r.status==="absent"||r.status==="ok")return null;let t=`${r.kind}_${r.status}`,n="";switch(t){case"pm_min_version_invalid":n=`pm_min_version "${r.required}" is not a valid version; the extension is treated as incompatible and the loader skips it.`;break;case"pm_min_version_unchecked":n=`pm_min_version "${r.required}" could not be compared against pm ${e}; compatibility is unverified.`;break;case"pm_min_version_unmet":n=`Requires pm >= ${r.required} but the target is pm ${e}; the loader skips the extension.`;break;case"pm_max_version_invalid":n=`pm_max_version "${r.required}" is not a valid inclusive upper bound (version ranges are not allowed); the extension is treated as incompatible and the loader skips it.`;break;case"pm_max_version_unchecked":n=`pm_max_version "${r.required}" could not be compared against pm ${e}; compatibility is unverified.`;break;case"pm_max_version_exceeded":n=`Allows pm <= ${r.required} but the target is pm ${e}; the loader skips the extension.`;break;case"pm_max_version_exceeded_warn":n=`Target pm ${e} is newer than pm_max_version ${r.required}, but the "warn" exceeded mode lets it load with a warning.`;break}return{code:t,severity:r.allowed?"warning":"error",constraint:r.kind,required:r.required,current:e,message:n}}function B(r,e){let t=re(r.pm_min_version,e.pmVersion),n=te(r.pm_max_version,e.pmVersion,e.pmMaxVersionExceededMode??"block"),o=ee(r).findings.map(c=>({code:c.code,severity:"warning",constraint:"manifest",required:c.code==="manifest_unknown_key"?c.path:"pm_min_version",current:e.pmVersion,path:c.path,...c.suggested_key?{suggested_key:c.suggested_key}:{},message:c.message})),i=[],a=Te(t,e.pmVersion);a!==null&&i.push(a);let d=Te(n,e.pmVersion);return d!==null&&i.push(d),{compatible:t.allowed&&n.allowed,findings:[...o,...i],pmVersion:e.pmVersion}}var Er=new Set(["capability_undeclared","capability_unused","manifest_capabilities_absent"]);function je(r,e={}){let t=R(r,{declaredCapabilities:e.declaredCapabilities}),n=e.identity?Ie(r,e.identity):null,s=e.target?B(n??r.manifest??{},e.target):null,a=[...(n!==null&&e.declaredCapabilities===void 0?t.findings.filter(d=>!Er.has(d.code)):t.findings).map(d=>({source:"blueprint",severity:d.severity,code:d.code,message:d.message})),...(s?.findings??[]).map(d=>({source:"compatibility",severity:d.severity,code:d.code,message:d.message}))];return{ok:a.every(d=>d.severity!=="error"),capabilities:t.used,blueprint:t,manifest:n,compatibility:s,findings:a}}import{decode as Wt,encode as Yt}from"@toon-format/toon";var Le=Symbol.for("pm.sdk.testing.activatedFlagRegistrations");function br(r){return r[Le]}var He=Symbol.for("pm.sdk.testing.activatedServices"),Ke=Symbol.for("pm.sdk.testing.activatedRenderers");function wr(r){return r[Ke]}function _r(r){return r[He]}async function $r(r,e,t,n){if(r===void 0||!n.handled||[...r.commands].reverse().find(a=>a.command===t.command)?.read_output===void 0)return n;let o=process.exitCode,i=!1;return await N(async()=>{xe(e),Ee(_r(e)??null),be(wr(e)??null),F(r),we({command:t.command,args:t.args,options:t.options,global:t.global,pm_root:t.pm_root});let a=t.global;process.exitCode=0;try{X(J(n.result,a),{...a,command:t.command,commandArgs:t.args,commandOptions:t.options,pmRoot:t.pm_root}),i=process.exitCode===A.USAGE}finally{process.exitCode=o}}),i&&kr(t.command),n}function kr(r){throw new U(`Read output for extension command '${r}' does not fit the requested output budget; native delivery omits the result and exits 2.`,A.USAGE,{code:"output_budget_exceeded",required:"Raise outputBudget, or return fewer or smaller rows so the delivered output fits.",why:"The delivered output, including any output_format or renderer string, answers to the caller's output budget, and an infeasible budget omits the result natively.",nextSteps:["Re-run with a larger outputBudget, or without one, to inspect the full result."]})}function g(r,e){return r.name??e??""}var Cr={before_command:"beforeCommand",before_mutation:"beforeMutation",after_command:"afterCommand",on_read:"onRead",on_write:"onWrite",on_index:"onIndex"},D={before_command:"beforeCommand",after_command:"afterCommand",on_read:"onRead",on_write:"onWrite",on_index:"onIndex"};function u(r){return r.trim().toLowerCase()}function Be(r){return u(r).replaceAll("-","_")}function p(r){return r?` from extension "${r}"`:""}function f(r){return[...new Set(r)].sort((e,t)=>e.localeCompare(t))}function x(r){if(typeof r!="string")throw new Error('A command name string is required. Pass it via the options object, e.g. runRegisteredCommandForTest(activation, { command: "my command" }) \u2014 positional command arguments are not supported.');return r.trim().toLowerCase().split(/\s+/).filter(e=>e.length>0).join(" ")}function m(r){return r.length>0?r.join(", "):"(none)"}function De(r,e,t){let n=new Set(r??[]),s=f(e.filter(o=>!n.has(o)));if(s.length>0)throw new Error(`Expected package manifest ${t} to include ${s.join(", ")}; available: ${m(f(r??[]))}`)}function qe(r){let e=new Set;for(let t of r)typeof t.long=="string"&&t.long.trim().length>0&&e.add(t.long.trim()),typeof t.short=="string"&&t.short.trim().length>0&&e.add(t.short.trim());return e}function H(r){let e=b(r);if(!e)return{};let t=b(e.manifest);if(t)return t;let n=b(e.default),s=b(n?.manifest);return s||(n&&typeof e.default!="function"&&("name"in n||"capabilities"in n)?n:typeof r!="function"&&("name"in e||"capabilities"in e)?e:{})}function K(r,e){return e??(typeof r.name=="string"&&r.name.trim().length>0?r.name.trim():"test-extension")}function Ue(r,e){return Array.isArray(e.capabilities)?[...e.capabilities]:Array.isArray(r.capabilities)?r.capabilities.filter(t=>typeof t=="string"):[]}function Ve(r,e,t){return{disabled_by_flag:!1,roots:{global:"",project:""},configured_enabled:[],configured_disabled:[],discovered:[],effective:[],warnings:[],policy:t.policy,failed:[],loaded:[{layer:t.layer,directory:"",manifest_path:"",name:t.name,version:typeof e.version=="string"?e.version:"0.0.0",entry:typeof e.entry=="string"?e.entry:"./index.js",priority:typeof e.priority=="number"?e.priority:0,entry_path:"",capabilities:t.capabilities,manifest_version:typeof e.manifest_version=="number"?e.manifest_version:void 0,pm_min_version:typeof e.pm_min_version=="string"?e.pm_min_version:void 0,pm_max_version:typeof e.pm_max_version=="string"?e.pm_max_version:void 0,engines:e.engines,trusted:e.trusted,provenance:e.provenance,sandbox_profile:e.sandbox_profile,permissions:e.permissions,activation:e.activation,module:r}]}}async function Rr(r,e={}){let t=H(r),n=await he(Ve(r,t,{name:K(t,e.name),layer:e.layer??"project",capabilities:Ue(t,e),policy:e.policy??S()}));return Object.defineProperty(n.commands,Le,{value:n.registrations,enumerable:!1}),Object.defineProperty(n.commands,He,{value:n.services,enumerable:!1}),Object.defineProperty(n.commands,Ke,{value:n.renderers,enumerable:!1}),n}async function Or(r,e={}){let t=H(r);return ge(Ve(r,t,{name:K(t,e.name),layer:e.layer??"project",capabilities:Ue(t,{}),policy:S()}),e.activation,e.deactivateTimeoutMs===void 0?{}:{deactivate_timeout_ms:e.deactivateTimeoutMs})}async function q(r,e){let t=x(e.command);if(t.length===0)throw new Error("Expected command name must be a non-empty string");if(!r.handlers.some(O=>O.command===t)){let O=f(r.handlers.map(Ye=>Ye.command));throw new Error(`Expected a registered command handler for "${t}" to invoke. Available command handlers: ${m(O)}`)}if(e.sdk!==void 0&&e.sdkFactory!==void 0)throw new TypeError("runRegisteredCommandForTest accepts sdk or sdkFactory, not both");let s=e.pmRoot??"",o={json:!0,quiet:!0,noPager:!0,...e.global},i=br(r),a=e.options?{...e.options}:{},d=e.args?[...e.args]:[],c=Sr(a,i===void 0?[]:P(i,t));await Nr(i,t,d,c,o),Object.assign(o,Fr(L(c)),L(o));let y=e.sdk??e.sdkFactory?.({pmRoot:s,global:o})??(s.length>0?Ce(s,new Pe({pmRoot:s}),void 0,t):void 0),E={command:t,args:d,options:i===void 0?a:Oe(a,P(i,t),t,Ae(t)),global:o,pm_root:s,...ye(s.length>0?s:void 0),...y===void 0?{}:{sdk:y}},_=await me(r,E);return await $r(i,r,E,_)}function Sr(r,e){let t={...r};for(let[n,s]of Object.entries(r)){let o=Se(e,n,s);o!==void 0&&t[o.key]===void 0&&(t[o.key]=o.value);let i=e.find(d=>d.short!==void 0&&(d.short===n||d.short===`-${n}`)),a=Re(i??{long:n.startsWith("-")?n:`--${n}`});a!==null&&t[a]===void 0&&(t[a]=s)}return t}var Ar=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor","outputRowContract"];async function Nr(r,e,t,n,s){r!==void 0&&await N(async()=>{F(r),Y(e,{...n,...W(e,t),...L(s)})})}function Fr(r){return Object.fromEntries(Object.entries(r).map(([e,t])=>[e,typeof t=="number"?String(t):Array.isArray(t)?t.join(","):typeof t=="object"?JSON.stringify(t):t]))}function L(r){let e=r;return Object.fromEntries(Ar.flatMap(t=>{let n=e[t]??e[t.replaceAll(/[A-Z]/gu,s=>`_${s.toLowerCase()}`)];return n===void 0?[]:[[t,n]]}))}async function Pr(r,e){if((r.beforeMutation?.length??0)===0)throw new Error("Expected a registered before_mutation hook to invoke");let{actor:t,author:n,dry_run:s,compensation:o,...i}=e.context,{resolveMutationActor:a}=await import("./mutation-actor-QOKPDYM4.js"),d=await oe(r,{...i,actor:t??a(n??"unknown"),dry_run:s===!0,...o===void 0||s===!0?{}:{compensation:o}});return o===void 0?void 0:d}async function Tr(r,e){let t=e.kind;if(t==="before_mutation")throw new Error("Invoke before_mutation hooks with runRegisteredMutationGuardForTest so denials and failures retain fail-closed semantics.");if((r[D[t]]?.length??0)===0){let n=f(Object.keys(D).filter(s=>(r[D[s]]?.length??0)>0));throw new Error(`Expected a registered "${t}" hook to invoke. Hook kinds with registrations: ${m(n)}`)}switch(e.kind){case"before_command":return ne(r,e.context);case"after_command":return ie(r,e.context);case"on_read":return ae(r,e.context);case"on_write":return se(r,e.context);case"on_index":return de(r,e.context)}}async function Mr(r,e){let t=x(e.command);if(!r.overrides.some(n=>n.command===t))throw new Error(`Expected a registered parser override for command "${t}" to invoke. Available parser override commands: ${m(f(r.overrides.map(n=>n.command)))}`);return ce(r,e)}async function Ir(r,e){if(r.overrides.length===0)throw new Error("Expected a registered preflight override to invoke, but none are registered.");return fe(r,e)}async function jr(r,e){let t=x(e.command);if(!r.overrides.some(n=>n.command===t))throw new Error(`Expected a registered command override for command "${t}" to invoke. Available command override commands: ${m(f(r.overrides.map(n=>n.command)))}`);return ue(r,e)}async function Br(r,e){if(!r.overrides.some(t=>t.format===e.format))throw new Error(`Expected a registered renderer override for format "${e.format}" to invoke. Available renderer override formats: ${m(f(r.overrides.map(t=>t.format)))}`);return pe(r,e)}async function Dr(r,e){if(!r.overrides.some(t=>t.service===e.service))throw new Error(`Expected a registered service override for service "${e.service}" to invoke. Available service override services: ${m(f(r.overrides.map(t=>t.service)))}`);return le(r,e)}var Lr={query:["query"],embed:["embed"],embedBatch:["embedBatch","embed_batch"],queryExpansion:["queryExpansion","query_expansion"],rerank:["rerank"]};async function Hr(r,e){let t=_e(r,e.provider);if(!t){let o=f(r.search_providers.map(i=>i.definition.name));throw new Error(`Expected a registered search provider "${e.provider}" to invoke. Available search providers: ${m(o)}`)}let n=t.runtime_definition,s=Lr[e.operation].map(o=>n[o]).find(o=>typeof o=="function");if(typeof s!="function")throw new Error(`Registered search provider "${e.provider}" does not implement the "${e.operation}" operation.`);return await s(e.context)}async function Kr(r,e){let t=$e(r,e.adapter);if(!t){let s=f(r.vector_store_adapters.map(o=>o.definition.name));throw new Error(`Expected a registered vector store adapter "${e.adapter}" to invoke. Available vector store adapters: ${m(s)}`)}let n=t.runtime_definition[e.operation];if(typeof n!="function")throw new Error(`Registered vector store adapter "${e.adapter}" does not implement the "${e.operation}" operation.`);return await n(e.context)}async function qr(r,e){let t=We(r,{migration:e.migration,extensionName:e.extensionName}),n=ke(t).run;if(typeof n!="function")throw new Error(`Registered migration "${e.migration}" does not implement a run function to invoke.`);let s=t.definition.status,o={id:t.definition.id,command:"migration",layer:t.layer,extension:t.name,pm_root:e.pmRoot??"",status:(typeof s=="string"?s.trim().toLowerCase():"")||"pending"};return await n(o)}async function Ur(r,e){let t=Ge(r.registrations,{importer:e.importer,extensionName:e.extensionName});return q(r.commands,{command:`${t.importer} import`,args:e.args,options:e.options,global:e.global,pmRoot:e.pmRoot})}async function Vr(r,e){let t=ze(r.registrations,{exporter:e.exporter,extensionName:e.extensionName});return q(r.commands,{command:`${t.exporter} export`,args:e.args,options:e.options,global:e.global,pmRoot:e.pmRoot})}function Bt(r,e={}){let t=e.deactivated??1;if(r.deactivated!==t)throw new Error(`Expected ${t} extension${t===1?"":"s"} to deactivate cleanly, but ${r.deactivated} did.`);let n=e.failed??0;if(r.failed.length!==n){let s=r.failed.map(o=>`${o.layer}:${o.name} (${o.error})`).join(", ");throw new Error(`Expected ${n} teardown failure${n===1?"":"s"}, but observed ${r.failed.length}${s.length>0?`: ${s}`:""}.`)}return r}function Dt(r,e){if(e.packageName!==void 0&&r.package_name!==e.packageName)throw new Error(`Expected package manifest package_name to be "${e.packageName}"; received "${r.package_name??"(none)"}"`);if(e.aliases!==void 0&&De(r.aliases,e.aliases,"aliases"),e.resources!==void 0)for(let[t,n]of Object.entries(e.resources))De(r.resources[t],n,`pm.${t}`);return r}function Gr(r,e){let t=x(g(e,e.command));if(t.length===0)throw new Error("Expected command name must be a non-empty string");let n=r.commands.filter(i=>i.command===t),s=e.extensionName?n.find(i=>i.name===e.extensionName):n[0];if(!s){let i=r.commands.map(d=>d.command).sort((d,c)=>d.localeCompare(c)),a=e.extensionName?` from extension "${e.extensionName}"`:"";throw new Error(`Expected extension command "${t}"${a} to be registered. Available commands: ${m(i)}`)}if(e.action!==void 0&&s.action!==e.action)throw new Error(`Expected extension command "${t}" action "${e.action}", received "${s.action}"`);if(e.arguments!==void 0){let i=(s.arguments??[]).map(d=>d.name),a=e.arguments.filter(d=>!i.includes(d));if(a.length>0)throw new Error(`Expected extension command "${t}" arguments ${m(e.arguments)}; missing ${m(a)}; available ${m(i)}`)}let o=r.flags.filter(i=>i.target_command===t&&(e.extensionName===void 0||i.name===e.extensionName)).flatMap(i=>i.flags);if(e.flags!==void 0){let i=qe(o),a=e.flags.filter(d=>!i.has(d));if(a.length>0)throw new Error(`Expected extension command "${t}" flags ${m(e.flags)}; missing ${m(a)}; available ${m([...i].sort((d,c)=>d.localeCompare(c)))}`)}return{command:s,flags:o}}function zr(r,e){let t=x(g(e,e.targetCommand));if(t.length===0)throw new Error("Expected target command name must be a non-empty string");let n=r.flags.filter(o=>o.target_command===t),s;if(e.extensionName)s=n.find(o=>o.name===e.extensionName);else if(n.length===1)s=n[0];else if(n.length>1){let o=f(n.map(i=>i.name));throw new Error(`Expected flags for target command "${t}" matched multiple extensions: ${m(o)}. Specify extensionName to choose one registration.`)}if(!s){let o=f(r.flags.map(a=>a.target_command)),i=f(n.map(a=>a.name));throw new Error(`Expected flags for target command "${t}"${p(e.extensionName)} to be registered. Available flag target commands: ${m(o)}; matching extensions: ${m(i)}`)}if(e.flags!==void 0){let o=qe(s.flags),i=e.flags.filter(a=>!o.has(a));if(i.length>0)throw new Error(`Expected flags for target command "${t}" to include ${m(e.flags)}; missing ${m(i)}; available ${m([...o].sort((a,d)=>a.localeCompare(d)))}`)}return s}function Wr(r,e){let t=Cr[e.kind],n=r[t]??[],s=e.extensionName?n.find(o=>o.name===e.extensionName):n[0];if(!s){let o=f(n.map(i=>i.name));throw new Error(`Expected a "${e.kind}" hook${p(e.extensionName)} to be registered. Available "${e.kind}" hooks: ${m(o)}`)}return s}function Yr(r,e){let t=u(g(e,e.provider));if(t.length===0)throw new Error("Expected search provider name must be a non-empty string");let n=r.search_providers.filter(o=>u(o.definition.name)===t),s=e.extensionName?n.find(o=>o.name===e.extensionName):n[0];if(!s){let o=f(r.search_providers.map(i=>i.definition.name));throw new Error(`Expected search provider "${t}"${p(e.extensionName)} to be registered. Available search providers: ${m(o)}`)}return s}function Xr(r,e){let t=u(g(e,e.adapter));if(t.length===0)throw new Error("Expected vector store adapter name must be a non-empty string");let n=r.vector_store_adapters.filter(o=>u(o.definition.name)===t),s=e.extensionName?n.find(o=>o.name===e.extensionName):n[0];if(!s){let o=f(r.vector_store_adapters.map(i=>i.definition.name));throw new Error(`Expected vector store adapter "${t}"${p(e.extensionName)} to be registered. Available vector store adapters: ${m(o)}`)}return s}function Ge(r,e){let t=u(g(e,e.importer));if(t.length===0)throw new Error("Expected importer name must be a non-empty string");let n=r.importers.filter(o=>u(o.importer)===t),s=e.extensionName?n.find(o=>o.name===e.extensionName):n[0];if(!s){let o=f(r.importers.map(i=>i.importer));throw new Error(`Expected importer "${t}"${p(e.extensionName)} to be registered. Available importers: ${m(o)}`)}return s}function ze(r,e){let t=u(g(e,e.exporter));if(t.length===0)throw new Error("Expected exporter name must be a non-empty string");let n=r.exporters.filter(o=>u(o.exporter)===t),s=e.extensionName?n.find(o=>o.name===e.extensionName):n[0];if(!s){let o=f(r.exporters.map(i=>i.exporter));throw new Error(`Expected exporter "${t}"${p(e.extensionName)} to be registered. Available exporters: ${m(o)}`)}return s}function Jr(r,e){let t=u(g(e,e.field));if(t.length===0)throw new Error("Expected item field name must be a non-empty string");let s=r.item_fields.filter(o=>e.extensionName===void 0||o.name===e.extensionName).map(o=>({registration:o,field:o.fields.find(i=>u(i.name)===t)})).filter(o=>o.field!==void 0).find(o=>e.type===void 0||o.field.type===e.type);if(!s){let o=f(r.item_fields.flatMap(i=>i.fields.map(a=>`${a.name}:${a.type}`)));throw new Error(`Expected item field "${t}"${p(e.extensionName)} to be registered. Available item fields: ${m(o)}`)}return s}function Zr(r,e){let t=u(g(e,e.itemType));if(t.length===0)throw new Error("Expected item type name must be a non-empty string");let s=r.item_types.filter(o=>e.extensionName===void 0||o.name===e.extensionName).map(o=>({registration:o,itemType:o.types.find(i=>u(i.name)===t)})).filter(o=>o.itemType!==void 0).find(o=>e.folder===void 0||o.itemType.folder===e.folder);if(!s){let o=f(r.item_types.flatMap(i=>i.types.map(a=>`${a.name}:${a.folder}`)));throw new Error(`Expected item type "${t}"${p(e.extensionName)} to be registered. Available item types: ${m(o)}`)}return s}function Qr(r,e){let t=Be(g(e,e.profile));if(t.length===0)throw new Error("Expected profile name must be a non-empty string");let n=r.profiles.filter(s=>e.extensionName===void 0||s.name===e.extensionName).find(s=>Be(s.profile.name)===t);if(!n){let s=f(r.profiles.map(o=>o.profile.name));throw new Error(`Expected profile "${t}"${p(e.extensionName)} to be registered. Available profiles: ${m(s)}`)}return{registration:n,profile:n.profile}}function et(r,e){let t=x(g(e,e.command));if(t.length===0)throw new Error("Expected command name must be a non-empty string");let n=r.overrides.filter(o=>o.command===t),s=e.extensionName?n.find(o=>o.name===e.extensionName):n[0];if(!s){let o=f(r.overrides.map(i=>i.command));throw new Error(`Expected command override "${t}"${p(e.extensionName)} to be registered. Available command overrides: ${m(o)}`)}return s}function rt(r,e){let t=x(g(e,e.command));if(t.length===0)throw new Error("Expected command name must be a non-empty string");let n=r.overrides.filter(o=>o.command===t),s=e.extensionName?n.find(o=>o.name===e.extensionName):n[0];if(!s){let o=f(r.overrides.map(i=>i.command));throw new Error(`Expected parser override "${t}"${p(e.extensionName)} to be registered. Available parser overrides: ${m(o)}`)}return s}function tt(r,e={}){let t=e.extensionName?r.overrides.find(n=>n.name===e.extensionName):r.overrides[0];if(!t){let n=f(r.overrides.map(s=>s.name));throw new Error(`Expected a preflight override${p(e.extensionName)} to be registered. Available preflight overrides: ${m(n)}`)}return t}function nt(r,e){let t=u(g(e,e.format));if(t.length===0)throw new Error("Expected renderer format must be a non-empty string");let n=r.overrides.filter(o=>o.format===t),s=e.extensionName?n.find(o=>o.name===e.extensionName):n[0];if(!s){let o=f(r.overrides.map(i=>i.format));throw new Error(`Expected renderer override "${t}"${p(e.extensionName)} to be registered. Available renderer overrides: ${m(o)}`)}return s}function ot(r,e){let t=u(g(e,e.service));if(t.length===0)throw new Error("Expected service name must be a non-empty string");let n=r.overrides.filter(o=>u(o.service)===t),s=e.extensionName?n.find(o=>o.name===e.extensionName):n[0];if(!s){let o=f(r.overrides.map(i=>i.service));throw new Error(`Expected service override "${t}"${p(e.extensionName)} to be registered. Available service overrides: ${m(o)}`)}return s}function We(r,e){let t=u(g(e,e.migration));if(t.length===0)throw new Error("Expected migration id must be a non-empty string");let n=r.migrations.filter(a=>(e.extensionName===void 0||a.name===e.extensionName)&&typeof a.definition.id=="string"&&u(a.definition.id)===t),s=n.find(a=>e.mandatory===void 0||(a.definition.mandatory??!1)===e.mandatory);if(s)return s;let o=n[0];if(o!==void 0)throw new Error(`Expected migration "${t}"${p(e.extensionName)} to have mandatory=${e.mandatory}, but it is mandatory=${o.definition.mandatory??!1}.`);let i=f(r.migrations.map(a=>`${typeof a.definition.id=="string"&&a.definition.id.trim().length>0?a.definition.id.trim():"(unnamed)"}:${a.definition.mandatory===!0}`));throw new Error(`Expected migration "${t}"${p(e.extensionName)} to be registered. Available migrations: ${m(i)}`)}function it(r,e){let t=(d,c)=>{let y=new Set;for(let E of d){let _=$(E);if(_===null)throw new Error(`Expected ${c} capability "${E}" to be a known extension capability. Use canonical capability names (see manifest.capabilities).`);y.add(_)}return y},n=[...t(e.declared,"declared")].sort((d,c)=>d.localeCompare(c)),s=t(e.allowUnused??[],"allowUnused"),o=ve(r,{extensionName:e.extensionName}),i=new Set(o),a=n.filter(d=>!i.has(d)&&!s.has(d));if(a.length>0){let d=p(e.extensionName);throw new Error(`Expected every declared capability${d} to be exercised, but [${a.join(", ")}] ${a.length===1?"is":"are"} declared yet never registered against. Remove ${a.length===1?"it":"them"} from manifest.capabilities for least privilege, or pass allowUnused for capabilities registered only behind a runtime flag.`)}return{declared:n,used:o,unused:a}}function Lt(r,e={}){let t=R(r,e);if(!t.ok){let n=t.findings.filter(s=>s.severity==="error");throw new Error(`Extension blueprint failed preflight with ${n.length} ${n.length===1?"error":"errors"}:
|
|
1
|
+
import{O as Fe,Wa as Pe,k as Ce,l as Ae}from"./chunk-NZSXWIX7.js";import{w as Re,x as P,y as Oe,z as Se}from"./chunk-WFYE34TO.js";import{la as Ne,n as T}from"./chunk-IGEFPHV7.js";import{V as _e,W as $e,X as ke}from"./chunk-3TXEWHQX.js";import{$g as F,Ag as ce,Bg as fe,Cg as le,Dg as ue,Eg as pe,Kg as ge,Lg as he,Od as W,Pd as Y,Rg as ve,Se as X,Te as J,Tg as N,U as V,Uf as h,Ug as ye,V as G,Wg as xe,Xf as $,Yf as Z,Zg as Ee,_g as be,ca as b,ch as we,da as z,gg as Q,ng as ee,rg as re,sg as te,tg as ne,ug as oe,vg as ie,wg as se,xg as ae,yg as de,zg as me}from"./chunk-SJWIPGZW.js";import{A,C as U,k as S}from"./chunk-K672XXGQ.js";function pt(r){return r}function gt(r){return r}function Xe(r,e){for(let t of e.commands??[])r.registerCommand(t);for(let[t,n]of Object.entries(e.commandOverrides??{}))r.registerCommand(t,n);for(let[t,n]of Object.entries(e.flags??{}))r.registerFlags(t,n);for(let[t,n]of Object.entries(e.parsers??{}))r.registerParser(t,n);for(let[t,n]of Object.entries(e.renderers??{}))if(typeof n=="function")r.registerRenderer(t,n);else{let{run:s,...o}=n;r.registerRenderer(t,s,o)}for(let[t,n]of Object.entries(e.services??{}))r.registerService(t,n)}function Je(r,e){for(let o of e.preflights??[])r.registerPreflight(o);let t=e.itemTypes??[];t.length>0&&r.registerItemTypes(t);let n=e.itemFields??[];n.length>0&&r.registerItemFields(n);let s=e.relationshipKinds??[];s.length>0&&r.registerRelationshipKinds(s);for(let o of e.migrations??[])r.registerMigration(o);for(let o of e.profiles??[])r.registerProfile(o)}function Ze(r,e){for(let t of e.searchProviders??[])r.registerSearchProvider(t);for(let t of e.vectorStoreAdapters??[])r.registerVectorStoreAdapter(t);for(let t of e.assuranceProviders??[])r.registerAssuranceMeasurementProvider(t);for(let t of e.importers??[])r.registerImporter(t.name,t.importer,t.options);for(let t of e.exporters??[])r.registerExporter(t.name,t.exporter,t.options)}function Qe(r,e){for(let t of e.beforeCommand??[])r.hooks.beforeCommand(t);for(let t of e.beforeMutation??[])r.hooks.beforeMutation(t);for(let t of e.afterCommand??[])r.hooks.afterCommand(t);for(let t of e.onWrite??[])r.hooks.onWrite(t);for(let t of e.onRead??[])r.hooks.onRead(t);for(let t of e.onIndex??[])r.hooks.onIndex(t)}function er(r){let t={activate:async n=>{Xe(n,r),Je(n,r),Ze(n,r),Qe(n,r.hooks??{}),await r.activate?.(n)}};return r.manifest&&(t.manifest=r.manifest),r.deactivate&&(t.deactivate=r.deactivate),t}function v(r){let e=r.flatMap(t=>t??[]);return e.length>0?e:void 0}function k(r){let e=Object.assign({},...r.map(t=>t??{}));return Object.keys(e).length>0?e:void 0}function rr(r){let e={};for(let t of r)for(let[n,s]of Object.entries(t??{}))e[n]=[...e[n]??[],...s];return Object.keys(e).length>0?e:void 0}var tr=["beforeCommand","beforeMutation","afterCommand","onWrite","onRead","onIndex"];function nr(r,e,t){let n=e.map(o=>o?.[t]),s=v(n);if(s!==void 0){let o=r;o[t]=s}}function or(r){let e={};for(let t of tr)nr(e,r,t);return Object.keys(e).length>0?e:void 0}function ht(...r){let e={},t=(i,a)=>{a!==void 0&&(e[i]=a)};t("commands",v(r.map(i=>i.commands))),t("commandOverrides",k(r.map(i=>i.commandOverrides))),t("flags",rr(r.map(i=>i.flags))),t("parsers",k(r.map(i=>i.parsers))),t("renderers",k(r.map(i=>i.renderers))),t("services",k(r.map(i=>i.services))),t("preflights",v(r.map(i=>i.preflights))),t("itemTypes",v(r.map(i=>i.itemTypes))),t("itemFields",v(r.map(i=>i.itemFields))),t("relationshipKinds",v(r.map(i=>i.relationshipKinds))),t("migrations",v(r.map(i=>i.migrations))),t("profiles",v(r.map(i=>i.profiles))),t("searchProviders",v(r.map(i=>i.searchProviders))),t("vectorStoreAdapters",v(r.map(i=>i.vectorStoreAdapters))),t("assuranceProviders",v(r.map(i=>i.assuranceProviders))),t("importers",v(r.map(i=>i.importers))),t("exporters",v(r.map(i=>i.exporters))),t("hooks",or(r.map(i=>i.hooks)));let n;for(let i of r)i.manifest&&(n=i.manifest);t("manifest",n);let s=r.some(i=>i.activate);t("activate",s?async i=>{for(let a of r)a.activate&&await a.activate(i)}:void 0);let o=r.some(i=>i.deactivate);return t("deactivate",o?async()=>{let i=[];for(let a of[...r].reverse())if(a.deactivate)try{await a.deactivate()}catch(d){i.push(d)}if(i.length>0)throw i.length>1?new AggregateError(i,"Multiple extension blueprint deactivate hooks failed."):i[0]}:void 0),e}var ir=[["commands","commands"],["commandOverrides","commands"],["flags","schema"],["itemTypes","schema"],["itemFields","schema"],["relationshipKinds","schema"],["migrations","schema"],["profiles","schema"],["parsers","parser"],["renderers","renderers"],["services","services"],["preflights","preflight"],["searchProviders","search"],["vectorStoreAdapters","search"],["assuranceProviders","services"],["importers","importers"],["exporters","importers"]];function C(r){return r?Array.isArray(r)?r.length>0:Object.keys(r).length>0:!1}function M(r){let e=new Set;for(let[s,o]of ir)C(r[s])&&e.add(o);(r.commands??[]).filter(w).some(s=>s.flags!==void 0)&&e.add("schema");let t=[...r.importers??[],...r.exporters??[]].filter(w);t.some(s=>s?.options?.flags!==void 0)&&e.add("schema"),t.some(s=>typeof s=="object")&&e.add("commands");let n=r.hooks??{};return[n.beforeCommand,n.beforeMutation,n.afterCommand,n.onWrite,n.onRead,n.onIndex].some(C)&&e.add("hooks"),[...e].sort((s,o)=>s.localeCompare(o))}var sr=[["beforeCommand","before_command"],["beforeMutation","before_mutation"],["afterCommand","after_command"],["onWrite","on_write"],["onRead","on_read"],["onIndex","on_index"]];function l(r){return[...new Set(r)].sort((e,t)=>e.localeCompare(t))}function w(r){return r!=null}function I(r){return h(`${r.name} import`)}function j(r){return h(`${r.name} export`)}function ar(r,e,t){return[...r.map(n=>h(n.name)),...e.filter(n=>n.options!==void 0).map(I),...t.filter(n=>n.options!==void 0).map(j)]}function dr(r,e,t,n){return[...Object.keys(r.flags??{}).map(s=>h(s)),...e.filter(s=>s.flags!==void 0).map(s=>h(s.name)),...t.filter(s=>s.options?.flags!==void 0).map(I),...n.filter(s=>s.options?.flags!==void 0).map(j)]}function mr(r){return sr.filter(([e])=>(r[e]?.length??0)>0).map(([,e])=>e)}function cr(r){let e=Object.entries(r??{}).filter(([,t])=>typeof t!="function"&&((t.commands?.length??0)>0||t.resultDiscriminator!==void 0)).map(([t,n])=>{let s=n;return{format:t,commands:l((s.commands??[]).map(o=>h(o))),result_discriminator:s.resultDiscriminator!==void 0}}).sort((t,n)=>t.format.localeCompare(n.format));return e.length>0?{renderer_ownership:e}:{}}function fr(r){return!r||r.length===0?{}:{assurance_providers:l(r.map(e=>e.id))}}function lr(r,e,t){return{item_types:l((r.itemTypes??[]).map(n=>n.name)),item_fields:l((r.itemFields??[]).map(n=>n.name)),...(r.relationshipKinds?.length??0)>0?{relationship_kinds:l(r.relationshipKinds.map(n=>n.kind))}:{},migrations:l((r.migrations??[]).flatMap(n=>typeof n.id=="string"?[n.id]:[])),profiles:l((r.profiles??[]).map(n=>n.name)),importers:l(e.map(n=>h(n.name))),exporters:l(t.map(n=>h(n.name))),search_providers:l((r.searchProviders??[]).map(n=>n.name)),vector_store_adapters:l((r.vectorStoreAdapters??[]).map(n=>n.name)),...fr(r.assuranceProviders),parser_overrides:l(Object.keys(r.parsers??{}).map(n=>h(n))),service_overrides:l(Object.keys(r.services??{}).map(n=>String(n).trim().toLowerCase())),renderer_overrides:l(Object.keys(r.renderers??{}).map(n=>String(n).trim().toLowerCase())),...cr(r.renderers),preflight_overrides:(r.preflights??[]).length,preflight_ownership:(r.preflights??[]).map(n=>({commands:[...n.commands??[]]}))}}function ur(r){let e=(r.commands??[]).filter(w),t=(r.importers??[]).filter(w),n=(r.exporters??[]).filter(w),s=t.map(I),o=n.map(j),i=ar(e,t,n),a=dr(r,e,t,n),d=r.hooks??{},c=lr(r,t,n);return{capabilities:M(r),commands:l(i),command_overrides:l(Object.keys(r.commandOverrides??{}).map(y=>h(y))),command_handlers:l([...i,...s,...o]),hooks:mr(d),flag_commands:l(a),...c}}var pr=["commands","commandOverrides","flags","parsers","renderers","services","preflights","itemTypes","itemFields","relationshipKinds","migrations","profiles","searchProviders","vectorStoreAdapters","assuranceProviders","importers","exporters"];function gr(r){return(r.itemFields??[]).filter(e=>typeof e?.name=="string"&&Q.has(e.name.trim())).map(e=>({code:"reserved_item_field",severity:"error",message:`Item field "${e.name}" collides with reserved item metadata; rename it with an extension-specific prefix before publishing.`,field:e.name}))}function hr(r){return[...Object.values(r.flags??{}).flat(),...(r.commands??[]).flatMap(t=>t.flags??[]),...(r.importers??[]).flatMap(t=>t.options?.flags??[]),...(r.exporters??[]).flatMap(t=>t.options?.flags??[])].flatMap(t=>{if(typeof t?.long!="string"&&typeof t?.short!="string")return[];let n=V(t.long,t.short);if(n===null)return[];let{token:s,failure:o}=n;return[{code:o,severity:"error",message:`Flag "${s}" ${G(s,o)}.`,field:s}]})}function Me(r){let e=new Set;for(let t of r){let n=Z(t)??$(t);n!==null&&e.add(n)}return[...e].sort((t,n)=>t.localeCompare(n))}function vr(r,e){let t=[];if(e===null)return r.length>0&&t.push({code:"manifest_capabilities_absent",severity:"warning",message:`Blueprint exercises ${r.length===1?"capability":"capabilities"} [${r.join(", ")}] but declares none; set capabilities to deriveExtensionCapabilities(blueprint) so the manifest grant matches.`}),t;let n=new Set(e),s=new Set(r);for(let o of r)n.has(o)||t.push({code:"capability_undeclared",severity:"error",message:`Blueprint exercises capability "${o}" but it is absent from the declared capabilities; activation throws extension_capability_missing \u2014 add "${o}" to the manifest capabilities.`,capability:o});for(let o of e)s.has(o)||t.push({code:"capability_unused",severity:"warning",message:`Capability "${o}" is declared but no blueprint surface exercises it; drop it to keep the manifest least-privilege (pm package doctor reports this as extension_capability_unused).`,capability:o});return t}function yr(r){let e=[],t=new Map;for(let s of r.commands??[]){let o=h(s.name);t.set(o,(t.get(o)??0)+1)}for(let[s,o]of t)o>1&&e.push({code:"duplicate_command",severity:"warning",message:`Command "${s}" is declared ${o} times in commands; the later registration shadows the earlier one at dispatch.`,command:s});let n=new Set(Object.keys(r.commandOverrides??{}).map(s=>h(s)));for(let s of t.keys())n.has(s)&&e.push({code:"command_override_conflict",severity:"warning",message:`Command "${s}" is declared both as a new command definition and as a command override; register one or the other.`,command:s});return e}function xr(r){let e=[];for(let t of pr)t in r&&!C(r[t])&&e.push({code:"empty_surface",severity:"warning",message:`Blueprint field "${t}" is present but empty; remove it or populate it.`,field:t});if("hooks"in r){let t=r.hooks??{};[t.beforeCommand,t.beforeMutation,t.afterCommand,t.onWrite,t.onRead,t.onIndex].some(C)||e.push({code:"empty_surface",severity:"warning",message:'Blueprint field "hooks" is present but registers no lifecycle hooks; remove it or populate it.',field:"hooks"})}return e}function R(r,e={}){let t=M(r),n=e.declaredCapabilities??r.manifest?.capabilities,s=Array.isArray(n)?Me(n):null,o=[...vr(t,s),...yr(r),...hr(r),...gr(r),...xr(r)];return{ok:o.every(i=>i.severity!=="error"),findings:o,used:t,declared:s}}function Ie(r,e){let{additionalCapabilities:t,...n}=e,s=Array.isArray(t)?Me(t):[],o=[...new Set([...M(r),...s])].sort((i,a)=>i.localeCompare(a));return{...n,capabilities:o}}function vt(r,e){let t=Ie(r,e);return{module:er({...r,manifest:t}),manifest:t}}function Te(r,e){if(r.status==="absent"||r.status==="ok")return null;let t=`${r.kind}_${r.status}`,n="";switch(t){case"pm_min_version_invalid":n=`pm_min_version "${r.required}" is not a valid version; the extension is treated as incompatible and the loader skips it.`;break;case"pm_min_version_unchecked":n=`pm_min_version "${r.required}" could not be compared against pm ${e}; compatibility is unverified.`;break;case"pm_min_version_unmet":n=`Requires pm >= ${r.required} but the target is pm ${e}; the loader skips the extension.`;break;case"pm_max_version_invalid":n=`pm_max_version "${r.required}" is not a valid inclusive upper bound (version ranges are not allowed); the extension is treated as incompatible and the loader skips it.`;break;case"pm_max_version_unchecked":n=`pm_max_version "${r.required}" could not be compared against pm ${e}; compatibility is unverified.`;break;case"pm_max_version_exceeded":n=`Allows pm <= ${r.required} but the target is pm ${e}; the loader skips the extension.`;break;case"pm_max_version_exceeded_warn":n=`Target pm ${e} is newer than pm_max_version ${r.required}, but the "warn" exceeded mode lets it load with a warning.`;break}return{code:t,severity:r.allowed?"warning":"error",constraint:r.kind,required:r.required,current:e,message:n}}function B(r,e){let t=re(r.pm_min_version,e.pmVersion),n=te(r.pm_max_version,e.pmVersion,e.pmMaxVersionExceededMode??"block"),o=ee(r).findings.map(c=>({code:c.code,severity:"warning",constraint:"manifest",required:c.code==="manifest_unknown_key"?c.path:"pm_min_version",current:e.pmVersion,path:c.path,...c.suggested_key?{suggested_key:c.suggested_key}:{},message:c.message})),i=[],a=Te(t,e.pmVersion);a!==null&&i.push(a);let d=Te(n,e.pmVersion);return d!==null&&i.push(d),{compatible:t.allowed&&n.allowed,findings:[...o,...i],pmVersion:e.pmVersion}}var Er=new Set(["capability_undeclared","capability_unused","manifest_capabilities_absent"]);function je(r,e={}){let t=R(r,{declaredCapabilities:e.declaredCapabilities}),n=e.identity?Ie(r,e.identity):null,s=e.target?B(n??r.manifest??{},e.target):null,a=[...(n!==null&&e.declaredCapabilities===void 0?t.findings.filter(d=>!Er.has(d.code)):t.findings).map(d=>({source:"blueprint",severity:d.severity,code:d.code,message:d.message})),...(s?.findings??[]).map(d=>({source:"compatibility",severity:d.severity,code:d.code,message:d.message}))];return{ok:a.every(d=>d.severity!=="error"),capabilities:t.used,blueprint:t,manifest:n,compatibility:s,findings:a}}import{decode as Wt,encode as Yt}from"@toon-format/toon";var Le=Symbol.for("pm.sdk.testing.activatedFlagRegistrations");function br(r){return r[Le]}var He=Symbol.for("pm.sdk.testing.activatedServices"),Ke=Symbol.for("pm.sdk.testing.activatedRenderers");function wr(r){return r[Ke]}function _r(r){return r[He]}async function $r(r,e,t,n){if(r===void 0||!n.handled||[...r.commands].reverse().find(a=>a.command===t.command)?.read_output===void 0)return n;let o=process.exitCode,i=!1;return await N(async()=>{xe(e),Ee(_r(e)??null),be(wr(e)??null),F(r),we({command:t.command,args:t.args,options:t.options,global:t.global,pm_root:t.pm_root});let a=t.global;process.exitCode=0;try{X(J(n.result,a),{...a,command:t.command,commandArgs:t.args,commandOptions:t.options,pmRoot:t.pm_root}),i=process.exitCode===A.USAGE}finally{process.exitCode=o}}),i&&kr(t.command),n}function kr(r){throw new U(`Read output for extension command '${r}' does not fit the requested output budget; native delivery omits the result and exits 2.`,A.USAGE,{code:"output_budget_exceeded",required:"Raise outputBudget, or return fewer or smaller rows so the delivered output fits.",why:"The delivered output, including any output_format or renderer string, answers to the caller's output budget, and an infeasible budget omits the result natively.",nextSteps:["Re-run with a larger outputBudget, or without one, to inspect the full result."]})}function g(r,e){return r.name??e??""}var Cr={before_command:"beforeCommand",before_mutation:"beforeMutation",after_command:"afterCommand",on_read:"onRead",on_write:"onWrite",on_index:"onIndex"},D={before_command:"beforeCommand",after_command:"afterCommand",on_read:"onRead",on_write:"onWrite",on_index:"onIndex"};function u(r){return r.trim().toLowerCase()}function Be(r){return u(r).replaceAll("-","_")}function p(r){return r?` from extension "${r}"`:""}function f(r){return[...new Set(r)].sort((e,t)=>e.localeCompare(t))}function x(r){if(typeof r!="string")throw new Error('A command name string is required. Pass it via the options object, e.g. runRegisteredCommandForTest(activation, { command: "my command" }) \u2014 positional command arguments are not supported.');return r.trim().toLowerCase().split(/\s+/).filter(e=>e.length>0).join(" ")}function m(r){return r.length>0?r.join(", "):"(none)"}function De(r,e,t){let n=new Set(r??[]),s=f(e.filter(o=>!n.has(o)));if(s.length>0)throw new Error(`Expected package manifest ${t} to include ${s.join(", ")}; available: ${m(f(r??[]))}`)}function qe(r){let e=new Set;for(let t of r)typeof t.long=="string"&&t.long.trim().length>0&&e.add(t.long.trim()),typeof t.short=="string"&&t.short.trim().length>0&&e.add(t.short.trim());return e}function H(r){let e=b(r);if(!e)return{};let t=b(e.manifest);if(t)return t;let n=b(e.default),s=b(n?.manifest);return s||(n&&typeof e.default!="function"&&("name"in n||"capabilities"in n)?n:typeof r!="function"&&("name"in e||"capabilities"in e)?e:{})}function K(r,e){return e??(typeof r.name=="string"&&r.name.trim().length>0?r.name.trim():"test-extension")}function Ue(r,e){return Array.isArray(e.capabilities)?[...e.capabilities]:Array.isArray(r.capabilities)?r.capabilities.filter(t=>typeof t=="string"):[]}function Ve(r,e,t){return{disabled_by_flag:!1,roots:{global:"",project:""},configured_enabled:[],configured_disabled:[],discovered:[],effective:[],warnings:[],policy:t.policy,failed:[],loaded:[{layer:t.layer,directory:"",manifest_path:"",name:t.name,version:typeof e.version=="string"?e.version:"0.0.0",entry:typeof e.entry=="string"?e.entry:"./index.js",priority:typeof e.priority=="number"?e.priority:0,entry_path:"",capabilities:t.capabilities,manifest_version:typeof e.manifest_version=="number"?e.manifest_version:void 0,pm_min_version:typeof e.pm_min_version=="string"?e.pm_min_version:void 0,pm_max_version:typeof e.pm_max_version=="string"?e.pm_max_version:void 0,engines:e.engines,trusted:e.trusted,provenance:e.provenance,sandbox_profile:e.sandbox_profile,permissions:e.permissions,activation:e.activation,module:r}]}}async function Rr(r,e={}){let t=H(r),n=await he(Ve(r,t,{name:K(t,e.name),layer:e.layer??"project",capabilities:Ue(t,e),policy:e.policy??S()}));return Object.defineProperty(n.commands,Le,{value:n.registrations,enumerable:!1}),Object.defineProperty(n.commands,He,{value:n.services,enumerable:!1}),Object.defineProperty(n.commands,Ke,{value:n.renderers,enumerable:!1}),n}async function Or(r,e={}){let t=H(r);return ge(Ve(r,t,{name:K(t,e.name),layer:e.layer??"project",capabilities:Ue(t,{}),policy:S()}),e.activation,e.deactivateTimeoutMs===void 0?{}:{deactivate_timeout_ms:e.deactivateTimeoutMs})}async function q(r,e){let t=x(e.command);if(t.length===0)throw new Error("Expected command name must be a non-empty string");if(!r.handlers.some(O=>O.command===t)){let O=f(r.handlers.map(Ye=>Ye.command));throw new Error(`Expected a registered command handler for "${t}" to invoke. Available command handlers: ${m(O)}`)}if(e.sdk!==void 0&&e.sdkFactory!==void 0)throw new TypeError("runRegisteredCommandForTest accepts sdk or sdkFactory, not both");let s=e.pmRoot??"",o={json:!0,quiet:!0,noPager:!0,...e.global},i=br(r),a=e.options?{...e.options}:{},d=e.args?[...e.args]:[],c=Sr(a,i===void 0?[]:P(i,t));await Nr(i,t,d,c,o),Object.assign(o,Fr(L(c)),L(o));let y=e.sdk??e.sdkFactory?.({pmRoot:s,global:o})??(s.length>0?Ce(s,new Pe({pmRoot:s}),void 0,t):void 0),E={command:t,args:d,options:i===void 0?a:Oe(a,P(i,t),t,Ae(t)),global:o,pm_root:s,...ye(s.length>0?s:void 0),...y===void 0?{}:{sdk:y}},_=await me(r,E);return await $r(i,r,E,_)}function Sr(r,e){let t={...r};for(let[n,s]of Object.entries(r)){let o=Se(e,n,s);o!==void 0&&t[o.key]===void 0&&(t[o.key]=o.value);let i=e.find(d=>d.short!==void 0&&(d.short===n||d.short===`-${n}`)),a=Re(i??{long:n.startsWith("-")?n:`--${n}`});a!==null&&t[a]===void 0&&(t[a]=s)}return t}var Ar=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor","outputRowContract"];async function Nr(r,e,t,n,s){r!==void 0&&await N(async()=>{F(r),Y(e,{...n,...W(e,t),...L(s)})})}function Fr(r){return Object.fromEntries(Object.entries(r).map(([e,t])=>[e,typeof t=="number"?String(t):Array.isArray(t)?t.join(","):typeof t=="object"?JSON.stringify(t):t]))}function L(r){let e=r;return Object.fromEntries(Ar.flatMap(t=>{let n=e[t]??e[t.replaceAll(/[A-Z]/gu,s=>`_${s.toLowerCase()}`)];return n===void 0?[]:[[t,n]]}))}async function Pr(r,e){if((r.beforeMutation?.length??0)===0)throw new Error("Expected a registered before_mutation hook to invoke");let{actor:t,author:n,dry_run:s,compensation:o,...i}=e.context,{resolveMutationActor:a}=await import("./mutation-actor-UK3QNEEB.js"),d=await oe(r,{...i,actor:t??a(n??"unknown"),dry_run:s===!0,...o===void 0||s===!0?{}:{compensation:o}});return o===void 0?void 0:d}async function Tr(r,e){let t=e.kind;if(t==="before_mutation")throw new Error("Invoke before_mutation hooks with runRegisteredMutationGuardForTest so denials and failures retain fail-closed semantics.");if((r[D[t]]?.length??0)===0){let n=f(Object.keys(D).filter(s=>(r[D[s]]?.length??0)>0));throw new Error(`Expected a registered "${t}" hook to invoke. Hook kinds with registrations: ${m(n)}`)}switch(e.kind){case"before_command":return ne(r,e.context);case"after_command":return ie(r,e.context);case"on_read":return ae(r,e.context);case"on_write":return se(r,e.context);case"on_index":return de(r,e.context)}}async function Mr(r,e){let t=x(e.command);if(!r.overrides.some(n=>n.command===t))throw new Error(`Expected a registered parser override for command "${t}" to invoke. Available parser override commands: ${m(f(r.overrides.map(n=>n.command)))}`);return ce(r,e)}async function Ir(r,e){if(r.overrides.length===0)throw new Error("Expected a registered preflight override to invoke, but none are registered.");return fe(r,e)}async function jr(r,e){let t=x(e.command);if(!r.overrides.some(n=>n.command===t))throw new Error(`Expected a registered command override for command "${t}" to invoke. Available command override commands: ${m(f(r.overrides.map(n=>n.command)))}`);return ue(r,e)}async function Br(r,e){if(!r.overrides.some(t=>t.format===e.format))throw new Error(`Expected a registered renderer override for format "${e.format}" to invoke. Available renderer override formats: ${m(f(r.overrides.map(t=>t.format)))}`);return pe(r,e)}async function Dr(r,e){if(!r.overrides.some(t=>t.service===e.service))throw new Error(`Expected a registered service override for service "${e.service}" to invoke. Available service override services: ${m(f(r.overrides.map(t=>t.service)))}`);return le(r,e)}var Lr={query:["query"],embed:["embed"],embedBatch:["embedBatch","embed_batch"],queryExpansion:["queryExpansion","query_expansion"],rerank:["rerank"]};async function Hr(r,e){let t=_e(r,e.provider);if(!t){let o=f(r.search_providers.map(i=>i.definition.name));throw new Error(`Expected a registered search provider "${e.provider}" to invoke. Available search providers: ${m(o)}`)}let n=t.runtime_definition,s=Lr[e.operation].map(o=>n[o]).find(o=>typeof o=="function");if(typeof s!="function")throw new Error(`Registered search provider "${e.provider}" does not implement the "${e.operation}" operation.`);return await s(e.context)}async function Kr(r,e){let t=$e(r,e.adapter);if(!t){let s=f(r.vector_store_adapters.map(o=>o.definition.name));throw new Error(`Expected a registered vector store adapter "${e.adapter}" to invoke. Available vector store adapters: ${m(s)}`)}let n=t.runtime_definition[e.operation];if(typeof n!="function")throw new Error(`Registered vector store adapter "${e.adapter}" does not implement the "${e.operation}" operation.`);return await n(e.context)}async function qr(r,e){let t=We(r,{migration:e.migration,extensionName:e.extensionName}),n=ke(t).run;if(typeof n!="function")throw new Error(`Registered migration "${e.migration}" does not implement a run function to invoke.`);let s=t.definition.status,o={id:t.definition.id,command:"migration",layer:t.layer,extension:t.name,pm_root:e.pmRoot??"",status:(typeof s=="string"?s.trim().toLowerCase():"")||"pending"};return await n(o)}async function Ur(r,e){let t=Ge(r.registrations,{importer:e.importer,extensionName:e.extensionName});return q(r.commands,{command:`${t.importer} import`,args:e.args,options:e.options,global:e.global,pmRoot:e.pmRoot})}async function Vr(r,e){let t=ze(r.registrations,{exporter:e.exporter,extensionName:e.extensionName});return q(r.commands,{command:`${t.exporter} export`,args:e.args,options:e.options,global:e.global,pmRoot:e.pmRoot})}function Bt(r,e={}){let t=e.deactivated??1;if(r.deactivated!==t)throw new Error(`Expected ${t} extension${t===1?"":"s"} to deactivate cleanly, but ${r.deactivated} did.`);let n=e.failed??0;if(r.failed.length!==n){let s=r.failed.map(o=>`${o.layer}:${o.name} (${o.error})`).join(", ");throw new Error(`Expected ${n} teardown failure${n===1?"":"s"}, but observed ${r.failed.length}${s.length>0?`: ${s}`:""}.`)}return r}function Dt(r,e){if(e.packageName!==void 0&&r.package_name!==e.packageName)throw new Error(`Expected package manifest package_name to be "${e.packageName}"; received "${r.package_name??"(none)"}"`);if(e.aliases!==void 0&&De(r.aliases,e.aliases,"aliases"),e.resources!==void 0)for(let[t,n]of Object.entries(e.resources))De(r.resources[t],n,`pm.${t}`);return r}function Gr(r,e){let t=x(g(e,e.command));if(t.length===0)throw new Error("Expected command name must be a non-empty string");let n=r.commands.filter(i=>i.command===t),s=e.extensionName?n.find(i=>i.name===e.extensionName):n[0];if(!s){let i=r.commands.map(d=>d.command).sort((d,c)=>d.localeCompare(c)),a=e.extensionName?` from extension "${e.extensionName}"`:"";throw new Error(`Expected extension command "${t}"${a} to be registered. Available commands: ${m(i)}`)}if(e.action!==void 0&&s.action!==e.action)throw new Error(`Expected extension command "${t}" action "${e.action}", received "${s.action}"`);if(e.arguments!==void 0){let i=(s.arguments??[]).map(d=>d.name),a=e.arguments.filter(d=>!i.includes(d));if(a.length>0)throw new Error(`Expected extension command "${t}" arguments ${m(e.arguments)}; missing ${m(a)}; available ${m(i)}`)}let o=r.flags.filter(i=>i.target_command===t&&(e.extensionName===void 0||i.name===e.extensionName)).flatMap(i=>i.flags);if(e.flags!==void 0){let i=qe(o),a=e.flags.filter(d=>!i.has(d));if(a.length>0)throw new Error(`Expected extension command "${t}" flags ${m(e.flags)}; missing ${m(a)}; available ${m([...i].sort((d,c)=>d.localeCompare(c)))}`)}return{command:s,flags:o}}function zr(r,e){let t=x(g(e,e.targetCommand));if(t.length===0)throw new Error("Expected target command name must be a non-empty string");let n=r.flags.filter(o=>o.target_command===t),s;if(e.extensionName)s=n.find(o=>o.name===e.extensionName);else if(n.length===1)s=n[0];else if(n.length>1){let o=f(n.map(i=>i.name));throw new Error(`Expected flags for target command "${t}" matched multiple extensions: ${m(o)}. Specify extensionName to choose one registration.`)}if(!s){let o=f(r.flags.map(a=>a.target_command)),i=f(n.map(a=>a.name));throw new Error(`Expected flags for target command "${t}"${p(e.extensionName)} to be registered. Available flag target commands: ${m(o)}; matching extensions: ${m(i)}`)}if(e.flags!==void 0){let o=qe(s.flags),i=e.flags.filter(a=>!o.has(a));if(i.length>0)throw new Error(`Expected flags for target command "${t}" to include ${m(e.flags)}; missing ${m(i)}; available ${m([...o].sort((a,d)=>a.localeCompare(d)))}`)}return s}function Wr(r,e){let t=Cr[e.kind],n=r[t]??[],s=e.extensionName?n.find(o=>o.name===e.extensionName):n[0];if(!s){let o=f(n.map(i=>i.name));throw new Error(`Expected a "${e.kind}" hook${p(e.extensionName)} to be registered. Available "${e.kind}" hooks: ${m(o)}`)}return s}function Yr(r,e){let t=u(g(e,e.provider));if(t.length===0)throw new Error("Expected search provider name must be a non-empty string");let n=r.search_providers.filter(o=>u(o.definition.name)===t),s=e.extensionName?n.find(o=>o.name===e.extensionName):n[0];if(!s){let o=f(r.search_providers.map(i=>i.definition.name));throw new Error(`Expected search provider "${t}"${p(e.extensionName)} to be registered. Available search providers: ${m(o)}`)}return s}function Xr(r,e){let t=u(g(e,e.adapter));if(t.length===0)throw new Error("Expected vector store adapter name must be a non-empty string");let n=r.vector_store_adapters.filter(o=>u(o.definition.name)===t),s=e.extensionName?n.find(o=>o.name===e.extensionName):n[0];if(!s){let o=f(r.vector_store_adapters.map(i=>i.definition.name));throw new Error(`Expected vector store adapter "${t}"${p(e.extensionName)} to be registered. Available vector store adapters: ${m(o)}`)}return s}function Ge(r,e){let t=u(g(e,e.importer));if(t.length===0)throw new Error("Expected importer name must be a non-empty string");let n=r.importers.filter(o=>u(o.importer)===t),s=e.extensionName?n.find(o=>o.name===e.extensionName):n[0];if(!s){let o=f(r.importers.map(i=>i.importer));throw new Error(`Expected importer "${t}"${p(e.extensionName)} to be registered. Available importers: ${m(o)}`)}return s}function ze(r,e){let t=u(g(e,e.exporter));if(t.length===0)throw new Error("Expected exporter name must be a non-empty string");let n=r.exporters.filter(o=>u(o.exporter)===t),s=e.extensionName?n.find(o=>o.name===e.extensionName):n[0];if(!s){let o=f(r.exporters.map(i=>i.exporter));throw new Error(`Expected exporter "${t}"${p(e.extensionName)} to be registered. Available exporters: ${m(o)}`)}return s}function Jr(r,e){let t=u(g(e,e.field));if(t.length===0)throw new Error("Expected item field name must be a non-empty string");let s=r.item_fields.filter(o=>e.extensionName===void 0||o.name===e.extensionName).map(o=>({registration:o,field:o.fields.find(i=>u(i.name)===t)})).filter(o=>o.field!==void 0).find(o=>e.type===void 0||o.field.type===e.type);if(!s){let o=f(r.item_fields.flatMap(i=>i.fields.map(a=>`${a.name}:${a.type}`)));throw new Error(`Expected item field "${t}"${p(e.extensionName)} to be registered. Available item fields: ${m(o)}`)}return s}function Zr(r,e){let t=u(g(e,e.itemType));if(t.length===0)throw new Error("Expected item type name must be a non-empty string");let s=r.item_types.filter(o=>e.extensionName===void 0||o.name===e.extensionName).map(o=>({registration:o,itemType:o.types.find(i=>u(i.name)===t)})).filter(o=>o.itemType!==void 0).find(o=>e.folder===void 0||o.itemType.folder===e.folder);if(!s){let o=f(r.item_types.flatMap(i=>i.types.map(a=>`${a.name}:${a.folder}`)));throw new Error(`Expected item type "${t}"${p(e.extensionName)} to be registered. Available item types: ${m(o)}`)}return s}function Qr(r,e){let t=Be(g(e,e.profile));if(t.length===0)throw new Error("Expected profile name must be a non-empty string");let n=r.profiles.filter(s=>e.extensionName===void 0||s.name===e.extensionName).find(s=>Be(s.profile.name)===t);if(!n){let s=f(r.profiles.map(o=>o.profile.name));throw new Error(`Expected profile "${t}"${p(e.extensionName)} to be registered. Available profiles: ${m(s)}`)}return{registration:n,profile:n.profile}}function et(r,e){let t=x(g(e,e.command));if(t.length===0)throw new Error("Expected command name must be a non-empty string");let n=r.overrides.filter(o=>o.command===t),s=e.extensionName?n.find(o=>o.name===e.extensionName):n[0];if(!s){let o=f(r.overrides.map(i=>i.command));throw new Error(`Expected command override "${t}"${p(e.extensionName)} to be registered. Available command overrides: ${m(o)}`)}return s}function rt(r,e){let t=x(g(e,e.command));if(t.length===0)throw new Error("Expected command name must be a non-empty string");let n=r.overrides.filter(o=>o.command===t),s=e.extensionName?n.find(o=>o.name===e.extensionName):n[0];if(!s){let o=f(r.overrides.map(i=>i.command));throw new Error(`Expected parser override "${t}"${p(e.extensionName)} to be registered. Available parser overrides: ${m(o)}`)}return s}function tt(r,e={}){let t=e.extensionName?r.overrides.find(n=>n.name===e.extensionName):r.overrides[0];if(!t){let n=f(r.overrides.map(s=>s.name));throw new Error(`Expected a preflight override${p(e.extensionName)} to be registered. Available preflight overrides: ${m(n)}`)}return t}function nt(r,e){let t=u(g(e,e.format));if(t.length===0)throw new Error("Expected renderer format must be a non-empty string");let n=r.overrides.filter(o=>o.format===t),s=e.extensionName?n.find(o=>o.name===e.extensionName):n[0];if(!s){let o=f(r.overrides.map(i=>i.format));throw new Error(`Expected renderer override "${t}"${p(e.extensionName)} to be registered. Available renderer overrides: ${m(o)}`)}return s}function ot(r,e){let t=u(g(e,e.service));if(t.length===0)throw new Error("Expected service name must be a non-empty string");let n=r.overrides.filter(o=>u(o.service)===t),s=e.extensionName?n.find(o=>o.name===e.extensionName):n[0];if(!s){let o=f(r.overrides.map(i=>i.service));throw new Error(`Expected service override "${t}"${p(e.extensionName)} to be registered. Available service overrides: ${m(o)}`)}return s}function We(r,e){let t=u(g(e,e.migration));if(t.length===0)throw new Error("Expected migration id must be a non-empty string");let n=r.migrations.filter(a=>(e.extensionName===void 0||a.name===e.extensionName)&&typeof a.definition.id=="string"&&u(a.definition.id)===t),s=n.find(a=>e.mandatory===void 0||(a.definition.mandatory??!1)===e.mandatory);if(s)return s;let o=n[0];if(o!==void 0)throw new Error(`Expected migration "${t}"${p(e.extensionName)} to have mandatory=${e.mandatory}, but it is mandatory=${o.definition.mandatory??!1}.`);let i=f(r.migrations.map(a=>`${typeof a.definition.id=="string"&&a.definition.id.trim().length>0?a.definition.id.trim():"(unnamed)"}:${a.definition.mandatory===!0}`));throw new Error(`Expected migration "${t}"${p(e.extensionName)} to be registered. Available migrations: ${m(i)}`)}function it(r,e){let t=(d,c)=>{let y=new Set;for(let E of d){let _=$(E);if(_===null)throw new Error(`Expected ${c} capability "${E}" to be a known extension capability. Use canonical capability names (see manifest.capabilities).`);y.add(_)}return y},n=[...t(e.declared,"declared")].sort((d,c)=>d.localeCompare(c)),s=t(e.allowUnused??[],"allowUnused"),o=ve(r,{extensionName:e.extensionName}),i=new Set(o),a=n.filter(d=>!i.has(d)&&!s.has(d));if(a.length>0){let d=p(e.extensionName);throw new Error(`Expected every declared capability${d} to be exercised, but [${a.join(", ")}] ${a.length===1?"is":"are"} declared yet never registered against. Remove ${a.length===1?"it":"them"} from manifest.capabilities for least privilege, or pass allowUnused for capabilities registered only behind a runtime flag.`)}return{declared:n,used:o,unused:a}}function Lt(r,e={}){let t=R(r,e);if(!t.ok){let n=t.findings.filter(s=>s.severity==="error");throw new Error(`Extension blueprint failed preflight with ${n.length} ${n.length===1?"error":"errors"}:
|
|
2
2
|
`+n.map(s=>` - [${s.code}] ${s.message}`).join(`
|
|
3
3
|
`))}return t}function Ht(r,e={}){let t=Fe(r),n=t.findings.filter(s=>s.severity==="error"||e.strict===!0&&s.severity==="warning");if(n.length>0)throw new Error(`Project profile "${t.profile}" failed lint with ${n.length} ${n.length===1?"issue":"issues"}:
|
|
4
4
|
`+n.map(s=>` - ${s.severity} [${s.code}] ${s.message}`).join(`
|
|
5
5
|
`));return t}function Kt(r,e){let t=Array.isArray(r.capabilities)?r.capabilities:[],n=R(e,{declaredCapabilities:t}),s=n.declared,o=new Set(s),i=new Set(n.used),a=n.used.filter(c=>!o.has(c)),d=s.filter(c=>!i.has(c));if(a.length>0||d.length>0){let c=[];throw a.length>0&&c.push(`missing [${a.join(", ")}] (the blueprint registers ${a.length===1?"a surface":"surfaces"} requiring ${a.length===1?"it":"them"}; activation throws extension_capability_missing)`),d.length>0&&c.push(`unused [${d.join(", ")}] (declared but no surface exercises ${d.length===1?"it":"them"}; drop for least privilege)`),new Error(`Manifest capabilities do not match the blueprint: ${c.join("; ")}. Set capabilities to synthesizeExtensionManifest(blueprint, identity).capabilities to stay in sync.`)}return{used:n.used,declared:s,missing:a,unused:d,findings:n.findings}}function qt(r,e){let t=B(r,e),n=t.findings.filter(s=>s.severity==="error");if(n.length>0)throw new Error(`Extension manifest is not compatible with pm ${t.pmVersion}: ${n.map(s=>s.message).join("; ")}`);return t}function Ut(r,e={}){let t=je(r,e);if(!t.ok){let n=t.findings.filter(s=>s.severity==="error");throw new Error(`Extension failed preflight with ${n.length} ${n.length===1?"error":"errors"}:
|
|
6
6
|
`+n.map(s=>` - [${s.source}:${s.code}] ${s.message}`).join(`
|
|
7
7
|
`))}return t}function st(r){if(!z(r))throw new Error("createExtensionTestHarness received a module with no activate export. Pass the extension module (with an activate(api) function on the module or its default export) as the first argument, and options second.")}async function Vt(r,e={}){st(r);let t=H(r),n=K(t,e.name),s=e.layer??"project",o=await Rr(r,e);if(o.failed.length>0){let i=o.failed.map(a=>{let d=a.trace?.missing_capability,c=d?`${a.error}; missing capability "${d}"`:a.error;return`${a.layer}:${a.name} (${c})`}).join(", ");throw new Error(`createExtensionTestHarness could not activate the extension cleanly: ${i}. Declare the required capability in the manifest (or pass it via options.capabilities), or use activateExtensionForTest directly to inspect a failed activation.`)}return{module:r,name:n,layer:s,activation:o,activationSummary(i){return T(o,i)},renderMarkdown(i={}){let{extensionName:a,...d}=i??{};return Ne(T(o,{extensionName:a}),d)},assertCommandContract(i){return Gr(o.registrations,i)},assertFlags(i){return zr(o.registrations,i)},assertItemField(i){return Jr(o.registrations,i)},assertItemType(i){return Zr(o.registrations,i)},assertProfile(i){return Qr(o.registrations,i)},assertHook(i){return Wr(o.hooks,i)},assertCommandOverride(i){return et(o.commands,i)},assertParserOverride(i){return rt(o.parsers,i)},assertPreflightOverride(i){return tt(o.preflight,i)},assertRendererOverride(i){return nt(o.renderers,i)},assertServiceOverride(i){return ot(o.services,i)},assertSearchProvider(i){return Yr(o.registrations,i)},assertVectorStoreAdapter(i){return Xr(o.registrations,i)},assertImporter(i){return Ge(o.registrations,i)},assertExporter(i){return ze(o.registrations,i)},assertMigration(i){return We(o.registrations,i)},assertCapabilityUsage(i){return it(o,i)},runCommand(i){return q(o.commands,i)},runHook(i){return Tr(o.hooks,i)},runMutationGuard:(i=>Pr(o.hooks,i)),runCommandOverride(i){return jr(o.commands,i)},runParserOverride(i){return Mr(o.parsers,i)},runPreflightOverride(i){return Ir(o.preflight,i)},runRendererOverride(i){return Br(o.renderers,i)},runServiceOverride(i){return Dr(o.services,i)},runSearchProvider(i){return Hr(o.registrations,i)},runVectorStoreAdapter(i){return Kr(o.registrations,i)},runMigration(i){return qr(o.registrations,i)},runImporter(i){return Ur(o,i)},runExporter(i){return Vr(o,i)},deactivate(i={}){return Or(r,{name:n,layer:s,activation:o,deactivateTimeoutMs:i.deactivateTimeoutMs})}}}export{pt as a,gt as b,er as c,ht as d,M as e,ur as f,R as g,Ie as h,vt as i,B as j,je as k,Rr as l,Or as m,q as n,Pr as o,Tr as p,Mr as q,Ir as r,jr as s,Br as t,Dr as u,Hr as v,Kr as w,qr as x,Ur as y,Vr as z,Bt as A,Dt as B,Gr as C,zr as D,Wr as E,Yr as F,Xr as G,Ge as H,ze as I,Jr as J,Zr as K,Qr as L,et as M,rt as N,tt as O,nt as P,ot as Q,We as R,it as S,Lt as T,Ht as U,Kt as V,qt as W,Ut as X,Vt as Y,Wt as Z,Yt as _};
|
|
8
|
-
//# sourceMappingURL=chunk-
|
|
8
|
+
//# sourceMappingURL=chunk-FR7ULTM4.js.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{a as A,c as b,d as C,e as E,k as S,m as x}from"./chunk-
|
|
1
|
+
import{a as A,c as b,d as C,e as E,k as S,m as x}from"./chunk-2SBTXR6C.js";import{lb as w,mb as R,nb as k}from"./chunk-ZA5NS3PL.js";import{Ka as v,pa as p,sa as g,ta as a}from"./chunk-KCVSSONY.js";import{_ as O,kd as B}from"./chunk-3TXEWHQX.js";import{Pe as H,Ue as u,Ve as y,fh as I}from"./chunk-SJWIPGZW.js";import{A as c,C as f}from"./chunk-K672XXGQ.js";function _(r,e){if(typeof r!="string")return;let o=Number.parseInt(r,10);if(!/^\d+$/.test(r.trim())||!Number.isSafeInteger(o))throw new f(`history-compact ${e} must be a non-negative integer.`,c.USAGE);return o}async function D(r,e,o){let t=p(o),s=Date.now(),i=await O(a(e,"ids")),l=i===void 0?void 0:B(i),m=_(e.allOver,"--all-over"),d=_(e.minEntries,"--min-entries");if(e.closed===!0&&e.allStreams===!0)throw new f("history-compact: --closed and --all-streams are mutually exclusive; pick one lifecycle scope.",c.USAGE);let n=e.closed===!0?"closed":e.allStreams===!0?"all-streams":void 0;if((l!==void 0||m!==void 0||n!==void 0)&&typeof e.before=="string")throw new f("history-compact: --before applies only in single-id mode (bulk mode always compacts full streams).",c.USAGE);if(b(r,{ids:l,allOver:m,scope:n}),r!==void 0&&d!==void 0)throw new f("history-compact: --min-entries applies only in bulk mode (single-id mode compacts the named stream).",c.USAGE);if(r===void 0){let h=await C({ids:l,scope:n,allOver:m,minEntries:d,dryRun:e.dryRun===!0,author:a(e,"author"),message:a(e,"message"),force:!!e.force},t);u(h,t),h.totals.items_errored>0&&(process.exitCode=c.GENERIC_FAILURE)}else{let h=await A(r,{before:a(e,"before"),dryRun:e.dryRun===!0,author:a(e,"author"),message:a(e,"message"),force:!!e.force},t);u(h,t)}t.profile&&y(`profile:command=history-compact took_ms=${Date.now()-s}`)}async function N(r,e,o,t){let s=p(t),i=Date.now(),l=await x(r,e,{author:a(o,"author"),message:a(o,"message"),force:!!o.force},s);await v(s,l),u(l,s),s.profile&&y(`profile:command=restore took_ms=${Date.now()-i}`)}async function F(r,e){let o=p(e),t=await S({verify:a(r,"verify"),output:a(r,"output"),hashAlgorithm:a(r,"hashAlgorithm")},o);"format"in t?(I(t),o.quiet||H(`${JSON.stringify(t,null,2)}
|
|
2
2
|
`)):u(t,o),"ok"in t&&!t.ok&&(process.exitCode=c.GENERIC_FAILURE)}function ee(r,e){r.command(e?"attest":"history-attest",{hidden:!e}).summary("Export or verify history proof.").option("--verify <file>","Compare retained streams with a detached JSON proof").option("--output <file>","Create a proof file and return a compact receipt").option("--hash-algorithm <name>","Bundle digest algorithm: sha256 (default) or sha512").description("Export exact-byte history commitments, or verify an independently retained proof without tracker writes.").action(F),r.command("restore",{hidden:!e}).summary("Restore a version.").argument("<id>","Item id").argument("<target>","Restore target timestamp or version number").option("--author <value>","Mutation author").option("--message <value>","History message").option("--force","Force ownership/lock override").description("Restore an item to an earlier timestamp or version.").action(N),r.command(e?"redact":"history-redact",{hidden:!e}).summary("Redact sensitive values.").argument("<id>","Item id").option("--literal <value>","Literal; repeatable",g).option("--regex <value>","Raw RegExp source (repeatable; e.g. /var/[a-z]+) or /pattern/flags. Leading-slash input is a literal only when the final unescaped slash is followed by supported JavaScript flag letters or nothing.",g).option("--replacement <value>",'Default: "[redacted]"').option("--dry-run","Preview; no item/history edits").option("--author <value>","Author").option("--message <value>","Audit marker message").option("--force","Override owner/lock").description("Redact and reseal item history.").action(async(o,t,s)=>{let i=p(s),l=Date.now(),m=Array.isArray(t.literal)?t.literal:void 0,d=Array.isArray(t.regex)?t.regex:void 0,n=await E(o,{literal:m,regex:d,replacement:a(t,"replacement"),dryRun:t.dryRun===!0,author:a(t,"author"),message:a(t,"message"),force:!!t.force},i);n.changed&&!n.dry_run&&await v(i,n),u(n,i),i.profile&&y(`profile:command=history-redact took_ms=${Date.now()-l}`)}),r.command(e?"repair":"history-repair",{hidden:!e}).summary("Repair drift.").argument("[id]","Item id (omit with --all)").option("--salvage-tail","Recover invalid tail; requires verified prefix").option("--append-only","Bridge breaks; never rewrite entries").option("--all","Scan every stream for drift and repair each drifted stream in one audited pass").option("--dry-run","Preview the re-anchor impact without writing the history file").option("--normalize-provenance","Remove invalid provenance; return aggregate-only evidence").option("--author <value>","Mutation author").option("--message <value>","Audit history message for the repair marker entry").option("--force","Force ownership/lock override").description("Re-anchor a drifted item history chain (recompute hashes, reconcile with the on-disk item) and record an audit marker. Use --all to repair every drifted stream.").action(async(o,t,s)=>{let i=p(s),l=Date.now(),m=t.all===!0;R(o,m);let d={dryRun:t.dryRun===!0,author:a(t,"author"),message:a(t,"message"),force:!!t.force,normalizeProvenance:t.normalizeProvenance===!0,salvageTail:t.salvageTail===!0,appendOnly:t.appendOnly===!0};if(m){let n=await k(d,i);u(n,i),n.totals.failed>0&&(process.exitCode=c.GENERIC_FAILURE)}else{let n=await w(o,d,i);u(n,i)}i.profile&&y(`profile:command=history-repair took_ms=${Date.now()-l}`)}),r.command(e?"compact":"history-compact",{hidden:!e}).summary("Compact streams.").argument("[id]","Item id (omit when using a bulk selector)").option("--before <value>","Compact entries strictly before this version number or ISO timestamp (single-id mode only)").option("--ids <value>","Bulk IDs: comma/newline text, - stdin, or @path file").option("--all-over <n>","Bulk: compact every stream with more than N entries").option("--closed","Bulk: compact only closed (terminal) items' streams").option("--all-streams","Bulk: compact every history stream regardless of lifecycle state").option("--min-entries <n>","Bulk: skip streams with at most N entries (already compact; default 3)").option("--dry-run","Preview compaction impact without writing the history file").option("--author <value>","Mutation author").option("--message <value>","Audit history message for the compaction marker entry").option("--force","Force ownership/lock override").description("Compact item history streams into a synthetic baseline plus retained tail entries. Pass an item id for one stream, or a bulk selector (--ids/--all-over/--closed/--all-streams) to compact many.").action(D)}export{ee as a};
|
|
3
|
-
//# sourceMappingURL=chunk-
|
|
3
|
+
//# sourceMappingURL=chunk-HXQ3OHQR.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{c as re,d as x,e as Pt,f as gi,g as qe,h as _n,i as _i,j as yi,l as ce,m as ot,n as Rt,o as wi,p as Nt,q as vi,u as ki}from"./chunk-
|
|
1
|
+
import{c as re,d as x,e as Pt,f as gi,g as qe,h as _n,i as _i,j as yi,l as ce,m as ot,n as Rt,o as wi,p as Nt,q as vi,u as ki}from"./chunk-DCWGM7CY.js";import{i as mi,n as fi,p as hi}from"./chunk-AOTI76Q6.js";import{f as ui}from"./chunk-OGVSGXQX.js";import{_ as Ct}from"./chunk-KCVSSONY.js";import{$a as ai,Aa as it,Ba as Qr,Ca as ei,Da as ne,Ea as ze,Fa as ti,Ga as se,R as Rr,Rc as hn,Xa as ri,Ya as ii,Za as Ee,_a as oi,ac as li,db as si,ea as Se,jb as ci,mb as It,nb as Ot,qb as Re,vb as di,wb as fn,ya as Zr,za as Pe}from"./chunk-3TXEWHQX.js";import{H as Je,a as Kr,b as Vr,d as un,e as Xr,f as Yr,g as be,k as ni,n as fe,p as mn,u as A,v as he}from"./chunk-KXTKLDKD.js";import{Bb as Mr,Fg as pn,Hg as At,Ib as q,Jg as ke,Lg as xe,Nb as Ur,O as Y,Og as Wr,Qg as Tt,Rf as ve,Rg as Br,Sg as Hr,Wf as Gr,Zf as zr,_ as Cr,_f as Jr,a as bt,ah as W,b as vr,c as cn,d as dn,e as ln,fb as Q,g as kr,h as xr,ja as Pr,k as br,lh as H,ng as qr,qg as Ce,r as Er}from"./chunk-SJWIPGZW.js";import{e as $r,f as Ar,g as B,o as M,p as Tr,q as Oe,r as Ir}from"./chunk-GSLOAEY2.js";import{h as pi,i as gn}from"./chunk-NVYDPNQP.js";import{Q as I,n as Sr,v as Or,x as ae}from"./chunk-VCXQ6A35.js";import{$ as Fr,I as O,K as Nr,L as Ue,M as Ge,N as Lr,O as jr,P as V,R as Dr,V as K,Z,ba as rt,d as Et,da as $t}from"./chunk-TE6FBDHP.js";import{A as h,C as f,E as S,F as St,G as Me,H as U,L as me,a as _r,d as xt,t as sn,v as yr,y as wr}from"./chunk-K672XXGQ.js";import{AsyncLocalStorage as Ys}from"node:async_hooks";import xi from"node:path";var bi=new Ys;function Si(e,t){return bi.run({...e,pmRoot:xi.resolve(e.pmRoot)},t)}function af(e,t){let n=bi.getStore();return n!==void 0&&n.pmRoot===xi.resolve(e)&&n.transactionId===t?n.step:void 0}import{mkdir as Zs,readFile as Qs}from"node:fs/promises";import $i from"node:path";import{createHash as ec}from"node:crypto";var yn=class extends Error{constructor(t="Workspace transaction interrupted"){super(t),this.name="WorkspaceTransactionInterruptedError"}},Ai="sdk-workspace-transaction",Ti=/^[a-zA-Z0-9._-]+$/,Ii=30,Oi=3e3;function bn(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n||!Ti.test(n))throw new TypeError(`${t} must match [a-zA-Z0-9._-]+`);return n}function wn(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n)throw new TypeError(`${t} must be non-empty`);return n}function Sn(e){return{pmRoot:wn(e.pmRoot,"Transaction pmRoot"),transactionId:bn(e.transactionId,"Transaction id"),author:wn(e.author,"Transaction author")}}function jt(e,t,n){let r=e??t;if(!Number.isInteger(r)||r<=0)throw new TypeError(`${n} must be a positive integer`);return r}function Ci(e,t){return $i.join(e,"transactions","sdk",`${t}.json`)}async function de(e,t){t.updatedAt=I();let n=Ci(e,t.transactionId);await Zs($i.dirname(n),{recursive:!0}),await me(n,`${JSON.stringify(t,null,2)}
|
|
2
2
|
`)}function tc(e){return Number.isInteger(e.attempt)&&typeof e.author=="string"&&typeof e.createdAt=="string"&&typeof e.updatedAt=="string"&&nc(e)}function nc(e){let t=e.abandonment;return t===void 0?e.schemaVersion===1&&e.status!=="abandoned":e.schemaVersion!==2||t===null||typeof t!="object"||e.status==="committed"?!1:typeof t.reason=="string"&&t.reason.trim().length>0&&typeof t.author=="string"&&t.author.trim().length>0&&(t.supersededBy===void 0||typeof t.supersededBy=="string"&&Ti.test(t.supersededBy)&&t.supersededBy!==e.transactionId)}function Ne(e){return Object.assign(Object.create(null),e)}function Pi(e,t){try{let n=JSON.stringify(e,(r,i)=>{if(typeof i=="number"&&!Number.isFinite(i))throw new TypeError(`${t} contains a non-finite number`);if(i===void 0||typeof i=="function"||typeof i=="symbol")throw new TypeError(`${t} contains a non-JSON value`);return i});return JSON.parse(n)}catch(n){throw new TypeError(`${t} must be JSON serializable`,{cause:n})}}function vn(e,t){return e===void 0?void 0:Pi(e,t)}function kn(e,t,n,r){let i=vn(n,r);i===void 0?delete e[t]:e[t]=i}function Ei(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function xn(e,t){return Array.isArray(e)&&new Set(e).size===e.length&&e.every(n=>typeof n=="string"&&t.includes(n))}function rc(e,t){if(!xn(e.startedStepIds,t)||!xn(e.completedStepIds,t)||!Ei(e.results)||!Ei(e.compensationData))return!1;let n=e.startedStepIds,r=new Set(n),i=e.completedStepIds,o=new Set(i);return Object.keys(e.compensationData).some(a=>!r.has(a))||Object.keys(e.results).some(a=>!o.has(a))?!1:e.status==="committed"?t.every(a=>o.has(a)):!["compensated","abandoned"].includes(e.status??"")||o.size===0&&r.size===0}function Lt(e,t){return new f(`Workspace transaction ${e} journal is invalid (${t})`,h.CONFLICT,{code:"transaction_journal_invalid",required:"A valid durable journal is required before transaction recovery can continue.",why:"Corrupt journal data cannot establish which steps applied or still require compensation.",nextSteps:["Preserve the journal and inspect its integrity or restore a verified backup before retrying.","Do not switch to a new transaction id to bypass an unreadable journal; previously applied work may remain."]})}function Ri(e){return new f(`Workspace transaction ${e} journal does not match the supplied plan`,h.CONFLICT,{code:"transaction_plan_mismatch",required:"Replay the original plan or safely abandon the interrupted transaction before replacing it.",why:"A journal records the plan it is resuming; applying a different plan under the same id could skip or duplicate steps.",nextSteps:["Re-run with the original document to resume or replay it.","For item batches use client.itemTransactions.status(transactionId), then client.itemTransactions.abandon(transactionId, { reason }) before committing a changed plan with a new transactionId.","Run pm ops gc --scope transactions --dry-run to inspect retention; active and explicitly abandoned journals remain protected."]})}function ic(e,t,n){return n===void 0||e.abandonment!==void 0||e.status==="compensated"||t.length===n.length&&t.every((r,i)=>r===n[i])}function oc(e,t,n){let r;try{r=JSON.parse(e)}catch{throw Lt(t,"invalid JSON")}if(!r||typeof r!="object"||Array.isArray(r))throw Lt(t,"expected an object");let i=r;if(!((i.schemaVersion===1||i.schemaVersion===2)&&i.transactionId===t))throw Lt(t,"schema version or transaction id does not match the journal file");let a=i.stepIds;if(!Array.isArray(a)||!xn(a,a)||!rc(i,a)||!tc(i)||typeof i.status!="string"||!["applying","compensating","compensated","committed","abandoned"].includes(i.status))throw Lt(t,"invalid lifecycle, metadata, status or step ids");if(!ic(i,a,n))throw Ri(t);return{...i,results:Ne(i.results),compensationData:Ne(i.compensationData)}}async function ac(e,t,n,r,i){let o=i,a=o!==void 0;if(o?.status==="compensating"&&await En(e,o),o===void 0||o.status==="compensated"){let s=I();o={schemaVersion:1,transactionId:t,author:n,status:"applying",attempt:(o?.attempt??0)+1,createdAt:o?.createdAt??s,updatedAt:s,stepIds:r,startedStepIds:[],completedStepIds:[],results:Ne(),compensationData:Ne(),...e.recoveryData===void 0?{}:{recoveryData:Pi(e.recoveryData,"Transaction recovery data")}},await de(e.pmRoot,o),await ge(e,o,"prepared")}return{journal:o,recovered:a}}async function sc(e,t,n){try{await cc(t,e.steps),await de(e.pmRoot,t);let r=new Set(t.completedStepIds),i=new Set(t.startedStepIds);for(let o of e.steps){if(r.has(o.id))continue;let a=await o.inspect(),s=vn(a.result,`Step ${o.id} result`);if(a.state!=="applied"){let c=await o.prepareCompensation?.();kn(t.compensationData,o.id,c,`Step ${o.id} compensation data`),i.add(o.id),t.startedStepIds=e.steps.map(l=>l.id).filter(l=>i.has(l)),await de(e.pmRoot,t);let d=await o.apply();s=vn(d,`Step ${o.id} result`)}await ge(e,t,"step_applied",o.id),r.add(o.id),t.completedStepIds=e.steps.map(c=>c.id).filter(c=>r.has(c)),kn(t.results,o.id,s,`Step ${o.id} result`),await de(e.pmRoot,t),await ge(e,t,"step_recorded",o.id)}return await ge(e,t,"committing"),t.status="committed",await de(e.pmRoot,t),await ge(e,t,"committed"),{transactionId:t.transactionId,status:"committed",recovered:n,results:Ne(t.results)}}catch(r){if(r instanceof yn||t.status==="committed")throw r;try{await En(e,t)}catch(i){throw new AggregateError([r,i],`Workspace transaction failed and compensation failed: ${String(i)}`,{cause:i})}throw r}}async function Dt(e,t,n){try{return oc(await Qs(Ci(e,t),"utf8"),t,n)}catch(r){if(r!==null&&typeof r=="object"&&"code"in r&&Me(r))return;throw r}}async function ge(e,t,n,r){await e.onTransition?.({transactionId:t.transactionId,attempt:t.attempt,transition:n,...r===void 0?{}:{stepId:r}})}async function cc(e,t){let n=new Set,r=Ne();for(let i of t){let o=await i.inspect();o.state==="applied"&&(n.add(i.id),kn(r,i.id,o.result,`Step ${i.id} result`))}e.results=r,e.completedStepIds=t.map(i=>i.id).filter(i=>n.has(i))}async function En(e,t){t.status="compensating",await de(e.pmRoot,t),await ge(e,t,"compensating");let n=new Set(t.completedStepIds),r=new Set(t.startedStepIds);for(let i of[...e.steps].reverse()){if(!r.has(i.id)&&!n.has(i.id))continue;let o;try{let a=(await i.inspect()).state;o=r.has(i.id)&&(a==="applied"||a==="pending"&&i.compensatePending===!0)}catch{o=r.has(i.id)}o&&(await ge(e,t,"step_compensating",i.id),await Si({pmRoot:e.pmRoot,transactionId:t.transactionId,step:i},()=>i.compensate(t.compensationData[i.id]))),n.delete(i.id),r.delete(i.id),t.completedStepIds=e.steps.map(a=>a.id).filter(a=>n.has(a)),t.startedStepIds=e.steps.map(a=>a.id).filter(a=>r.has(a)),delete t.results[i.id],delete t.compensationData[i.id],await de(e.pmRoot,t),await ge(e,t,"step_compensated",i.id)}t.status="compensated",await de(e.pmRoot,t),await ge(e,t,"compensated")}async function Ni(e){let{pmRoot:t,transactionId:n,author:r}=Sn(e),i=jt(e.lockTtlSeconds,Ii,"Transaction lock TTL"),o=jt(e.lockWaitMs,Oi,"Transaction lock wait"),a=[...e.steps];if(a.length===0)throw new TypeError("Workspace transaction requires at least one step");let s=a.map(l=>{let p=bn(l.id,"Transaction step id");if(p!==l.id)throw new TypeError("Transaction step id must not contain surrounding whitespace");return p});if(new Set(s).size!==s.length)throw new TypeError("Workspace transaction step ids must be unique");let c={...e,pmRoot:t,transactionId:n,author:r,steps:a,lockTtlSeconds:i,lockWaitMs:o},d=await Q(t,Ai,i,r,!1,!1,o);try{let l=await Dt(t,n,s);if(l?.status==="abandoned"||l?.abandonment!==void 0)throw Li(l);let p=l!==void 0;if(l?.status==="committed")return{transactionId:n,status:"committed",recovered:!0,results:Ne(l.results)};let u=await ac(c,n,r,s,l);return await sc(c,u.journal,p||u.recovered)}finally{await d()}}function Li(e){let t=e.status!=="abandoned",n=e.abandonment.supersededBy,r=n===void 0?`Retry abandonment without supersededBy to finish retirement of ${JSON.stringify(e.transactionId)}.`:`Retry abandonment with supersededBy ${JSON.stringify(n)} to finish retirement of ${JSON.stringify(e.transactionId)}.`;return new f(t?`Transaction ${e.transactionId} retirement is incomplete`:`Transaction ${e.transactionId} has been abandoned`,h.CONFLICT,{code:"transaction_abandoned",required:t?r:"Use a new transactionId for the replacement plan.",why:t?"Forward replay is fenced, but the recorded retirement has not finished. Preserve its replacement identity.":"An explicitly retired transaction identity cannot be resumed.",...t?{retirement:{state:"pending",superseded_by:n??null},nextSteps:[r]}:{}})}async function wf(e,t){let n=Sn({pmRoot:e,transactionId:t,author:"reader"});return Dt(n.pmRoot,n.transactionId)}function dc(e){return ec("sha256").update(JSON.stringify(e.stepIds)).digest("hex")}async function vf(e){let t=Sn(e),n=wn(e.reason,"Abandonment reason"),r=e.supersededBy===void 0?void 0:bn(e.supersededBy,"Replacement transaction id");if(r===t.transactionId)throw new TypeError("Replacement transaction id must differ from the abandoned id");let i=jt(e.lockTtlSeconds,Ii,"Transaction lock TTL"),o=jt(e.lockWaitMs,Oi,"Transaction lock wait"),a=await Q(t.pmRoot,Ai,i,t.author,!1,!1,o);try{let s=await Dt(t.pmRoot,t.transactionId);if(s===void 0)throw new f(`Transaction ${t.transactionId} was not found`,h.NOT_FOUND);if(s.status==="committed")throw new f(`Transaction ${t.transactionId} is committed and cannot be abandoned`,h.CONFLICT,{code:"transaction_committed",required:"Plan a separate explicit corrective mutation.",why:"Recovery cannot silently undo committed work."});if(s.abandonment!==void 0&&s.abandonment.supersededBy!==r)throw Li(s);if(s.status==="abandoned")return s;let c=e.resolveSteps(structuredClone(s));if(JSON.stringify(c.map(d=>d.id))!==JSON.stringify(s.stepIds))throw Ri(t.transactionId);if(s.abandonment===void 0){if(r!==void 0&&await Dt(t.pmRoot,r)!==void 0)throw new f(`Replacement transaction ${r} already exists`,h.CONFLICT);s.schemaVersion=2,s.abandonment={reason:n,author:t.author,...r===void 0?{}:{supersededBy:r}},await de(t.pmRoot,s)}return s.status!=="compensated"&&await En({...e,...t,steps:c},s),await lc(s,t.pmRoot,i,o),s.status="abandoned",await de(t.pmRoot,s),s}finally{await a()}}async function lc(e,t,n,r){let i=dc(e);if((await Ur(Vr(t),Kr)).some(s=>s.op==="transaction_abandon"&&s.context?.transaction_id===e.transactionId&&s.context?.attempt===e.attempt&&s.context?.plan_digest===i))return;let a=e.abandonment;await Xr({pmRoot:t,author:a.author,lockTtlSeconds:n,lockWaitMs:r,op:"transaction_abandon",message:a.reason,context:{transaction_id:e.transactionId,attempt:e.attempt,plan_digest:i,...a.supersededBy===void 0?{}:{superseded_by:a.supersededBy}}})}import pc from"node:fs/promises";import uc from"node:path";function $n(e){return uc.join(e,"extension-migrations.json")}function ji(e,t){let n=e.definition.id;return typeof n=="string"&&n.trim().length>0?n.trim():`migration-${String(t+1).padStart(3,"0")}`}function Di(e,t){return`${e.layer}:${e.name}:${t}`}async function mc(e){let t=$n(e);if(!await S(t))return{version:1,updated_at:"",entries:[]};let n=JSON.parse(await pc.readFile(t,"utf8"));return{version:1,updated_at:typeof n.updated_at=="string"?n.updated_at:"",entries:Array.isArray(n.entries)?n.entries.filter(r=>typeof r?.key=="string"&&(r.status==="applied"||r.status==="failed")):[]}}async function fc(e,t){let n=await mc(e),r=new Map(n.entries.map(i=>[i.key,i]));return t.forEach((i,o)=>{let a=ji(i,o),s=r.get(Di(i,a));s&&(i.definition.status=s.status,s.status==="failed"?i.definition.reason=s.error:(delete i.definition.reason,delete i.definition.error,delete i.definition.message))}),n}async function hc(e){let t=await fc(e.pmRoot,e.migrations),n=new Map(t.entries.map(l=>[l.key,l])),r=[],i=!1,o=e.migrations.map((l,p)=>({migration:l,index:p})).filter(({migration:l})=>e.scope===void 0||l.layer===e.scope);for(let{migration:l,index:p}of o){let u=ji(l,p),_=Di(l,u),g=n.get(_),w=String(l.definition.status??"pending").toLowerCase(),m=g?.status??(w==="applied"||w==="failed"?w:"pending");if(m==="applied"){r.push({key:_,layer:l.layer,extension:l.name,id:u,before:m,outcome:"skipped"});continue}if(e.dryRun===!0){r.push({key:_,layer:l.layer,extension:l.name,id:u,before:m,outcome:"pending"});continue}let y=l.runtime_definition?.run??l.definition.run;if(typeof y!="function"){r.push({key:_,layer:l.layer,extension:l.name,id:u,before:m,outcome:"pending"});continue}let v=new Date().toISOString();try{await Promise.resolve(y({id:u,command:"migration",layer:l.layer,extension:l.name,pm_root:e.pmRoot,status:m}));let k={key:_,layer:l.layer,extension:l.name,id:u,status:"applied",attempted_at:v};n.set(_,k),l.definition.status="applied",delete l.definition.reason,delete l.definition.error,delete l.definition.message,r.push({key:_,layer:l.layer,extension:l.name,id:u,before:m,outcome:"applied"}),i=!0}catch(k){let b=k instanceof Error?k.message:String(k),L={key:_,layer:l.layer,extension:l.name,id:u,status:"failed",attempted_at:v,error:b};n.set(_,L),l.definition.status="failed",l.definition.reason=b,r.push({key:_,layer:l.layer,extension:l.name,id:u,before:m,outcome:"failed",error:b}),i=!0}}if(i){let l=await A(e.pmRoot),p={version:1,updated_at:new Date().toISOString(),entries:[...n.values()].sort((u,_)=>u.key.localeCompare(_.key))};await be({pmRoot:e.pmRoot,filePath:$n(e.pmRoot),raw:`${JSON.stringify(p,null,2)}
|
|
3
3
|
`,op:"extension_migrations_apply",author:e.author,lockTtlSeconds:l.locks.ttl_seconds,lockWaitMs:l.locks.wait_ms})}let a=r.filter(l=>l.outcome==="pending").length,s=r.filter(l=>l.outcome==="applied").length,c=r.filter(l=>l.outcome==="skipped").length,d=r.filter(l=>l.outcome==="failed").length;return{ok:d===0,dry_run:e.dryRun===!0,state_path:$n(e.pmRoot),total:r.length,pending_count:a,applied_count:s,skipped_count:c,failed_count:d,migrations:r}}async function Fi(e){let t=await A(e.resolvedRoots.settings_root),n=await ke({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),r=await xe(n);e.warnings.push(...n.warnings,...r.warnings);let i=await hc({pmRoot:e.resolvedRoots.pm_root,migrations:r.registrations.migrations,author:typeof e.global.author=="string"&&e.global.author.trim().length>0?e.global.author.trim():"pm-extension-migration",dryRun:e.options.dryRun===!0,...e.scope==="global"?{scope:"global"}:{}});return e.withResult({migration:i,load_failure_count:n.failed.length,activation_failure_count:r.failed.length},i.ok)}var gc=[["beforeCommand","before_command"],["beforeMutation","before_mutation"],["afterCommand","after_command"],["onWrite","on_write"],["onRead","on_read"],["onIndex","on_index"]];function We(e,t={}){let n=new Set;t.extensionName!==void 0&&n.add(Tt(t.extensionName));for(let m of t.extensionNames??[])n.add(Tt(m));let r=m=>n.size===0||n.has(Tt(m)),i=(m,y)=>Mi(m.filter(v=>r(v.name)).map(y)),o=(m,y)=>Mi(m.filter(v=>r(v.name)).flatMap(y)),{registrations:a,commands:s,parsers:c,preflight:d,services:l,renderers:p,hooks:u}=e,_=o(a.relationship_kinds??[],m=>m.definitions.map(y=>y.kind)),g=p.overrides.filter(m=>r(m.name)&&((m.commands?.length??0)>0||m.resultDiscriminator!==void 0)).map(m=>({format:m.format,commands:[...m.commands??[]],result_discriminator:m.resultDiscriminator!==void 0})).sort((m,y)=>m.format.localeCompare(y.format)),w=i(a.assurance_providers??[],m=>m.definition.id);return{capabilities:Br(e,t),commands:i(a.commands,m=>m.command),command_overrides:i(s.overrides,m=>m.command),command_handlers:i(s.handlers,m=>m.command),hooks:gc.filter(([m])=>u[m].some(y=>r(y.name))).map(([,m])=>m),flag_commands:i(a.flags,m=>m.target_command),item_types:o(a.item_types,m=>m.types.map(y=>y.name)),item_fields:o(a.item_fields,m=>m.fields.map(y=>y.name)),..._.length>0?{relationship_kinds:_}:{},migrations:o(a.migrations,m=>typeof m.definition.id=="string"?[m.definition.id]:[]),profiles:i(a.profiles,m=>m.profile.name),importers:i(a.importers,m=>m.importer),exporters:i(a.exporters,m=>m.exporter),search_providers:i(a.search_providers,m=>m.definition.name),vector_store_adapters:i(a.vector_store_adapters,m=>m.definition.name),...w.length>0?{assurance_providers:w}:{},parser_overrides:i(c.overrides,m=>m.command),service_overrides:i(l.overrides,m=>m.service),renderer_overrides:i(p.overrides,m=>m.format),...g.length>0?{renderer_ownership:g}:{},preflight_overrides:d.overrides.filter(m=>r(m.name)).length,preflight_ownership:d.overrides.filter(m=>r(m.name)).map(m=>({commands:[...m.commands??[]]}))}}function Mi(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}var at={type:"string",minLength:1,maxLength:128,pattern:"\\S"},Ft={type:"array",minItems:1,maxItems:cn,items:at},Ui={...Ft,items:{...at,pattern:"^(?!(?:.*\\.)?(?:__proto__|constructor|prototype)(?:\\.|$))[a-zA-Z_][a-zA-Z0-9_]*(?:\\.[a-zA-Z_][a-zA-Z0-9_]*){0,7}$"}},_c={type:"object",additionalProperties:!1,required:["id","rule"],properties:{id:{type:"string",minLength:1,maxLength:128,pattern:"^[a-zA-Z0-9][a-zA-Z0-9._-]*$"},description:{type:"string",minLength:1,maxLength:500,pattern:"\\S"},effect:{enum:["advise","warn","refuse"]},subject:{type:"object",additionalProperties:!1,properties:{...Object.fromEntries(["types","tags","statuses","operations","parents"].map(e=>[e,Ft])),dependency:{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:at,id:at}}}},rule:{oneOf:[{type:"object",additionalProperties:!1,required:["kind","fields"],properties:{kind:{const:"require_fields"},fields:Ui}},{type:"object",additionalProperties:!1,required:["kind","authors"],properties:{kind:{const:"authors"},authors:Ft}},...["field_writers","approval"].map(e=>({type:"object",additionalProperties:!1,required:["kind","fields","authors"],properties:{kind:{const:e},fields:Ui,authors:Ft}})),{type:"object",additionalProperties:!1,required:["kind","allowed"],properties:{kind:{const:"transition"},allowed:{type:"array",maxItems:cn,items:{type:"array",minItems:2,maxItems:2,items:at}}}}]}}},Pf={$schema:"https://json-schema.org/draft/2020-12/schema",title:"pm workflow policy registry",type:"object",additionalProperties:!1,required:["version","policies"],properties:{version:{const:1},enforcement:{enum:["advise","refuse"],default:"advise"},policies:{type:"array",maxItems:vr,items:_c}}};async function jf(e,t,n,r){let i=await Ee(e).catch(()=>null);return i===null?{check:{name:"completeness",status:"error",ok:!1,details:{policy_registry_readable:!1,policy_registry_path:"schema/policies.json",remediation_hint:"Repair schema/policies.json, then rerun pm validate."}},warnings:["validate_completeness_policy_registry_unreadable"]}:Gi(i,t,n,r)}function yc(e,t,n){return e===0?"undeclared":t===0?"empty":n===0?"inapplicable":n===t?"covered":"partial"}function Gi(e,t,n=5,r=!1){let i=[],o=new Map,a=e.policies.filter(m=>m.rule.kind==="require_fields"),s=a.filter(m=>m.subject?.operations===void 0),c=new Set,d=0,l=0,p=0,u=0,_=0,g=br(e);for(let m of t){let y=g({operation:"",author:"",before:m,after:m,completeness_only:!0});d+=+(y.decisions.length>0),l+=y.decisions.length,y.decisions.forEach(b=>c.add(b.policy_id));let v=y.decisions.filter(b=>!b.satisfied);if(v.length===0)continue;u+=1;let k=o.get(m.type)??{items:0,violations:0,missing_fields:0};k.items+=1;for(let b of v)p+=1,k.violations+=1,k.missing_fields+=b.missing_fields.length,b.effect==="refuse"&&(_+=1),i.length<n&&i.push({id:m.id,type:m.type,status:m.status,decision:b});o.set(m.type,k)}let w=r||_>0?"error":p>0?"warn":"ok";return{check:{name:"completeness",status:w,ok:w==="ok",details:{scope:"operation_independent_require_fields",declared_requirement_count:a.length,state_requirement_count:s.length,applicable_requirement_count:c.size,requirement_application_count:l,governed_items:d,ungoverned_items:t.length-d,contract_status:yc(a.length,t.length,d),applied_policy_ids:[...c].sort().slice(0,Math.max(0,n)),applied_policy_ids_truncated:c.size>Math.max(0,n),checked_items:t.length,incomplete_items:u,violation_count:p,refused_violations:_,missing_by_type:Object.fromEntries(o),violations:i,violations_truncated:i.length<p,enforcement:e.enforcement}},warnings:[...p>0?[`validate_completeness_missing_fields:${p}`]:[],...r?["validate_completeness_source_incomplete"]:[]]}}import wc from"node:path";function vc(){return{version:1,enforcement:"advise",policies:[...[["Epic",["goal","objective","body"]],["Story",["description","value","acceptance_criteria"]],["Decision",["body","resolution"]],["Feature",["acceptance_criteria","expected_result"]],["Task",["description"]],["Issue",["repro_steps","expected_result"]],["Chore",["description"]]].map(([t,n])=>({id:`completeness-${t.toLowerCase()}`,effect:"advise",description:`Evidence expected when ${t} work reaches completion.`,subject:{types:[t],statuses:["closed"]},rule:{kind:"require_fields",fields:[...n]}})),{id:"completeness-resolution",effect:"advise",subject:{statuses:["closed"]},rule:{kind:"require_fields",fields:["resolution","expected_result","actual_result"]}}]}}function qi(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{throw new f("Policy definition must be valid JSON.",h.USAGE)}if(typeof t!="object"||t===null||Array.isArray(t))throw new f("Policy definition must be an object.",h.USAGE);return t}async function kc(e,t){let n=M(process.cwd(),e.path);await Je(n);let r=await A(n);return{pmRoot:n,settings:r,author:q(t,r.author_default)}}function zi(e,t,n,r){if(e==="policy-mode")return ln({...n,enforcement:t});let i=n.policies.filter(s=>s.id!==t);if(e==="policy-remove")return{...n,policies:i};let o=dn(r.definition),a=ln({...n,policies:[...i,o].sort((s,c)=>s.id.localeCompare(c.id))});if(Buffer.byteLength(`${JSON.stringify(a,null,2)}
|
|
4
4
|
`)>ri)throw new f("Policy registry exceeds its byte ceiling.",h.USAGE);return a}async function Ji(e,t,n,r){if(n.dryRun)return{policy_result:!0,action:e,changed:!1,result:zi(e,t,await Ee(r.pmRoot),n)};let i=await Yr({pmRoot:r.pmRoot,filePath:wc.join(r.pmRoot,"schema","policies.json"),op:`schema:${e}`,author:r.author,message:n.message,lockTtlSeconds:r.settings.locks.ttl_seconds,lockWaitMs:r.settings.locks.wait_ms,mutate(o){let a=zi(e,t,ii(o),n);return{raw:`${JSON.stringify(a,null,2)}
|
|
@@ -66,4 +66,4 @@ Agent guidance check
|
|
|
66
66
|
`),X.write(`Telemetry helps improve reliability. The choice applies to this CLI install; change it with pm config global set telemetry-tracking.
|
|
67
67
|
`);let l=await n.question(`Enable telemetry for this CLI install? [${t?"Y/n":"y/N"}] `);d=js(l,t)}return X.write(`
|
|
68
68
|
`),{prefix:o,preset:c,telemetry_enabled:d}}finally{n.close()}}function Um(e){return{presetFromOption:mr(e.preset),useDefaults:e.defaults===!0,authorFromOption:Ps(e.author),installBundledPackages:e.withPackages===!0,agentGuidanceMode:Ls(e.agentGuidance),typePreset:Cs(e.typePreset)}}function Gm(e){let t=[];return e.prefixArg!==void 0&&e.settings.id_prefix!==e.normalizedPrefix&&t.push("id_prefix"),e.presetFromOption!==void 0&&e.settings.governance.preset!==e.presetFromOption&&t.push("governance_preset"),e.authorFromOption!==void 0&&e.settings.author_default!==e.authorFromOption&&t.push("author_default"),t}function zm(e,t,n,r){if(t.length===0||n)return;let i=r.discovery==="ancestor";throw new f(`${i?`No tracker exists in ${r.requested_cwd}; pm init found an ancestor tracker at ${r.tracker_root}. `:""}Refusing to update existing tracker settings at ${e} without --force.`,h.USAGE,{code:"init_existing_settings_requires_force",type:"urn:pm-cli:error:init_existing_settings_requires_force",required:`--force for ${t.join(", ")}`,why:i?"Ancestor discovery is useful for normal commands, but init must make the selected existing workspace explicit before changing its identity or policy settings.":"pm init is safe to rerun, but changing id prefix, governance preset, or default author on an existing tracker can corrupt long-lived project context when an agent meant to initialize a sandbox path.",resolved_path:r.tracker_root,requested_path:r.requested_cwd,suggested_path:r.suggested_current_tracker_root,examples:["pm init --yes","pm init ./sandbox-pm --yes",...i?['pm init <name> --yes --pm-path "$PWD/.agents/pm"']:[],"pm init acme --yes --force"],nextSteps:[...i?['To create a new tracker in the current directory, rerun with --pm-path "$PWD/.agents/pm".']:[],"If you meant to initialize a sandbox tracker, pass a path-like positional such as ./sandbox-pm or /tmp/pm-test.","If you intentionally want to rewrite this existing tracker's init-managed settings, rerun with --force."]})}function Jm(e){let t=!1;return e.prefixArg!==void 0&&e.settings.id_prefix!==e.normalizedPrefix&&(e.settings.id_prefix=e.normalizedPrefix,e.warnings.push(`updated:id_prefix:${e.normalizedPrefix}`),t=!0),e.presetFromOption!==void 0&&e.settings.governance.preset!==e.presetFromOption&&(fr(e.settings,e.presetFromOption),e.warnings.push(`updated:governance_preset:${e.presetFromOption}`),t=!0),e.authorFromOption!==void 0&&e.settings.author_default!==e.authorFromOption&&(e.settings.author_default=e.authorFromOption,e.warnings.push(`updated:author_default:${e.authorFromOption}`),t=!0),t}async function qm(e){let t=await A(e.pmRoot);e.warnings.push(`already_exists:${e.settingsPath}`);let n=Gm({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption});return zm(e.settingsPath,n,e.options.force===!0,e.target),Jm({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption,warnings:e.warnings})&&await he(e.pmRoot,t),{settings:t,normalizedPrefix:e.normalizedPrefix,chosenPreset:e.normalizedOptions.presetFromOption,wizardUsed:!1}}async function Wm(e){let t=e.normalizedPrefix,n=e.normalizedOptions.presetFromOption,r,i=!1;if(e.normalizedOptions.presetFromOption===void 0&&!e.normalizedOptions.useDefaults&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0){let d=await zs(t,await Bm());t=d.prefix,n=d.preset,r=d.telemetry_enabled,i=!0}let o=n??"minimal",a=Dm();a.id_prefix=t,fr(a,o);let s=Mr()?.trim()||void 0;a.author_default=e.normalizedOptions.authorFromOption??s??"";let c=Js(e.pmRoot);return r!==void 0&&(a.telemetry.enabled=r,a.telemetry.first_run_prompt_completed=!0),await he(e.pmRoot,a,void 0,c),r!==void 0&&c.omitSections&&await Hm(r,e.warnings),{settings:a,normalizedPrefix:t,chosenPreset:n,wizardUsed:i}}function Js(e){return P.resolve(e)===P.resolve(Oe(process.cwd()))?{}:{omitSections:["telemetry"]}}async function Bm(){let e=await A(Oe(process.cwd()));if(!(li().telemetry_disabled||e.telemetry.first_run_prompt_completed||mn(e)))return e.telemetry.enabled}async function Hm(e,t){let n=Oe(process.cwd()),r=await A(n);if(mn(r)){t.push("telemetry_consent_not_recorded:global_settings_unreadable");return}let i=!1;r.telemetry.enabled=e,r.telemetry.first_run_prompt_completed=!0,await he(n,r,"telemetry:first_run_prompt",{skipIfStored:o=>i=o.telemetry?.first_run_prompt_completed===!0}),i&&t.push("telemetry_consent_kept:recorded_while_prompting")}async function Km(e){let{telemetry:t}=await A(Oe(process.cwd()));return{...e,telemetry:{...e.telemetry,enabled:t.enabled,first_run_prompt_completed:t.first_run_prompt_completed,capture_level:t.capture_level}}}async function As(e){return e.settingsExists?await qm(e):await Wm({pmRoot:e.pmRoot,normalizedPrefix:e.normalizedPrefix,normalizedOptions:e.normalizedOptions,warnings:e.warnings})}async function Vm(e){let t=await $s({pm_root:e.pmRoot,cwd:e.cwd,mode:e.agentGuidanceMode,interactive:process.stdin.isTTY===!0&&process.stdout.isTTY===!0,settings:e.settings});return e.warnings.push(...t.warnings),t.settings_changed&&await he(e.pmRoot,e.settings,void 0,Js(e.pmRoot)),{...t.summary,next_steps:t.next_steps}}async function Xm(e,t){let n=[],r=[],i=await Fr(e,t.schema);for(let o of i.created_paths)n.push(o),r.push(...await H({path:o,scope:"project",op:"init:runtime_schema_file"}));return{createdDirs:n,warnings:r}}async function Ym(e){if(e.typePreset===void 0)return;let t=await Fs(e.pmRoot,e.settings,e.typePreset);return e.warnings.push(`registered_type_preset:${e.typePreset}`),e.warnings.push(...await H({path:t.file,scope:"project",op:"init:type_preset"})),t}async function Zm(e){let n=B(e.settings,W()).folders.filter(i=>!sn.includes(i)),r=await Gs(e.pmRoot,n);e.createdDirs.push(...r.createdDirs),e.warnings.push(...r.warnings)}function Qm(e){let t=P.resolve(e.tracker_root),n=P.dirname(t);return P.basename(t)==="pm"&&P.basename(n)===".agents"?P.dirname(n):e.workspace_root}async function ef(e,t,n,r){if(!e)return;let i=await ir("all",{install:!0,project:!0},{...t,path:n});r.push(...i.warnings);let o=Ds(i),a=o.packages.filter(s=>!s.ok).map(s=>s.alias);if(!o.installed_all||a.length>0)throw new f(`pm init --with-packages did not install all bundled packages successfully${a.length>0?`: ${a.join(", ")}`:"."}`,h.GENERIC_FAILURE);return o}function qs(e){let t=r=>ae([...e.target.mode==="workspace-discovery"?[]:["--pm-path",e.target.tracker_root],...r]),n=[`Create your first item: ${t(["create","--type","Task","--title","<title>"])}`,`List active items: ${t(["list"])}`,`Get agent-friendly project context: ${t(["context"])}`];e.installBundledPackages?n.push(`Explore newly-available commands: ${t(["cal"])}, ${t(["templates"])}, ${t(["guide"])}`):(n.push(`Add optional packages for richer workflows: ${t(["install","calendar","--project"])}, ${t(["install","templates","--project"])}, ${t(["install","guide-shell","--project"])}`),n.push(`Or install everything bundled: ${t(["init","--with-packages"])} (idempotent on re-run)`)),e.registeredTypePreset&&n.push(`Inspect registered preset types: ${t(["schema","list"])}, ${t(["schema","show",e.registeredTypePreset.registered[0]??e.registeredTypePreset.updated[0]])}`),n.push("Supported agent harnesses are attributed automatically; use --author or PM_AUTHOR only when an explicit identity override is required.");for(let r of e.agentGuidanceNextSteps){let i=e.target.mode==="workspace-discovery"?r:r.replace(/\bpm (?=[a-z])/g,()=>`${t([])} `);n.includes(i)||n.push(i)}return n}async function Ws(e,t,n,r=hi){if(t===null){n.push("merge_fence_skipped:not_git_repository:run pm merge install after moving the tracker into a Git repository");return}try{let i=await r({pmRoot:e,workspaceRoot:t});i.gitattributes.changed&&n.push(`updated:merge_fence:${i.gitattributes.path}`)}catch(i){if(!(i instanceof f))throw i;n.push(`merge_fence_skipped:install_failed:${i.context.code??"pm_error"}:${i.message}:run pm merge install after resolving the Git repository error`)}}async function tf(e,t,n,r){if(e==null||n==="status")return;let i=await ui(e,{pmRoot:t});i.changed&&r.push(`updated:gitignore:${i.path}`)}async function jv(e,t,n={}){let r=t[Lm],i=typeof r=="string"?r:process.cwd(),o=Rs(i,t,e,n.workspace),a=o.pmRoot;e=Ns(o.prefixArg,n.idPrefix);let s=Um(n);await Us(a,o.target.mode==="tracker-path",n.force===!0);let c=[],d=[],l=P.join(a,"settings.json"),p=await S(l),u;p&&(u=await As({pmRoot:a,settingsPath:l,settingsExists:p,normalizedPrefix:Se(e),prefixArg:e,options:n,normalizedOptions:s,warnings:d,target:o.target}));let _=await Gs(a,sn);c.push(..._.createdDirs),d.push(..._.warnings),u??=await As({pmRoot:a,settingsPath:l,settingsExists:p,normalizedPrefix:Se(e),prefixArg:e,options:n,normalizedOptions:s,warnings:d,target:o.target});let{settings:g}=u,w=Qm(o.target),m=await mi(w??P.dirname(a)),y=w??m,v=await Vm({pmRoot:a,cwd:y??i,agentGuidanceMode:s.agentGuidanceMode,settings:g,warnings:d}),k=await Xm(a,g);c.push(...k.createdDirs),d.push(...k.warnings);let b=await Ym({pmRoot:a,settings:g,typePreset:s.typePreset,warnings:d});b&&(g=await A(a)),await Zm({pmRoot:a,settings:g,createdDirs:c,warnings:d}),await tf(y,a,s.agentGuidanceMode,d),!p&&n.mergeFence!==!1&&s.agentGuidanceMode!=="status"&&await Ws(a,m,d);let L=await ef(s.installBundledPackages,t,a,d),F=qs({installBundledPackages:s.installBundledPackages,registeredTypePreset:b,agentGuidanceNextSteps:v.next_steps,target:o.target});return{ok:!0,path:a,target:o.target,settings:await Km(g),created_dirs:c,warnings:d,governance_preset:g.governance.preset,wizard_used:u.wizardUsed,...b?{registered_type_preset:b}:{},...L?{installed_packages:L}:{},next_steps:F,agent_guidance:v}}export{af as a,yn as b,Sn as c,Ni as d,wf as e,dc as f,vf as g,$n as h,mc as i,fc as j,hc as k,Fi as l,Hl as m,We as n,Wi as o,Be as p,He as q,Bi as r,_c as s,Pf as t,jf as u,Gi as v,vc as w,Yf as x,Zi as y,ro as z,Zc as A,Qc as B,j_ as C,D_ as D,F_ as E,gt as F,M_ as G,U_ as H,G_ as I,z_ as J,J_ as K,q_ as L,W_ as M,B_ as N,H_ as O,K_ as P,V_ as Q,X_ as R,Y_ as S,Z_ as T,Q_ as U,ey as V,ty as W,ny as X,ry as Y,iy as Z,oy as _,ay as $,sy as aa,cy as ba,dy as ca,Ut as da,ed as ea,st as fa,Gt as ga,Pn as ha,sd as ia,yo as ja,Ao as ka,Bn as la,Uo as ma,Ag as na,la as oa,hp as pa,ka as qa,xa as ra,Pa as sa,Zo as ta,zl as ua,Qp as va,ea as wa,ir as xa,fs as ya,dv as za,$s as Aa,Lm as Ba,Nv as Ca,Lv as Da,jv as Ea};
|
|
69
|
-
//# sourceMappingURL=chunk-
|
|
69
|
+
//# sourceMappingURL=chunk-IGEFPHV7.js.map
|