@unbrained/pm-cli 2026.10.19 → 2026.10.20
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/CHANGELOG.md +33 -0
- package/dist/cli/error-guidance.d.ts +7 -0
- package/dist/cli/error-guidance.js +2 -2
- package/dist/cli/register-structured-mutation.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/{chunk-QBNEZII5.js → chunk-2GGGOD7P.js} +13 -13
- package/dist/cli-bundle/chunks/{chunk-4CXQSRSP.js → chunk-7NHA5K77.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-NX7Q4LGN.js → chunk-7ZOIZ2AZ.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-6DS5CAN2.js → chunk-GHJOMRSF.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-O2ZRRLAP.js → chunk-KU4Q3MSI.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-DMFM5R4G.js → chunk-LS55VKRK.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-QG4LMU7A.js → chunk-PNPE2OVJ.js} +43 -43
- package/dist/cli-bundle/chunks/chunk-PTL3TBT6.js +20 -0
- package/dist/cli-bundle/chunks/{chunk-LBEMB3BW.js → chunk-QETMESEB.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-4MJ6WBMA.js → chunk-QMZ73FCW.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-QQYCB2LO.js +2 -0
- package/dist/cli-bundle/chunks/chunk-TZU6U5ZE.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-H3XYP24A.js → chunk-VLJLWZBO.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-XAWE4EAK.js +2 -0
- package/dist/cli-bundle/chunks/chunk-YECCKB4E.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-5GZSX5HU.js → chunk-YT2Z3JPC.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-4XFVAXA4.js → chunk-YTHI5DTH.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-D3EDNAN7.js → chunk-YW6SIKYP.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-XH7C3A5N.js → chunk-ZA3XXHEE.js} +6 -6
- package/dist/cli-bundle/chunks/context-budget-recovery-L2WP5S26.js +2 -0
- package/dist/cli-bundle/{focused-chunks/indexed-receipt-blobs-QW2VWWJE.js → chunks/indexed-receipt-blobs-U7VGKIYC.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-WQUVDJIH.js → register-list-query-NNDV6F6I.js} +3 -3
- package/dist/cli-bundle/chunks/{register-mutation-IWIBQIO3.js → register-mutation-3GCBSNQS.js} +4 -4
- package/dist/cli-bundle/chunks/register-operations-YKDGNKUL.js +2 -0
- package/dist/cli-bundle/chunks/register-setup-AOUZQQWB.js +2 -0
- package/dist/cli-bundle/chunks/{settlement-hook-UNFMCKKQ.js → settlement-hook-CLRGA6O7.js} +2 -2
- package/dist/cli-bundle/chunks/stage-6QXYRMSU.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-WZTEFFQI.js → chunk-37SU7BZI.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-5YTOYBTZ.js → chunk-6IU7BESB.js} +3 -3
- package/dist/cli-bundle/focused-chunks/chunk-AS3MOBO3.js +25 -0
- package/dist/cli-bundle/focused-chunks/{chunk-PXDR77TO.js → chunk-AW35RDKA.js} +22 -22
- package/dist/cli-bundle/focused-chunks/{chunk-RLRMNFLF.js → chunk-E4II2D2B.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-FEN7WOOP.js → chunk-F7FD25TG.js} +12 -12
- package/dist/cli-bundle/focused-chunks/{chunk-JDBO7SMR.js → chunk-GYHZ7W6O.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-EOQ6W25I.js → chunk-H5Q2HUU6.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-3TEIACFU.js → chunk-HUZAXSIJ.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-JBJJW2WL.js → chunk-J6EYUGAR.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-JEXZEIAX.js +91 -0
- package/dist/cli-bundle/focused-chunks/{chunk-ENZMATOY.js → chunk-KDGUIIRU.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-H6BVQ63U.js → chunk-KKRFSI2N.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-GWTV45SB.js → chunk-LJPUJ2KK.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-MQ42BFGX.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-HYMYAGSY.js → chunk-NI6NS44Q.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-L4PL3GZR.js → chunk-VAYS754X.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-SKYLOPU2.js → chunk-VLSER3XW.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-JCLC6HKT.js → chunk-VS6VTWTZ.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-OV2WVLUR.js → chunk-ZGEK57KD.js} +2 -2
- package/dist/cli-bundle/focused-chunks/context-budget-recovery-5MKOCGY5.js +2 -0
- package/dist/cli-bundle/{chunks/indexed-receipt-blobs-BVSHK4WQ.js → focused-chunks/indexed-receipt-blobs-H2G6CCGO.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{settlement-hook-X4FNHTOD.js → settlement-hook-5SNBBT7C.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{stage-MZSVQYO4.js → stage-EMTISXR7.js} +2 -2
- package/dist/cli-bundle/main.js +21 -21
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +2 -2
- package/dist/cli-bundle/sdk-core.js +21 -21
- 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 +55 -55
- 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 +8 -8
- package/dist/core/fs/fs-utils.d.ts +2 -2
- package/dist/core/fs/fs-utils.js +1 -1
- package/dist/core/history/event-index.js +2 -2
- package/dist/core/output/output.d.ts +7 -2
- package/dist/core/output/output.js +5 -5
- package/dist/core/shared/errors.d.ts +48 -0
- package/dist/core/shared/errors.js +1 -1
- package/dist/core/store/settings.js +2 -2
- package/dist/mcp/server.js +1 -1
- package/dist/sdk/core.d.ts +1 -1
- package/dist/sdk/core.js +1 -1
- package/dist/sdk/dependencies/context-budget-recovery.d.ts +21 -0
- package/dist/sdk/dependencies/context-budget-recovery.js +2 -0
- package/dist/sdk/dependencies.js +1 -1
- package/dist/sdk/errors.d.ts +4 -1
- package/dist/sdk/errors.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/index.d.ts +1 -1
- package/dist/sdk/index.js +1 -1
- package/dist/sdk/item-transaction.d.ts +13 -0
- package/dist/sdk/item-transaction.js +1 -1
- package/dist/sdk/lifecycle/structured-mutation-plan.d.ts +14 -1
- package/dist/sdk/lifecycle/structured-mutation-plan.js +1 -1
- package/dist/sdk/output/list-envelope.d.ts +7 -0
- package/dist/sdk/output/list-envelope.js +2 -0
- package/dist/sdk/output.d.ts +1 -0
- package/dist/sdk/output.js +2 -2
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/relationship-context.d.ts +2 -0
- package/dist/sdk/relationship-context.js +1 -1
- package/dist/sdk/structured-mutations.d.ts +2 -0
- package/dist/sdk/structured-mutations.js +1 -1
- package/docs/COMMANDS.md +14 -0
- package/docs/PR_REVIEW_LOOP.md +32 -12
- package/docs/SCRIPTING.md +10 -0
- package/docs/SDK.md +77 -0
- package/docs/TESTING.md +25 -1
- 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-4ICKT4GH.js +0 -3
- package/dist/cli-bundle/chunks/chunk-OEJ3G7XT.js +0 -20
- package/dist/cli-bundle/chunks/chunk-QKAAZWGC.js +0 -3
- package/dist/cli-bundle/chunks/chunk-TK3G3GAP.js +0 -2
- package/dist/cli-bundle/chunks/register-operations-SUWOZNDU.js +0 -2
- package/dist/cli-bundle/chunks/register-setup-QGM5YJW7.js +0 -2
- package/dist/cli-bundle/chunks/stage-7DELI4Z5.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-2IEWB6MB.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-BJMPRB7A.js +0 -91
- package/dist/cli-bundle/focused-chunks/chunk-KLJN44VY.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-Y54ONBEX.js +0 -25
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{A as p,C as f,G as g}from"./chunk-YECCKB4E.js";import{readFile as R,writeFile as I}from"node:fs/promises";import o from"node:path";(function(){try{var t=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new t.Error().stack;e&&(t._sentryDebugIds=t._sentryDebugIds||{},t._sentryDebugIds[e]="1de99e25-e132-5071-833e-37361b4cc7e6")}catch{}})();var m="# pm-cli:runtime-cache:start",c="# pm-cli:runtime-cache:end",E=".agents/pm",_=["runtime/","search/","locks/","transactions/","checkpoints/"],T=["search/eval-queries.json"];async function h(t){try{return await t()}catch(e){throw e instanceof Error&&"code"in e&&typeof e.code=="string"&&["EACCES","EPERM","EROFS"].includes(e.code)?new f("The workspace .gitignore is not writable.",p.GENERIC_FAILURE,{code:"init_gitignore_unwritable",reason:e.code.toLowerCase(),required:"Grant the current user read and write access to the workspace .gitignore before initialization.",why:"pm init must publish its managed runtime-cache ignore fence without replacing unrelated entries.",nextSteps:["Grant read and write access to the workspace .gitignore and rerun pm init.","If the workspace is intentionally read-only, initialize pm in a writable workspace or clone."]}):e}}function w(t){return t.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/\/+$/,"")}function G(t){let e=t.replaceAll("\\","/");return o.isAbsolute(t)||e===".."||e.startsWith("../")}function y(t=E){let e=w(t);return[m,..._.map(r=>r==="search/"?`${e}/${r}*`:`${e}/${r}`),...T.map(r=>`!${e}/${r}`),c].join(`
|
|
2
2
|
`)}async function v(t,e={}){let r=o.join(t,".gitignore"),s=E;if(e.pmRoot!==void 0){let i=w(o.relative(o.resolve(t),o.resolve(e.pmRoot)));if(G(i))return{path:r,changed:!1};i.length>0&&(s=i)}let n="";try{n=await h(()=>R(r,"utf8"))}catch(i){if(!(i instanceof Error&&"code"in i&&g(i)))throw i}let a=n.indexOf(m),l=n.indexOf(c),d=(a>=0&&l>=a?`${n.slice(0,a)}${n.slice(l+c.length)}`:n).trimEnd(),u=`${d.length>0?`${d}
|
|
3
3
|
|
|
4
4
|
`:""}${y(s)}
|
|
5
5
|
`;return u===n?{path:r,changed:!1}:(await h(()=>I(r,u,"utf8")),{path:r,changed:!0})}export{m as a,c as b,_ as c,G as d,y as e,v as f};
|
|
6
|
-
//# sourceMappingURL=chunk-
|
|
6
|
+
//# sourceMappingURL=chunk-QETMESEB.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{A as o,C as r}from"./chunk-YECCKB4E.js";(function(){try{var n=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new n.Error().stack;e&&(n._sentryDebugIds=n._sentryDebugIds||{},n._sentryDebugIds[e]="be9abae1-85ae-5a68-96bc-c738218ace5e")}catch{}})();function u(n){return n instanceof r||n instanceof Error?n.message:"Unknown failure"}function d(n){if(typeof n!="object"||n===null||!("exitCode"in n))return;let e=n.exitCode;return typeof e=="number"&&Number.isFinite(e)?e:void 0}function f(n){let e=Math.trunc(n);return e>o.SUCCESS?e:o.GENERIC_FAILURE}function s(n){return typeof n=="object"&&n!==null&&"code"in n&&typeof n.code=="string"&&n.code.startsWith("commander.")}function l(n,e){if(n instanceof Error)return n;let t=new Error(e),i=d(n);return i!==void 0&&(t.exitCode=f(i)),t}export{u as a,d as b,f as c,s as d,l as e};
|
|
2
|
+
//# sourceMappingURL=chunk-QMZ73FCW.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as he}from"./chunk-QMZ73FCW.js";import{Rb as je,Sb as Fe,Ub as W,Xb as Pe,Ya as z,Zb as Ge,_b as xe,a as ye,uc as qe}from"./chunk-YT2Z3JPC.js";import{yc as De}from"./chunk-2GGGOD7P.js";import{b as Oe,c as J}from"./chunk-VLJLWZBO.js";import{L as Me,Ya as Re,cb as ke,g as Ie,i as O,r as Ae,rf as Ce,uf as Ne,wc as $e,yc as Ue}from"./chunk-7NHA5K77.js";import{$f as we,Db as me,Lg as Se,Nc as fe,Oc as q,Pa as le,bg as K,cg as ge,fg as ve,ig as _e,jg as E,ji as be,kh as L,lg as Ee,ni as Te,pa as x,ti as M,ya as pe}from"./chunk-PNPE2OVJ.js";import{A as u,C as c,G,I as ue,J as A,l as se,q as I,t as ce,y as de}from"./chunk-YECCKB4E.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4175f7f5-a689-5d05-982a-f92e21bc83e7")}catch{}})();import Xe from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="01728cbc-2037-50d2-8318-5f106714b8da")}catch{}})();var S=new Set(["id","title","description","type","status","priority","tags","body","deadline","estimated_minutes","acceptance_criteria","definition_of_ready","order","rank","assignee",...se,"affected_version","fixed_version","component","regression","customer_impact","close_reason","completed_at","dependencies","comments","notes","learnings","files","tests","docs","reminders","events","type_options"]);function R(e){if(e===void 0)return;let t=e.replace(/[A-Z]/gu,n=>`_${n.toLowerCase()}`);return S.has(t)?t:e}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6456f85b-e076-5048-9c21-03d477267259")}catch{}})();function k(e,t,n){let i=e?.estimatedMinutes;if(!(i===void 0||typeof i=="string"))throw new c(`Mutation ${n+1} ${t} option "estimatedMinutes" must be a string.`,u.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."]})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7b430d12-7a5b-52c2-9a6b-e4c33a39da76")}catch{}})();var V=["op","id","reason","options","unique","match"],bt=[...V,"ref"],Ke=[...bt,"item"],Tt="mutate-",Le="row-",Je=["schema_version","mutations"],Ze="[a-z][a-z0-9._-]{0,63}",ze=new RegExp(`^${Ze}$`,"u"),Qe=new RegExp(`(^|,)id=@(${Ze})(?=,|$)`,"gu"),We=e=>e.slice(2).replaceAll(/-([a-z])/gu,(t,n)=>n.toUpperCase()),$=["item","linked","schedule","claim_state","children","omission_receipt","row_contract","context_intent"],et=new Set(["created_at","updated_at","closed_at","version","format_version","path","author","collection_counts","notes_count","tests_count"]),It=new Set([...et,"completed_at","id"]),tt={create:Ce.map(e=>e.target),update:Ne.map(e=>e.target),close:Re.map(e=>We(e.flag)).filter(e=>e!=="reason"),release:ke.map(e=>We(e.flag))};function nt(e){let t=Xe.createHash("sha256").update(e).digest("hex");return`${Tt}${t.slice(0,24)}`}function _i(e){let t={},n=e.createCompensation;if(n!==void 0){if(n!=="close"&&n!=="delete")throw new c("createCompensation must be close or delete.",u.USAGE);t.createCompensation=n}for(let i of["lockTtlSeconds","lockWaitMs"]){let r=e[i];if(r===void 0)continue;let o=typeof r=="number"||typeof r=="string"&&r.trim().length>0?Number(r):Number.NaN;if(!Number.isSafeInteger(o)||o<=0)throw new c(`${i} must be a positive safe integer.`,u.USAGE);t[i]=o}return t}function y(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function U(e,t){let n=Math.max(1,Math.min(3,Math.floor(e.length/4)+1)),i;for(let r of t){let o=me(e,r,n);o!==null&&(i===void 0||o<i.distance)&&(i={key:r,distance:o})}return i?.key}function b(e,t,n){let i=U(t,n);return new c(i===void 0?`${e} does not recognize key "${t}". Allowed keys: ${n.join(", ")}.`:`${e} does not recognize key "${t}". Did you mean "${i}"?`,u.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:[i===void 0?`Remove or correct "${t}".`:`Replace "${t}" with "${i}".`]})}function H(e,t){try{return JSON.parse(e)}catch(n){let i=n instanceof Error?n.message:String(n);throw new c(`${t} must be valid JSON: ${i}`,u.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 At(e,t){if(!y(e))throw new c(`Mutation ${t+1} must be an object.`,u.USAGE);for(let n of Object.keys(e))if(!V.includes(n))throw b(`mutation ${t+1}`,n,V);return e}function Mt(e,t,n,i){if(e===void 0)return;if(!y(e))throw new c(`Mutation ${n+1} options must be an object.`,u.USAGE);let r=[...tt[t],...ot(t,i)];for(let o of Object.keys(e))if(!r.includes(o))throw b(`mutation ${n+1} ${t} options`,o,r);return k(e,t,n),e}function Ve(e,t,n,i){if(e===void 0)return;let r=i==="unique"?"create":"update";if(t!==r)throw new c(`Mutation ${n+1} ${i} is only valid for ${r} operations.`,u.USAGE);let o=y(e)&&typeof e.key=="string"?e.key.trim():"";if(!y(e)||o.length===0||e.value===void 0||e.value===null)throw new c(`Mutation ${n+1} ${i} must be an object with a non-empty key and a value.`,u.USAGE);return{key:o,value:e.value}}function Ot(e,t,n){let i=At(e,t),{op:r,id:o,reason:a}=i;if(r!=="create"&&r!=="update"&&r!=="close"&&r!=="release")throw new c(`Mutation ${t+1} op must be create, update, close, or release.`,u.USAGE);let s=Mt(i.options,r,t,n),d=Ve(i.unique,r,t,"unique"),l=Ve(i.match,r,t,"match");if(typeof o!="string"||o.trim().length===0)throw new c(`Mutation ${t+1} requires a non-empty id.`,u.USAGE);let p=o.trim();if(r==="close"){if(typeof a!="string"||a.trim().length===0)throw new c(`Mutation ${t+1} close requires a non-empty reason.`,u.USAGE);return{op:r,id:p,reason:a.trim(),...s===void 0?{}:{options:s}}}if(r==="release")return{op:r,id:p,...s===void 0?{}:{options:s}};if(!y(s))throw new c(`Mutation ${t+1} ${r} requires an options object.`,u.USAGE);return{op:r,id:p,options:s,...d===void 0?{}:{unique:d},...l===void 0?{}:{match:l}}}function it(e,t={}){let n=H(e,"Mutation batch"),i=Array.isArray(n)?n:y(n)&&Array.isArray(n.mutations)?n.mutations:void 0;if(i===void 0||i.length===0)throw new c("Mutation batch must be a non-empty JSON array or an object with a non-empty mutations array.",u.USAGE);let r=t.runtimeFields??[];return i.map((o,a)=>{let s=Ot(o,a,r);return s.options!==void 0&&$e(s.options),s})}function Rt(e,t,n){let i=Xe.createHash("sha256").update(e).update("\0").update(t).digest("hex"),r=BigInt(`0x${i.slice(0,16)}`).toString(36).padStart(13,"0").slice(-12);return`${Ie(n)}${r}`}function Be(e,t){if(typeof e!="string"||!e.startsWith("@"))return e;let n=e.slice(1),i=t[n];if(i===void 0)throw new c(`Unknown mutation reference "${e}".`,u.USAGE);return i}function Ye(e,t){if(typeof e!="string")return e;let n=e.replace(Qe,(i,r,o)=>{let a=t[o];if(a===void 0)throw new c(`Unknown mutation reference "@${o}".`,u.USAGE);return`${r}id=${a}`});if(/(^|,)id=@/u.test(n))throw new c(`Malformed mutation reference in dependency "${e}".`,u.USAGE);return n}function kt(e){return typeof e!="string"?[]:e.startsWith("@")?[e.slice(1)]:[...e.matchAll(Qe)].map(t=>t[1]).filter(t=>t!==void 0)}function $t(e,t){let n=new Map;for(let[a,s]of e.entries()){let d=t[a];if(d===void 0)continue;let l=y(s.options)?s.options:{},p=Array.isArray(l.dep)?l.dep:l.dep===void 0?[]:[l.dep];n.set(d,[l.parent,l.blockedBy,...p].flatMap(kt))}let i=new Set,r=new Set,o=a=>{if(i.has(a))throw new c(`Mutation reference cycle includes "@${a}".`,u.USAGE);if(!r.has(a)){i.add(a);for(let s of n.get(a))n.has(s)&&o(s);i.delete(a),r.add(a)}};for(let a of n.keys())o(a)}function Ut(e){let t=e.split(/\r?\n/u).map((o,a)=>({line:o.trim(),number:a+1})).filter(o=>o.line.length>0);if(t.length<2)return null;let n=t.map(o=>{try{return{...o,ok:!0,value:JSON.parse(o.line)}}catch(a){return{...o,ok:!1,error:a}}}),i=n[0];if(!i.ok&&(i.line.startsWith("[")||i.line==="{"||n.at(-1).line==="}")||!n.some(o=>o.ok&&y(o.value)))return null;let r=[];for(let o of n){if(!o.ok)throw new c(`Mutation document line ${o.number} must be one valid JSON object: ${he(o.error)}`,u.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(!y(o.value))throw new c(`Mutation document line ${o.number} must be a JSON object.`,u.USAGE);r.push(o.value)}return r}function Ct(e){return Object.hasOwn(e,"mutations")||Object.hasOwn(e,"schema_version")}function Nt(e){let t;try{t=H(e,"Mutation document")}catch(n){let i=Ut(e);if(i===null)throw n;return{schema_version:1,mutations:i}}return Array.isArray(t)?{schema_version:1,mutations:t}:y(t)&&!Ct(t)?{schema_version:1,mutations:[t]}:t}function Dt(e,t){let n=Object.hasOwn(e,"op")?jt(e,t):Ft(e,t);if(n.op==="create"&&n.id===void 0&&y(n.item)&&n.item.id!==void 0){if(typeof n.item.id!="string")throw new c(`Mutation ${t+1} item id must be a string.`,u.USAGE);n.id=n.item.id}return n}function jt(e,t){for(let n of Object.keys(e))if(!Ke.includes(n))throw b(`mutation ${t+1}`,n,Ke);if(e.item!==void 0&&e.op!=="create")throw new c(`Mutation ${t+1} item documents are only valid for create operations.`,u.USAGE);if(e.item!==void 0&&e.options!==void 0)throw new c(`Mutation ${t+1} must declare either item or options, not both.`,u.USAGE);return{...e}}function Ft(e,t){let{ref:n,id:i,item:r,...o}=e,a=r!==void 0?r:o;if(r!==void 0&&Object.keys(o).length>0)throw new c(`Mutation ${t+1} must not mix item document keys with top-level fields.`,u.USAGE);if(!y(a))throw new c(`Mutation ${t+1} item document must be an object.`,u.USAGE);return{op:"create",...n===void 0?{}:{ref:n},...i===void 0?{}:{id:i},item:a}}function Pt(e){let t=Nt(e);if(!y(t))throw new c("Mutation document must be a JSON array or object.",u.USAGE);for(let n of Object.keys(t))if(!Je.includes(n))throw b("mutation document",n,Je);if(t.schema_version!==void 0&&t.schema_version!==1)throw new c("Mutation document schema_version must be 1.",u.USAGE);if(!Array.isArray(t.mutations)||t.mutations.length===0)throw new c("Mutation document requires a non-empty mutations array.",u.USAGE);return t.mutations.map((n,i)=>{if(!y(n))throw new c(`Mutation ${i+1} must be an object.`,u.USAGE);return Dt(n,i)})}function Gt(e,t,n){let i=new Set(Object.values(st(t,n,Object.create(null))));for(let r of t)r.op==="create"&&typeof r.id=="string"&&r.id.trim().length>0&&i.add(O(r.id,n.idPrefix));return{...e,existing:e.existing.filter(r=>!i.has(r.id))}}function xt(e){let t=new Set(e.map(n=>n.ref).filter(n=>typeof n=="string"));for(let[n,i]of e.entries()){if(i.op!=="create"||i.ref!==void 0||typeof i.id=="string"&&i.id.trim().length>0)continue;let r=`${Le}${n+1}`;if(t.has(r))throw new c(`Mutation ${n+1} receives the synthesized ref "${r}", but another row declares that ref. Rename it or give mutation ${n+1} its own ref; ${Le}<n> aliases are reserved for rows without one.`,u.USAGE);i.ref=r}}function rt(e,t,n){let i=en(JSON.stringify(e),t,{},n);return delete i.stdinJson,delete i.documentAnnotationSnapshot,i}function ot(e,t){return e!=="create"&&e!=="update"?[]:t.filter(n=>n.commands.includes(e)).map(n=>E(n))}function qt(e,t){for(let n of e)y(n.item)&&(n.options=rt(n.item,"create",t),delete n.item)}function at(e,t){return t.some(n=>n.metadata_key===e)?e:R(e)}function B(e,t,n){let i=t.replaceAll(/_([a-z])/gu,(a,s)=>s.toUpperCase());if(y(e.item)){if(e.item[t]!==void 0)return e.item[t];if(at(i,n)===t&&e.item[i]!==void 0)return e.item[i]}let r=y(e.options)?e.options:{},o=n.find(a=>a.metadata_key===t);return o!==void 0&&r[E(o)]!==void 0?r[E(o)]:r[t]!==void 0?r[t]:r[i]!==void 0?r[i]:(Array.isArray(r.field)?r.field:[]).map(String).find(a=>a.startsWith(`${t}=`))?.slice(t.length+1)}function Kt(e,t){return e<t?-1:+(e!==t)}function Y(e){return Array.isArray(e)?e.map(Y):y(e)?Object.fromEntries(Object.entries(e).sort(([t],[n])=>Kt(t,n)).map(([t,n])=>[t,Y(n)])):e}function v(e){return typeof e=="string"?e.trim():JSON.stringify(Y(e))}function Lt(e,t,n,i,r){let o=t.key.trim();if(o.length===0)throw new c("Upsert key must be a non-empty field name.",u.USAGE);let a=Jt(t.existing),s=new Map,d=new Set;for(let[l,p]of e.entries()){if(p.op!=="create")continue;let f=zt(p,o,l,s,i),w=Wt(a.get(f)??[],o,f);if(w===void 0){p.unique={key:o,value:B(p,o,i)};continue}let h=O(w,n);typeof p.ref=="string"&&(r[p.ref]=h),Vt(p,h,i,{key:o,value:B(p,o,i)}),d.add(l)}return d}function Jt(e){let t=new Map;for(let n of e){if(n.value===void 0||n.value===null)continue;let i=v(n.value);t.set(i,[...t.get(i)??[],n.id])}return t}function zt(e,t,n,i,r){let o=B(e,t,r);if(o==null||o==="")throw new c(`Mutation ${n+1} is missing the upsert key "${t}".`,u.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 a=v(o),s=i.get(a);if(s!==void 0)throw new c(`Mutations ${s+1} and ${n+1} share the upsert key value ${JSON.stringify(a)} for "${t}".`,u.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 i.set(a,n),a}function Wt(e,t,n){if(e.length>1)throw new c(`Upsert key "${t}" value ${JSON.stringify(n)} matches ${e.length} existing items: ${e.join(", ")}.`,u.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 Vt(e,t,n,i){let r=new Set([...tt.update,...ot("update",n)]),o=y(e.item)?rt(e.item,"update",n):Object.fromEntries(Object.entries(e.options).filter(([a])=>r.has(a)));delete e.item,delete e.ref,e.op="update",e.id=t,e.options=o,e.match=i}function st(e,t,n){for(let[i,r]of e.entries())if(r.ref!==void 0){if(r.op!=="create")throw new c(`Mutation ${i+1} ref is only valid for create operations.`,u.USAGE);if(typeof r.ref!="string"||!ze.test(r.ref))throw new c(`Mutation ${i+1} ref must match ${ze.source}.`,u.USAGE);if(n[r.ref]!==void 0)throw new c(`Duplicate mutation ref "${r.ref}".`,u.USAGE);n[r.ref]=typeof r.id=="string"&&r.id.trim().length>0?O(r.id,t.idPrefix):Rt(t.transactionId,r.ref,t.idPrefix)}return n}function ct(e,t){let n=Pt(e);xt(n);let i=n.map(p=>typeof p.ref=="string"?p.ref:void 0),r=Object.create(null),o=t.upsert===void 0?new Set:Lt(n,Gt(t.upsert,n,t),t.idPrefix,t.runtimeFields??[],r);qt(n,t.runtimeFields??[]),st(n,t,r),$t(n,i);let a=n.map(p=>{let f={...p},w=typeof f.ref=="string"?f.ref:void 0;if(delete f.ref,w!==void 0?f.id=r[w]:f.id=Be(f.id,r),y(f.options)){let h={...f.options};for(let g of["parent","blockedBy"])h[g]!==void 0&&(h[g]=Be(h[g],r));Array.isArray(h.dep)?h.dep=h.dep.map(g=>Ye(g,r)):h.dep!==void 0&&(h.dep=Ye(h.dep,r)),f.options=h}return f}),s=it(JSON.stringify(a),{runtimeFields:t.runtimeFields??[]}),d=s.filter(p=>p.op==="create").map(p=>p.id);if(new Set(d).size!==d.length)throw new c("Duplicate resolved create id in mutation document.",u.USAGE);let l=s.map((p,f)=>{let w=i[f];return{index:f,...typeof w=="string"?{ref:w}:{},id:p.id,op:p.op,...o.has(f)?{upserted:!0}:{}}});return{schema_version:1,mutations:s,references:r,rows:l}}function Bt(e,t){return t.filter(n=>e[n]!==void 0&&e[n]!==null).map(n=>{let i=String(e[n]);return`${n}=${/[",\n\r\\]/u.test(i)?JSON.stringify(i):i}`}).join(",")}function Yt(e,t,n){if(e!==void 0){if(!Array.isArray(e)||!e.every(y))throw new c(`${n} must be an array of objects.`,u.USAGE);return e.map(i=>Bt(i,t))}}function Ht(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 He(e,t,n=!1){for(let[i,r,o]of De){let a=t[i],s=Yt(n&&["comments","notes","learnings"].includes(i)&&Array.isArray(a)?a.filter(d=>!y(d)||d.created_at===void 0):a,o,i);s!==void 0&&s.length>0&&(e[r]=s)}}function Xt(e,t){for(let n of Object.keys(e)){if(t){if(!$.includes(n))throw b("item envelope",n,$);continue}if(!S.has(n)&&U(n,[...S])===void 0&&U(n,$)==="item")throw b("item envelope",n,$)}}function Zt(e){let t=Object.hasOwn(e,"item");Xt(e,t);let n=t?e.item:e;if(!y(n))throw new c("Item document item must be an object.",u.USAGE);return{item:n,...t&&y(e.linked)?{linked:e.linked}:{}}}function Qt(e,t,n,i,r,o){if((i==="update"?It:et).has(t))return;let a=r.find(s=>s.metadata_key===t&&s.commands.includes(i));if(a!==void 0){let s=Ee(o,a);e[E(a)]=s!==void 0?s:a.type==="array"||a.type==="object"?JSON.stringify(n):n;return}if(!S.has(t)){if(U(t,[...S])!==void 0)throw b("item document",t,[...S]);let s=Array.isArray(e.field)?e.field:[];s.push(`${t}=${typeof n=="string"?n:JSON.stringify(n)}`),e.field=s;return}["dependencies","comments","notes","learnings","files","tests","docs","reminders","events","type_options"].includes(t)||(e[t.replaceAll(/_([a-z])/gu,(s,d)=>d.toUpperCase())]=Ht(t,n))}function en(e,t,n={},i=[]){let r=H(e,"Item document");if(!y(r))throw new c("Item document must be a JSON object.",u.USAGE);let{item:o,linked:a}=Zt(r),s={};for(let[d,l]of Object.entries(o)){let p=at(d,i);p!==d&&Object.hasOwn(o,p)||Qt(s,p,l,t,i,n)}if(He(s,o,t==="update"),a!==void 0&&He(s,a),t==="update"){let d=Object.fromEntries(["comments","notes","learnings"].filter(l=>Object.hasOwn(o,l)).map(l=>[l,o[l].filter(p=>y(p)&&p.created_at!==void 0)]));Object.keys(d).length>0&&(s.documentAnnotationSnapshot=d)}return{...s,...Object.fromEntries(Object.entries(n).filter(([,d])=>d!==void 0)),...Array.isArray(s.field)&&Array.isArray(n.field)?{field:[...s.field,...n.field]}:{},stdinJson:void 0}}function Ei(e){return it(JSON.stringify(e))}import ee from"node:crypto";import{constants as X}from"node:fs";import{cp as tn,lstat as ut,mkdir as nn,mkdtemp as pt,open as rn,readdir as on,realpath as lt,rm as mt,stat as te,writeFile as ft}from"node:fs/promises";import{tmpdir as yt}from"node:os";import m from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="89f9137d-876a-5aa7-8272-f83df5edf9e9")}catch{}})();async function ne(e,t){if(!Te(e))return{schema:K(t.schema),typeDefinitionsFromFile:[]};let n=await fn(e,t.schema);return{schema:n.schema,typeDefinitionsFromFile:n.type_definitions_from_file??[]}}async function ie(e,t,n,i){let r=x({...t,item_types:{...t.item_types,definitions:[...t.item_types?.definitions??[],...n.typeDefinitionsFromFile]}},q());return(await Me(e,t.item_format,r.type_to_folder,void 0,n.schema)).flatMap(o=>{let a=o[i];return a==null?[]:[{id:o.id,value:a}]})}function ht(e){let t=new Map,n=async i=>{let r=await M(e),o=await ne(e,r),a=new Map;for(let s of await ie(e,r,o,i)){let d=v(s.value);a.set(d,[...a.get(d)??[],s.id])}return a};return{lookup(i){let r=t.get(i)??n(i);return t.set(i,r),r},async recordCreate(i){for(let[r,o]of t){let a=i[r];if(a==null)continue;let s=await o,d=v(a);s.set(d,[...s.get(d)??[],String(i.id)])}},invalidate(){t.clear()}}}async function an(e,t){let n=v(t.value),i=(await e.lookup(t.key)).get(n)??[];if(i.length!==0)throw new c(`Upsert key "${t.key}" value ${JSON.stringify(n)} now matches existing item ${i.join(", ")}; the plan was resolved before it existed.`,u.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 sn(e,t,n){let i=e.metadata[n.key],r=v(n.value);if(v(i)!==r)throw new c(`Item ${t} no longer carries upsert key "${n.key}" value ${JSON.stringify(r)}; the plan selected it before the key changed.`,u.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 dt(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 j(e,t){let n={...e,...t};return e===void 0?n:Ue(e,n)}async function _(e,t){try{let n=(await z(t,{},{pmRoot:e})).item;return{id:n.id,closedAt:n.closed_at,updatedAt:n.updated_at,assignee:n.assignee,claimPrincipal:n.claim_principal}}catch(n){if(n instanceof c&&n.exitCode===u.NOT_FOUND)return;throw n}}function re(e,t){let n=e.id.replaceAll(/[^a-zA-Z0-9._-]/gu,"_"),i=ee.createHash("sha256").update(le(e)).digest("hex").slice(0,12);return`${t+1}-${e.op}-${n}-${i}`}function cn(e,t){let n=e.id.replaceAll(/[^a-zA-Z0-9._-]/gu,"_");return`${t+1}-${e.op}-${n}`}function T(e,t,n){return`bulk-item-transaction ${e} ${t} ${n}`}async function F(e,t,n,i){let r=await L(m.join(e,"history",`${t}.jsonl`),t),o=T(n,i,"apply"),a=T(n,i,"compensate");for(let s=r.length-1;s>=0;s-=1){let d=r[s].message;if(d===o)return!0;if(d===a)return!1}return!1}async function oe(e,t){let n=await _(e,t.id);if(n?.updatedAt===void 0)throw new c(`Bulk ${t.op} target ${t.id} does not exist or has no restorable version`,u.NOT_FOUND);return{target_updated_at:n.updatedAt}}async function P(e,t,n,i){let r=i!==null&&typeof i=="object"&&!Array.isArray(i)?i.target_updated_at:void 0;typeof r=="string"&&await _(e.pmRoot,t)!==void 0&&await xe(t,r,{force:!0,author:e.author,message:T(e.transactionId,n,"compensate")},{pmRoot:e.pmRoot})}function wt(e,t,n){return{id:n,async inspect(){let i=await _(e.pmRoot,t.id);if(i===void 0)return{state:"pending"};if(i.closedAt!==void 0){let r=await L(m.join(e.pmRoot,"history",`${i.id}.jsonl`),i.id),o=`Compensated: interrupted bulk transaction ${e.transactionId}`;if(r.filter(a=>a.op==="close").at(-1)?.patch.some(a=>a.op==="add"||a.op==="replace"?a.path==="/metadata/close_reason"&&a.value===o:!1)??!1)throw new c(`Created item ${i.id} remains closed by transaction compensation; explicitly reopen or reconcile it before retrying.`,u.CONFLICT,{code:"transaction_create_compensated",item_id:i.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 ${i.id} "Retry compensated creation" after reviewing its history, then retry the transaction.`]})}return{state:"applied",result:{id:i.id,op:"create"}}},async apply(){t.unique!==void 0&&await an(e.uniqueIndex,t.unique);let i=await je(j(t.options,{author:e.author,id:t.id}),{pmRoot:e.pmRoot}),r=i.item;return e.onCreateWarnings?.(String(r.id),i.warnings),await e.uniqueIndex.recordCreate(r),{id:String(r.id),op:"create"}},async compensate(){let i=await _(e.pmRoot,t.id);if(i!==void 0){if(e.createCompensation==="delete"){await Ge(t.id,{force:!0,author:e.author,message:`Compensate interrupted bulk transaction ${e.transactionId}`},{pmRoot:e.pmRoot});return}i.closedAt===void 0&&await W(t.id,`Compensated: interrupted bulk transaction ${e.transactionId}`,{force:!0,author:e.author},{pmRoot:e.pmRoot})}}}}function dn(e,t,n){return{id:n,async inspect(){let i=await _(e.pmRoot,t.id);return i===void 0?{state:"pending"}:await F(e.pmRoot,i.id,e.transactionId,n)?{state:"applied",result:{id:i.id,op:"update"}}:{state:"pending"}},async prepareCompensation(){return oe(e.pmRoot,t)},async apply(){let i=()=>Fe(t.id,j(t.options,{author:e.author,message:T(e.transactionId,n,"apply")}),{pmRoot:e.pmRoot}),r=t.match,o=(r===void 0?await i():await Ae({pmRoot:e.pmRoot,id:String((await z(t.id,{},{pmRoot:e.pmRoot})).item.id),validate:a=>sn(a,t.id,r)},i)).item;return e.uniqueIndex.invalidate(),{id:String(o.id),op:"update"}},async compensate(i){await P(e,t.id,n,i)}}}function un(e,t,n){return{id:n,async inspect(){let i=await _(e.pmRoot,t.id);return i===void 0?{state:"pending"}:await F(e.pmRoot,i.id,e.transactionId,n)?{state:"applied",result:{id:i.id,op:"close"}}:i.closedAt===void 0?{state:"pending"}:{state:"applied",result:{id:i.id,op:"close"}}},async prepareCompensation(){return oe(e.pmRoot,t)},async apply(){let i=(await W(t.id,t.reason,j(t.options,{author:e.author,message:T(e.transactionId,n,"apply")}),{pmRoot:e.pmRoot})).item;return e.uniqueIndex.invalidate(),{id:String(i.id),op:"close"}},async compensate(i){await P(e,t.id,n,i)}}}function pn(e,t,n){return{id:n,async inspect(){let i=await _(e.pmRoot,t.id);return i===void 0?{state:"pending"}:await F(e.pmRoot,i.id,e.transactionId,n)?{state:"applied",result:{id:i.id,op:"release"}}:i.assignee!==void 0||i.claimPrincipal!==void 0?{state:"pending"}:{state:"applied",result:{id:i.id,op:"release"}}},async prepareCompensation(){return oe(e.pmRoot,t)},async apply(){let i=(await Pe(t.id,j(t.options,{author:e.author,message:T(e.transactionId,n,"apply")}),{pmRoot:e.pmRoot})).item;return e.uniqueIndex.invalidate(),{id:String(i.id),op:"release"}},async compensate(i){await P(e,t.id,n,i)}}}function gt(e,t,n){let i=re(t,n);switch(t.op){case"create":return wt(e,t,i);case"update":return dn(e,t,i);case"close":return un(e,t,i);case"release":return pn(e,t,i)}}function ln(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"].includes(e.op))throw new TypeError(`Bulk mutation ${t+1} op must be create, update, close, or release`);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(e.op==="create"&&e.unique!==void 0&&!dt(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.match!==void 0&&!dt(e.match))throw new TypeError(`Bulk update mutation ${t+1} match must be an object with a non-empty key and a value`);k(e.options,e.op,t)}function vt(e){if(e.length===0)throw new TypeError("Bulk item transaction requires at least one mutation");let t=new Map;for(let[n,i]of e.entries()){if(ln(i,n),i.op!=="create"||i.unique===void 0)continue;let{key:r,value:o}=i.unique,a=t.get(r)??new Map,s=v(o),d=a.get(s);if(d!==void 0)throw new c(`Bulk create mutations ${d+1} and ${n+1} share the upsert key value ${JSON.stringify(s)} for "${r}".`,u.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."});a.set(s,n),t.set(r,a)}}async function Z(e,t,n){try{return await n()}catch(i){throw i instanceof c?new c(i.message,i.exitCode,{...i.context,transaction_operation:{index:t,op:e.op,id:e.id}}):i}}function _t(e,t,n,i){let r=m.relative(e,t);return["locks","runtime","search"].includes(r.split(m.sep)[0])?i.some(o=>r===o||r.startsWith(`${o}${m.sep}`)||o.startsWith(`${r}${m.sep}`)):r===""||n===void 0||n.some(o=>r===o||r.startsWith(`${o}${m.sep}`)||o.startsWith(`${r}${m.sep}`))}async function N(e,t){let n=await ut(t);if(n.isSymbolicLink())await te(t);else if(n.isDirectory()||n.isFile())return n;throw A(m.relative(e,t))}async function mn(e,t){let n=await rn(t,X.O_RDONLY|X.O_NOFOLLOW|X.O_NONBLOCK);try{let i=await n.stat();if(!i.isFile())throw A(m.relative(e,t));let r=ee.createHash("sha256");if(i.size>0)for await(let o of n.createReadStream({highWaterMark:64*1024,end:i.size-1,autoClose:!1}))r.update(o);return r.digest()}finally{await n.close()}}async function Q(e,t,n){let i=ee.createHash("sha256");async function r(o){for(let a of(await on(o)).sort()){let s=m.join(o,a);_t(e,s,t,n)&&((await N(e,s)).isDirectory()?await r(s):(i.update(JSON.stringify(m.relative(e,s))),i.update(await mn(e,s))))}}return await r(e),i.digest("hex")}function C(){return new c("Tracker changed while preparing the transaction preview; retry against stable state.",u.CONFLICT,{code:"transaction_preview_snapshot_changed"})}async function ae(e){if(!G(e))return!1;let t=e.path;if(typeof t!="string")return!1;let n=m.resolve(t),i=n;for(;;)try{let r=await ut(i);return i!==n&&r.isDirectory()}catch(r){if(!G(r))return!1;let o=m.dirname(i);if(o===i)return!1;i=o}}async function D(e,t){let n=m.join(e,t);try{let i=e;for(let r of t.split(m.sep).slice(0,-1))i=m.join(i,r),await N(e,i);if(!(await N(e,n)).isFile())throw A(t);return await ue(n,A(t))}catch(i){if(await ae(i))return;throw i}}async function Et(e,t,n,i){let r=K(n);for(let[o,a]of Object.entries(r.files)){let s=m.relative(e,ge(e,a,we[o]));if(s===""||!m.resolve(e,s).startsWith(m.join(e,m.sep)))throw new c("Transaction preview requires schema files inside the selected tracker root; relocate the configured schema file before retrying.",u.USAGE,{code:"transaction_preview_external_schema",field:`schema.files.${o}`});r.files[o]=s;let d=await D(e,s);if(i?.set(s,d),d!==void 0){let l=m.join(t,s);await nn(m.dirname(l),{recursive:!0}),await ft(l,d)}}return ve(t,r)}async function fn(e,t){await te(e);let n=await pt(m.join(yt(),"pm-schema-plan-"));try{let i=await lt(e);return await Et(i,m.join(n,"configuration"),t)}catch(i){throw await ae(i)?C():i}finally{await mt(n,{recursive:!0,force:!0})}}async function yn(e,t,n){let i=new Map,r=await D(e,I);i.set(I,r);let o;try{o=JSON.parse(r??"null")}catch{o=null}let a=be(o),s=a.success?a.data:void 0,d=await Et(e,t,s?.schema,i),l=d.schema,p=m.relative(e,Se(e));i.set(p,await D(e,p));let f=x({...de,item_types:{definitions:[...s?.item_types?.definitions??[],...d.type_definitions_from_file??[]]}},n),w=pe(e)===e?[...ce.filter(Boolean),I,ye,"transactions",...f.folders,...i.keys()].map(g=>m.normalize(g)):void 0,h=s===void 0?void 0:JSON.stringify({...o,schema:{...s.schema,files:l.files}});return{configuration:i,ownedPaths:w,stagedSettings:h,registryFolders:f.folders}}async function hn(e,t,n){await te(e);try{let i=await lt(e),r=await yn(i,m.join(m.dirname(t),"configuration"),n),o=[...r.configuration.keys(),...r.registryFolders].map(l=>m.normalize(l)),a=await Q(i,r.ownedPaths,o);await tn(i,t,{recursive:!0,dereference:!1,filter:async l=>_t(i,l,r.ownedPaths,o)?(await N(i,l),!0):!1});let[s,d]=await Promise.all([Q(i,r.ownedPaths,o),Q(t,r.ownedPaths,o)]);if(a!==s||a!==d)throw C();for(let[l,p]of r.configuration)if(await D(t,l)!==p)throw C();r.stagedSettings!==void 0&&await ft(m.join(t,I),r.stagedSettings)}catch(i){throw await ae(i)?C():i}}async function St(e){let t=Oe(e),n=[...e.mutations];vt(n);let i=q(),r=await pt(m.join(yt(),"pm-transaction-preview-")),o=m.join(r,"tracker");try{await hn(t.pmRoot,o,i);let a=!1,s=[];return await qe({path:o,noExtensions:!0},async()=>{fe(i);let d={...t,pmRoot:o,createCompensation:"close",uniqueIndex:ht(o)},l=n.map((p,f)=>{let w=gt({...d,onCreateWarnings:(h,g)=>{g.length>0&&s.push({index:f,id:h,op:"create",warnings:g})}},p,f);return{...w,inspect:()=>Z(p,f,()=>w.inspect()),prepareCompensation:()=>Z(p,f,async()=>w.prepareCompensation?.()),apply:()=>Z(p,f,()=>w.apply())}});await J({...t,pmRoot:o,steps:l,onTransition:({transition:p})=>{p==="committed"&&(a=!0)}})}),{validated:a,state:a?"staged_snapshot":"replayed_committed_plan",warnings:s,unresolved_commit_constraints:["concurrent_tracker_changes","extension_mutation_guards_and_hooks"]}}finally{await mt(r,{recursive:!0,force:!0})}}async function wn(e){let t=[...e.mutations];vt(t);let n=e.createCompensation??"close";if(!["close","delete"].includes(n))throw new TypeError("Bulk item transaction createCompensation must be close or delete");let i={pmRoot:e.pmRoot,author:e.author,transactionId:e.transactionId,createCompensation:n,uniqueIndex:ht(e.pmRoot)},r=await J({pmRoot:e.pmRoot,transactionId:e.transactionId,author:e.author,steps:t.map((a,s)=>gt(i,a,s)),...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,s]of t.entries()){let d=re(s,a),l=r.results[d];o[cn(s,a)]=l}return{transactionId:r.transactionId,status:"committed",recovered:r.recovered,results:o}}function gn(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 Bi(e){return wn({pmRoot:e.pmRoot,transactionId:e.transactionId,author:e.author,mutations:gn(e),...e.lockTtlSeconds===void 0?{}:{lockTtlSeconds:e.lockTtlSeconds},...e.lockWaitMs===void 0?{}:{lockWaitMs:e.lockWaitMs},...e.onTransition===void 0?{}:{onTransition:e.onTransition}})}var Yi={buildCreateStep:wt,bulkHistoryMarker:T,compensateByRestore:P,deriveStepId:re,isUpdateMarkerApplied:F,readItemSnapshot:_};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3041c268-69c8-58e5-8a68-eaaa3c0dbd3b")}catch{}})();async function rr(e){let{plan:t}=e,n=await St({pmRoot:e.pmRoot,author:e.author,transactionId:t.transaction_id,mutations:t.mutations}),i=new Map(n.warnings.map(o=>[o.index,o.warnings])),r=t.rows.map(o=>{let a={...o};delete a.warnings;let s=i.get(o.index);return s!==void 0&&(a.warnings=s),a});return{validation:n,rows:r}}async function or(e){let t=e.upsertKey?.trim();if(t!==void 0&&t.length===0)throw new c("Upsert key must be a non-empty field name.",u.USAGE);let n=e.settings??await M(e.pmRoot),i=e.transactionId?.trim()??"",r=i.length>0?i:nt(e.input),o=await ne(e.pmRoot,n),a=_e(o.schema).definitions,s=(a.find(l=>l.metadata_key===t)??a.find(l=>l.key===t||E(l)===t))?.metadata_key??R(t),d=s===void 0?void 0:{key:s,existing:await ie(e.pmRoot,n,o,s)};return{...ct(e.input,{transactionId:r,idPrefix:n.id_prefix,runtimeFields:a,...d===void 0?{}:{upsert:d}}),transaction_id:r,transaction_id_source:i.length>0?"explicit":"derived",...d===void 0?{}:{upsert_key:d.key}}}export{nt as a,_i as b,it as c,v as d,ct as e,en as f,Ei as g,ne as h,ie as i,fn as j,St as k,wn as l,gn as m,Bi as n,Yi as o,rr as p,or as q};
|
|
2
|
+
//# sourceMappingURL=chunk-QQYCB2LO.js.map
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{Af as f,Cf as p,if as d,xf as c,yf as _}from"./chunk-PNPE2OVJ.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},r=new e.Error().stack;r&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[r]="8467eccc-684d-56cc-8b18-5f2e940abb42")}catch{}})();var m="not-a-declared-intent",i="not-a-declared-field";function g(){let e={get:["pm-domain"],search:["Domain query"]},r=[...new Set(d.map(({command:o})=>o))].map(o=>{let a=d.filter(n=>n.command===o),s=a[0],u=e[s.command]??[];return{probe_id:`${s.command}-invalid-intent`,command:s.command,flag:"--for",rejected_value:m,refusal_args:[s.command,...u,"--for",m],allowed_values:a.map(({intent:n})=>n).sort(),suggested_retry_args:[s.command,...u,"--for",s.intent],error_code:"unknown_context_intent"}}),t=_(),l=Object.keys(c).map(o=>({probe_id:`${o}-invalid-field`,command:o,flag:"--fields",rejected_value:i,refusal_args:[o,"--fields",i],allowed_values:t,suggested_retry_args:[o,"--fields","id,title,status"],error_code:"unknown_field_projection"}));return[...r,...l,{probe_id:"get-invalid-field",command:"get",flag:"--fields",rejected_value:i,refusal_args:["get","pm-domain","--fields",i],allowed_values:f(),suggested_retry_args:["get","pm-domain","--fields","id,title,status"],error_code:"unknown_field_projection"},{probe_id:"list-mutually-exclusive-projection",command:"list",flag:"--projection",rejected_value:"--brief+--full",refusal_args:["list","--brief","--full"],allowed_values:[],suggested_retry_args:["list","--brief"],error_code:"projection_options_mutually_exclusive",allowed_values_required:!1},{probe_id:"get-mutually-exclusive-projection",command:"get",flag:"--projection",rejected_value:"--full+--fields",refusal_args:["get","pm-domain","--full","--fields","id"],allowed_values:[],suggested_retry_args:["get","pm-domain","--full"],error_code:"projection_options_mutually_exclusive",allowed_values_required:!1},{probe_id:"search-mutually-exclusive-projection",command:"search",flag:"--projection",rejected_value:"--full+--fields",refusal_args:["search","Domain query","--full","--fields","id"],allowed_values:[],suggested_retry_args:["search","Domain query","--full"],error_code:"projection_options_mutually_exclusive",allowed_values_required:!1},{probe_id:"package-upgrade-mutually-exclusive-modes",command:"package upgrade",flag:"--cli-only/--packages-only",rejected_value:"--cli-only+--packages-only",refusal_args:["package","upgrade","--cli-only","--packages-only","--dry-run"],allowed_values:[],suggested_retry_args:["package","upgrade","--packages-only","--dry-run"],error_code:"package_upgrade_modes_mutually_exclusive",allowed_values_required:!1},{probe_id:"search-invalid-field",command:"search",flag:"--fields",rejected_value:i,refusal_args:["search","Domain query","--fields",i],allowed_values:p(),suggested_retry_args:["search","Domain query","--fields","id,title,status,score"],error_code:"unknown_field_projection"}].sort((o,a)=>o.probe_id.localeCompare(a.probe_id))}function v(e,r){let t=g().find(a=>a.command===e&&a.flag===r);if(!t)return"No stable core values are declared.";let l=t.allowed_values.filter(a=>!a.startsWith("item.")),o=r==="--fields"?" item.<field> aliases and configured runtime metadata fields are also accepted.":" Configured package and workspace intents may extend this domain.";return`Allowed core values: ${l.join("|")}.${o}`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},r=new e.Error().stack;r&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[r]="6279da21-92a5-57fe-bc0e-15a02111ab41")}catch{}})();function y(e){return e.map((r,t)=>{if(typeof r!="object"||r===null||Array.isArray(r))throw new TypeError(`NDJSON row ${t} must be a non-null object.`);let l=JSON.stringify(r);if(l===void 0)throw new TypeError(`NDJSON row ${t} must serialize to a non-null object.`);let o=JSON.parse(l);if(typeof o!="object"||o===null||Array.isArray(o))throw new TypeError(`NDJSON row ${t} must serialize to a non-null object.`);return l}).join(`
|
|
2
|
+
`)}function x(e,r){if(r.count!==e.length)throw new TypeError(`NDJSON trailer count ${r.count} does not match ${e.length} ${e.length===1?"row":"rows"}.`);for(let[t,l]of e.entries())if(typeof l=="object"&&l!==null&&!Array.isArray(l)&&Reflect.get(l,"record_type")==="pm.stream.trailer")throw new TypeError(`NDJSON row ${t} uses reserved record_type pm.stream.trailer`);return y([...e,{...r,record_type:"pm.stream.trailer"}])}export{g as a,v as b,y as c,x as d};
|
|
3
|
+
//# sourceMappingURL=chunk-TZU6U5ZE.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{$c as Ce,E as Ja,H as It,I as At,L as Oe,Q as qa,R as mn,_c as Ba,ad as tt,bd as Ha,cd as Ka,dd as ae,ed as ze,fd as Va,g as be,gd as re,hc as Wa,hf as Tt,k as Fa,l as Ma,m as ke,n as Ua,o as za,qe as Ya,y as Ga}from"./chunk-
|
|
1
|
+
import{$c as Ce,E as Ja,H as It,I as At,L as Oe,Q as qa,R as mn,_c as Ba,ad as tt,bd as Ha,cd as Ka,dd as ae,ed as ze,fd as Va,g as be,gd as re,hc as Wa,hf as Tt,k as Fa,l as Ma,m as ke,n as Ua,o as za,qe as Ya,y as Ga}from"./chunk-7NHA5K77.js";import{i as Za,n as Qa,p as ei}from"./chunk-KU4Q3MSI.js";import{$f as V,Aa as ga,Ac as Oa,Bb as ka,Bd as Ra,Cb as xa,Cc as Et,Cd as Qe,Db as Sa,Dc as Ca,Ec as Pa,G as pa,Gb as Ea,Hb as $a,Lf as Me,Oc as J,Pb as Ia,Q as kt,R as rn,Rb as Aa,Re as A,S as on,Sa as xt,Ta as ya,Ua as sn,Ub as Te,Va as cn,Wa as dn,Ya as _a,Ye as ne,Za as wa,Zc as W,_f as I,ab as va,ag as Na,bg as H,cg as ee,dh as ja,di as pn,eg as Da,fi as La,gg as et,gi as Ue,hb as ba,ig as $t,ih as K,j as sa,na as ma,oa as ua,oi as pe,pa as q,rc as ln,sc as Ta,tc as St,ti as C,ui as ve,v as B,vc as _e,xa as F,xc as we,ya as fa,z as ye,za as ha}from"./chunk-PNPE2OVJ.js";import{f as Xa}from"./chunk-QETMESEB.js";import{A as h,C as f,E as k,F as bt,G as ge,H as G,K as le,a as ca,d as vt,m as da,t as nn,v as la,y as an}from"./chunk-YECCKB4E.js";import{mkdir as gs,readFile as ys}from"node:fs/promises";import ii from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1fae5539-4eb8-5eba-bfd6-a191c89448ec")}catch{}})();var un=class extends Error{constructor(t="Workspace transaction interrupted"){super(t),this.name="WorkspaceTransactionInterruptedError"}},_s="sdk-workspace-transaction",ws=/^[a-zA-Z0-9._-]+$/,vs=30,bs=3e3;function ri(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let n=e.trim();if(!n||!ws.test(n))throw new TypeError(`${t} must match [a-zA-Z0-9._-]+`);return n}function ti(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 ks(e){return{pmRoot:ti(e.pmRoot,"Transaction pmRoot"),transactionId:ri(e.transactionId,"Transaction id"),author:ti(e.author,"Transaction author")}}function ni(e,t,n){let a=e??t;if(!Number.isInteger(a)||a<=0)throw new TypeError(`${n} must be a positive integer`);return a}function oi(e,t){return ii.join(e,"transactions","sdk",`${t}.json`)}async function xe(e,t){t.updatedAt=A();let n=oi(e,t.transactionId);await gs(ii.dirname(n),{recursive:!0}),await le(n,`${JSON.stringify(t,null,2)}
|
|
2
2
|
`)}function xs(e){return Number.isInteger(e.attempt)&&typeof e.author=="string"&&typeof e.createdAt=="string"&&typeof e.updatedAt=="string"}function Pe(e){return Object.assign(Object.create(null),e)}function Ss(e,t){try{let n=JSON.stringify(e,(a,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 fn(e,t){return e===void 0?void 0:Ss(e,t)}function hn(e,t,n,a){let i=fn(n,a);i===void 0?delete e[t]:e[t]=i}function ai(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function gn(e,t){return Array.isArray(e)&&new Set(e).size===e.length&&e.every(n=>typeof n=="string"&&t.includes(n))}function Es(e,t){if(!gn(e.startedStepIds,t)||!gn(e.completedStepIds,t)||!ai(e.results)||!ai(e.compensationData))return!1;let n=e.startedStepIds,a=new Set(n),i=e.completedStepIds,r=new Set(i);return Object.keys(e.compensationData).some(o=>!a.has(o))||Object.keys(e.results).some(o=>!r.has(o))?!1:e.status==="committed"?t.every(o=>r.has(o)):e.status!=="compensated"||r.size===0&&a.size===0}function Ot(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 $s(e){return new f(`Workspace transaction ${e} journal does not match the supplied plan`,h.CONFLICT,{code:"transaction_plan_mismatch",required:"Replay the exact plan that started this transaction, or start a new transaction with a different id.",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.","Pass --transaction-id <new-id> (or a new transactionId over MCP) to commit the changed plan as its own transaction.","Run pm ops gc --scope transactions --dry-run to inspect abandoned journals before pruning them."]})}function Is(e,t,n){let a;try{a=JSON.parse(e)}catch{throw Ot(t,"invalid JSON")}if(!a||typeof a!="object"||Array.isArray(a))throw Ot(t,"expected an object");let i=a;if(!(i.schemaVersion===1&&i.transactionId===t))throw Ot(t,"schema version or transaction id does not match the journal file");let r=i.stepIds;if(!Array.isArray(r)||!gn(r,r)||!Es(i,r)||!xs(i)||typeof i.status!="string"||!["applying","compensating","compensated","committed"].includes(i.status))throw Ot(t,"invalid lifecycle, metadata, status or step ids");if(!(i.status==="compensated"||r.length===n.length&&r.every((o,s)=>o===n[s])))throw $s(t);return{...i,results:Pe(i.results),compensationData:Pe(i.compensationData)}}async function As(e,t,n,a,i){let r=i,o=r!==void 0;if(r?.status==="compensating"&&await si(e,r),r===void 0||r.status==="compensated"){let s=A();r={schemaVersion:1,transactionId:t,author:n,status:"applying",attempt:(r?.attempt??0)+1,createdAt:r?.createdAt??s,updatedAt:s,stepIds:a,startedStepIds:[],completedStepIds:[],results:Pe(),compensationData:Pe()},await xe(e.pmRoot,r),await me(e,r,"prepared")}return{journal:r,recovered:o}}async function Ts(e,t,n){try{await Cs(t,e.steps),await xe(e.pmRoot,t);let a=new Set(t.completedStepIds),i=new Set(t.startedStepIds);for(let r of e.steps){if(a.has(r.id))continue;let o=await r.inspect(),s=fn(o.result,`Step ${r.id} result`);if(o.state!=="applied"){let d=await r.prepareCompensation?.();hn(t.compensationData,r.id,d,`Step ${r.id} compensation data`),i.add(r.id),t.startedStepIds=e.steps.map(l=>l.id).filter(l=>i.has(l)),await xe(e.pmRoot,t);let c=await r.apply();s=fn(c,`Step ${r.id} result`)}await me(e,t,"step_applied",r.id),a.add(r.id),t.completedStepIds=e.steps.map(d=>d.id).filter(d=>a.has(d)),hn(t.results,r.id,s,`Step ${r.id} result`),await xe(e.pmRoot,t),await me(e,t,"step_recorded",r.id)}return await me(e,t,"committing"),t.status="committed",await xe(e.pmRoot,t),await me(e,t,"committed"),{transactionId:t.transactionId,status:"committed",recovered:n,results:Pe(t.results)}}catch(a){if(a instanceof un||t.status==="committed")throw a;try{await si(e,t)}catch(i){throw new AggregateError([a,i],`Workspace transaction failed and compensation failed: ${String(i)}`,{cause:i})}throw a}}async function Os(e,t,n){try{return Is(await ys(oi(e,t),"utf8"),t,n)}catch(a){if(a!==null&&typeof a=="object"&&"code"in a&&ge(a))return;throw a}}async function me(e,t,n,a){await e.onTransition?.({transactionId:t.transactionId,attempt:t.attempt,transition:n,...a===void 0?{}:{stepId:a}})}async function Cs(e,t){let n=new Set,a=Pe();for(let i of t){let r=await i.inspect();r.state==="applied"&&(n.add(i.id),hn(a,i.id,r.result,`Step ${i.id} result`))}e.results=a,e.completedStepIds=t.map(i=>i.id).filter(i=>n.has(i))}async function si(e,t){t.status="compensating",await xe(e.pmRoot,t),await me(e,t,"compensating");let n=new Set(t.completedStepIds),a=new Set(t.startedStepIds);for(let i of[...e.steps].reverse()){if(!a.has(i.id)&&!n.has(i.id))continue;let r;try{r=a.has(i.id)&&(await i.inspect()).state==="applied"}catch{r=a.has(i.id)}r&&(await me(e,t,"step_compensating",i.id),await i.compensate(t.compensationData[i.id])),n.delete(i.id),a.delete(i.id),t.completedStepIds=e.steps.map(o=>o.id).filter(o=>n.has(o)),t.startedStepIds=e.steps.map(o=>o.id).filter(o=>a.has(o)),delete t.results[i.id],delete t.compensationData[i.id],await xe(e.pmRoot,t),await me(e,t,"step_compensated",i.id)}t.status="compensated",await xe(e.pmRoot,t),await me(e,t,"compensated")}async function ci(e){let{pmRoot:t,transactionId:n,author:a}=ks(e),i=ni(e.lockTtlSeconds,vs,"Transaction lock TTL"),r=ni(e.lockWaitMs,bs,"Transaction lock wait"),o=[...e.steps];if(o.length===0)throw new TypeError("Workspace transaction requires at least one step");let s=o.map(l=>{let p=ri(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 d={...e,pmRoot:t,transactionId:n,author:a,steps:o,lockTtlSeconds:i,lockWaitMs:r},c=await ne(t,_s,i,a,!1,!1,r);try{let l=await Os(t,n,s),p=l!==void 0;if(l?.status==="committed")return{transactionId:n,status:"committed",recovered:!0,results:Pe(l.results)};let m=await As(d,n,a,s,l);return await Ts(d,m.journal,p||m.recovered)}finally{await c()}}import Ps from"node:fs/promises";import Rs from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7be00b26-4a56-5399-94f6-f2f67cc5c1e6")}catch{}})();function yn(e){return Rs.join(e,"extension-migrations.json")}function di(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 li(e,t){return`${e.layer}:${e.name}:${t}`}async function Ns(e){let t=yn(e);if(!await k(t))return{version:1,updated_at:"",entries:[]};let n=JSON.parse(await Ps.readFile(t,"utf8"));return{version:1,updated_at:typeof n.updated_at=="string"?n.updated_at:"",entries:Array.isArray(n.entries)?n.entries.filter(a=>typeof a?.key=="string"&&(a.status==="applied"||a.status==="failed")):[]}}async function Ds(e,t){let n=await Ns(e),a=new Map(n.entries.map(i=>[i.key,i]));return t.forEach((i,r)=>{let o=di(i,r),s=a.get(li(i,o));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 js(e){let t=await Ds(e.pmRoot,e.migrations),n=new Map(t.entries.map(l=>[l.key,l])),a=[],i=!1,r=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 r){let m=di(l,p),y=li(l,m),g=n.get(y),_=String(l.definition.status??"pending").toLowerCase(),u=g?.status??(_==="applied"||_==="failed"?_:"pending");if(u==="applied"){a.push({key:y,layer:l.layer,extension:l.name,id:m,before:u,outcome:"skipped"});continue}if(e.dryRun===!0){a.push({key:y,layer:l.layer,extension:l.name,id:m,before:u,outcome:"pending"});continue}let w=l.runtime_definition?.run??l.definition.run;if(typeof w!="function"){a.push({key:y,layer:l.layer,extension:l.name,id:m,before:u,outcome:"pending"});continue}let v=new Date().toISOString();try{await Promise.resolve(w({id:m,command:"migration",layer:l.layer,extension:l.name,pm_root:e.pmRoot,status:u}));let S={key:y,layer:l.layer,extension:l.name,id:m,status:"applied",attempted_at:v};n.set(y,S),l.definition.status="applied",delete l.definition.reason,delete l.definition.error,delete l.definition.message,a.push({key:y,layer:l.layer,extension:l.name,id:m,before:u,outcome:"applied"}),i=!0}catch(S){let x=S instanceof Error?S.message:String(S),T={key:y,layer:l.layer,extension:l.name,id:m,status:"failed",attempted_at:v,error:x};n.set(y,T),l.definition.status="failed",l.definition.reason=x,a.push({key:y,layer:l.layer,extension:l.name,id:m,before:u,outcome:"failed",error:x}),i=!0}}if(i){let l=await C(e.pmRoot),p={version:1,updated_at:new Date().toISOString(),entries:[...n.values()].sort((m,y)=>m.key.localeCompare(y.key))};await Ue({pmRoot:e.pmRoot,filePath:yn(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 o=a.filter(l=>l.outcome==="pending").length,s=a.filter(l=>l.outcome==="applied").length,d=a.filter(l=>l.outcome==="skipped").length,c=a.filter(l=>l.outcome==="failed").length;return{ok:c===0,dry_run:e.dryRun===!0,state_path:yn(e.pmRoot),total:a.length,pending_count:o,applied_count:s,skipped_count:d,failed_count:c,migrations:a}}async function pi(e){let t=await C(e.resolvedRoots.settings_root),n=await _e({pmRoot:e.resolvedRoots.pm_root,settings:t,cwd:process.cwd(),noExtensions:e.global.noExtensions===!0}),a=await we(n);e.warnings.push(...n.warnings,...a.warnings);let i=await js({pmRoot:e.resolvedRoots.pm_root,migrations:a.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:a.failed.length},i.ok)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="184c43e0-a543-5b0b-ac09-9139ba5ded6a")}catch{}})();var Ls=[["beforeCommand","before_command"],["beforeMutation","before_mutation"],["afterCommand","after_command"],["onWrite","on_write"],["onRead","on_read"],["onIndex","on_index"]];function Ge(e,t={}){let n=new Set;t.extensionName!==void 0&&n.add(Et(t.extensionName));for(let u of t.extensionNames??[])n.add(Et(u));let a=u=>n.size===0||n.has(Et(u)),i=(u,w)=>mi(u.filter(v=>a(v.name)).map(w)),r=(u,w)=>mi(u.filter(v=>a(v.name)).flatMap(w)),{registrations:o,commands:s,parsers:d,preflight:c,services:l,renderers:p,hooks:m}=e,y=r(o.relationship_kinds??[],u=>u.definitions.map(w=>w.kind)),g=p.overrides.filter(u=>a(u.name)&&((u.commands?.length??0)>0||u.resultDiscriminator!==void 0)).map(u=>({format:u.format,commands:[...u.commands??[]],result_discriminator:u.resultDiscriminator!==void 0})).sort((u,w)=>u.format.localeCompare(w.format)),_=i(o.assurance_providers??[],u=>u.definition.id);return{capabilities:Ca(e,t),commands:i(o.commands,u=>u.command),command_overrides:i(s.overrides,u=>u.command),command_handlers:i(s.handlers,u=>u.command),hooks:Ls.filter(([u])=>m[u].some(w=>a(w.name))).map(([,u])=>u),flag_commands:i(o.flags,u=>u.target_command),item_types:r(o.item_types,u=>u.types.map(w=>w.name)),item_fields:r(o.item_fields,u=>u.fields.map(w=>w.name)),...y.length>0?{relationship_kinds:y}:{},migrations:r(o.migrations,u=>typeof u.definition.id=="string"?[u.definition.id]:[]),profiles:i(o.profiles,u=>u.profile.name),importers:i(o.importers,u=>u.importer),exporters:i(o.exporters,u=>u.exporter),search_providers:i(o.search_providers,u=>u.definition.name),vector_store_adapters:i(o.vector_store_adapters,u=>u.definition.name),..._.length>0?{assurance_providers:_}:{},parser_overrides:i(d.overrides,u=>u.command),service_overrides:i(l.overrides,u=>u.service),renderer_overrides:i(p.overrides,u=>u.format),...g.length>0?{renderer_ownership:g}:{},preflight_overrides:c.overrides.filter(u=>a(u.name)).length,preflight_ownership:c.overrides.filter(u=>a(u.name)).map(u=>({commands:[...u.commands??[]]}))}}function mi(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="caa9f916-c7ce-5e74-a00b-dd0fc6a41b5d")}catch{}})();var nt={type:"string",minLength:1,maxLength:128,pattern:"\\S"},Ct={type:"array",minItems:1,maxItems:sn,items:nt},ui={...Ct,items:{...nt,pattern:"^(?!(?:.*\\.)?(?:__proto__|constructor|prototype)(?:\\.|$))[a-zA-Z_][a-zA-Z0-9_]*(?:\\.[a-zA-Z_][a-zA-Z0-9_]*){0,7}$"}},Fs={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,Ct])),dependency:{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:nt,id:nt}}}},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:Ct}},...["field_writers","approval"].map(e=>({type:"object",additionalProperties:!1,required:["kind","fields","authors"],properties:{kind:{const:e},fields:ui,authors:Ct}})),{type:"object",additionalProperties:!1,required:["kind","allowed"],properties:{kind:{const:"transition"},allowed:{type:"array",maxItems:sn,items:{type:"array",minItems:2,maxItems:2,items:nt}}}}]}}},Tu={$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:ya,items:Fs}}};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="808f3bb5-cca5-5f9c-b557-7923c79ae6ce")}catch{}})();async function Ru(e,t,n,a){let i=await ke(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"]}:fi(i,t,n,a)}function Ms(e,t,n){return e===0?"undeclared":t===0?"empty":n===0?"inapplicable":n===t?"covered":"partial"}function fi(e,t,n=5,a=!1){let i=[],r=new Map,o=e.policies.filter(u=>u.rule.kind==="require_fields"),s=o.filter(u=>u.subject?.operations===void 0),d=new Set,c=0,l=0,p=0,m=0,y=0,g=va(e);for(let u of t){let w=g({operation:"",author:"",before:u,after:u,completeness_only:!0});c+=+(w.decisions.length>0),l+=w.decisions.length,w.decisions.forEach(x=>d.add(x.policy_id));let v=w.decisions.filter(x=>!x.satisfied);if(v.length===0)continue;m+=1;let S=r.get(u.type)??{items:0,violations:0,missing_fields:0};S.items+=1;for(let x of v)p+=1,S.violations+=1,S.missing_fields+=x.missing_fields.length,x.effect==="refuse"&&(y+=1),i.length<n&&i.push({id:u.id,type:u.type,status:u.status,decision:x});r.set(u.type,S)}let _=a||y>0?"error":p>0?"warn":"ok";return{check:{name:"completeness",status:_,ok:_==="ok",details:{scope:"operation_independent_require_fields",declared_requirement_count:o.length,state_requirement_count:s.length,applicable_requirement_count:d.size,requirement_application_count:l,governed_items:c,ungoverned_items:t.length-c,contract_status:Ms(o.length,t.length,c),applied_policy_ids:[...d].sort().slice(0,Math.max(0,n)),applied_policy_ids_truncated:d.size>Math.max(0,n),checked_items:t.length,incomplete_items:m,violation_count:p,refused_violations:y,missing_by_type:Object.fromEntries(r),violations:i,violations_truncated:i.length<p,enforcement:e.enforcement}},warnings:[...p>0?[`validate_completeness_missing_fields:${p}`]:[],...a?["validate_completeness_source_incomplete"]:[]]}}import Us from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0c3bed4d-4a17-5004-a1c5-65f6acec2a9b")}catch{}})();function zs(){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(([e,t])=>({id:`completeness-${e.toLowerCase()}`,effect:"advise",description:`Evidence expected when ${e} work reaches completion.`,subject:{types:[e],statuses:["closed"]},rule:{kind:"require_fields",fields:[...t]}})),{id:"completeness-resolution",effect:"advise",subject:{statuses:["closed"]},rule:{kind:"require_fields",fields:["resolution","expected_result","actual_result"]}}]}}function yi(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 Gs(e,t){let n=F(process.cwd(),e.path);await Me(n);let a=await C(n);return{pmRoot:n,settings:a,author:K(t,a.author_default)}}function hi(e,t,n,a){if(e==="policy-mode")return dn({...n,enforcement:t});let i=n.policies.filter(s=>s.id!==t);if(e==="policy-remove")return{...n,policies:i};let r=cn(a.definition),o=dn({...n,policies:[...i,r].sort((s,d)=>s.id.localeCompare(d.id))});if(Buffer.byteLength(`${JSON.stringify(o,null,2)}
|
|
4
4
|
`)>Fa)throw new f("Policy registry exceeds its byte ceiling.",h.USAGE);return o}async function gi(e,t,n,a){if(n.dryRun)return{policy_result:!0,action:e,changed:!1,result:hi(e,t,await ke(a.pmRoot),n)};let i=await La({pmRoot:a.pmRoot,filePath:Us.join(a.pmRoot,"schema","policies.json"),op:`schema:${e}`,author:a.author,message:n.message,lockTtlSeconds:a.settings.locks.ttl_seconds,lockWaitMs:a.settings.locks.wait_ms,mutate(r){let o=hi(e,t,Ma(r),n);return{raw:`${JSON.stringify(o,null,2)}
|
|
@@ -67,4 +67,4 @@ Agent guidance check
|
|
|
67
67
|
`),X.write(`Telemetry helps improve reliability and can be disabled anytime via pm config.
|
|
68
68
|
`);let d=t?"Y/n":"y/N",c=await n.question(`Enable telemetry for this project? [${d}] `),l=ns(c,t);return X.write(`
|
|
69
69
|
`),{prefix:i,preset:s,telemetry_enabled:l}}finally{n.close()}}function Xm(e){return{presetFromOption:aa(e.preset),useDefaults:e.defaults===!0,authorFromOption:Zo(e.author),installBundledPackages:e.withPackages===!0,agentGuidanceMode:ts(e.agentGuidance),typePreset:Xo(e.typePreset)}}function Zm(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 Qm(e,t,n,a){if(t.length===0||n)return;let i=a.discovery==="ancestor";throw new f(`${i?`No tracker exists in ${a.requested_cwd}; pm init found an ancestor tracker at ${a.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:a.tracker_root,requested_path:a.requested_cwd,suggested_path:a.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 eu(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&&(ia(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 tu(e){let t=await C(e.pmRoot);e.warnings.push(`already_exists:${e.settingsPath}`);let n=Zm({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption});return Qm(e.settingsPath,n,e.options.force===!0,e.target),eu({settings:t,normalizedPrefix:e.normalizedPrefix,prefixArg:e.prefixArg,presetFromOption:e.normalizedOptions.presetFromOption,authorFromOption:e.normalizedOptions.authorFromOption,warnings:e.warnings})&&await ve(e.pmRoot,t),{settings:t,normalizedPrefix:e.normalizedPrefix,chosenPreset:e.normalizedOptions.presetFromOption,wizardUsed:!1}}async function nu(e){let t=e.normalizedPrefix,n=e.normalizedOptions.presetFromOption,a,i=!1;if(e.normalizedOptions.presetFromOption===void 0&&!e.normalizedOptions.useDefaults&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0){let d=await cs(t,an.telemetry.enabled);t=d.prefix,n=d.preset,a=d.telemetry_enabled,i=!0}let r=n??"minimal",o=Km();o.id_prefix=t,ia(o,r);let s=ja()?.trim()||void 0;return o.author_default=e.normalizedOptions.authorFromOption??s??"",a!==void 0&&(o.telemetry.enabled=a,o.telemetry.first_run_prompt_completed=!0),await ve(e.pmRoot,o),{settings:o,normalizedPrefix:t,chosenPreset:n,wizardUsed:i}}async function Ho(e){return e.settingsExists?await tu(e):await nu({pmRoot:e.pmRoot,normalizedPrefix:e.normalizedPrefix,normalizedOptions:e.normalizedOptions})}async function au(e){let t=await Bo({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 ve(e.pmRoot,e.settings),{...t.summary,next_steps:t.next_steps}}async function iu(e,t){let n=[],a=[],i=await Da(e,t.schema);for(let r of i.created_paths)n.push(r),a.push(...await W({path:r,scope:"project",op:"init:runtime_schema_file"}));return{createdDirs:n,warnings:a}}async function ru(e){if(e.typePreset===void 0)return;let t=await is(e.pmRoot,e.settings,e.typePreset);return e.warnings.push(`registered_type_preset:${e.typePreset}`),e.warnings.push(...await W({path:t.file,scope:"project",op:"init:type_preset"})),t}async function ou(e){let t=q(e.settings,J()).folders.filter(a=>!nn.includes(a)),n=await ss(e.pmRoot,t);e.createdDirs.push(...n.createdDirs),e.warnings.push(...n.warnings)}function su(e){let t=j.resolve(e.tracker_root),n=j.dirname(t);return j.basename(t)==="pm"&&j.basename(n)===".agents"?j.dirname(n):e.workspace_root}async function cu(e,t,n,a){if(!e)return;let i=await Kn("all",{install:!0,project:!0},{...t,path:n});a.push(...i.warnings);let r=as(i),o=r.packages.filter(s=>!s.ok).map(s=>s.alias);if(!r.installed_all||o.length>0)throw new f(`pm init --with-packages did not install all bundled packages successfully${o.length>0?`: ${o.join(", ")}`:"."}`,h.GENERIC_FAILURE);return r}function ds(e){let t=a=>Qe([...e.target.mode==="workspace-discovery"?[]:["--pm-path",e.target.tracker_root],...a]),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 a of e.agentGuidanceNextSteps){let i=e.target.mode==="workspace-discovery"?a:a.replace(/\bpm (?=[a-z])/g,()=>`${t([])} `);n.includes(i)||n.push(i)}return n}async function ls(e,t,n,a=ei){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 a({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 du(e,t,n,a){if(e==null||n==="status")return;let i=await Xa(e,{pmRoot:t});i.changed&&a.push(`updated:gitignore:${i.path}`)}async function Ow(e,t,n={}){let a=t[Bm],i=typeof a=="string"?a:process.cwd(),r=Qo(i,t,e,n.workspace),o=r.pmRoot;e=es(r.prefixArg,n.idPrefix);let s=Xm(n);await os(o,r.target.mode==="tracker-path",n.force===!0);let d=[],c=[],l=j.join(o,"settings.json"),p=await k(l),m;p&&(m=await Ho({pmRoot:o,settingsPath:l,settingsExists:p,normalizedPrefix:be(e),prefixArg:e,options:n,normalizedOptions:s,warnings:c,target:r.target}));let y=await ss(o,nn);d.push(...y.createdDirs),c.push(...y.warnings),m??=await Ho({pmRoot:o,settingsPath:l,settingsExists:p,normalizedPrefix:be(e),prefixArg:e,options:n,normalizedOptions:s,warnings:c,target:r.target});let{settings:g}=m,_=su(r.target),u=await Za(_??j.dirname(o)),w=_??u,v=await au({pmRoot:o,cwd:w??i,agentGuidanceMode:s.agentGuidanceMode,settings:g,warnings:c}),S=await iu(o,g);d.push(...S.createdDirs),c.push(...S.warnings);let x=await ru({pmRoot:o,settings:g,typePreset:s.typePreset,warnings:c});x&&(g=await C(o)),await ou({pmRoot:o,settings:g,createdDirs:d,warnings:c}),await du(w,o,s.agentGuidanceMode,c),!p&&n.mergeFence!==!1&&s.agentGuidanceMode!=="status"&&await ls(o,u,c);let T=await cu(s.installBundledPackages,t,o,c),te=ds({installBundledPackages:s.installBundledPackages,registeredTypePreset:x,agentGuidanceNextSteps:v.next_steps,target:r.target});return{ok:!0,path:o,target:r.target,settings:g,created_dirs:d,warnings:c,governance_preset:g.governance.preset,wizard_used:m.wizardUsed,...x?{registered_type_preset:x}:{},...T?{installed_packages:T}:{},next_steps:te,agent_guidance:v}}export{un as a,ks as b,ci as c,yn as d,Ns as e,Ds as f,js as g,pi as h,Il as i,Ge as j,$i as k,We as l,Be as m,Ii as n,xi as o,Je as p,qe as q,Si as r,Fs as s,Tu as t,Ru as u,fi as v,zs as w,Yu as x,Ri as y,Li as z,$c as A,Ic as B,Qg as C,ny as D,ay as E,ht as F,iy as G,ry as H,oy as I,sy as J,cy as K,dy as L,ly as M,py as N,my as O,uy as P,fy as Q,hy as R,gy as S,yy as T,_y as U,wy as V,vy as W,by as X,ky as Y,xy as Z,Sy as _,Ey as $,$y as aa,Iy as ba,Ay as ca,Z as da,b as ea,Sn as fa,qc as ga,se as ha,Rt as ia,Ac as ja,at as ka,Nt as la,Zi as ma,sr as na,Ln as oa,vr as pa,Wh as qa,Vl as ra,eo as sa,to as ta,Jn as ua,Pr as va,kl as wa,lp as xa,Nr as ya,Kn as za,No as Aa,iw as Ba,Bo as Ca,Bm as Da,Aw as Ea,Tw as Fa,Ow as Ga};
|
|
70
|
-
//# sourceMappingURL=chunk-
|
|
70
|
+
//# sourceMappingURL=chunk-VLJLWZBO.js.map
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="826dab45-600c-58df-a150-eacecfb6ef95")}catch{}})();var b=["commands","renderers","hooks","schema","importers","search","parser","preflight","services"],F=2,v=Object.freeze({migration:"schema",validation:"schema"}),M=Object.freeze({version:2,capabilities:[...b],legacy_aliases:{...v}}),P=["off","warn","enforce"],U=["off","warn","enforce"],Y=["none","restricted","strict"],q=["block","warn"],W=["commands.override","commands.handler","hooks.beforecommand","hooks.beforemutation","hooks.aftercommand","hooks.onwrite","hooks.onread","hooks.onindex","schema.flags","schema.itemfields","schema.itemtypes","schema.relationshipkinds","schema.migrations","schema.profiles","parser.override","preflight.override","services.override","renderers.override","importers.importer","importers.exporter","search.provider","search.vectorstore","services.assuranceprovider"],X=["output_format","error_format","help_format","lock_acquire","lock_release","history_append","item_store_write","item_store_delete","context_relevance","command_result"];function m(){return{mode:"off",trust_mode:"off",require_provenance:!1,trusted_extensions:[],default_sandbox_profile:"none",allowed_extensions:[],blocked_extensions:[],allowed_capabilities:[],blocked_capabilities:[],allowed_surfaces:[],blocked_surfaces:[],allowed_commands:[],blocked_commands:[],allowed_actions:[],blocked_actions:[],allowed_services:[],blocked_services:[],extension_overrides:[]}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3d6df465-e82e-57d8-a687-6c2e720c99c1")}catch{}})();var E=["goal","objective","value","impact","outcome","why_now","parent","reviewer","risk","confidence","sprint","release","blocked_by","blocked_reason","unblock_note","reporter","severity","environment","repro_steps","resolution","expected_result","actual_result"],T=["id","title","description","type","pm_format_version","source_type","type_options","status","priority","tags","created_at","updated_at","deadline","reminders","events","closed_at","completed_at","assignee","claim_principal","source_owner","author","estimated_minutes","acceptance_criteria","design","external_ref","definition_of_ready","order",...E,"affected_version","fixed_version","component","regression","customer_impact","dependencies","comments","notes","learnings","files","tests","test_runs","docs","close_reason","duplicate_of","plan_mode","plan_scope","plan_harness","plan_resume_context","plan_validation","plan_decisions","plan_discoveries","plan_steps"],k=T;(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9a92abe3-1900-5a69-a35d-6aa592c83da0")}catch{}})();var I=Object.freeze([{id:"draft",roles:["draft"]},{id:"open",roles:["active","default_open"]},{id:"in_progress",aliases:["in-progress"],roles:["active"]},{id:"blocked",roles:["blocked"]},{id:"closed",roles:["terminal","terminal_done","default_close"]},{id:"canceled",aliases:["cancelled"],roles:["terminal","terminal_canceled","default_cancel"]}]),O=Object.freeze({draft_status:"draft",open_status:"open",in_progress_status:"in_progress",blocked_status:"blocked",close_status:"closed",canceled_status:"canceled"}),z=".agents/pm",$="settings.json",V="Closed at creation via pm create",N=["","epics","features","tasks","chores","issues","schema","history","search","extensions","locks"],A=["decisions","events","reminders","milestones","meetings","plans"],J=[...N,...A],Q={Epic:"epics",Feature:"features",Task:"tasks",Chore:"chores",Issue:"issues",Decision:"decisions",Event:"events",Reminder:"reminders",Milestone:"milestones",Meeting:"meetings",Plan:"plans"},D={minimal:{ownership_enforcement:"none",create_mode_default:"progressive",close_validation_default:"off",require_close_reason:!0,parent_reference:"strict_error",metadata_profile:"core",force_required_for_stale_lock:!1,duplicate_detection_mode:"off",duplicate_detection_threshold:.8,duplicate_detection_limit:3},default:{ownership_enforcement:"warn",create_mode_default:"progressive",close_validation_default:"warn",require_close_reason:!0,parent_reference:"strict_error",metadata_profile:"core",force_required_for_stale_lock:!0,duplicate_detection_mode:"strict",duplicate_detection_threshold:.8,duplicate_detection_limit:3},strict:{ownership_enforcement:"strict",create_mode_default:"strict",close_validation_default:"strict",require_close_reason:!0,parent_reference:"strict_error",metadata_profile:"strict",force_required_for_stale_lock:!0,duplicate_detection_mode:"strict",duplicate_detection_threshold:.8,duplicate_detection_limit:3}},S=["no active blocker","ready for planned execution sequencing","work completed","work is closed"],f={blocked_reason:["no active blocker because work is closed","work is closed"],resolution:["closed with implementation evidence","closed with verification evidence","work completed and recorded","work is closed"],actual_result:["closed and recorded","work completed","work completed and recorded"]};function h(e){return e?[...e]:void 0}var Z={version:1,id_prefix:"pm-",ids:{token_length:4},author_default:"",agent_identity:{probes_enabled:!0,identity_vocabulary:{version:1,aliases:{}},harness_signals:[]},mutation_guard:{require_attributed_author:!1,secret_guard:"advise",stale_in_progress_hours:72},item_format:"toon",locks:{ttl_seconds:1800,wait_ms:3e3},checkpoints:{retention_days:14},output:{default_format:"toon"},ux:{deprecation_hints:!0},history:{missing_stream:"auto_create",compact_policy:{enabled:!1,max_entries:500,trigger:"health_warn"}},validation:{sprint_release_format:"warn",parent_reference:"warn",metadata_profile:"core",metadata_required_fields:[],lifecycle_stale_blocker_reason_patterns:[...S],lifecycle_closure_like_blocked_reason_patterns:[...f.blocked_reason],lifecycle_closure_like_resolution_patterns:[...f.resolution],lifecycle_closure_like_actual_result_patterns:[...f.actual_result],estimate_defaults_by_type:{}},governance:{preset:"minimal",...D.minimal},workflow:{definition_of_done:[]},testing:{record_results_to_items:!1,allow_untrusted_linked_tests:!1},telemetry:{enabled:!0,first_run_prompt_completed:!1,capture_level:"redacted",endpoint:"https://pm-cli.unbrained.dev/v1/events",installation_id:"",retention_days:365},agent_guidance:{prompt_completed:!1,declined:!1,declined_at:"",template_version:1,last_checked_files:[]},item_types:{definitions:[]},schema:{version:1,files:{types:"schema/types.json",statuses:"schema/statuses.json",fields:"schema/fields.json",workflows:"schema/workflows.json"},statuses:I.map(e=>({...e,aliases:h(e.aliases),roles:h(e.roles)})),fields:[],workflow:{...O},unknown_field_policy:"allow"},extensions:{enabled:[],disabled:[],policy:m()},search:{score_threshold:0,hybrid_semantic_weight:.7,max_results:50,embedding_model:"",embedding_batch_size:32,embedding_timeout_ms:3e4,scanner_max_batch_retries:3,provider:"",default_mode:"auto",mutation_refresh_policy:"semantic_configured",query_expansion:{enabled:!1,provider:""},rerank:{enabled:!1,model:"",top_k:20}},providers:{openai:{base_url:"",api_key:"",model:""},ollama:{base_url:"",model:""}},context:{default_depth:"brief",activity_limit:10,stale_threshold_days:7,sections:{hierarchy:!0,activity:!0,progress:!0,recently_created:!0,unparented:!0,blockers:!0,files:!0,workload:!0,staleness:!0,tests:!0}},vector_store:{adapter:"",collection_name:"pm_items",qdrant:{url:"",api_key:""},lancedb:{path:""}}},H={metadata:{},body:""},w={SUCCESS:0,GENERIC_FAILURE:1,USAGE:2,NOT_FOUND:3,CONFLICT:4,DEPENDENCY_FAILED:5,NO_EFFECT:6,PARTIAL_EFFECT:7},R=Object.freeze({unknown_command:"usage",unknown_option:"usage",missing_required_option:"usage",missing_required_argument:"usage",invalid_command_usage:"usage",linked_test_value_not_quoted:"usage",invalid_argument_value:"validation",health_findings:"validation",validation_findings:"validation",close_through_update:"validation",no_update_fields:"validation",unsupported_update_option:"validation",tracker_not_initialized:"validation",item_not_found:"validation",ownership_conflict:"conflict",lock_conflict:"conflict",terminal_state_conflict:"conflict",dependency_failed:"runtime",init_gitignore_unwritable:"runtime",merge_git_config_unwritable:"runtime",command_failed:"runtime",unknown_error:"runtime"});function ee(e){let t=(e??"").trim().toLowerCase();if(t.length===0)return"unknown";let o=R[t];return typeof o=="string"?o:t.includes("conflict")||t.includes("locked")?"conflict":t.startsWith("unknown_")||t.startsWith("missing_required_")?"usage":t.startsWith("invalid_")||t.endsWith("_not_found")||t.includes("validation")?"validation":t.endsWith("_error")||t.endsWith("_failed")?"runtime":"unknown"}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1e7d4217-da18-5bfc-a00b-67bba61f57c2")}catch{}})();var u=class extends Error{exitCode;code;context;constructor(t,o,i={}){super(t),this.name="PmCliError",this.exitCode=o,this.context=i,this.code=i.code}};import*as r from"node:fs/promises";import{constants as p}from"node:fs";import c from"node:path";import C from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3792f1fd-ed9d-5252-887d-e4517a55fb9c")}catch{}})();var L=[10,25,50,100];async function y(e){await r.mkdir(e,{recursive:!0})}async function le(e){try{return await r.access(e),!0}catch{return!1}}function g(e){return x(e)||l(e,"ENOTDIR")}function x(e){return l(e,"ENOENT")}async function ce(e){try{return await r.readFile(e,"utf8")}catch(t){if(g(t))return null;throw t}}async function de(e,t){let o=await r.open(e,p.O_RDONLY|p.O_NOFOLLOW|p.O_NONBLOCK);try{if(!(await o.stat()).isFile())throw t;return await o.readFile("utf8")}finally{await o.close()}}function _e(e){let t=e?.replaceAll(c.sep,"/"),o=t!==void 0&&!c.posix.isAbsolute(t)&&!c.win32.isAbsolute(t)&&!t.split("/").includes(".."),i=o?t.split("/")[0]:void 0,s={"settings.json":"settings",runtime:"runtime",schema:"schema",history:"history",transactions:"transactions"},n=i===void 0?"tracker_storage":Object.hasOwn(s,i)?s[i]:"tracker_storage",d=o&&t.length>0&&t.length<=160&&t.split("/").every(a=>a!=="."&&/^[a-zA-Z0-9_.-]+$/u.test(a)),_=d?t:`${n} (entry name redacted)`;return new u(`Transaction preview requires regular files and directories. Inspect ${_} relative to the selected tracker root.`,w.USAGE,{code:"transaction_preview_non_regular_file",preview_storage:{storage_area:n,...d?{relative_entry:t}:{},entry_redacted:!d},required:"regular files and directories within the configured tracker storage",why:"Preview does not follow linked entries or read special files.",nextSteps:[`Inspect ${_} within the selected tracker for links, directories used as files, or special files; do not follow link targets.`,"Restore the intended regular files and directories, then retry the original dry-run command."]})}async function ue(e,t,o={}){let i=c.dirname(e);o.createParentDirectories!==!1&&await y(i);let s=c.join(i,`.${c.basename(e)}.${process.pid}.${Date.now()}.${C.randomBytes(4).toString("hex")}.tmp`);await r.writeFile(s,t,"utf8");try{await r.rename(s,e)}catch(n){if(process.platform==="win32"&&(l(n,"EPERM")||l(n,"EBUSY"))){let d=n;for(let _ of L){await new Promise(a=>setTimeout(a,_));try{await r.rename(s,e);return}catch(a){if(d=a,!l(a,"EPERM")&&!l(a,"EBUSY"))break}}try{await r.unlink(s)}catch{}throw d}if(l(n,"EXDEV")){try{await r.copyFile(s,e)}finally{try{await r.unlink(s)}catch{}}return}try{await r.unlink(s)}catch{}throw n}}async function fe(e,t){let o=c.dirname(e);await y(o);let i=await r.open(e,"a");try{await i.writeFile(`${t}
|
|
2
|
+
`,"utf8")}finally{await i.close()}}async function pe(e){try{await r.unlink(e)}catch(t){if(!g(t))throw t}}function l(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}export{b as a,F as b,v as c,M as d,P as e,U as f,Y as g,q as h,W as i,X as j,m as k,E as l,k as m,I as n,O as o,z as p,$ as q,V as r,N as s,J as t,Q as u,D as v,S as w,f as x,Z as y,H as z,w as A,ee as B,u as C,y as D,le as E,g as F,x as G,ce as H,de as I,_e as J,ue as K,fe as L,pe as M};
|
|
3
|
+
//# sourceMappingURL=chunk-YECCKB4E.js.map
|