@unbrained/pm-cli 2026.10.22 → 2026.10.23
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 +17 -0
- package/dist/cli/error-guidance.d.ts +12 -0
- package/dist/cli/error-guidance.js +2 -2
- package/dist/cli/register-setup.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/{chunk-5LSN7K4N.js → chunk-2LTGJ5DL.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-E3JC3WQL.js → chunk-2UX2TAN2.js} +15 -15
- package/dist/cli-bundle/chunks/{chunk-2B5HAZFK.js → chunk-3S5FLCG7.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-J444ZX23.js → chunk-5DKCD4KV.js} +39 -39
- package/dist/cli-bundle/chunks/{chunk-LIC5EUQS.js → chunk-5V4HU6GK.js} +48 -48
- package/dist/cli-bundle/chunks/{chunk-UYYTV2TX.js → chunk-AAX7CNL7.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-AOAQDCXX.js → chunk-AXGFNNI3.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-F76ZUP73.js +113 -0
- package/dist/cli-bundle/chunks/chunk-HDKY2YX3.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-7OTYULIJ.js → chunk-KY34HTT2.js} +29 -29
- package/dist/cli-bundle/chunks/{chunk-TNU3XVPC.js → chunk-MMVX5L32.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-PCPOTFJP.js → chunk-MTRYEVZR.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-O67N62DT.js → chunk-QSY55FTA.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-GWIGZDRS.js → chunk-R7KWBFM2.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-HC2DCGFA.js → chunk-REXCO5AG.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-ZDVTXLA6.js +9 -0
- package/dist/cli-bundle/chunks/{chunk-MV3KYY2A.js → chunk-ZEI3DC5E.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-URV4VHQ4.js → chunk-ZMJF5HQW.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-ZNDYAZZ6.js +6 -0
- package/dist/cli-bundle/chunks/{indexed-receipt-blobs-L3BOTMZN.js → indexed-receipt-blobs-XANVELIV.js} +2 -2
- package/dist/cli-bundle/chunks/{mutation-admission-TATOFEXF.js → mutation-admission-P6LOBNLO.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-GULR2IYO.js → register-list-query-JOB65KDN.js} +2 -2
- package/dist/cli-bundle/chunks/{register-mutation-HLSQ4WVW.js → register-mutation-QMNIN3RJ.js} +2 -2
- package/dist/cli-bundle/chunks/{register-operations-FE3GGA7O.js → register-operations-Z4VET3I7.js} +2 -2
- package/dist/cli-bundle/chunks/register-setup-GNKWL3VL.js +2 -0
- package/dist/cli-bundle/chunks/{settlement-hook-UVFYSBMU.js → settlement-hook-YUVCO65H.js} +2 -2
- package/dist/cli-bundle/chunks/{stage-QCPZBZRC.js → stage-FW5OXCCR.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-EHPRSWJE.js → chunk-4MNUQCGR.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-CB7TSZ7P.js → chunk-6GTZ24YV.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-2GFTVXKZ.js → chunk-BM652VCB.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-3LWH2RJC.js → chunk-BUZ2Z4P3.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-QGDKWULS.js → chunk-CGL36F6I.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-TMN3RAXZ.js → chunk-DWQMYLFM.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-SXVJRLLP.js → chunk-EDXTOAXP.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-FO4U3FIP.js +91 -0
- package/dist/cli-bundle/focused-chunks/chunk-GXKP56W7.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-46HBJC6J.js → chunk-I2USTQNQ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-XX5JQCLF.js → chunk-JDN34LEZ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-GVKYTDOH.js → chunk-KI5YFKNN.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-UQ5JPBY2.js → chunk-LEHGCPZ6.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-KM77WU5U.js → chunk-MLET6I3I.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-25NQRZ7J.js → chunk-NSMZY6IK.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-OMXMYTEX.js +26 -0
- package/dist/cli-bundle/focused-chunks/{chunk-VYAZND5Q.js → chunk-P7DPS5M4.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-R536272H.js +9 -0
- package/dist/cli-bundle/focused-chunks/{chunk-CX5FNEFC.js → chunk-UNTCCJPL.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-A52W6GLA.js → chunk-XIZYJDYW.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-25L3L2PF.js → chunk-Z5LDTMZ3.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-ZHMF34DT.js +65 -0
- package/dist/cli-bundle/focused-chunks/{chunk-GC4VMLXL.js → chunk-ZR6ZKQUK.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-AAQOKO5B.js → indexed-receipt-blobs-FVOA3XMI.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{mutation-admission-TBKR4KRM.js → mutation-admission-HTFAIHJL.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{settlement-hook-MNCHFCAX.js → settlement-hook-2VXEB6PP.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{stage-RM6MJIMT.js → stage-X3BUGEJT.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 +5 -2
- package/dist/cli-bundle/sdk-core.js +33 -33
- 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 +58 -58
- 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 +12 -9
- package/dist/core/config/nested-settings.js +1 -1
- package/dist/core/extensions/loader.js +1 -1
- package/dist/core/extensions/version-diagnostics.d.ts +2 -0
- package/dist/core/extensions/version-diagnostics.js +2 -0
- package/dist/core/lock/lock.d.ts +40 -6
- package/dist/core/lock/lock.js +3 -3
- package/dist/core/shared/errors.d.ts +28 -0
- package/dist/core/shared/errors.js +1 -1
- package/dist/core/store/item-store.js +1 -1
- package/dist/mcp/http-server.js +2 -2
- package/dist/mcp/server.js +2 -2
- package/dist/sdk/cli-contracts/agent-output-contracts.js +1 -1
- package/dist/sdk/contracts.d.ts +1 -0
- package/dist/sdk/contracts.js +1 -1
- package/dist/sdk/extension/doctor.js +1 -1
- package/dist/sdk/extension/install-receipts.js +1 -1
- package/dist/sdk/extension/install-snapshot.d.ts +11 -0
- package/dist/sdk/extension/install-snapshot.js +1 -1
- package/dist/sdk/extension.d.ts +12 -0
- package/dist/sdk/extension.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
- package/dist/sdk/governance/health.d.ts +1 -0
- package/dist/sdk/governance/health.js +2 -2
- package/dist/sdk/index.d.ts +3 -2
- package/dist/sdk/index.js +1 -1
- package/dist/sdk/lifecycle/hierarchy-mutation-lock.js +1 -1
- package/dist/sdk/lifecycle/restore.js +1 -1
- package/dist/sdk/mcp/executable.d.ts +13 -0
- package/dist/sdk/mcp/executable.js +5 -0
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/runtime-primitives.d.ts +1 -1
- package/dist/sdk/runtime-primitives.js +1 -1
- package/dist/sdk/runtime.d.ts +1 -1
- package/dist/sdk/runtime.js +1 -1
- package/dist/sdk/workspace-snapshot.d.ts +5 -1
- package/dist/sdk/workspace-snapshot.js +3 -3
- package/dist/sdk/workspace.js +2 -2
- package/docs/CONFIGURATION.md +19 -3
- package/docs/EXTENSION_AUTHOR_CONTRACTS.md +2 -1
- package/docs/EXTENSION_LIFECYCLE.md +47 -0
- package/docs/MCP_REMOTE_TRANSPORT_SECURITY.md +16 -1
- package/docs/RELEASING.md +9 -0
- package/docs/SDK.md +39 -5
- package/docs/SDK_STORAGE_LIFECYCLE.md +2 -1
- package/docs/TESTING.md +11 -7
- package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +6 -3
- package/marketplace.json +1 -1
- package/package.json +1 -1
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-claude/package.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/pm-codex/package.json +1 -1
- package/plugins/pm-codex/plugin.json +1 -1
- package/runtime-dependencies.json +1 -1
- package/dist/cli-bundle/chunks/chunk-35ISFIPC.js +0 -113
- package/dist/cli-bundle/chunks/chunk-BAIVTLJM.js +0 -6
- package/dist/cli-bundle/chunks/chunk-C37RDYZI.js +0 -3
- package/dist/cli-bundle/chunks/chunk-VO3KDIU7.js +0 -9
- package/dist/cli-bundle/chunks/register-setup-XUIKAIZA.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-DVNUHTVK.js +0 -9
- package/dist/cli-bundle/focused-chunks/chunk-QWKCQ5PW.js +0 -91
- package/dist/cli-bundle/focused-chunks/chunk-SOVXHW6Z.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-UUPJ6OZL.js +0 -26
- package/dist/cli-bundle/focused-chunks/chunk-W2CND3BD.js +0 -65
|
@@ -1,91 +0,0 @@
|
|
|
1
|
-
import{$ as yt,Ea as $e,Ga as le,Oa as gt,Wa as wt,bb as bt,ca as ht,cb as ue,ea as _t,m as Le,n as ft,ua as Pe,va as je,wa as X,x as de,y as pt,z}from"./chunk-VYAZND5Q.js";import{b as ne}from"./chunk-EHPRSWJE.js";import{h as mt}from"./chunk-YLVHHWHN.js";import{Aa as Ne,Ba as ke,Ca as x,Dc as B,Jd as ce,Na as st,Ra as ct,Sa as dt,Ub as lt,a as ie,ic as U,kc as Oe,lc as ae,ma as it,mc as M,na as nt,nc as De,oc as se,pc as Me,qa as rt,sc as Fe,va as re,vd as ut,wd as Ae,xa as at}from"./chunk-UUPJ6OZL.js";import{A as ot,B as H,D as W,H as N,s as D,x as tt,y as h,z as f}from"./chunk-3LWH2RJC.js";import eo from"node:crypto";import me from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},o=new e.Error().stack;o&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[o]="664124e5-715d-5f86-ae69-89f203db76c3")}catch{}})();function It(e){let o=[],t=!1;for(let i of(e??"").toLowerCase()){let n=i.charCodeAt(0),r=n>=48&&n<=57,a=n>=97&&n<=122;if(!r&&!a){t=o.length>0;continue}t&&(o.push("-"),t=!1),o.push(i)}return o.length===0?"pm-":`${o.join("")}-`}function Y(e){let o=e.trim().toLowerCase();return o.startsWith("#")&&(o=o.slice(1)),o}function G(e,o){let t=It(o),i=Y(e);return i.startsWith(t)?i:`${t}${i}`}function to(e){let o=ut(e);if(o!==void 0)return o;let t="";for(let i=0;i<e;i+=1)t+=eo.randomInt(0,36).toString(36);return t}async function oo(e,o,t){let i=[...new Set(Object.values(t))].flatMap(n=>[me.join(e,n,`${o}.md`),me.join(e,n,`${o}.toon`)]);return i.push(me.join(e,"history",`${o}.jsonl`)),(await Promise.all(i.map(n=>H(n)))).some(Boolean)}var Et=4,vt=12;function io(e){return typeof e!="number"||!Number.isFinite(e)?Et:Math.min(vt,Math.max(Et,Math.trunc(e)))}async function Li(e,o,t={}){let i=io(t.tokenLength),n=Math.min(i+6,vt),r=0;for(;i<=n;){for(let a=0;a<32;a+=1){let c=`${It(o)}${to(i)}`;if(!await(t.probeExisting===!1?H(me.join(e,"history",`${c}.jsonl`)):oo(e,c,t.typeToFolder??D)))return c;r+=1}i+=1}throw new Error(`Unable to generate unique id after ${r} attempts`)}import Ct from"node:fs/promises";import K from"node:path";import{isUtf8 as no}from"node:buffer";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},o=new e.Error().stack;o&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[o]="7db1d069-0038-57f8-8c3e-0b0ba66579ca")}catch{}})();var ro=1048576,ao=4194304;async function Tt(e,o){let t=K.dirname(e);for(;t!==K.parse(e).root;){let n=await Ct.stat(t).catch(r=>{if(W(r))return null;throw r});if(n!==null){if(!n.isDirectory())throw new f("Workflow policy storage ancestor must be a directory.",h.CONFLICT,{code:"workflow_policy_input_unreadable",nextSteps:["Restore the policy or approval history directory before retrying."]});break}t=K.dirname(t)}let i=await Ct.open(e,"r").catch(n=>{if(W(n))return null;throw n});if(i===null)return null;try{let n=(await i.stat()).size,r=Buffer.alloc(Math.min(o,n)+1),a=0;for(;a<r.length;){let c=await i.read(r,a,r.length-a,a);if(c.bytesRead===0)break;a+=c.bytesRead}if(a===r.length||!no(r.subarray(0,a)))throw new f("Workflow policy input exceeds its byte bound or is not valid UTF-8.",h.CONFLICT,{code:"workflow_policy_input_unreadable",nextSteps:["Inspect the policy and approval history; reduce the declaration or use verified history compaction before retrying."]});return r.toString("utf8",0,a)}finally{await i.close()}}function so(e){if(e===null)return{version:1,enforcement:"advise",policies:[]};let o;try{o=JSON.parse(e)}catch{throw new f("schema/policies.json must contain valid JSON.",h.CONFLICT,{code:"workflow_policy_registry_invalid",nextSteps:["Restore valid policy JSON before retrying the mutation."]})}return st(o)}async function co(e){return so(await Tt(K.join(e,"schema","policies.json"),ro))}async function lo(e,o){let t=await Tt(x(e,o),ao);if(t===null)return[];let i;try{if(i=t.split(/\r?\n/).filter(n=>n.trim()).map(n=>JSON.parse(n)),!le(i).ok)throw new Error("invalid chain")}catch{throw new f("Approval evidence requires a valid item history chain.",h.CONFLICT,{code:"workflow_policy_approval_history_invalid",nextSteps:[`Run pm history ${o} --verify before recording or using an approval.`]})}return i.flatMap(n=>{let r=n.context?.workflow_approval;if(n.op!=="policy_approve"||n.record_hash_version!==1||typeof n.record_hash!="string"||typeof r!="object"||r===null)return[];let a=r;return typeof a.policy_fingerprint!="string"||typeof a.content_fingerprint!="string"?[]:[{policy_fingerprint:a.policy_fingerprint,content_fingerprint:a.content_fingerprint,author:n.author}]})}async function uo(e,o,t){let i=t.before?.status!==t.after?.status&&o.policies.some(a=>a.rule.kind==="approval"&&ct(a,t)),n=t.before?.id??t.after?.id,r=i&&typeof n=="string"?await lo(e,n):[];return dt(o,{...t,approvals:r})}async function He(e){let o=await co(e.pmRoot),t=await uo(e.pmRoot,o,{operation:e.operation,author:e.author,before:e.before?{...e.before.metadata,body:e.before.body}:null,after:e.after?{...e.after.metadata,body:e.after.body}:null});if(t.allowed)return t;let i=t.decisions.filter(d=>!d.satisfied&&d.effect==="refuse");if(!e.dryRun)try{await gt({pmRoot:e.pmRoot,op:"policy_refused",author:e.author,context:{item_id:e.after?.metadata.id??e.before?.metadata.id,operation:e.operation,workflow_policies:t.decisions},message:"Workflow policy refused a proposed item mutation.",lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}catch(d){let u=new f("Workflow policy refusal could not be recorded in workspace history.",h.CONFLICT,{code:"workflow_policy_audit_failed",nextSteps:["Resolve workspace-history lock or storage failures, then retry the refused mutation; no item changes were written."]});throw u.cause=d,u}let n=i.slice(0,3).map(d=>({policy_id:d.policy_id,rule:d.rule,description:o.policies.find(u=>u.id===d.policy_id).description,missing_fields:d.missing_fields})),r=[...new Set(n.flatMap(d=>d.missing_fields))],a=n.map(d=>`${d.policy_id} (${d.rule})`).join(", "),c=i.length>3?` and ${i.length-3} more`:"",s=e.after?.metadata.id??e.before.metadata.id,l=r.map(d=>{if(e.before===null)return`Supply ${d} in the original ${e.operation} request, then retry; the item was not created.`;let u=it("update",d);return u===void 0?`Supply ${d} using its declared SDK or package mutation contract, then retry.`:B(["update",s,nt("update",u),`<${d}>`,"--pm-path",K.resolve(e.pmRoot)])});throw new f(`Workflow policy refused ${e.operation}: ${a}${c}.${r.length?` Missing: ${r.join(", ")}.`:""}`,h.CONFLICT,{code:"workflow_policy_refused",reason:n.map(d=>d.policy_id).join(","),policy_violations:n,policy_violation_count:i.length,required:r.length?`Supply missing fields: ${r.join(", ")}, then retry the refused mutation.`:"Satisfy the declared workflow policy before retrying.",why:n.map(d=>d.description).filter(Boolean).join(" ")||void 0,recovery:{missing_required_fields:r},nextSteps:[...l,...new Set(i.slice(0,3).filter(d=>d.missing_fields.length===0).map(d=>d.remediation)),...i.length>3?[`Inspect all policies with pm schema policies before retrying ${e.operation}.`]:[]]})}import{AsyncLocalStorage as mo}from"node:async_hooks";import{channel as fo}from"node:diagnostics_channel";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},o=new e.Error().stack;o&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[o]="b2b2d49a-bb8c-54d7-89d2-1dbe76879129")}catch{}})();var We=new mo,Ue=fo("@unbrained/pm-cli/item-metadata-enumeration/v1");function fe(e){Ue.publish(e)}async function Zi(e){let o={enumeration_calls:0,metadata_rows:0},t=i=>{We.getStore()?.includes(o)&&(o.enumeration_calls+=1,o.metadata_rows+=i)};Ue.subscribe(t);try{return{result:await We.run([...We.getStore()??[],o],e),work:{...o}}}finally{Ue.unsubscribe(t)}}import F from"node:fs/promises";import xt from"node:path";import{randomUUID as po}from"node:crypto";import{createRequire as yo}from"node:module";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},o=new e.Error().stack;o&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[o]="84a3dae8-69b6-589d-a8ec-11f77c1d103a")}catch{}})();var ho="metadata-query-index.sqlite",q="5",Be;function V(){return Be!==void 0||(Be=_t(process.versions.node,yo(import.meta.url))),Be}function St(e,o){return Math.max(0,Math.floor(e===void 0?o:e))}function A(e){return xt.join(e,"runtime",ho)}function _o(e){e.exec(`
|
|
2
|
-
PRAGMA foreign_keys = ON;
|
|
3
|
-
PRAGMA journal_mode = OFF;
|
|
4
|
-
PRAGMA synchronous = OFF;
|
|
5
|
-
CREATE TABLE metadata (
|
|
6
|
-
key TEXT PRIMARY KEY,
|
|
7
|
-
value TEXT NOT NULL
|
|
8
|
-
) STRICT;
|
|
9
|
-
CREATE TABLE items (
|
|
10
|
-
id TEXT PRIMARY KEY,
|
|
11
|
-
relative_path TEXT NOT NULL UNIQUE,
|
|
12
|
-
metadata_json TEXT NOT NULL,
|
|
13
|
-
status TEXT NOT NULL,
|
|
14
|
-
type TEXT NOT NULL,
|
|
15
|
-
priority INTEGER NOT NULL,
|
|
16
|
-
updated_at TEXT NOT NULL,
|
|
17
|
-
created_at TEXT NOT NULL,
|
|
18
|
-
parent TEXT,
|
|
19
|
-
assignee TEXT,
|
|
20
|
-
sprint TEXT,
|
|
21
|
-
release TEXT
|
|
22
|
-
) STRICT;
|
|
23
|
-
CREATE INDEX items_default_order
|
|
24
|
-
ON items(priority, updated_at DESC, id);
|
|
25
|
-
CREATE INDEX items_status_default_order
|
|
26
|
-
ON items(status, priority, updated_at DESC, id);
|
|
27
|
-
CREATE INDEX items_type_default_order
|
|
28
|
-
ON items(type, priority, updated_at DESC, id);
|
|
29
|
-
CREATE INDEX items_parent_default_order
|
|
30
|
-
ON items(parent, priority, updated_at DESC, id);
|
|
31
|
-
CREATE TABLE item_metadata_keys (
|
|
32
|
-
item_id TEXT NOT NULL,
|
|
33
|
-
key TEXT NOT NULL,
|
|
34
|
-
PRIMARY KEY(item_id, key),
|
|
35
|
-
FOREIGN KEY(item_id) REFERENCES items(id) ON DELETE CASCADE
|
|
36
|
-
) STRICT;
|
|
37
|
-
CREATE INDEX item_metadata_keys_key_item
|
|
38
|
-
ON item_metadata_keys(key, item_id);
|
|
39
|
-
CREATE TABLE item_linked_files (
|
|
40
|
-
item_id TEXT NOT NULL,
|
|
41
|
-
path TEXT NOT NULL,
|
|
42
|
-
scope TEXT NOT NULL,
|
|
43
|
-
note TEXT,
|
|
44
|
-
PRIMARY KEY(item_id, path, scope),
|
|
45
|
-
FOREIGN KEY(item_id) REFERENCES items(id) ON DELETE CASCADE
|
|
46
|
-
) STRICT;
|
|
47
|
-
CREATE INDEX item_linked_files_path_scope_item
|
|
48
|
-
ON item_linked_files(path, scope, item_id);
|
|
49
|
-
CREATE VIRTUAL TABLE item_search USING fts5(
|
|
50
|
-
id UNINDEXED,
|
|
51
|
-
title,
|
|
52
|
-
description,
|
|
53
|
-
tags,
|
|
54
|
-
tokenize = 'unicode61'
|
|
55
|
-
);
|
|
56
|
-
`)}function ye(e,o,t){e.prepare("INSERT INTO metadata(key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(o,t)}function Rt(e,o){let t=o.metadata;e.prepare(`INSERT INTO items(
|
|
57
|
-
id, relative_path, metadata_json, status, type, priority,
|
|
58
|
-
updated_at, created_at, parent, assignee, sprint, release
|
|
59
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
60
|
-
ON CONFLICT(id) DO UPDATE SET
|
|
61
|
-
relative_path = excluded.relative_path,
|
|
62
|
-
metadata_json = excluded.metadata_json,
|
|
63
|
-
status = excluded.status,
|
|
64
|
-
type = excluded.type,
|
|
65
|
-
priority = excluded.priority,
|
|
66
|
-
updated_at = excluded.updated_at,
|
|
67
|
-
created_at = excluded.created_at,
|
|
68
|
-
parent = excluded.parent,
|
|
69
|
-
assignee = excluded.assignee,
|
|
70
|
-
sprint = excluded.sprint,
|
|
71
|
-
release = excluded.release`).run(t.id,o.relativePath,JSON.stringify(t),t.status,t.type,t.priority,t.updated_at,t.created_at,t.parent??null,t.assignee??null,t.sprint??null,t.release??null),e.prepare("DELETE FROM item_metadata_keys WHERE item_id = ?").run(t.id),e.prepare("DELETE FROM item_linked_files WHERE item_id = ?").run(t.id),e.prepare("DELETE FROM item_search WHERE rowid = (SELECT rowid FROM items WHERE id = ?)").run(t.id),e.prepare("INSERT INTO item_search(rowid, id, title, description, tags) SELECT rowid, ?, ?, ?, ? FROM items WHERE id = ?").run(t.id,t.title,t.description,t.tags.join(" "),t.id);let i=e.prepare("INSERT INTO item_metadata_keys(item_id, key) VALUES (?, ?)");for(let r of Object.keys(t))i.run(t.id,r);let n=e.prepare("INSERT INTO item_linked_files(item_id, path, scope, note) VALUES (?, ?, ?, ?)");for(let r of o.linkedFiles??[])n.run(t.id,r.path,r.scope,r.note??null)}async function Nt(e){let o=A(e.pmRoot),t=V();if(!t){await F.rm(o,{force:!0});return}await F.mkdir(xt.dirname(o),{recursive:!0});let i=`${o}.${po()}.tmp`,n;try{n=new t(i),_o(n),n.exec("BEGIN IMMEDIATE"),ye(n,"version",q),ye(n,"context_fingerprint",e.contextFingerprint),ye(n,"source_cursor",e.sourceCursor);for(let r of e.rows)Rt(n,r);n.exec("COMMIT"),n.close(),n=void 0,await F.rm(o,{force:!0}),await F.rename(i,o)}catch(r){throw n?.close(),await Promise.allSettled([F.rm(i,{force:!0})]),r}}function he(e){return Object.fromEntries(e.prepare("SELECT key, value FROM metadata").all().map(o=>[String(o.key),String(o.value)]))}async function kt(e){let o=V();if(!o)return!1;let t=A(e.pmRoot),i;try{await F.access(t),i=new o(t),i.exec("PRAGMA foreign_keys = ON");let n=he(i);if(n.version!==q||n.context_fingerprint!==e.contextFingerprint||n.source_cursor!==e.expectedSourceCursor)return i.close(),!1;i.exec("BEGIN IMMEDIATE");let r=i.prepare("DELETE FROM items WHERE relative_path = ?"),a=i.prepare("SELECT rowid FROM items WHERE relative_path = ?"),c=i.prepare("DELETE FROM item_search WHERE rowid = ?");for(let s of e.deletedRelativePaths??[]){let l=a.get(s);r.run(s),l&&c.run(l.rowid)}return e.row&&Rt(i,e.row),ye(i,"source_cursor",e.sourceCursor),i.exec("COMMIT"),i.close(),!0}catch{try{i?.exec("ROLLBACK")}catch{}return i?.close(),!1}}function pe(e,o,t,i,n){!i||i.length===0||(e.push(`${t} ${n} (${i.map(()=>"?").join(", ")})`),o.push(...i))}function go(e){let o=[],t=[];pe(o,t,"status",e.statuses,"IN"),pe(o,t,"status",e.excludeStatuses,"NOT IN"),pe(o,t,"type",e.types,"IN"),pe(o,t,"id",e.ids,"IN");for(let i of e.metadataKeys??[])o.push("EXISTS (SELECT 1 FROM item_metadata_keys AS indexed_key WHERE indexed_key.item_id = items.id AND indexed_key.key = ?)"),t.push(i);for(let[i,n]of[["parent",e.parent],["assignee",e.assignee],["sprint",e.sprint],["release",e.release]])n!==void 0&&(o.push(`${i} = ?`),t.push(n));return e.priority!==void 0&&(o.push("priority = ?"),t.push(e.priority)),{where:o.length===0?"":` WHERE ${o.join(" AND ")}`,parameters:t}}async function cn(e){let o=V();if(!o)return null;let t=e.query??{},{where:i,parameters:n}=go(t),r;try{r=new o(A(e.pmRoot),{readOnly:!0});let a=he(r);if(a.version!==q||a.source_cursor!==e.expectedSourceCursor)return r.close(),null;let c=r.prepare(`SELECT COUNT(*) AS count FROM items${i}`).get(...n),s=[],l="";t.limit!==void 0?(l+=" LIMIT ?",s.push(Math.max(0,Math.floor(t.limit))),t.offset!==void 0&&(l+=" OFFSET ?",s.push(Math.max(0,Math.floor(t.offset))))):t.offset!==void 0&&(l+=" LIMIT -1 OFFSET ?",s.push(Math.max(0,Math.floor(t.offset))));let d=r.prepare(`SELECT metadata_json FROM items${i}
|
|
72
|
-
ORDER BY ${t.terminalStatuses&&t.terminalStatuses.length>0?`CASE WHEN status IN (${t.terminalStatuses.map(()=>"?").join(", ")}) THEN 1 ELSE 0 END ASC, `:""}priority ASC, updated_at DESC, id ASC${l}`).all(...n,...t.terminalStatuses??[],...s).map(u=>{let p=JSON.parse(String(u.metadata_json));if(!p.id)throw new TypeError("Indexed metadata row has no id");return p});return r.close(),{source_cursor:a.source_cursor,total:Number(c.count),items:d}}catch{return r?.close(),null}}async function dn(e){let o=V();if(!o||e.paths.length===0)return null;let t;try{t=new o(A(e.pmRoot),{readOnly:!0});let i=he(t);if(i.version!==q||i.source_cursor!==e.expectedSourceCursor)return t.close(),null;let n=e.paths.map(()=>"?").join(", "),r=e.scope===void 0?"":" AND scope = ?",a=[...e.paths,...e.scope===void 0?[]:[e.scope]],c=`path IN (${n})${r}`,s=t.prepare(`SELECT COUNT(DISTINCT item_id) AS count
|
|
73
|
-
FROM item_linked_files
|
|
74
|
-
WHERE ${c}`).get(...a),l=St(e.limit,50),d=St(e.offset,0),u=t.prepare(`SELECT items.id, items.metadata_json
|
|
75
|
-
FROM items
|
|
76
|
-
WHERE EXISTS (
|
|
77
|
-
SELECT 1 FROM item_linked_files
|
|
78
|
-
WHERE item_linked_files.item_id = items.id AND ${c}
|
|
79
|
-
)
|
|
80
|
-
ORDER BY items.priority ASC, items.updated_at DESC, items.id ASC
|
|
81
|
-
LIMIT ? OFFSET ?`).all(...a,l,d),p=[];if(u.length>0){let m=u.map(y=>String(y.id)),_=t.prepare(`SELECT item_id, path, scope, note
|
|
82
|
-
FROM item_linked_files
|
|
83
|
-
WHERE item_id IN (${m.map(()=>"?").join(", ")})
|
|
84
|
-
AND ${c}
|
|
85
|
-
ORDER BY path ASC, scope ASC`).all(...m,...a),g=new Map(m.map(y=>[y,[]]));for(let y of _){let b=String(y.item_id),T=g.get(b);T.push({path:String(y.path),scope:String(y.scope),...y.note===null?{}:{note:String(y.note)}}),g.set(b,T)}for(let y of u){let b=JSON.parse(String(y.metadata_json));p.push({item:b,files:g.get(String(y.id))})}}return t.close(),{source_cursor:i.source_cursor,total:Number(s.count),matches:p}}catch{return t?.close(),null}}async function ln(e){let o=V();if(!o)return null;let t;try{t=new o(A(e.pmRoot),{readOnly:!0});let i=he(t);if(i.version!==q||i.source_cursor!==e.expectedSourceCursor)return t.close(),null;let n=t.prepare(`SELECT items.metadata_json
|
|
86
|
-
FROM item_search
|
|
87
|
-
JOIN items ON items.id = item_search.id
|
|
88
|
-
WHERE item_search MATCH ?
|
|
89
|
-
ORDER BY bm25(item_search), items.priority, items.updated_at DESC, items.id
|
|
90
|
-
LIMIT ?`).all(e.query,Math.max(0,Math.floor(e.limit))).map(r=>JSON.parse(String(r.metadata_json)));return t.close(),{source_cursor:i.source_cursor,items:n}}catch{return t?.close(),null}}async function _e(e){await F.rm(A(e),{force:!0})}import E from"node:fs/promises";import w from"node:path";import{createHash as wo,randomUUID as At}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},o=new e.Error().stack;o&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[o]="846c1c5d-8a5c-56ee-832a-bfc780283e70")}catch{}})();var S=8,Lt=500,bo="metadata-derived-index",Eo="metadata-cache.json",Io="metadata-cache-bodies.json",vo="metadata-cache-collections.json",Co="metadata-cache-delta.json",To="metadata-cache-manifest.json",Ot=4,So=["comments","notes","learnings","files","tests","test_runs","docs"];function Pt(){return ne(U())}function we(e){let o={...e},t={};for(let i of So)i in o&&(t[i]=o[i],delete o[i]);return{light:o,heavy:t}}function jt(e,o){return!o||Object.keys(o).length===0?e:{...e,...o}}function $t(e,o,t,i){let n=wo("sha256");n.update(`format:${e??"default"}`);let r=Object.entries(o).sort(([a],[c])=>a.localeCompare(c)).map(([a,c])=>`${a}=${c}`).join(",");return n.update(`|types:${r}`),t&&n.update(`|schema:${JSON.stringify(t)}`),i.length>0&&n.update(`|extension_fields:${i.join(",")}`),n.digest("hex").slice(0,16)}function be(e){return w.join(e,"runtime",Eo)}function Ee(e){return w.join(e,"runtime",Io)}function Ie(e){return w.join(e,"runtime",vo)}function Xe(e){return w.join(e,"runtime",Co)}function Ye(e){return w.join(e,"runtime",To)}function ve(e,o){let t=w.extname(e);return`${e.slice(0,-t.length)}.${o}${t}`}var xo=24,C=new Map,Ce=new WeakMap;function Ge(e){return Ce.get(e)??e.source_cursor}function Ro(e,o){let t=Ge(e);if(!(o.base_source_cursor!==t||e.source_cursor===o.source_cursor)){Ce.set(e,t);for(let[i,n]of Object.entries(o.changes))n.entry?e.entries[i]=n.entry:delete e.entries[i];e.directory_signatures=o.directory_signatures,e.source_cursor=o.source_cursor}}function No(e,o){if(!e)return;let t=Ge(e);if(!(o.base_source_cursor!==t||e.source_cursor===o.source_cursor)){Ce.set(e,t);for(let[i,n]of Object.entries(o.changes))n.body?e.bodies[i]=n.body:delete e.bodies[i];e.source_cursor=o.source_cursor}}function ko(e,o){if(!e)return;let t=Ge(e);if(!(o.base_source_cursor!==t||e.source_cursor===o.source_cursor)){Ce.set(e,t);for(let[i,n]of Object.entries(o.changes))n.collections?e.collections[i]=n.collections:delete e.collections[i];e.source_cursor=o.source_cursor}}function Oo(e,o,t,i){!e||!i||e.context_fingerprint!==i.context_fingerprint||(Ro(e,i),No(o,i),ko(t,i))}function ze(e,o){C.size>=xo&&!C.has(e)&<(C),C.set(e,o)}async function k(e,o){let t;try{t=await E.stat(e)}catch{return C.delete(e),null}let i=C.get(e);if(i&&J(i.signature,t.mtimeMs,t.ctimeMs,t.size))return C.delete(e),C.set(e,i),i.envelope;let n;try{n=o(await E.readFile(e,"utf8"))}catch{n=null}return ze(e,{signature:{mtime_ms:t.mtimeMs,ctime_ms:t.ctimeMs,size:t.size},envelope:n}),n}async function Do(e,o,t){let i=c=>{let s=JSON.parse(c);return s.version!==S||typeof s.source_cursor!="string"||typeof s.entries!="object"||s.entries===null?null:s},n=be(e),r=await k(n,i);if(!o||r===null||r.context_fingerprint===o)return r;let a=await k(ve(n,o),i);return a===null&&ee(t,`metadata_cache_context_changed:${r.context_fingerprint}->${o}`),a}async function Mo(e,o){let t=r=>{let a=JSON.parse(r);return a.version!==S||typeof a.source_cursor!="string"||typeof a.bodies!="object"||a.bodies===null?null:a},i=Ee(e),n=await k(i,t);return o&&n?.context_fingerprint!==o?await k(ve(i,o),t):n}async function Fo(e,o){let t=r=>{let a=JSON.parse(r);return a.version!==S||typeof a.source_cursor!="string"||typeof a.collections!="object"||a.collections===null?null:a},i=Ie(e),n=await k(i,t);return o&&n?.context_fingerprint!==o?await k(ve(i,o),t):n}async function Ke(e){let o=Xe(e),t=await k(o,i=>{let n=JSON.parse(i);return n.version!==S||typeof n.base_source_cursor!="string"||typeof n.source_cursor!="string"||typeof n.changes!="object"||n.changes===null?null:n});if(t)return{envelope:t,invalid:!1};try{return await E.stat(o),{envelope:null,invalid:!0}}catch{return{envelope:null,invalid:!1}}}async function qe(e){let o=Ye(e),t=await k(o,i=>{let n=JSON.parse(i);return n.version!==S||typeof n.context_fingerprint!="string"||typeof n.source_cursor!="string"||!Number.isInteger(n.entry_count)||n.entry_count<0||typeof n.directory_signatures!="object"||n.directory_signatures===null?null:n});if(t)return t;try{await E.stat(o),await L(e)}catch{}return null}async function Q(e,o){await E.mkdir(w.dirname(e),{recursive:!0}),await N(e,JSON.stringify(o));try{let i=await E.stat(e);ze(e,{signature:{mtime_ms:i.mtimeMs,ctime_ms:i.ctimeMs,size:i.size},envelope:o})}catch{C.delete(e)}let t=w.dirname(w.dirname(e));if(e===be(t)||e===Ee(t)||e===Ie(t)){let i=ve(e,o.context_fingerprint);await N(i,JSON.stringify(o));try{let s=await E.stat(i);ze(i,{signature:{mtime_ms:s.mtimeMs,ctime_ms:s.ctimeMs,size:s.size},envelope:o})}catch{C.delete(i)}let n=w.dirname(e),r=w.extname(e),a=w.basename(e,r),c=(await E.readdir(n,{withFileTypes:!0}).catch(()=>[])).filter(s=>s.isFile()&&s.name!==w.basename(e)&&s.name.startsWith(`${a}.`)&&s.name.endsWith(r)).map(s=>w.join(n,s.name));if(c.length>Ot){let s=(await Promise.all(c.map(async l=>{try{return{path:l,mtime:(await E.stat(l)).mtimeMs}}catch{return null}}))).filter(l=>l!==null);for(let l of s.sort((d,u)=>d.mtime-u.mtime).slice(0,Math.max(0,s.length-Ot)))await E.rm(l.path,{force:!0}),C.delete(l.path)}}}function Ao(e,o,t){return t?o===t&&e!==t:o==="toon"&&e!=="toon"}function Ht(e,o,t){return e===void 0||Ao(e,o,t)}function ee(e,o){e&&!e.includes(o)&&e.push(o)}function J(e,o,t,i){return e.mtime_ms===o&&e.ctime_ms===t&&e.size===i}async function Lo(e,o,t){let i=w.join(e,o);try{let n=await E.readdir(i);return{folder:o,dirPath:i,files:n}}catch(n){return typeof n=="object"&&n!==null&&"code"in n&&!W(n)&&ee(t,`item_list_directory_read_failed:${o}`),{folder:o,dirPath:i,files:[]}}}async function Po(e,o){try{let t=await E.stat(w.join(e,o));return[o,{exists:!0,mtime_ms:t.mtimeMs,ctime_ms:t.ctimeMs,size:t.size}]}catch{return[o,{exists:!1,mtime_ms:0,ctime_ms:0,size:0}]}}async function ge(e,o){return Object.fromEntries(await Promise.all(o.map(async t=>await Po(e,t))))}function Z(e,o){return!e||Object.keys(e).length!==Object.keys(o).length?!1:Object.entries(o).every(([t,i])=>{let n=e[t];return n!==void 0&&n.exists===i.exists&&J(n,i.mtime_ms,i.ctime_ms,i.size)})}function jo(e){return re.some(o=>e.toLowerCase().endsWith(o))}function $o(e,o,t,i,n,r){i||(e.metadata=!0),o&&!n&&(e.body=!0),t&&!r&&(e.collections=!0)}async function Ho(e,o,t){if(t)for(let i of await se({path:e,scope:"project"}))ee(o,i)}function Dt(e,o,t,i){if(e)return o&&t?t.collections:i}async function Wo(e,o,t){let i=await E.stat(e),n=i.mtimeMs,r=i.ctimeMs,{size:a}=i,c=ke(e);await Ho(e,t.warnings,t.dispatchReadHooks);let s=t.previousEntries[o],l=!t.forceSourceRead&&s!==void 0&&J(s,n,r,a),d=t.previousBodies[o],u=!t.forceSourceRead&&d!==void 0&&J(d,n,r,a),p=t.previousCollections[o],m=!t.forceSourceRead&&p!==void 0&&J(p,n,r,a);if(!(!l||t.includeBody&&!u||t.includeCollections&&!m))return{mtimeMs:n,ctimeMs:r,size:a,itemFormat:c,lightMetadata:s.metadata,heavyMetadata:Dt(t.includeCollections,m,p,void 0),bodyLength:s.body_length,body:t.includeBody?d.body:void 0};let _=await E.readFile(e,"utf8"),g=de(_,{format:c,schema:t.schema,extensionFieldNames:t.extensionFieldNames,onWarning:b=>ee(t.warnings,b)}),y=we(g.metadata);return $o(t.state.misses,t.includeBody,t.includeCollections,l,u,m),{mtimeMs:n,ctimeMs:r,size:a,itemFormat:c,lightMetadata:l?s.metadata:y.light,heavyMetadata:Dt(t.includeCollections,m,p,y.heavy),bodyLength:l?s.body_length:g.body.length,body:t.includeBody?g.body:void 0}}function Uo(e,o,t,i){t.state.newEntries[o]={mtime_ms:i.mtimeMs,ctime_ms:i.ctimeMs,size:i.size,metadata:i.lightMetadata,body_length:i.bodyLength},t.includeBody&&i.body!==void 0&&(t.state.newBodies[o]={mtime_ms:i.mtimeMs,ctime_ms:i.ctimeMs,size:i.size,body:i.body}),t.includeCollections&&i.heavyMetadata!==void 0&&(t.state.newCollections[o]={mtime_ms:i.mtimeMs,ctime_ms:i.ctimeMs,size:i.size,collections:i.heavyMetadata});let n=t.includeCollections?jt(i.lightMetadata,i.heavyMetadata):i.lightMetadata,r=t.state.documentsById.get(n.id),a={metadata:n,body:i.body,item_format:i.itemFormat,item_path:e};Ht(r?.itemFormat,i.itemFormat,t.preferredFormat)&&t.state.documentsById.set(n.id,{candidate:a,itemFormat:i.itemFormat})}async function Bo(e,o,t,i){try{let n=await Wo(o,t,i);Uo(o,t,i,n)}catch{ee(i.warnings,`item_list_item_read_failed:${e}/${w.basename(o)}`)}}function zo(e,o){return e&&e.context_fingerprint===o?e.entries:{}}function Xo(e,o){return e&&e.context_fingerprint===o?e.bodies:{}}function Yo(e,o){return e&&e.context_fingerprint===o?e.collections:{}}function Go(){return{newEntries:{},newBodies:{},newCollections:{},documentsById:new Map,misses:{metadata:!1,body:!1,collections:!1}}}async function Ko(e,o){let t=[];for(let{folder:i,dirPath:n,files:r}of e)for(let a of r){if(!jo(a))continue;let c=w.join(n,a),s=w.relative(o.pmRoot,c);t.push(Bo(i,c,s,o)),t.length===32&&(await Promise.all(t),t.length=0)}await Promise.all(t)}async function qo(e){if(!(!(e.state.misses.metadata||Object.keys(e.previousEntries).length!==Object.keys(e.state.newEntries).length||!Z(e.existingCache?.directory_signatures,e.directorySignatures))&&e.existingCache!==null&&e.existingCache.context_fingerprint===e.contextFingerprint))try{await Q(be(e.pmRoot),{version:S,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,directory_signatures:e.directorySignatures,entries:e.state.newEntries}),await Q(Ye(e.pmRoot),{version:S,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,entry_count:Object.keys(e.state.newEntries).length,directory_signatures:e.directorySignatures});let o=[...e.state.documentsById.values()].map(({candidate:t})=>({relativePath:w.relative(e.pmRoot,t.item_path),metadata:we(t.metadata).light,linkedFiles:t.metadata.files??[]}));o.length>=e.minimumIndexedItems?await Nt({pmRoot:e.pmRoot,contextFingerprint:e.contextFingerprint,sourceCursor:e.sourceCursor,rows:o}):await _e(e.pmRoot)}catch{}}async function Vo(e){!(e.state.misses.body||Object.keys(e.previousBodies).length!==Object.keys(e.state.newBodies).length)&&e.existingBodyCache!==null&&e.existingBodyCache.context_fingerprint===e.contextFingerprint||await Q(Ee(e.pmRoot),{version:S,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,bodies:e.state.newBodies}).catch(()=>{})}async function Jo(e){!(e.state.misses.collections||Object.keys(e.previousCollections).length!==Object.keys(e.state.newCollections).length)&&e.existingCollectionsCache!==null&&e.existingCollectionsCache.context_fingerprint===e.contextFingerprint||await Q(Ie(e.pmRoot),{version:S,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,collections:e.state.newCollections}).catch(()=>{})}async function Ve(e,o,t={}){let i=await qe(e);return t.required!==!0&&(i===null||i.entry_count<Lt)?async()=>{}:ce(e,bo,30,o,!1,!1,3e3)}async function vn(e,o){let t=await qe(e);if(t===null)return null;let i=await Ke(e);if(i.invalid)return await L(e),null;let n=i.envelope?.context_fingerprint===t.context_fingerprint&&i.envelope.base_source_cursor===t.source_cursor?i.envelope.source_cursor:t.source_cursor,r=i.envelope?.context_fingerprint===t.context_fingerprint&&i.envelope.base_source_cursor===t.source_cursor?i.envelope.directory_signatures:t.directory_signatures;return o&&!Z(r,await ge(e,o))?null:{source_cursor:n,entry_count:t.entry_count}}function Mt(e,o){let t=w.relative(e,o);return t===""||t===".."||t.startsWith(`..${w.sep}`)||w.isAbsolute(t)?null:t}async function L(e){await Promise.all([be(e),Ee(e),Ie(e),Xe(e),Ye(e)].map(async o=>{await E.rm(o,{force:!0}),C.delete(o)})),await _e(e)}async function Qo(e){if(e.mutation.document===null)return{entry:null,body:null,collections:null};let o=await E.stat(e.mutation.itemPath),t=we(e.mutation.document.metadata),i={mtime_ms:o.mtimeMs,ctime_ms:o.ctimeMs,size:o.size};return{entry:{...i,metadata:t.light,body_length:e.mutation.document.body.length},body:{...i,body:e.mutation.document.body},collections:{...i,collections:t.heavy}}}function Zo(e,o,t){return e?.context_fingerprint===o&&e.base_source_cursor===t?structuredClone(e.changes):{}}async function Je(e){let o=Mt(e.pmRoot,e.itemPath),t=e.previousItemPath?Mt(e.pmRoot,e.previousItemPath):void 0;if(o===null||t===null)return await L(e.pmRoot),["metadata_derived_index_path_invalidated"];try{let i=$t(e.preferredFormat,e.typeToFolder,e.schema,Pt()),n=await qe(e.pmRoot);if(n===null||n.context_fingerprint!==i)return[];let r=n.source_cursor,a=await Ke(e.pmRoot);if(a.invalid)return await L(e.pmRoot),["metadata_derived_index_refresh_failed"];let c=Zo(a.envelope,i,r),s=a.envelope?.context_fingerprint===i&&a.envelope.base_source_cursor===r?a.envelope.source_cursor:r;t!==void 0&&(c[t]={entry:null,body:null,collections:null}),c[o]=await Qo({mutation:e});let l=At();return await Q(Xe(e.pmRoot),{version:S,context_fingerprint:i,base_source_cursor:r,source_cursor:l,directory_signatures:await ge(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]),changes:c}),await kt({pmRoot:e.pmRoot,contextFingerprint:i,expectedSourceCursor:s,sourceCursor:l,row:e.document===null?null:{relativePath:o,metadata:we(e.document.metadata).light,linkedFiles:e.document.metadata.files},deletedRelativePaths:[...t===void 0?[]:[t],...e.document===null?[o]:[]]})||await _e(e.pmRoot),[]}catch{return await L(e.pmRoot).catch(()=>{}),["metadata_derived_index_refresh_failed"]}}function ei(e){return[...e.documentsById.values()].sort((o,t)=>o.candidate.metadata.id.localeCompare(t.candidate.metadata.id)).map(o=>o.candidate)}function Ft(e,o,t){return e?.context_fingerprint===o&&e.source_cursor===t}function ti(e,o,t,i,n){return e.every(r=>(!o||i[r]!==void 0)&&(!t||n[r]!==void 0))}function oi(e){let o=new Map;for(let[t,i]of Object.entries(e.previousEntries)){let n=ke(t);if(!n)continue;let r=e.includeCollections?jt(i.metadata,e.previousCollections[t]?.collections):i.metadata,a=o.get(r.id);Ht(a?.itemFormat,n,e.preferredFormat)&&o.set(r.id,{itemFormat:n,candidate:{metadata:r,body:e.includeBody?e.previousBodies[t]?.body:void 0,item_format:n,item_path:w.join(e.pmRoot,t)}})}return[...o.values()].sort((t,i)=>t.candidate.metadata.id.localeCompare(i.candidate.metadata.id)).map(t=>t.candidate)}function ii(e){return e.forceSourceScan||Me()||e.existingCache?.context_fingerprint!==e.contextFingerprint||e.entryKeys.length<e.minimumIndexedItems||!Z(e.existingCache?.directory_signatures,e.directorySignatures)?!1:[!e.includeBody||Ft(e.existingBodyCache,e.contextFingerprint,e.existingCache.source_cursor),!e.includeCollections||Ft(e.existingCollectionsCache,e.contextFingerprint,e.existingCache.source_cursor)].every(Boolean)&&ti(e.entryKeys,e.includeBody,e.includeCollections,e.previousBodies,e.previousCollections)}async function Te(e,o,t,i,n,r={}){let a=r.includeBody!==!1,c=r.includeCollections!==!1,s=Pt(),l=$t(o,t,n,s),d=await Ke(e);d.invalid&&await L(e);let u=await Do(e,l,r.cacheDiagnostics),p=a?await Mo(e,l):null,m=c?await Fo(e,l):null;Oo(u,p,m,d.envelope);let _=zo(u,l),g=Xo(p,l),y=Yo(m,l),b=[...new Set(Object.values(t))],T=await ge(e,b),R=Object.keys(_),O=Math.max(1,Math.floor(r.derivedIndexMinimumItems??Lt));if(ii({forceSourceScan:r.forceSourceScan===!0,contextFingerprint:l,existingCache:u,existingBodyCache:p,existingCollectionsCache:m,directorySignatures:T,entryKeys:R,minimumIndexedItems:O,includeBody:a,includeCollections:c,previousBodies:g,previousCollections:y}))return oi({pmRoot:e,preferredFormat:o,includeBody:a,includeCollections:c,previousEntries:_,previousBodies:g,previousCollections:y});let I=await Promise.all(b.map(Re=>Lo(e,Re,i))),Se=Me(),v=Go(),xe={pmRoot:e,preferredFormat:o,warnings:i,schema:n,extensionFieldNames:s,includeBody:a,includeCollections:c,forceSourceRead:r.forceSourceScan===!0,dispatchReadHooks:Se,previousEntries:_,previousBodies:g,previousCollections:y,state:v};await Ko(I,xe);let j=await ge(e,b),oe=Z(T,j)?j:{},$=v.misses.metadata||Object.keys(_).length!==Object.keys(v.newEntries).length||!Z(u?.directory_signatures,oe)||u===null?At():u.source_cursor;return await qo({pmRoot:e,contextFingerprint:l,sourceCursor:$,existingCache:u,previousEntries:_,directorySignatures:oe,state:v,minimumIndexedItems:O}),a&&await Vo({pmRoot:e,contextFingerprint:l,sourceCursor:$,existingBodyCache:p,previousBodies:g,state:v}),c&&await Jo({pmRoot:e,contextFingerprint:l,sourceCursor:$,existingCollectionsCache:m,previousCollections:y,state:v}),ei(v)}async function Wt(e,o,t,i,n){return(await Te(e,o,t,i,n,{includeBody:!1})).map(r=>({metadata:r.metadata,body:r.body??""}))}async function Ut(e,o,t,i,n){return(await Te(e,o,t,i,n,{includeBody:!1,includeCollections:!1})).map(r=>({metadata:r.metadata,body:r.body??""}))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},o=new e.Error().stack;o&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[o]="e23f9ca6-9fa6-566b-9bfb-7cbe6d449a59")}catch{}})();function ni(e,o){let t=e.trim().toLowerCase();if(t.length===0)return;let i=Math.floor(t.length/3);return o.map(n=>({candidate:n,distance:ie(t,n.toLowerCase(),i)??Number.POSITIVE_INFINITY})).filter(({distance:n})=>Number.isFinite(n)).sort((n,r)=>n.distance!==r.distance?n.distance-r.distance:n.candidate.localeCompare(r.candidate))[0]?.candidate}function Bt(e){return["pm",...e].map(o=>/^[A-Za-z0-9_./:@=-]+$/u.test(o)?o:JSON.stringify(o)).join(" ")}function Rn(e){let o=e.command_path.trim().replaceAll(/\s+/gu," "),t=e.token.trim(),i=t.length===0?"<empty>":t,n=[...new Set(e.allowed.map(p=>p.trim()))].filter(Boolean).sort((p,m)=>p.localeCompare(m));if(o.length===0||i.length===0||n.length===0)throw new TypeError("Unknown-subcommand contracts require a path, token, and allowed set");let r=o.split(" "),a=e.trailing_args??[],c=e.display_name??`pm ${o}`,s=e.token_kind??"subcommand",l=e.retry_command?void 0:ni(i,n),d=Bt([...r,i,...a]),u=e.retry_command??(l?Bt([...r,l,...a]):void 0);return new f(`Unknown ${c} ${s} "${i}". Allowed: ${n.join(", ")}${e.message_suffix??""}`,e.exit_code??h.USAGE,{code:"unknown_subcommand",reason:"unknown_positional_token",value:i,examples:[...u?[u]:[],...e.examples??[],`pm ${o} --help`],nextSteps:u?[`Retry with the suggested command: ${u}`]:["Choose one value from recovery.allowed_values."],recovery:{attempted_command:d,allowed_values:n,suggested_retry:u,fallback_candidates:e.fallback_candidates}})}import ri from"node:fs/promises";import ai from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},o=new e.Error().stack;o&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[o]="1d746e4d-ff6c-54ec-a94f-4ec4cb8f77b5")}catch{}})();function si(e){return[...new Set(e.filter(o=>o.trim().length>0))].sort((o,t)=>o.localeCompare(t))}function ci(e,o){return new f(`Missing history stream for ${e}. ${o} requires history streams when settings.history.missing_stream is strict_error.`,h.NOT_FOUND)}async function di(e,o){return await ot(ai.dirname(e)),await(await ri.open(e,"a")).close(),M({path:e,scope:"project",op:`${o}:history:auto_create`})}async function Qe(e){return li({pmRoot:e.pmRoot,settings:e.settings,itemIds:[e.itemId],commandLabel:e.commandLabel})}async function li(e){let o=si(e.itemIds),t=[],i=[];for(let n of o){let r=x(e.pmRoot,n);if(!await H(r)){if(e.settings.history.missing_stream==="strict_error")throw ci(n,e.commandLabel);i.push(...await di(r,e.commandLabel)),i.push(`history_stream_auto_created:${n}`),t.push(n)}}return{auto_created_ids:t,warnings:i}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},o=new e.Error().stack;o&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[o]="5db05e2f-4742-526b-b1c8-b97ff302b40e")}catch{}})();function te(e,o=!1){let t=e[0];if(t?.op!=="history_compact_baseline")return 0;let i=t.context?.history_compaction,n=typeof i=="object"&&i!==null&&"version_offset"in i?i.version_offset:void 0;if(typeof n=="number"&&Number.isSafeInteger(n)&&n>=0&&Number.isSafeInteger(n+e.length))return n;if(o)return null;throw new f("This compacted stream has no trustworthy version offset; numeric history addresses are unavailable.",h.USAGE,{code:"history_version_mapping_unavailable",required:"Use a retained timestamp or recover the pre-compaction stream from version control.",nextSteps:["Run pm history <id> --full to inspect the retained timestamps and checkpoint evidence."]})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},o=new e.Error().stack;o&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[o]="ddc5bb8f-83bc-5121-a628-a501e7ed5a73")}catch{}})();function ui(e,o){let t=-1;return e.forEach((i,n)=>{let r=Date.parse(i.ts);if(!Number.isFinite(r))throw new f(`History for this item contains invalid timestamp at entry ${n+1}.`,h.GENERIC_FAILURE);r<=o&&(t=n)}),t}function mi(e,o){let t=e[0]?.ts??null,i=e.at(-1)?.ts??null,n={code:"history_target_out_of_range",required:"Choose a target within the available item history.",why:"Point-in-time reads and restores can only reconstruct recorded versions.",examples:[],nextSteps:["Run pm history <id> to inspect available versions and timestamps."],valid_range:{first_version:null,last_version:null,first_timestamp:t,last_timestamp:i}};return i!==null&&(n.examples=[i],o!==null&&(n.examples.unshift(String(o+1),String(o+e.length)),n.valid_range.first_version=o+1,n.valid_range.last_version=o+e.length)),{guidance:n,lastTimestamp:i}}function fi(e,o){let t={};if(o instanceof Error&&o.message.trim().length>0&&(t.reason=o.message.trim()),typeof o!="object"||o===null)return t;let i=o;if(typeof i.index=="number"&&Number.isInteger(i.index)&&i.index>=0&&(t.patchIndex=i.index),typeof i.operation=="object"&&i.operation!==null){let n=i.operation;Object.assign(t,Object.fromEntries(["op","path","from"].flatMap(r=>{let a=n[r];return typeof a=="string"?[[r,a]]:[]})))}if(t.patchIndex!==void 0){let n=e[t.patchIndex];n&&(t.op??=n.op,t.path??=n.path,t.from??=n.from)}return t}function zt(e,o,t={}){let i=e.trim(),n=t.errorSubject??"history",r=n==="restore"?"Restore":"History",{guidance:a,lastTimestamp:c}=mi(o,te(o,!0));if(!i)throw new f(`Missing ${n} target. Use a timestamp or version number.`,h.USAGE,a);if(/^\d+$/.test(i)){let d=te(o),u=Number(i);if(u>=1&&u<=d)throw new f(`History version ${u} was pruned by compaction.`,h.USAGE,{...a,code:"history_version_pruned"});if(!Number.isSafeInteger(u)||u<1||u>d+o.length)throw new f(`${r} version must be between ${d+1} and ${d+o.length} for this item.`,h.USAGE,a);return{kind:"version",raw:i,historyIndex:u-d-1}}let s=Date.parse(i);if(!Number.isFinite(s))throw new f(`Invalid ${n} target "${e}". Use a positive version number or ISO timestamp.`,h.USAGE,a);let l=ui(o,s);if(l<0||t.allowFutureTimestamp!==!0&&s>Date.parse(c))throw new f(n==="restore"?`No history entries exist at or before timestamp ${i}.`:`No history entry exists at timestamp ${i}.`,h.USAGE,a);return{kind:"timestamp",raw:i,historyIndex:l}}function Ze(e,o,t,i){let n=$e(e,o);if(n.ok)return n.document;let r=fi(o,n.error),a=[`history_op=${i}`,r.patchIndex===void 0?null:`patch_index=${r.patchIndex}`,r.op?`op=${r.op}`:null,r.path?`path=${r.path}`:null,r.from?`from=${r.from}`:null].filter(c=>c!==null);throw new f(`Failed to apply history patch at entry ${t} (${a.join(", ")}). ${r.reason??String(n.error)}`,h.GENERIC_FAILURE)}function Xt(e,o){let t=e[0];if(t&&t.op!=="create"&&t.op!=="history_compact_baseline"){let a=$e(X,t.patch);if(!a.ok||typeof a.document.metadata.id!="string")throw new f("History starts without a reconstructable item baseline.",h.GENERIC_FAILURE,{code:"history_baseline_unavailable",required:"Recover the original create entry or a complete checkpoint from version control.",nextSteps:["Run pm history <id> --full to inspect the missing baseline."]})}let i=e.slice(0,o+1),n=le([...i]),r=structuredClone(X);for(let a=0;a<=o;a+=1){let c=e[a];if(!c)throw new f(`History target entry ${a+1} does not exist.`,h.USAGE);r=Ze(r,c.patch,a+1,c.op)}if(!n.ok)throw new f(`History cannot be replayed: ${n.errors.join(", ")}.`,h.GENERIC_FAILURE,{code:"history_replay_invalid",verification_errors:n.errors,required:"Inspect the history integrity findings before attempting recovery.",nextSteps:["Run pm history <id> --verify --full."]});return r}function Xn(e,o){if(Object.keys(e.metadata).length>0){if(typeof e.metadata.id!="string"||!Array.isArray(e.metadata.tags))throw new f("History has no complete item baseline for this target.",h.GENERIC_FAILURE,{code:"history_baseline_unavailable",required:"Recover the original create entry or a complete checkpoint from version control.",nextSteps:["Run pm history <id> --full to inspect the first recorded state."]});return e}throw new f(`History target ${o.raw} resolves to a deleted state; choose a version or timestamp where the item exists.`,h.USAGE)}import P from"node:fs/promises";import{statSync as pi}from"node:fs";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},o=new e.Error().stack;o&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[o]="be69f1e8-4543-5cf5-abb0-9d38ca1d0cc6")}catch{}})();function yi(e,o){let t=-1,i=structuredClone(X);for(let[c,s]of e.entries()){if(i=Ze(i,s.patch,c+1,s.op),i.metadata.id!==void 0&&i.metadata.id!==o)throw new f(`History belongs to item ${String(i.metadata.id)}, expected ${o}.`,h.GENERIC_FAILURE,{code:"history_replay_invalid",required:"Recover the correct history stream for this item before attempting restoration."});i.metadata.id===o&&Array.isArray(i.metadata.tags)&&(t=c)}let n=te(e,!0),r=t<0||n===null?null:n+t+1,a=r===null?void 0:String(r);if(t>=0&&a===void 0){let c=e[t].ts;zt(c,e).historyIndex===t&&(a=c)}return{version:r,target:a}}async function Yt(e,o,t){let i=new Set([G(o,t),Y(o)]);for(let n of i){let r=x(e,n);if(!pi(r,{throwIfNoEntry:!1})?.isFile())continue;let a=await ht(r,n),c=-1;if(a.forEach((m,_)=>{m.op==="delete"&&(c=_)}),c<0)continue;let s=Xt(a,a.length-1);if(Object.keys(s.metadata).length!==0)continue;let{version:l,target:d}=yi(a,n),u=d===void 0?["history",n,"--verify"]:["get",n,"--at",d],p=B(u);return new f(`Item ${n} was deleted at ${a[c].ts}; its history is retained.`,h.NOT_FOUND,{code:"item_deleted",required:"Read a retained materialized version, then restore it if the item should exist again.",item_id:n,tombstone:{deleted:!0,deleted_at:a[c].ts,recoverable:d!==void 0,last_materialized_version:l},nextSteps:[p,...d===void 0?["Recover the pre-compaction history from version control."]:[B(["restore",n,d])]],recovery:{suggested_retry:p,suggested_retry_args:u}})}}import{AsyncLocalStorage as hi}from"node:async_hooks";import _i from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},o=new e.Error().stack;o&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[o]="53df109f-bd64-5879-96a6-39f70334910e")}catch{}})();var gi=new hi;function Gt(e,o){for(let t of gi.getStore()??[])t.pmRoot===_i.resolve(e)&&t.id===o.metadata.id&&t.validate(o)}import et from"node:path";import{isUtf8 as wi}from"node:buffer";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},o=new e.Error().stack;o&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[o]="018adb6c-4e3c-58d5-b636-04dbf4307d7a")}catch{}})();async function bi(e){try{return await P.access(e),!0}catch{return!1}}function Ei(e,o){e&&(e.includes(o)||e.push(o))}function Kt(e){return e??ne(U())}function Ii(e){return e==="toon"?["toon","json_markdown"]:e==="json_markdown"?["json_markdown","toon"]:["toon","json_markdown"]}async function qt(e,o,t="pm-",i,n=D){let r=o.trim(),a=r.startsWith("#")?r.slice(1):r;if(a.length===0)return null;let c=G(o,t),s=Y(o),l=[...new Set([a,c,s])].filter(p=>p.length>0),d=Object.entries(n),u=Ii(i);for(let p of l){let m=new Map;for(let[_]of d)for(let g of u){let y=Ne(e,_,p,g,n);await bi(y)&&m.set(y,m.get(y)??{id:p,type:_,itemPath:y,item_format:g})}if(m.size>1){let _=[...m.keys()].map(g=>et.relative(e,g).split(et.sep).join("/")).sort();throw new f(`Item ${p} has ambiguous identity across ${_.join(", ")}. Preserve both documents and inspect pm ops validate --check-storage-integrity before resolving the collision.`,h.CONFLICT,{code:"item_identity_ambiguous",item_id:p,paths:_})}for(let _ of m.values())return _}return null}async function Vt(e,o={}){let t=await vi(e,o);if(t.error!==null)throw t.error;return{raw:t.raw,document:t.document}}async function vi(e,o={}){let t=await P.readFile(e.itemPath);if(!wi(t))throw new f("Item contains invalid UTF-8; preserve a binary backup before recovering it.",h.CONFLICT,{code:"item_document_encoding_invalid",item_id:e.id,item_path:e.itemPath,byte_length:t.length,empty:!1});let i=t.toString("utf8");await se({path:e.itemPath,scope:"project"});let n;try{n=de(i,{format:e.item_format,requireSupportedFormat:!0,schema:o.schema,extensionFieldNames:Kt(o.extensionFieldNames),onWarning:r=>Ei(o.warnings,r)})}catch(r){if(r instanceof f&&r.code==="item_format_version_unsupported")throw new f(`Item ${e.id}: ${r.message}`,r.exitCode,{...r.context,item_id:e.id,item_path:e.itemPath});if(r instanceof f&&r.code==="item_document_invalid")return{raw:i,document:null,error:new f(`Cannot read ${e.id} at ${e.itemPath}${t.length===0?" (zero-length file)":""}: ${r.message}`,r.exitCode,{...r.context,item_id:e.id,item_path:e.itemPath,byte_length:t.length,empty:t.length===0,nextSteps:[`Run pm history ${e.id} --full, then pm restore ${e.id} <version> to recover a recorded state.`]})};throw r}return{raw:i,document:n,error:null}}async function Ci(e,o,t=D,i,n){await ue(e);let r=await Wt(e,o,t,i,n);return fe(r.length),r.map(a=>a.metadata)}async function Ar(e,o,t=D,i,n){await ue(e);let r=await Ut(e,o,t,i,n);return fe(r.length),r.map(a=>a.metadata)}async function Lr(e,o,t=D,i,n,r={}){await ue(e);let a=await Te(e,o,t,i,n,{includeBody:!0,forceSourceScan:r.forceSourceScan});return fe(a.length),a.map(c=>({...c.metadata,body:c.body}))}function Jt(e){return{async get(o){let t=await qt(e.pmRoot,o,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!t)return null;let{document:i}=await Vt(t,{schema:e.settings.schema});return{item:i.metadata,body:i.body}},list:()=>Ci(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}}async function Ti(e,o){let t=new Set(Object.values(o)),i=[];return await Promise.all([...t].map(async n=>{try{let r=await P.readdir(et.join(e,n));for(let a of r)for(let c of re)if(a.toLowerCase().endsWith(c)){i.push(a.slice(0,-c.length));break}}catch{}})),i}async function Si(e,o,t,i){let n=G(o,t),r=await Ti(e,i);if(r.length===0)return[];let a=Math.max(3,Math.floor(n.length/2));return r.map(c=>({id:c,distance:ie(c,n,a)})).filter(c=>c.distance!==null).sort((c,s)=>c.distance-s.distance).slice(0,3).map(c=>c.id)}async function xi(e,o,t,i){let n=await Yt(e,o,t);if(n)return n;let r=await Si(e,o,t,i),a=["Confirm the active --path/PM_PATH scope, then retry with a valid id."];return r.length>0&&a.unshift(`Did you mean one of: ${r.join(", ")}?`),new f(`Item ${o} not found`,h.NOT_FOUND,{nextSteps:a})}function Ri(e,o){return e==="claim"||o===!0&&(e==="comment_add"||e==="comment_edit"||e==="comment_delete"||e==="note_add"||e==="learning_add"||e==="release"||e==="update"||e==="update_ownership_bypass"||e==="update_audit")}async function Qt(e){let o=e.typeToFolder??rt(e.settings,U()).type_to_folder,t=await qt(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,o);if(!t)throw await xi(e.pmRoot,e.id,e.settings.id_prefix,o);let i=await ce(e.pmRoot,t.id,e.settings.locks.ttl_seconds,e.author,!!e.force,e.settings.governance.force_required_for_stale_lock,e.settings.locks.wait_ms);try{let n=[],{raw:r,document:a}=await Vt(t,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames,warnings:n}),c=a.metadata.assignee?.trim(),s=a.metadata.claim_principal?.trim()||c,l=yt(e.author),d=wt(e.settings);if(c&&s!==l&&!e.force&&!Ri(e.op,e.bypassAssigneeConflict)){if(d.ownership_enforcement==="strict")throw new f(`Item ${t.id} is assigned to ${c}. Use --force to override.`,h.CONFLICT);d.ownership_enforcement==="warn"&&n.push(`ownership_warning:assignee_conflict:${t.id}:${c}`)}return{typeToFolder:o,located:t,originalRaw:r,document:a,warnings:n,releaseLock:i}}catch(n){throw await i(),n}}function Ni(e,o,t){if(!e.handled||typeof e.result!="object"||e.result===null)return{effectiveTargetItemPath:o,effectiveSerializedAfter:t,skipItemWrite:!1};let i=e.result;return{effectiveTargetItemPath:typeof i.target_item_path=="string"&&i.target_item_path.trim().length>0?i.target_item_path:o,effectiveSerializedAfter:typeof i.contents=="string"?i.contents:t,skipItemWrite:i.skip_write===!0}}async function ki(e){if(!e.skipItemWrite){if(e.effectiveTargetItemPath!==e.originalItemPath){await N(e.originalItemPath,e.originalRaw),await P.rm(e.effectiveTargetItemPath,{force:!0});return}await N(e.originalItemPath,e.originalRaw)}}async function Zt(e){mt(e.op);let o=await Qt({pmRoot:e.pmRoot,settings:e.settings,id:e.id,op:e.op,author:e.author,force:e.force,bypassAssigneeConflict:e.bypassAssigneeConflict,extensionFieldNames:e.extensionFieldNames,typeToFolder:e.typeToFolder}),{typeToFolder:t,located:i,originalRaw:n,document:r,warnings:a,releaseLock:c}=o;try{Gt(e.pmRoot,r);let s=z(r,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),l=z(structuredClone(r),{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),d=await e.mutate(l);if(e.skipNoop===!0&&d.changedFields.length===0)return{item:s.metadata,body:s.body,changedFields:[],warnings:[...a,...d.warnings??[]]};let u=e.resolveHistoryContext?.(),p=Math.max(Le(s.metadata),Le(l.metadata));bt(at(e.pmRoot),p),p>ft(l.metadata)&&(l.metadata.pm_format_version=p,d.changedFields.push("pm_format_version")),l.metadata.updated_at=Ae();let m=z(l,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),_=await He({pmRoot:e.pmRoot,settings:e.settings,operation:e.op,author:e.author,before:s,after:m});await De({pm_root:e.pmRoot,operation:e.op,before:s,after:m,changed_fields:d.changedFields,sdk:Jt({pmRoot:e.pmRoot,settings:e.settings,typeToFolder:t})});let g=await Qe({pmRoot:e.pmRoot,settings:e.settings,itemId:i.id,commandLabel:e.op}),y="toon",b=pt(m,{format:y,schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),T=Ne(e.pmRoot,m.metadata.type,i.id,y,t),R=x(e.pmRoot,i.id),O=await Fe("item_store_write",{op:e.op,pm_root:e.pmRoot,item_id:i.id,source_item_path:i.itemPath,target_item_path:T,history_path:R,item_format:y,before:s,after:m,contents:b}),{effectiveTargetItemPath:I,effectiveSerializedAfter:Se,skipItemWrite:v}=Ni(O,T,b),xe=await Ve(e.pmRoot,e.author),j=[];try{v||await N(I,Se),!v&&I!==i.itemPath&&await P.rm(i.itemPath);let $=Pe({nowIso:m.metadata.updated_at,author:e.author,op:e.op,before:s,after:m,message:e.message,context:_.decisions.length===0?u:{...u,workflow_policies:_.decisions}});try{await je(R,$)}catch(Re){throw await ki({skipItemWrite:v,effectiveTargetItemPath:I,originalItemPath:i.itemPath,originalRaw:n}),Re}v||(j=await Je({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:t,schema:e.settings.schema,itemPath:I,previousItemPath:i.itemPath,document:m}))}finally{await xe()}let oe=[...await M({path:I,scope:"project",op:e.op,item_id:m.metadata.id,item_type:m.metadata.type,before:s,after:m,changed_fields:d.changedFields}),...await M({path:R,scope:"project",op:`${e.op}:history`,item_id:m.metadata.id,item_type:m.metadata.type,before:s,after:m,changed_fields:d.changedFields})];return Oe({id:m.metadata.id,op:e.op,item_type:m.metadata.type,previous_status:s.metadata.status,status:m.metadata.status,previous:ae(s.metadata,d.changedFields),current:ae(m.metadata,d.changedFields),changed_fields:d.changedFields}),{item:m.metadata,body:m.body,changedFields:d.changedFields,warnings:[...a,...d.warnings??[],..._.warnings,...g.warnings,...O.warnings,...j,...oe]}}finally{await c()}}async function Pr(e){return Zt(e)}async function jr(e){return Zt(e)}async function $r(e){let o=await Qt({pmRoot:e.pmRoot,settings:e.settings,id:e.id,op:"delete",author:e.author,force:e.force}),{located:t,originalRaw:i,document:n,warnings:r,releaseLock:a}=o;try{let c=Kt(void 0),s=z(n,{schema:e.settings.schema,extensionFieldNames:c}),l=await He({pmRoot:e.pmRoot,settings:e.settings,operation:"delete",author:e.author,before:s,after:null,dryRun:e.dryRun});await De({pm_root:e.pmRoot,operation:"delete",before:s,after:null,changed_fields:["deleted"],sdk:Jt({pmRoot:e.pmRoot,settings:e.settings,typeToFolder:o.typeToFolder})});let d=await Qe({pmRoot:e.pmRoot,settings:e.settings,itemId:t.id,commandLabel:"delete"}),u=Ae(),p=tt,m=Pe({nowIso:u,author:e.author,op:"delete",before:s,after:p,message:e.message,context:l.decisions.length===0?void 0:{workflow_policies:l.decisions}}),_=x(e.pmRoot,t.id),g=await Fe("item_store_delete",{op:"delete",pm_root:e.pmRoot,item_id:t.id,item_path:t.itemPath,history_path:_,before:s}),y=t.itemPath,b=!1;if(g.handled&&typeof g.result=="object"&&g.result!==null){let I=g.result;typeof I.item_path=="string"&&I.item_path.trim().length>0&&(y=I.item_path),I.skip_delete===!0&&(b=!0)}if(e.dryRun===!0)return{item:s.metadata,changedFields:["deleted"],targetPath:y,warnings:[...r,...l.warnings,...d.warnings,...g.warnings]};let T=await Ve(e.pmRoot,e.author),R=[];try{b||await P.rm(y);try{await je(_,m)}catch(I){throw b||await N(y,i),I}b||(R=await Je({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:o.typeToFolder,schema:e.settings.schema,itemPath:y,document:null}))}finally{await T()}let O=[...await M({path:y,scope:"project",op:"delete",item_id:s.metadata.id,item_type:s.metadata.type,before:s,after:p,changed_fields:["deleted"]}),...await M({path:_,scope:"project",op:"delete:history",item_id:s.metadata.id,item_type:s.metadata.type,before:s,after:p,changed_fields:["deleted"]})];return Oe({id:s.metadata.id,op:"delete",item_type:s.metadata.type,previous_status:s.metadata.status,previous:ae(s.metadata,Object.keys(s.metadata)),changed_fields:["deleted"]}),{item:s.metadata,changedFields:["deleted"],warnings:[...r,...l.warnings,...d.warnings,...g.warnings,...R,...O]}}finally{await a()}}export{Rn as a,Qe as b,li as c,It as d,Y as e,G as f,Li as g,te as h,zt as i,Ze as j,Xt as k,Xn as l,ro as m,so as n,co as o,lo as p,uo as q,He as r,Zi as s,cn as t,dn as u,ln as v,Lt as w,So as x,Ve as y,vn as z,Je as A,Te as B,qt as C,Vt as D,vi as E,Ci as F,Ar as G,Lr as H,Jt as I,xi as J,Pr as K,jr as L,$r as M};
|
|
91
|
-
//# sourceMappingURL=chunk-QWKCQ5PW.js.map
|