@unbrained/pm-cli 2026.12.1 → 2026.12.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/{chunk-CWPR234D.js → chunk-7NAO7I75.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-4YQMQOUO.js → chunk-7V65VACG.js} +52 -52
- package/dist/cli-bundle/chunks/{chunk-NA6D75V5.js → chunk-G6TARHFK.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-YSVOXCYH.js → chunk-GOEQXVOI.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-OKEJ4U2I.js → chunk-ROTEELDL.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-U7RBJGLF.js → chunk-SDXCJZKB.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-XME6GIFQ.js → chunk-TKUG2X24.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-Q6GLSAJY.js → chunk-UNBW2LF3.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-V2S4XAX3.js +2 -0
- package/dist/cli-bundle/chunks/{item-transaction-66RDV7PH.js → item-transaction-56J5OCHA.js} +2 -2
- package/dist/cli-bundle/chunks/{linked-resource-value-list-E2DX52LY.js → linked-resource-value-list-ZBIY4H23.js} +2 -2
- package/dist/cli-bundle/chunks/{register-mutation-2F6JUBST.js → register-mutation-EK6DVIQK.js} +2 -2
- package/dist/cli-bundle/chunks/{register-operations-ET3UKPYK.js → register-operations-6MURXE4V.js} +2 -2
- package/dist/cli-bundle/chunks/{register-setup-I63QTFCU.js → register-setup-RW26X3GJ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-SQ72CVUH.js → chunk-3COWDIPX.js} +54 -54
- package/dist/cli-bundle/focused-chunks/{chunk-PT7RT3T6.js → chunk-J72TRWR5.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{item-transaction-2K4SFLJ7.js → item-transaction-LQLQLZE7.js} +2 -2
- package/dist/cli-bundle/main.js +3 -3
- package/dist/cli-bundle/sdk-core.js +1 -1
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +1 -1
- package/dist/sdk/extension/install-sources.d.ts +2 -2
- package/dist/sdk/extension/install-sources.js +5 -5
- package/marketplace.json +1 -1
- package/node_modules/tar/README.md +1792 -1147
- package/node_modules/tar/dist/commonjs/bytes.d.ts +21 -0
- package/node_modules/tar/dist/commonjs/bytes.js +83 -0
- package/node_modules/tar/dist/commonjs/codec.d.ts +53 -0
- package/node_modules/tar/dist/commonjs/codec.js +35 -0
- package/node_modules/tar/dist/commonjs/concat.d.ts +3 -0
- package/node_modules/tar/dist/commonjs/concat.js +20 -0
- package/node_modules/tar/dist/commonjs/create.d.ts +39 -2
- package/node_modules/tar/dist/commonjs/create.js +150 -64
- package/node_modules/tar/dist/commonjs/dealias.d.ts +79 -0
- package/node_modules/tar/dist/commonjs/dealias.js +50 -0
- package/node_modules/tar/dist/commonjs/delete.d.ts +19 -0
- package/node_modules/tar/dist/commonjs/delete.js +121 -0
- package/node_modules/tar/dist/commonjs/entries.d.ts +82 -0
- package/node_modules/tar/dist/commonjs/entries.js +398 -0
- package/node_modules/tar/dist/commonjs/extract.d.ts +14 -2
- package/node_modules/tar/dist/commonjs/extract.js +40 -81
- package/node_modules/tar/dist/commonjs/fs.d.ts +201 -0
- package/node_modules/tar/dist/commonjs/fs.js +5 -0
- package/node_modules/tar/dist/commonjs/header.d.ts +4 -4
- package/node_modules/tar/dist/commonjs/header.js +71 -53
- package/node_modules/tar/dist/commonjs/index.d.ts +25 -18
- package/node_modules/tar/dist/commonjs/index.js +46 -18
- package/node_modules/tar/dist/commonjs/index.min.js +2 -3
- package/node_modules/tar/dist/commonjs/large-numbers.d.ts +2 -2
- package/node_modules/tar/dist/commonjs/large-numbers.js +4 -4
- package/node_modules/tar/dist/commonjs/list.d.ts +23 -6
- package/node_modules/tar/dist/commonjs/list.js +99 -138
- package/node_modules/tar/dist/commonjs/mkdir.d.ts +16 -11
- package/node_modules/tar/dist/commonjs/mkdir.js +121 -159
- package/node_modules/tar/dist/commonjs/normalize-unicode.js +9 -0
- package/node_modules/tar/dist/commonjs/options.d.ts +284 -513
- package/node_modules/tar/dist/commonjs/options.js +20 -61
- package/node_modules/tar/dist/commonjs/pack.d.ts +150 -96
- package/node_modules/tar/dist/commonjs/pack.js +752 -445
- package/node_modules/tar/dist/commonjs/parser.d.ts +98 -0
- package/node_modules/tar/dist/commonjs/parser.js +452 -0
- package/node_modules/tar/dist/commonjs/path-reservations.d.ts +17 -7
- package/node_modules/tar/dist/commonjs/path-reservations.js +110 -140
- package/node_modules/tar/dist/commonjs/path.d.ts +19 -0
- package/node_modules/tar/dist/commonjs/path.js +90 -0
- package/node_modules/tar/dist/commonjs/pax.d.ts +3 -1
- package/node_modules/tar/dist/commonjs/pax.js +67 -36
- package/node_modules/tar/dist/commonjs/read-entry.d.ts +97 -11
- package/node_modules/tar/dist/commonjs/read-entry.js +251 -97
- package/node_modules/tar/dist/commonjs/read-file.d.ts +22 -0
- package/node_modules/tar/dist/commonjs/read-file.js +104 -0
- package/node_modules/tar/dist/commonjs/replace.d.ts +45 -1
- package/node_modules/tar/dist/commonjs/replace.js +164 -211
- package/node_modules/tar/dist/commonjs/server/codecs.d.ts +38 -0
- package/node_modules/tar/dist/commonjs/server/codecs.js +252 -0
- package/node_modules/tar/dist/commonjs/server/index.d.ts +115 -0
- package/node_modules/tar/dist/commonjs/server/index.js +166 -0
- package/node_modules/tar/dist/commonjs/server/index.min.js +3 -0
- package/node_modules/tar/dist/commonjs/strip-absolute-path.d.ts +8 -0
- package/node_modules/tar/dist/commonjs/strip-absolute-path.js +17 -20
- package/node_modules/tar/dist/commonjs/to-stream.d.ts +7 -0
- package/node_modules/tar/dist/commonjs/to-stream.js +22 -0
- package/node_modules/tar/dist/commonjs/types.d.ts +4 -3
- package/node_modules/tar/dist/commonjs/types.js +4 -3
- package/node_modules/tar/dist/commonjs/unpack.d.ts +143 -89
- package/node_modules/tar/dist/commonjs/unpack.js +780 -725
- package/node_modules/tar/dist/commonjs/update.d.ts +11 -1
- package/node_modules/tar/dist/commonjs/update.js +37 -28
- package/node_modules/tar/dist/commonjs/warn.d.ts +27 -0
- package/node_modules/tar/dist/commonjs/warn.js +36 -0
- package/node_modules/tar/dist/commonjs/win32-path.d.ts +16 -0
- package/node_modules/tar/dist/commonjs/win32-path.js +67 -0
- package/node_modules/tar/dist/commonjs/write-entry.d.ts +64 -111
- package/node_modules/tar/dist/commonjs/write-entry.js +108 -672
- package/node_modules/tar/dist/commonjs/write-flag.d.ts +18 -0
- package/node_modules/tar/dist/commonjs/write-flag.js +29 -0
- package/node_modules/tar/dist/esm/bytes.d.ts +21 -0
- package/node_modules/tar/dist/esm/bytes.js +72 -0
- package/node_modules/tar/dist/esm/codec.d.ts +53 -0
- package/node_modules/tar/dist/esm/codec.js +32 -0
- package/node_modules/tar/dist/esm/concat.d.ts +3 -0
- package/node_modules/tar/dist/esm/concat.js +16 -0
- package/node_modules/tar/dist/esm/create.d.ts +39 -2
- package/node_modules/tar/dist/esm/create.js +144 -61
- package/node_modules/tar/dist/esm/dealias.d.ts +79 -0
- package/node_modules/tar/dist/esm/dealias.js +46 -0
- package/node_modules/tar/dist/esm/delete.d.ts +19 -0
- package/node_modules/tar/dist/esm/delete.js +117 -0
- package/node_modules/tar/dist/esm/entries.d.ts +82 -0
- package/node_modules/tar/dist/esm/entries.js +388 -0
- package/node_modules/tar/dist/esm/extract.d.ts +14 -2
- package/node_modules/tar/dist/esm/extract.js +37 -44
- package/node_modules/tar/dist/esm/fs.d.ts +201 -0
- package/node_modules/tar/dist/esm/fs.js +4 -0
- package/node_modules/tar/dist/esm/header.d.ts +4 -4
- package/node_modules/tar/dist/esm/header.js +71 -53
- package/node_modules/tar/dist/esm/index.d.ts +25 -18
- package/node_modules/tar/dist/esm/index.js +23 -18
- package/node_modules/tar/dist/esm/index.min.js +2 -3
- package/node_modules/tar/dist/esm/large-numbers.d.ts +2 -2
- package/node_modules/tar/dist/esm/large-numbers.js +4 -4
- package/node_modules/tar/dist/esm/list.d.ts +23 -6
- package/node_modules/tar/dist/esm/list.js +96 -101
- package/node_modules/tar/dist/esm/mkdir.d.ts +16 -11
- package/node_modules/tar/dist/esm/mkdir.js +119 -154
- package/node_modules/tar/dist/esm/normalize-unicode.js +9 -0
- package/node_modules/tar/dist/esm/options.d.ts +284 -513
- package/node_modules/tar/dist/esm/options.js +17 -51
- package/node_modules/tar/dist/esm/pack.d.ts +150 -96
- package/node_modules/tar/dist/esm/pack.js +750 -441
- package/node_modules/tar/dist/esm/parser.d.ts +98 -0
- package/node_modules/tar/dist/esm/parser.js +448 -0
- package/node_modules/tar/dist/esm/path-reservations.d.ts +17 -7
- package/node_modules/tar/dist/esm/path-reservations.js +110 -140
- package/node_modules/tar/dist/esm/path.d.ts +19 -0
- package/node_modules/tar/dist/esm/path.js +80 -0
- package/node_modules/tar/dist/esm/pax.d.ts +3 -1
- package/node_modules/tar/dist/esm/pax.js +66 -35
- package/node_modules/tar/dist/esm/read-entry.d.ts +97 -11
- package/node_modules/tar/dist/esm/read-entry.js +248 -96
- package/node_modules/tar/dist/esm/read-file.d.ts +22 -0
- package/node_modules/tar/dist/esm/read-file.js +99 -0
- package/node_modules/tar/dist/esm/replace.d.ts +45 -1
- package/node_modules/tar/dist/esm/replace.js +160 -207
- package/node_modules/tar/dist/esm/server/codecs.d.ts +38 -0
- package/node_modules/tar/dist/esm/server/codecs.js +214 -0
- package/node_modules/tar/dist/esm/server/index.d.ts +115 -0
- package/node_modules/tar/dist/esm/server/index.js +102 -0
- package/node_modules/tar/dist/esm/server/index.min.js +3 -0
- package/node_modules/tar/dist/esm/strip-absolute-path.d.ts +8 -0
- package/node_modules/tar/dist/esm/strip-absolute-path.js +17 -20
- package/node_modules/tar/dist/esm/to-stream.d.ts +7 -0
- package/node_modules/tar/dist/esm/to-stream.js +18 -0
- package/node_modules/tar/dist/esm/types.d.ts +4 -3
- package/node_modules/tar/dist/esm/types.js +4 -3
- package/node_modules/tar/dist/esm/unpack.d.ts +143 -89
- package/node_modules/tar/dist/esm/unpack.js +776 -719
- package/node_modules/tar/dist/esm/update.d.ts +11 -1
- package/node_modules/tar/dist/esm/update.js +35 -28
- package/node_modules/tar/dist/esm/warn.d.ts +27 -0
- package/node_modules/tar/dist/esm/warn.js +31 -0
- package/node_modules/tar/dist/esm/win32-path.d.ts +16 -0
- package/node_modules/tar/dist/esm/win32-path.js +60 -0
- package/node_modules/tar/dist/esm/write-entry.d.ts +64 -111
- package/node_modules/tar/dist/esm/write-entry.js +107 -633
- package/node_modules/tar/dist/esm/write-flag.d.ts +18 -0
- package/node_modules/tar/dist/esm/write-flag.js +25 -0
- package/node_modules/tar/package.json +68 -224
- package/package.json +2 -2
- 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-AJLU6KLW.js +0 -2
- package/node_modules/@isaacs/fs-minipass/LICENSE +0 -15
- package/node_modules/@isaacs/fs-minipass/README.md +0 -71
- package/node_modules/@isaacs/fs-minipass/dist/commonjs/index.d.ts +0 -118
- package/node_modules/@isaacs/fs-minipass/dist/commonjs/index.js +0 -430
- package/node_modules/@isaacs/fs-minipass/dist/commonjs/package.json +0 -3
- package/node_modules/@isaacs/fs-minipass/dist/esm/index.d.ts +0 -118
- package/node_modules/@isaacs/fs-minipass/dist/esm/index.js +0 -420
- package/node_modules/@isaacs/fs-minipass/dist/esm/package.json +0 -3
- package/node_modules/@isaacs/fs-minipass/package.json +0 -72
- package/node_modules/chownr/LICENSE.md +0 -63
- package/node_modules/chownr/README.md +0 -3
- package/node_modules/chownr/dist/commonjs/index.d.ts +0 -3
- package/node_modules/chownr/dist/commonjs/index.js +0 -93
- package/node_modules/chownr/dist/commonjs/package.json +0 -3
- package/node_modules/chownr/dist/esm/index.d.ts +0 -3
- package/node_modules/chownr/dist/esm/index.js +0 -85
- package/node_modules/chownr/dist/esm/package.json +0 -3
- package/node_modules/chownr/package.json +0 -69
- package/node_modules/minipass/LICENSE.md +0 -55
- package/node_modules/minipass/README.md +0 -825
- package/node_modules/minipass/dist/commonjs/index.d.ts +0 -545
- package/node_modules/minipass/dist/commonjs/index.js +0 -1038
- package/node_modules/minipass/dist/commonjs/package.json +0 -3
- package/node_modules/minipass/dist/esm/index.d.ts +0 -545
- package/node_modules/minipass/dist/esm/index.js +0 -1020
- package/node_modules/minipass/dist/esm/package.json +0 -3
- package/node_modules/minipass/package.json +0 -77
- package/node_modules/minizlib/LICENSE +0 -26
- package/node_modules/minizlib/README.md +0 -64
- package/node_modules/minizlib/dist/commonjs/constants.d.ts +0 -2
- package/node_modules/minizlib/dist/commonjs/constants.js +0 -123
- package/node_modules/minizlib/dist/commonjs/index.d.ts +0 -99
- package/node_modules/minizlib/dist/commonjs/index.js +0 -416
- package/node_modules/minizlib/dist/commonjs/package.json +0 -3
- package/node_modules/minizlib/dist/esm/constants.d.ts +0 -2
- package/node_modules/minizlib/dist/esm/constants.js +0 -117
- package/node_modules/minizlib/dist/esm/index.d.ts +0 -99
- package/node_modules/minizlib/dist/esm/index.js +0 -363
- package/node_modules/minizlib/dist/esm/package.json +0 -3
- package/node_modules/minizlib/package.json +0 -80
- package/node_modules/tar/dist/commonjs/get-write-flag.d.ts +0 -2
- package/node_modules/tar/dist/commonjs/get-write-flag.js +0 -32
- package/node_modules/tar/dist/commonjs/make-command.d.ts +0 -49
- package/node_modules/tar/dist/commonjs/make-command.js +0 -52
- package/node_modules/tar/dist/commonjs/normalize-windows-path.d.ts +0 -2
- package/node_modules/tar/dist/commonjs/normalize-windows-path.js +0 -12
- package/node_modules/tar/dist/commonjs/parse.d.ts +0 -92
- package/node_modules/tar/dist/commonjs/parse.js +0 -655
- package/node_modules/tar/dist/commonjs/process-umask.d.ts +0 -2
- package/node_modules/tar/dist/commonjs/process-umask.js +0 -7
- package/node_modules/tar/dist/commonjs/warn-method.d.ts +0 -24
- package/node_modules/tar/dist/commonjs/warn-method.js +0 -31
- package/node_modules/tar/dist/esm/get-write-flag.d.ts +0 -2
- package/node_modules/tar/dist/esm/get-write-flag.js +0 -26
- package/node_modules/tar/dist/esm/make-command.d.ts +0 -49
- package/node_modules/tar/dist/esm/make-command.js +0 -48
- package/node_modules/tar/dist/esm/normalize-windows-path.d.ts +0 -2
- package/node_modules/tar/dist/esm/normalize-windows-path.js +0 -9
- package/node_modules/tar/dist/esm/parse.d.ts +0 -92
- package/node_modules/tar/dist/esm/parse.js +0 -651
- package/node_modules/tar/dist/esm/process-umask.d.ts +0 -2
- package/node_modules/tar/dist/esm/process-umask.js +0 -3
- package/node_modules/tar/dist/esm/warn-method.d.ts +0 -24
- package/node_modules/tar/dist/esm/warn-method.js +0 -27
- package/node_modules/yallist/LICENSE.md +0 -63
- package/node_modules/yallist/README.md +0 -205
- package/node_modules/yallist/dist/commonjs/index.d.ts +0 -39
- package/node_modules/yallist/dist/commonjs/index.js +0 -384
- package/node_modules/yallist/dist/commonjs/package.json +0 -3
- package/node_modules/yallist/dist/esm/index.d.ts +0 -39
- package/node_modules/yallist/dist/esm/index.js +0 -379
- package/node_modules/yallist/dist/esm/package.json +0 -3
- package/node_modules/yallist/package.json +0 -68
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Ea as yt,sa as wt}from"./chunk-4YQMQOUO.js";import{a as Wn}from"./chunk-6H36ZHMI.js";import{a as ge,b as Fn}from"./chunk-Q6K7HWZ7.js";import{c as Dn}from"./chunk-AA52P34H.js";import{ja as Gn}from"./chunk-C6WM6ZN4.js";import{t as Un}from"./chunk-QDV7S2QS.js";import{A as Oe,B as pe,D as ft,E as mt,F as z,G as _e,H as J,I as pt,J as In,kd as kt,mb as je,n as En,nb as $e,o as G,p as Sn,q as bn,r as me,vb as Nn,wb as ae}from"./chunk-CBUC4X7Q.js";import{H as ie,b as gt,g as xt,u as W}from"./chunk-OXC5KBIQ.js";import{Ib as $,Q as oe,Ra as Mn,Xg as se,lg as _t,of as ht}from"./chunk-NRQCBUYD.js";import{g as re,l as An,o as B,p as Pn,q as Rn,r as D,w as On}from"./chunk-GSLOAEY2.js";import{Q as V,R as jn,U as $n,a as vn,b as U,c as Tn,x as E}from"./chunk-I4SPJQQI.js";import{i as F}from"./chunk-TE6FBDHP.js";import{A as u,C as l,D as Cn,E as he,F as Ie,G as K,H as lt,L as Ln}from"./chunk-K672XXGQ.js";import ns from"node:fs/promises";import C from"node:path";import{readdir as Kn,realpath as Bn,stat as zn}from"node:fs/promises";import S from"node:path";var Oo=4096,Io=32,jo=1e3,$o=5e4,Mo={nodes:1e4,edges:4e4,stateIds:2e6},Y=47,ce=class extends Error{},No=new Map(Object.entries({alnum:[[48,57],[65,90],[97,122]],alpha:[[65,90],[97,122]],ascii:[[0,127]],blank:[[9,9],[32,32]],cntrl:[[0,31],[127,127]],digit:[[48,57]],graph:[[33,126]],lower:[[97,122]],print:[[32,126]],punct:[[33,47],[58,64],[91,96],[123,126]],space:[[9,13],[32,32]],upper:[[65,90]],word:[[48,57],[65,90],[95,95],[97,122]],xdigit:[[48,57],[65,70],[97,102]]}));function Jn(){return new l("--add-glob does not support negated patterns (a leading ! or !(...)); list the files or patterns to link instead",u.USAGE)}function Uo(e,t){let n=t+1;for((e[n]==="!"||e[n]==="^")&&(n+=1),e[n]==="]"&&(n+=1);n<e.length;){let r=e[n];if(r==="\\")n+=2;else if(r==="["&&e[n+1]===":"){let o=e.indexOf(":",n+2);o===-1||e[o+1]!=="]"?n+=1:n=o+2}else{if(r==="]")return n+1;n+=1}}return-1}function Go(e,t,n){let r=e[t];if(r==="{")return{index:t,kind:"{"};if(r!=="(")return;let o=e[t-1];return o!==void 0&&"@?*+!".includes(o)&&!Vn(e,t-1)?{index:t-1,kind:"("}:n.some(s=>s.kind==="(")?{index:t,kind:"plain"}:void 0}function Fo(e,t,n,r,o){let s=e[t],i=n.at(-1);if(s===")"&&i?.kind==="plain"){n.pop(),o.set(i.index,t);return}let a=s==="}"?"{":s===")"?"(":void 0;if(!(a===void 0||i?.kind!==a)&&(n.pop(),r.set(i.index,t),e[i.index]==="!"))throw Jn()}function Do(e){let t=new Map,n=new Map,r=new Map,o=[],s=0;for(;s<e.length;){if(e[s]==="\\"){s+=2;continue}let i=e[s]==="["?Uo(e,s):-1;if(i!==-1){n.set(s,i),s=i;continue}let a=Go(e,s,o);if(a!==void 0?o.push(a):Fo(e,s,o,t,r),o.length>Io)throw new ce;s+=1}return{closers:t,brackets:n,groups:r}}function Vn(e,t){let n=0;for(let r=t-1;r>=0&&e[r]==="\\";r-=1)n+=1;return n%2===1}function X(e){return Array.from(e,t=>({kind:"char",value:t.codePointAt(0)}))}function Wo(e){let t=/^(-?(?:0|[1-9]\d{0,8}))\.\.(-?(?:0|[1-9]\d{0,8}))$/u.exec(e),n=/^([A-Za-z])\.\.([A-Za-z])$/u.exec(e);if(t===null&&n===null)return;let[r,o]=t!==null?[Number(t[1]),Number(t[2])]:[n[1].codePointAt(0),n[2].codePointAt(0)];if(Math.abs(o-r)+1>jo)throw new ce;let s=r<=o?1:-1,i=[];for(let a=r;a!==o+s;a+=s)i.push(t!==null?String(a):String.fromCodePoint(a));return i}function qo(e,t){if(e[t]!=="["||e[t+1]!==":")return;let n=e.indexOf(":",t+2);if(!(n===-1||e[n+1]!=="]"))return{ranges:No.get(e.slice(t+2,n).join(""))??[],next:n+2}}function qn(e,t,n){let r=e[t]==="\\"&&t+1<n;return{codePoint:e[r?t+1:t].codePointAt(0),next:t+(r?2:1)}}function Ho(e,t,n){let r=[];for(let o=t;o<n;o+=1)e[o]==="\\"&&o+1<n&&(o+=1),r.push(e[o].codePointAt(0));return r}function Ko(e,t,n){let r=t+1,o=e[r]==="!"||e[r]==="^";o&&(r+=1);let s=[],i=n-1;for(;r<i;){let a=qo(e,r);if(a!==void 0){s.push(...a.ranges),r=a.next;continue}let c=qn(e,r,i);if(r=c.next,e[r]!=="-"||r+1>=i){s.push([c.codePoint,c.codePoint]);continue}let d=qn(e,r+1,i);r=d.next,c.codePoint<=d.codePoint&&s.push([c.codePoint,d.codePoint])}return{kind:"class",negated:o,ranges:s,literal:Ho(e,t,n)}}var vt=class{chars;closers;brackets;groups;constructor(t,n){this.chars=t,this.closers=n.closers,this.brackets=n.brackets,this.groups=n.groups}alternatives(t,n,r){let o=[],s=t;for(;;){let{nodes:i,stop:a}=this.sequence(s,n,r);if(o.push(i),a>=n)return o;s=a+1}}sequence(t,n,r){let o=[],s=t;for(;s<n;){if(this.chars[s]===r)return{nodes:o,stop:s};let i=this.token(s,n);o.push(...i.nodes),s=i.next}return{nodes:o,stop:n}}token(t,n){let r=this.chars[t];if(r==="\\")return{nodes:X(t+1<n?this.chars[t+1]:"\\"),next:t+2};let o=this.closers.get(t);if(o!==void 0)return{nodes:r==="{"?this.brace(t,o):this.extglob(r,t,o),next:o+1};let s=this.groups.get(t);if(s!==void 0)return{nodes:[...X("("),...this.sequence(t+1,s,void 0).nodes,...X(")")],next:s+1};let i=this.brackets.get(t);return i!==void 0?{nodes:[Ko(this.chars,t,i)],next:i}:r==="*"?this.stars(t,n):{nodes:r==="?"?[{kind:"any"}]:X(r),next:t+1}}extglob(t,n,r){let o=this.alternatives(n+2,r,"|");return[t==="@"?{kind:"alt",options:o}:{kind:"repeat",optional:t!=="+",many:t!=="?",options:o}]}brace(t,n){let r=this.alternatives(t+1,n,",");if(r.length>1)return[{kind:"alt",options:r}];let o=Wo(this.chars.slice(t+1,n).join(""));return o!==void 0?[{kind:"alt",options:o.map(X)}]:[...X("{"),...r[0],...X("}")]}stars(t,n){let r=1;for(;this.chars[t+r]==="*"&&t+r<n&&!this.closers.has(t+r);)r+=1;if(r!==2)return{nodes:[{kind:"star"}],next:t+r};let o=t+r<n&&this.chars[t+r]==="/";return{nodes:[{kind:"globstar",slash:o}],next:t+r+(o?1:0)}}},Tt=["segment","inside"],Me={kind:"any"};function Et(e){return Tt.flatMap(t=>e[t]===void 0?[]:[e[t]])}var St=class{states=[];add(){if(this.states.length>=$o)throw new ce;return this.states.push({epsilon:[],syntactic:[],edges:[]}),this.states.length-1}epsilon(t,n,r=!0){this.states[t].epsilon.push(n),r&&this.states[t].syntactic.push(n)}consume(t,n,r){let o=this.add();for(let s of Et(t))this.states[s].edges.push({test:n,to:o});return{[r]:o}}join(t){let n={};for(let r of Tt){let o=t.flatMap(s=>s[r]===void 0?[]:[s[r]]);if(o.length===1&&(n[r]=o[0]),o.length>1){let s=this.add();for(let i of o)this.epsilon(i,s);n[r]=s}}return n}feed(t,n){for(let r of Tt)t[r]!==void 0&&this.epsilon(t[r],n[r])}build(t,n){let r=n;for(let o of t)r=this.node(o,r);return r}alternation(t,n){return this.join(t.map(r=>this.build(r,n)))}star(t){let n=this.add();for(let r of Et(t))this.epsilon(r,n,!1);return this.states[n].edges.push({test:Me,to:n}),{inside:n}}segments(t){let n=this.add();this.epsilon(t,n,!1);let r=this.add();return this.states[n].edges.push({test:Me,to:r}),this.states[r].edges.push({test:Me,to:r},{test:{kind:"char",value:Y},to:n}),n}globstar(t,n){if(n){let o=[];return t.segment!==void 0&&o.push({segment:this.segments(t.segment)}),t.inside!==void 0&&o.push(this.consume(this.star({inside:t.inside}),{kind:"char",value:Y},"segment")),this.join(o)}let r=this.star(t);return t.segment!==void 0&&this.globstars.push({continuation:r.inside,entry:t.segment}),r}globstars=[];syntacticClosure(t){let n=new Set(t),r=[...t];for(;r.length>0;)for(let o of this.states[r.pop()].syntactic)n.has(o)||(n.add(o),r.push(o));return n}resolveGlobstars(t){for(let{continuation:n,entry:r}of this.globstars){let o=this.syntacticClosure([n]);if(o.has(t)){let a=this.add();this.epsilon(r,a,!1),this.states[a].edges.push({test:{kind:"all"},to:a}),this.epsilon(a,t,!1)}let s=new Set;for(let a of o)for(let{test:c,to:d}of this.states[a].edges)Xn(c,Y)&&s.add(d);if(s.size===0)continue;let i=this.segments(r);for(let a of s)this.epsilon(i,a,!1)}}repeat(t,n){if(!t.many)return this.join([n,this.alternation(t.options,n)]);let r={segment:this.add(),inside:this.add()};return this.feed(t.optional?n:this.alternation(t.options,n),r),this.feed(this.alternation(t.options,r),r),r}node(t,n){switch(t.kind){case"char":return this.consume(n,{kind:"char",value:t.value},t.value===Y?"segment":"inside");case"any":return this.consume(n,Me,"inside");case"star":return this.star(n);case"globstar":return this.globstar(n,t.slash);case"class":return this.join([this.consume(n,{kind:"class",negated:t.negated,ranges:t.ranges},"inside"),this.build(t.literal.map(r=>({kind:"char",value:r})),n)]);case"alt":return this.alternation(t.options,n);case"repeat":return this.repeat(t,n)}}};function Xn(e,t){switch(e.kind){case"char":return e.value===t;case"any":return t!==Y;case"all":return!0;case"class":return t!==Y&&e.ranges.some(([n,r])=>t>=n&&t<=r)!==e.negated}}var bt=class{generation=0;nextId=0;nodes=new Map;edges=new Map;stateIds=0;nfa;acceptState;limits;start;constructor(t,n,r,o){this.nfa=t,this.acceptState=r,this.limits=o,this.start=this.node(this.closure([n]))}retained(){return{nodes:this.nodes.size,edges:this.edges.size,stateIds:this.stateIds}}reset(){this.generation+=1,this.nodes=new Map,this.edges=new Map,this.stateIds=0}closure(t){let n=new Set(t),r=[...t];for(;r.length>0;)for(let o of this.nfa.states[r.pop()].epsilon)n.has(o)||(n.add(o),r.push(o));return[...n].sort((o,s)=>o-s)}node(t){let n=t.join(","),r=this.nodes.get(n);if(r!==void 0)return r;(this.nodes.size>=this.limits.nodes||this.stateIds+t.length>this.limits.stateIds)&&this.reset();let o={id:this.nextId,generation:this.generation,states:t,accepting:t.includes(this.acceptState)};return this.nextId+=1,this.nodes.set(n,o),this.stateIds+=t.length,o}step(t,n){let r=`${t.id}:${n}`,o=t.generation===this.generation?this.edges.get(r):void 0;if(o!==void 0)return o;let s=[];for(let a of t.states)for(let{test:c,to:d}of this.nfa.states[a].edges)Xn(c,n)&&s.push(d);let i=this.node(this.closure(s));return this.edges.size>=this.limits.edges&&this.reset(),t.generation===this.generation&&this.edges.set(r,i),i}advance(t,n){let r=t;for(let o of n){if(r.states.length===0)return r;r=this.step(r,o.codePointAt(0))}return r}};function Bo(e,t=Mo){let n=Array.from(e),r=new vt(n,Do(n)).sequence(0,n.length,void 0).nodes,o=new St,s=o.add(),i=o.add();for(let a of Et(o.build(r,{segment:s})))o.epsilon(a,i);return o.resolveGlobstars(i),new bt(o,s,i,t)}function zo(e){return!/[*?[\]{}()!@+\\]/u.test(e)}function Hn(e){return e.isFile()?"file":e.isDirectory()?"directory":"other"}async function Jo(e,t,n){if(!n.isSymbolicLink())return{kind:Hn(n),real:S.join(t,n.name)};try{let r=await Bn(S.join(e,n.name));return{kind:Hn(await zn(r)),real:r}}catch{return}}async function Yn(e,t,n,r,o,s,i){let a;try{a=await Kn(t,{withFileTypes:!0})}catch{return}for(let c of a){let d=e.advance(o,c.name);if(d.states.length===0)continue;let f=await Jo(t,n,c);if(f===void 0)continue;let m=S.posix.join(r,c.name);if(f.kind==="file"&&d.accepting&&i.push(m),f.kind!=="directory")continue;let p=e.step(d,Y);p.states.length===0||s.has(f.real)||(s.add(f.real),await Yn(e,S.join(t,c.name),f.real,m,p,s,i),s.delete(f.real))}}function Vo(e){let t=S.posix.normalize(e);return/^\/\/[^/]/u.test(e)?`/${t}`:t}function Xo(e){let t=e;for(;t.length>1&&t.endsWith("/")&&!Vn(t,t.length-1);)t=t.slice(0,-1);return t}async function Zn(e,t){return(await Kn(e).catch(()=>[])).includes(t)}async function Qn(e,t){let n=e,r=0;for(;t[r]==="..";)n=S.dirname(n),r+=1;for(;r<t.length;r+=1){if(!await Zn(n,t[r]))return!1;n=S.join(n,t[r])}return!0}function er(e,t=process.platform){return e.startsWith("/")||t==="win32"&&/^[A-Za-z]:\//u.test(e)}async function Yo(e,t){let n=S.resolve(t,e),r=await zn(n).catch(()=>{});if(r===void 0||!r.isFile())return[];let o=er(e);return(o?await Zn(S.dirname(n),S.basename(n)):await Qn(t,e.split("/")))?[o?n.replaceAll("\\","/"):S.posix.normalize(e)]:[]}function Zo(e,t){let n=e.split("/"),r=0;for(;r<n.length&&zo(n[r]);)r+=1;if(r===n.length)return;let o=r===0?"":`${n.slice(0,r).join("/")}/`,s=S.resolve(t,o),i=n.slice(r).join("/");if(er(e))return{root:s,base:s.replaceAll("\\","/"),rest:i,prefix:[]};let a=S.posix.normalize(o===""?".":o).replace(/\/$/u,"");return{root:s,base:a==="."?"":a,rest:i,prefix:n.slice(0,r)}}function Qo(e){try{return Bo(e)}catch(t){if(t instanceof ce)return;throw t}}async function tr(e,t){if(e.startsWith("!"))throw Jn();if(Array.from(e).length>Oo)return[];let n=Xo(Vo(e)),r=Zo(n,t);if(r===void 0)return Yo(n,t);let o=Qo(r.rest);if(o===void 0||!await Qn(t,r.prefix))return[];let s=await Bn(r.root).catch(()=>{});if(s===void 0)return[];let i=[];return await Yn(o,r.root,s,"",o.start,new Set([s]),i),i.map(a=>es(r.base,a))}function es(e,t){return e.startsWith("//")?`/${S.posix.join(e.slice(1),t)}`:S.posix.join(e,t)}var ts=/^[a-z][a-z0-9+.-]+:\/\//i;function Ct(e){return ts.test(e.trim())}var Lt=["refuse","replace","append"],Rt="; ";function rs(e,t){if(e===void 0)return"refuse";let n=e.trim().toLowerCase();if(!Lt.some(r=>r===n))throw new l(`--note-conflict must be one of ${Lt.join(", ")}; got "${e}"`,u.USAGE,{code:"invalid_argument_value",flag:"--note-conflict",value:e,required:`Pass --note-conflict ${Lt.join("|")}.`});if(!t)throw new l("--note-conflict requires --add or --add-glob in the same invocation (it decides how those links treat an existing note)",u.USAGE,{code:"missing_required_argument",flag:"--note-conflict",required:"Pass --add or --add-glob with --note-conflict."});return n}function os(e,t,n){if(t===void 0||t===e)return{note:e,outcome:"unchanged",conflict:!1};if(e===void 0)return{note:t,outcome:"note_added",conflict:!1};if(n==="replace")return{note:t,outcome:"note_replaced",conflict:!1};if(n==="append"){let r=Rt;return`${r}${e}${r}`.includes(`${r}${t}${r}`)?{note:e,outcome:"unchanged",conflict:!1}:{note:`${e}${Rt}${t}`,outcome:"note_appended",conflict:!1}}return{note:e,outcome:"unchanged",conflict:!0}}function ss(e){let t=e.conflicts[0],n=e.conflicts.length>1?` and ${e.conflicts.length-1} more`:"",r=e.retryArgs("append"),o=e.retryArgs("replace"),s=t.source==="stored"?`${e.itemId} already links ${e.noun} ${t.path} with the note "${t.existing_note}"${n}; the add was refused so that note is kept`:`The add names ${e.noun} ${t.path} on ${e.itemId} with two notes, "${t.existing_note}" and then "${t.requested_note}"${n}; the add was refused because they disagree`;return new l(s,u.CONFLICT,{code:"linked_artifact_note_conflict",item_id:e.itemId,why:"A different stored note is usually another agent's rationale, so --add never overwrites it silently.",required:"Re-run with --note-conflict append to keep both notes, or --note-conflict replace to overwrite the stored note.",...r===void 0||o===void 0?{}:{nextSteps:[e.render(r),e.render(o)],recovery:{suggested_retry:e.render(r),suggested_retry_args:r}},details:{conflicts:e.conflicts.map(i=>({...i}))}})}var Ot=["path","scope","note"],is=["pattern","glob","path","scope","note"],as=["path"],cs=["from","to"],ds=new Set(["note","scope"]);function nr(e){return JSON.parse(JSON.stringify(e))}function Mt(e,t){let n=e.map(nr);return t.filter(r=>{let o=nr(r),s=n.findIndex(i=>U(i,o));return s>=0&&n.splice(s,1),s<0})}function xe(e){let t=e.fullHistory?[...e.stored]:[...e.written],n=t.length<e.stored.length;return{entries:t,total_count:e.stored.length,returned_count:t.length,has_more:n,mutation_receipt:{changed_count:e.written.length,removed_count:e.removedCount,full_history_included:!n,...e.linkOutcomes&&e.linkOutcomes.length>0?{link_outcomes:[...e.linkOutcomes]}:{}},omission_receipt:{has_omissions:n,omitted_field_group_count:n?1:0,omitted_field_groups:n?[{name:`${e.collectionKey}_history`,restore_with:{selector:"full_history",cli_flag:"--full-history",sdk_option:"fullHistory",mcp_option:"full"}}]:[]}}}function rr(e){let t=e??"project";if(!F.includes(t))throw new l(`Invalid scope "${e}". Valid scopes: ${F.join(", ")} (default: project).`,u.USAGE);return t}function It(e){if(e.startsWith("```")||e.includes(`
|
|
1
|
+
import{Ea as yt,sa as wt}from"./chunk-7V65VACG.js";import{a as Wn}from"./chunk-6H36ZHMI.js";import{a as ge,b as Fn}from"./chunk-Q6K7HWZ7.js";import{c as Dn}from"./chunk-AA52P34H.js";import{ja as Gn}from"./chunk-C6WM6ZN4.js";import{t as Un}from"./chunk-QDV7S2QS.js";import{A as Oe,B as pe,D as ft,E as mt,F as z,G as _e,H as J,I as pt,J as In,kd as kt,mb as je,n as En,nb as $e,o as G,p as Sn,q as bn,r as me,vb as Nn,wb as ae}from"./chunk-CBUC4X7Q.js";import{H as ie,b as gt,g as xt,u as W}from"./chunk-OXC5KBIQ.js";import{Ib as $,Q as oe,Ra as Mn,Xg as se,lg as _t,of as ht}from"./chunk-NRQCBUYD.js";import{g as re,l as An,o as B,p as Pn,q as Rn,r as D,w as On}from"./chunk-GSLOAEY2.js";import{Q as V,R as jn,U as $n,a as vn,b as U,c as Tn,x as E}from"./chunk-I4SPJQQI.js";import{i as F}from"./chunk-TE6FBDHP.js";import{A as u,C as l,D as Cn,E as he,F as Ie,G as K,H as lt,L as Ln}from"./chunk-K672XXGQ.js";import ns from"node:fs/promises";import C from"node:path";import{readdir as Kn,realpath as Bn,stat as zn}from"node:fs/promises";import S from"node:path";var Oo=4096,Io=32,jo=1e3,$o=5e4,Mo={nodes:1e4,edges:4e4,stateIds:2e6},Y=47,ce=class extends Error{},No=new Map(Object.entries({alnum:[[48,57],[65,90],[97,122]],alpha:[[65,90],[97,122]],ascii:[[0,127]],blank:[[9,9],[32,32]],cntrl:[[0,31],[127,127]],digit:[[48,57]],graph:[[33,126]],lower:[[97,122]],print:[[32,126]],punct:[[33,47],[58,64],[91,96],[123,126]],space:[[9,13],[32,32]],upper:[[65,90]],word:[[48,57],[65,90],[95,95],[97,122]],xdigit:[[48,57],[65,70],[97,102]]}));function Jn(){return new l("--add-glob does not support negated patterns (a leading ! or !(...)); list the files or patterns to link instead",u.USAGE)}function Uo(e,t){let n=t+1;for((e[n]==="!"||e[n]==="^")&&(n+=1),e[n]==="]"&&(n+=1);n<e.length;){let r=e[n];if(r==="\\")n+=2;else if(r==="["&&e[n+1]===":"){let o=e.indexOf(":",n+2);o===-1||e[o+1]!=="]"?n+=1:n=o+2}else{if(r==="]")return n+1;n+=1}}return-1}function Go(e,t,n){let r=e[t];if(r==="{")return{index:t,kind:"{"};if(r!=="(")return;let o=e[t-1];return o!==void 0&&"@?*+!".includes(o)&&!Vn(e,t-1)?{index:t-1,kind:"("}:n.some(s=>s.kind==="(")?{index:t,kind:"plain"}:void 0}function Fo(e,t,n,r,o){let s=e[t],i=n.at(-1);if(s===")"&&i?.kind==="plain"){n.pop(),o.set(i.index,t);return}let a=s==="}"?"{":s===")"?"(":void 0;if(!(a===void 0||i?.kind!==a)&&(n.pop(),r.set(i.index,t),e[i.index]==="!"))throw Jn()}function Do(e){let t=new Map,n=new Map,r=new Map,o=[],s=0;for(;s<e.length;){if(e[s]==="\\"){s+=2;continue}let i=e[s]==="["?Uo(e,s):-1;if(i!==-1){n.set(s,i),s=i;continue}let a=Go(e,s,o);if(a!==void 0?o.push(a):Fo(e,s,o,t,r),o.length>Io)throw new ce;s+=1}return{closers:t,brackets:n,groups:r}}function Vn(e,t){let n=0;for(let r=t-1;r>=0&&e[r]==="\\";r-=1)n+=1;return n%2===1}function X(e){return Array.from(e,t=>({kind:"char",value:t.codePointAt(0)}))}function Wo(e){let t=/^(-?(?:0|[1-9]\d{0,8}))\.\.(-?(?:0|[1-9]\d{0,8}))$/u.exec(e),n=/^([A-Za-z])\.\.([A-Za-z])$/u.exec(e);if(t===null&&n===null)return;let[r,o]=t!==null?[Number(t[1]),Number(t[2])]:[n[1].codePointAt(0),n[2].codePointAt(0)];if(Math.abs(o-r)+1>jo)throw new ce;let s=r<=o?1:-1,i=[];for(let a=r;a!==o+s;a+=s)i.push(t!==null?String(a):String.fromCodePoint(a));return i}function qo(e,t){if(e[t]!=="["||e[t+1]!==":")return;let n=e.indexOf(":",t+2);if(!(n===-1||e[n+1]!=="]"))return{ranges:No.get(e.slice(t+2,n).join(""))??[],next:n+2}}function qn(e,t,n){let r=e[t]==="\\"&&t+1<n;return{codePoint:e[r?t+1:t].codePointAt(0),next:t+(r?2:1)}}function Ho(e,t,n){let r=[];for(let o=t;o<n;o+=1)e[o]==="\\"&&o+1<n&&(o+=1),r.push(e[o].codePointAt(0));return r}function Ko(e,t,n){let r=t+1,o=e[r]==="!"||e[r]==="^";o&&(r+=1);let s=[],i=n-1;for(;r<i;){let a=qo(e,r);if(a!==void 0){s.push(...a.ranges),r=a.next;continue}let c=qn(e,r,i);if(r=c.next,e[r]!=="-"||r+1>=i){s.push([c.codePoint,c.codePoint]);continue}let d=qn(e,r+1,i);r=d.next,c.codePoint<=d.codePoint&&s.push([c.codePoint,d.codePoint])}return{kind:"class",negated:o,ranges:s,literal:Ho(e,t,n)}}var vt=class{chars;closers;brackets;groups;constructor(t,n){this.chars=t,this.closers=n.closers,this.brackets=n.brackets,this.groups=n.groups}alternatives(t,n,r){let o=[],s=t;for(;;){let{nodes:i,stop:a}=this.sequence(s,n,r);if(o.push(i),a>=n)return o;s=a+1}}sequence(t,n,r){let o=[],s=t;for(;s<n;){if(this.chars[s]===r)return{nodes:o,stop:s};let i=this.token(s,n);o.push(...i.nodes),s=i.next}return{nodes:o,stop:n}}token(t,n){let r=this.chars[t];if(r==="\\")return{nodes:X(t+1<n?this.chars[t+1]:"\\"),next:t+2};let o=this.closers.get(t);if(o!==void 0)return{nodes:r==="{"?this.brace(t,o):this.extglob(r,t,o),next:o+1};let s=this.groups.get(t);if(s!==void 0)return{nodes:[...X("("),...this.sequence(t+1,s,void 0).nodes,...X(")")],next:s+1};let i=this.brackets.get(t);return i!==void 0?{nodes:[Ko(this.chars,t,i)],next:i}:r==="*"?this.stars(t,n):{nodes:r==="?"?[{kind:"any"}]:X(r),next:t+1}}extglob(t,n,r){let o=this.alternatives(n+2,r,"|");return[t==="@"?{kind:"alt",options:o}:{kind:"repeat",optional:t!=="+",many:t!=="?",options:o}]}brace(t,n){let r=this.alternatives(t+1,n,",");if(r.length>1)return[{kind:"alt",options:r}];let o=Wo(this.chars.slice(t+1,n).join(""));return o!==void 0?[{kind:"alt",options:o.map(X)}]:[...X("{"),...r[0],...X("}")]}stars(t,n){let r=1;for(;this.chars[t+r]==="*"&&t+r<n&&!this.closers.has(t+r);)r+=1;if(r!==2)return{nodes:[{kind:"star"}],next:t+r};let o=t+r<n&&this.chars[t+r]==="/";return{nodes:[{kind:"globstar",slash:o}],next:t+r+(o?1:0)}}},Tt=["segment","inside"],Me={kind:"any"};function Et(e){return Tt.flatMap(t=>e[t]===void 0?[]:[e[t]])}var St=class{states=[];add(){if(this.states.length>=$o)throw new ce;return this.states.push({epsilon:[],syntactic:[],edges:[]}),this.states.length-1}epsilon(t,n,r=!0){this.states[t].epsilon.push(n),r&&this.states[t].syntactic.push(n)}consume(t,n,r){let o=this.add();for(let s of Et(t))this.states[s].edges.push({test:n,to:o});return{[r]:o}}join(t){let n={};for(let r of Tt){let o=t.flatMap(s=>s[r]===void 0?[]:[s[r]]);if(o.length===1&&(n[r]=o[0]),o.length>1){let s=this.add();for(let i of o)this.epsilon(i,s);n[r]=s}}return n}feed(t,n){for(let r of Tt)t[r]!==void 0&&this.epsilon(t[r],n[r])}build(t,n){let r=n;for(let o of t)r=this.node(o,r);return r}alternation(t,n){return this.join(t.map(r=>this.build(r,n)))}star(t){let n=this.add();for(let r of Et(t))this.epsilon(r,n,!1);return this.states[n].edges.push({test:Me,to:n}),{inside:n}}segments(t){let n=this.add();this.epsilon(t,n,!1);let r=this.add();return this.states[n].edges.push({test:Me,to:r}),this.states[r].edges.push({test:Me,to:r},{test:{kind:"char",value:Y},to:n}),n}globstar(t,n){if(n){let o=[];return t.segment!==void 0&&o.push({segment:this.segments(t.segment)}),t.inside!==void 0&&o.push(this.consume(this.star({inside:t.inside}),{kind:"char",value:Y},"segment")),this.join(o)}let r=this.star(t);return t.segment!==void 0&&this.globstars.push({continuation:r.inside,entry:t.segment}),r}globstars=[];syntacticClosure(t){let n=new Set(t),r=[...t];for(;r.length>0;)for(let o of this.states[r.pop()].syntactic)n.has(o)||(n.add(o),r.push(o));return n}resolveGlobstars(t){for(let{continuation:n,entry:r}of this.globstars){let o=this.syntacticClosure([n]);if(o.has(t)){let a=this.add();this.epsilon(r,a,!1),this.states[a].edges.push({test:{kind:"all"},to:a}),this.epsilon(a,t,!1)}let s=new Set;for(let a of o)for(let{test:c,to:d}of this.states[a].edges)Xn(c,Y)&&s.add(d);if(s.size===0)continue;let i=this.segments(r);for(let a of s)this.epsilon(i,a,!1)}}repeat(t,n){if(!t.many)return this.join([n,this.alternation(t.options,n)]);let r={segment:this.add(),inside:this.add()};return this.feed(t.optional?n:this.alternation(t.options,n),r),this.feed(this.alternation(t.options,r),r),r}node(t,n){switch(t.kind){case"char":return this.consume(n,{kind:"char",value:t.value},t.value===Y?"segment":"inside");case"any":return this.consume(n,Me,"inside");case"star":return this.star(n);case"globstar":return this.globstar(n,t.slash);case"class":return this.join([this.consume(n,{kind:"class",negated:t.negated,ranges:t.ranges},"inside"),this.build(t.literal.map(r=>({kind:"char",value:r})),n)]);case"alt":return this.alternation(t.options,n);case"repeat":return this.repeat(t,n)}}};function Xn(e,t){switch(e.kind){case"char":return e.value===t;case"any":return t!==Y;case"all":return!0;case"class":return t!==Y&&e.ranges.some(([n,r])=>t>=n&&t<=r)!==e.negated}}var bt=class{generation=0;nextId=0;nodes=new Map;edges=new Map;stateIds=0;nfa;acceptState;limits;start;constructor(t,n,r,o){this.nfa=t,this.acceptState=r,this.limits=o,this.start=this.node(this.closure([n]))}retained(){return{nodes:this.nodes.size,edges:this.edges.size,stateIds:this.stateIds}}reset(){this.generation+=1,this.nodes=new Map,this.edges=new Map,this.stateIds=0}closure(t){let n=new Set(t),r=[...t];for(;r.length>0;)for(let o of this.nfa.states[r.pop()].epsilon)n.has(o)||(n.add(o),r.push(o));return[...n].sort((o,s)=>o-s)}node(t){let n=t.join(","),r=this.nodes.get(n);if(r!==void 0)return r;(this.nodes.size>=this.limits.nodes||this.stateIds+t.length>this.limits.stateIds)&&this.reset();let o={id:this.nextId,generation:this.generation,states:t,accepting:t.includes(this.acceptState)};return this.nextId+=1,this.nodes.set(n,o),this.stateIds+=t.length,o}step(t,n){let r=`${t.id}:${n}`,o=t.generation===this.generation?this.edges.get(r):void 0;if(o!==void 0)return o;let s=[];for(let a of t.states)for(let{test:c,to:d}of this.nfa.states[a].edges)Xn(c,n)&&s.push(d);let i=this.node(this.closure(s));return this.edges.size>=this.limits.edges&&this.reset(),t.generation===this.generation&&this.edges.set(r,i),i}advance(t,n){let r=t;for(let o of n){if(r.states.length===0)return r;r=this.step(r,o.codePointAt(0))}return r}};function Bo(e,t=Mo){let n=Array.from(e),r=new vt(n,Do(n)).sequence(0,n.length,void 0).nodes,o=new St,s=o.add(),i=o.add();for(let a of Et(o.build(r,{segment:s})))o.epsilon(a,i);return o.resolveGlobstars(i),new bt(o,s,i,t)}function zo(e){return!/[*?[\]{}()!@+\\]/u.test(e)}function Hn(e){return e.isFile()?"file":e.isDirectory()?"directory":"other"}async function Jo(e,t,n){if(!n.isSymbolicLink())return{kind:Hn(n),real:S.join(t,n.name)};try{let r=await Bn(S.join(e,n.name));return{kind:Hn(await zn(r)),real:r}}catch{return}}async function Yn(e,t,n,r,o,s,i){let a;try{a=await Kn(t,{withFileTypes:!0})}catch{return}for(let c of a){let d=e.advance(o,c.name);if(d.states.length===0)continue;let f=await Jo(t,n,c);if(f===void 0)continue;let m=S.posix.join(r,c.name);if(f.kind==="file"&&d.accepting&&i.push(m),f.kind!=="directory")continue;let p=e.step(d,Y);p.states.length===0||s.has(f.real)||(s.add(f.real),await Yn(e,S.join(t,c.name),f.real,m,p,s,i),s.delete(f.real))}}function Vo(e){let t=S.posix.normalize(e);return/^\/\/[^/]/u.test(e)?`/${t}`:t}function Xo(e){let t=e;for(;t.length>1&&t.endsWith("/")&&!Vn(t,t.length-1);)t=t.slice(0,-1);return t}async function Zn(e,t){return(await Kn(e).catch(()=>[])).includes(t)}async function Qn(e,t){let n=e,r=0;for(;t[r]==="..";)n=S.dirname(n),r+=1;for(;r<t.length;r+=1){if(!await Zn(n,t[r]))return!1;n=S.join(n,t[r])}return!0}function er(e,t=process.platform){return e.startsWith("/")||t==="win32"&&/^[A-Za-z]:\//u.test(e)}async function Yo(e,t){let n=S.resolve(t,e),r=await zn(n).catch(()=>{});if(r===void 0||!r.isFile())return[];let o=er(e);return(o?await Zn(S.dirname(n),S.basename(n)):await Qn(t,e.split("/")))?[o?n.replaceAll("\\","/"):S.posix.normalize(e)]:[]}function Zo(e,t){let n=e.split("/"),r=0;for(;r<n.length&&zo(n[r]);)r+=1;if(r===n.length)return;let o=r===0?"":`${n.slice(0,r).join("/")}/`,s=S.resolve(t,o),i=n.slice(r).join("/");if(er(e))return{root:s,base:s.replaceAll("\\","/"),rest:i,prefix:[]};let a=S.posix.normalize(o===""?".":o).replace(/\/$/u,"");return{root:s,base:a==="."?"":a,rest:i,prefix:n.slice(0,r)}}function Qo(e){try{return Bo(e)}catch(t){if(t instanceof ce)return;throw t}}async function tr(e,t){if(e.startsWith("!"))throw Jn();if(Array.from(e).length>Oo)return[];let n=Xo(Vo(e)),r=Zo(n,t);if(r===void 0)return Yo(n,t);let o=Qo(r.rest);if(o===void 0||!await Qn(t,r.prefix))return[];let s=await Bn(r.root).catch(()=>{});if(s===void 0)return[];let i=[];return await Yn(o,r.root,s,"",o.start,new Set([s]),i),i.map(a=>es(r.base,a))}function es(e,t){return e.startsWith("//")?`/${S.posix.join(e.slice(1),t)}`:S.posix.join(e,t)}var ts=/^[a-z][a-z0-9+.-]+:\/\//i;function Ct(e){return ts.test(e.trim())}var Lt=["refuse","replace","append"],Rt="; ";function rs(e,t){if(e===void 0)return"refuse";let n=e.trim().toLowerCase();if(!Lt.some(r=>r===n))throw new l(`--note-conflict must be one of ${Lt.join(", ")}; got "${e}"`,u.USAGE,{code:"invalid_argument_value",flag:"--note-conflict",value:e,required:`Pass --note-conflict ${Lt.join("|")}.`});if(!t)throw new l("--note-conflict requires --add or --add-glob in the same invocation (it decides how those links treat an existing note)",u.USAGE,{code:"missing_required_argument",flag:"--note-conflict",required:"Pass --add or --add-glob with --note-conflict."});return n}function os(e,t,n){if(t===void 0||t===e)return{note:e,outcome:"unchanged",conflict:!1};if(e===void 0)return{note:t,outcome:"note_added",conflict:!1};if(n==="replace")return{note:t,outcome:"note_replaced",conflict:!1};if(n==="append"){let r=Rt;return`${r}${e}${r}`.includes(`${r}${t}${r}`)?{note:e,outcome:"unchanged",conflict:!1}:{note:`${e}${Rt}${t}`,outcome:"note_appended",conflict:!1}}return{note:e,outcome:"unchanged",conflict:!0}}function ss(e){let t=e.conflicts[0],n=e.conflicts.length>1?` and ${e.conflicts.length-1} more`:"",r=e.retryArgs("append"),o=e.retryArgs("replace"),s=t.source==="stored"?`${e.itemId} already links ${e.noun} ${t.path} with the note "${t.existing_note}"${n}; the add was refused so that note is kept`:`The add names ${e.noun} ${t.path} on ${e.itemId} with two notes, "${t.existing_note}" and then "${t.requested_note}"${n}; the add was refused because they disagree`;return new l(s,u.CONFLICT,{code:"linked_artifact_note_conflict",item_id:e.itemId,why:"A different stored note is usually another agent's rationale, so --add never overwrites it silently.",required:"Re-run with --note-conflict append to keep both notes, or --note-conflict replace to overwrite the stored note.",...r===void 0||o===void 0?{}:{nextSteps:[e.render(r),e.render(o)],recovery:{suggested_retry:e.render(r),suggested_retry_args:r}},details:{conflicts:e.conflicts.map(i=>({...i}))}})}var Ot=["path","scope","note"],is=["pattern","glob","path","scope","note"],as=["path"],cs=["from","to"],ds=new Set(["note","scope"]);function nr(e){return JSON.parse(JSON.stringify(e))}function Mt(e,t){let n=e.map(nr);return t.filter(r=>{let o=nr(r),s=n.findIndex(i=>U(i,o));return s>=0&&n.splice(s,1),s<0})}function xe(e){let t=e.fullHistory?[...e.stored]:[...e.written],n=t.length<e.stored.length;return{entries:t,total_count:e.stored.length,returned_count:t.length,has_more:n,mutation_receipt:{changed_count:e.written.length,removed_count:e.removedCount,full_history_included:!n,...e.linkOutcomes&&e.linkOutcomes.length>0?{link_outcomes:[...e.linkOutcomes]}:{}},omission_receipt:{has_omissions:n,omitted_field_group_count:n?1:0,omitted_field_groups:n?[{name:`${e.collectionKey}_history`,restore_with:{selector:"full_history",cli_flag:"--full-history",sdk_option:"fullHistory",mcp_option:"full"}}]:[]}}}function rr(e){let t=e??"project";if(!F.includes(t))throw new l(`Invalid scope "${e}". Valid scopes: ${F.join(", ")} (default: project).`,u.USAGE);return t}function It(e){if(e.startsWith("```")||e.includes(`
|
|
2
2
|
`)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(e))return!0;let t=e.indexOf(","),n=e.slice(0,t>=0?t:e.length),r=n.indexOf("=");return r>=0&&!/\s/u.test(e)&&(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)||/^(?:[A-Za-z]:[\\/]|[\\/]{1,2}|\.\.?(?:[\\/]))/u.test(e)||[e.indexOf("/"),e.indexOf("\\")].some(o=>o>=0&&o<r))?!1:n.includes("=")||Sn(e)}function us(e){let t=0;for(let n of e)if(n==="("&&(t+=1),n===")"&&(t-=1),t<0)return!1;return t===0}function ls(e){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)&&!It(e))return{path:e,scope:"project",note:void 0};let t=e.indexOf("](");if(e.startsWith("[")&&t>0&&e.endsWith(")")){let s=e.slice(t+2,-1).trim();if(s.length>0&&us(s))return{path:s,scope:"project",note:e.slice(1,t).trim()||void 0}}let n=e.indexOf(",");if(n<0)return;let r=e.slice(0,n).trim(),o=e.slice(n+1).trim();if(!(r.length===0||!/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(o)))return{path:o,scope:"project",note:r}}function Nt(e,t){return e?e.flatMap(n=>{let r=n.trim();if(t==="doc"){let s=ls(r);if(s!==void 0)return[s]}bn(r,"--add",`${t} path`,It(r));let o=It(r)?G(n,"--add"):{path:r};if(me(o,"--add",Ot),!o.path)throw new l(`--add requires path=<value> or a bare ${t} path`,u.USAGE);return[{path:o.path,scope:rr(o.scope),note:o.note?.trim()||void 0}]}):[]}function fs(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new l("--add-glob requires a glob pattern value",u.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(n)||n.startsWith("```")){let r=G(n,"--add-glob");me(r,"--add-glob",is);let o=r.pattern?.trim()||r.glob?.trim()||r.path?.trim();if(!o)throw new l("--add-glob key/value form requires pattern=<glob>",u.USAGE);return{pattern:o,scope:rr(r.scope),note:r.note?.trim()||void 0}}return{pattern:n,scope:"project"}}):[]}function ms(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new l("--remove requires a path value",u.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(n)||n.startsWith("```")){let r=G(n,"--remove"),o=Object.keys(r).filter(s=>ds.has(s.toLowerCase()));if(o.length>0)throw new l(`--remove identifies a linked artifact by path only and does not accept ${o.map(s=>`"${s}"`).join(", ")}. Pass just the path (path=<value>, path:<value>, or a bare path); record removal context with --message "<why removed>".`,u.USAGE);if(me(r,"--remove",as),!r.path)throw new l("--remove key/value form requires path=<value>",u.USAGE);return r.path}return n}):[]}function ps(e){return e?e.map(t=>{let n=G(t,"--migrate");me(n,"--migrate",cs);let r=n.from?.trim(),o=n.to?.trim();if(!r||!o)throw new l("--migrate requires from=<value> and to=<value>",u.USAGE);return{from:r,to:o}}):[]}function de(e,t){let n=e;for(let r of t)n.startsWith(r.from)&&(n=`${r.to}${n.slice(r.from.length)}`);return n}function hs(e,t,n=[]){if(e.length===0||t.length===0)return;let r=new Set(e.map(s=>q(de(s.path,n)))),o=[...new Set(t.map(s=>q(de(s,n))).filter(s=>r.has(s)))].sort((s,i)=>s.localeCompare(i));if(o.length!==0)throw new l(`Linked artifact mutation cannot add and remove the same normalized path in one transaction: ${o.join(", ")}. Split the replacement into separate commands so each history event has one unambiguous intent.`,u.USAGE,{code:"linked_artifact_mutation_conflict",reason:"same_path_added_and_removed",required:"Use distinct normalized paths for --add and --remove in one invocation.",why:"Conflicting batch intent cannot be applied deterministically without silently discarding metadata or a removal.",nextSteps:["Run the removal and addition as separate commands with a --message describing each intent."]})}function At(e){return e.split(C.sep).join("/")}function jt(e,t,n=process.cwd()){let r=e.trim();if(Ct(r))return r;if(C.isAbsolute(r)||/^[A-Za-z]:[\\/]/.test(r))return At(r.replaceAll("\\",C.sep));let o=C.relative(t,n);return o.startsWith(`..${C.sep}`)||o===".."||C.isAbsolute(o)?At(C.normalize(r)):At(C.relative(t,C.resolve(n,r)))}async function _s(e,t=process.cwd(),n=process.cwd()){let r=[];for(let o of e){if(C.resolve(n,o.pattern)===C.resolve(n))continue;let s=await tr(o.pattern,n),i=[...new Set(s.map(a=>jt(a,t,n)))].sort((a,c)=>a.localeCompare(c));for(let a of i)r.push({path:a,scope:o.scope,note:o.note})}return r}function gs(e,t,n){if(t===void 0)return e;if(!n)throw new l("--note requires --add or --add-glob in the same invocation (the note annotates the links being added)",u.USAGE);let r=t.trim();return r.length===0?e:e.map(o=>o.note===void 0?{...o,note:r}:o)}function $t(e){return`${e.path}::${e.scope}`}function xs(e){return[...e].sort((t,n)=>{let r=t.path.localeCompare(n.path);return r!==0?r:t.scope.localeCompare(n.scope)})}function ks(e){return[...new Map(e.map(t=>[$t(t),t])).values()].map(t=>({...t,note:t.note?.trim()||void 0}))}async function ws(e,t=process.cwd()){let n=[...new Set(e)].sort((a,c)=>a.localeCompare(c)),r=[],o=[],s=[],i=[];for(let a of n){if(Ct(a)){i.push(a.trim());continue}let c=C.isAbsolute(a)?a:C.resolve(t,a);try{(await ns.stat(c)).isFile()?r.push(a):s.push(a)}catch(d){if(typeof d=="object"&&d!==null&&"code"in d&&Ie(d)){o.push(a);continue}s.push(a)}}return{checked:n.length,existing_files:r,missing_paths:o,non_file_paths:s,remote_references:i}}function ys(e,t,n,r){let o=0;for(let i=0;i<e.length;i+=1){let a=de(e[i].path,r);a!==e[i].path&&(o+=1);let c=q(a);c!==e[i].path&&(e[i]={...e[i],path:c})}return{adds:t.map(i=>{let a=de(i.path,r);return a!==i.path&&(o+=1),{...i,path:q(a)}}),removes:n.map(i=>q(de(i,r))),count:o}}function q(e){return e.replaceAll("\\","/")}function Pt(e){return`${e.scope}\0${q(e.path)}`}function vs(e,t,n){let r=new Map(e.map(i=>[Pt(i),i.note])),o=new Map(t.map(i=>[Pt(i),i.note])),s=new Map;for(let i of n){let a=Pt(i);s.has(a)||s.set(a,{path:q(i.path),scope:i.scope,outcome:Ts(r.has(a),r.get(a),o.get(a))})}return[...s.values()]}function Ts(e,t,n){return e?n===t?"unchanged":t===void 0?"note_added":n?.startsWith(`${t}${Rt}`)?"note_appended":"note_replaced":"added"}function Es(e,t,n){let r=e.merged.findIndex(i=>i.path===t.path&&i.scope===t.scope),o=e.merged[r];if(o===void 0){e.merged.push(t),t.note!==void 0&&e.notedHere.add(t);return}let s=os(o.note,t.note,n);if(s.conflict)e.conflicts.push({path:t.path,scope:t.scope,existing_note:o.note,requested_note:t.note,source:e.notedHere.has(o)?"this_write":"stored"});else if(s.note!==o.note){let i={...o,note:s.note};e.merged[r]=i,e.notedHere.add(i)}}function Ss(e,t,n,r,o){let s=ks(e),i={merged:[...s],notedHere:new Set,conflicts:[]};for(let d of t)Es(i,d,o);let{merged:a}=i,c=vs(s,a,t);if(n.length>0)for(let d=a.length-1;d>=0;d-=1)n.includes(a[d].path)&&a.splice(d,1);return{entries:r?a:xs(a),outcomes:c,conflicts:i.conflicts}}async function or(e){let t=e.mutation?.entries??e.artifacts,n=e.options.validatePaths?e.artifacts:t,{counts:r,receipts:o}=Ue(e.mutation);return{id:e.id,artifacts:t,changed:e.changed,count:t.length,...r,migrations_applied:e.migrationsApplied&&e.migrationsApplied>0?e.migrationsApplied:void 0,validation:e.options.validatePaths||e.changed&&n.length>0?await ws(n.map(s=>s.path),e.workspaceRoot):void 0,...o}}function bs(e,t,n){let r=new Map;for(let s of t){let i=$t(s);r.set(i,(r.get(i)??0)+1)}let o=0;for(let s of e){let i=$t({...s,path:q(de(s.path,n))}),a=r.get(i)??0;a>0?r.set(i,a-1):o+=1}return o}function Cs(e,t){let n=/[\n\r]|^\s*[-*+`]/u.test(e)?[]:En(e),r=n.findIndex(f=>f.key?.toLowerCase()==="note");if(r<0)return;let o=n.slice(0,r).map(f=>f.raw.trim()),s=new Set(n.slice(0,r).map(f=>f.key?.toLowerCase())),i=[n[r].value],a;for(let f of n.slice(r+1)){let m=f.key?.toLowerCase();if((m==="path"||m==="scope")&&!s.has(m)){o.push(f.raw.trim()),s.add(m);continue}a??=f.key===void 0?void 0:{segment:f.text.trim(),key:f.key},i.push(f.text)}if(a===void 0)return;let c=i.join(",").trim(),d=[...o,`note=${JSON.stringify(c)}`].join(",");try{Nt([d],t)}catch{return}return{entry:d,note:c,...a}}function Ls(e,t){return e.findIndex(n=>{try{return Nt([n],t),!1}catch{return!0}})+1}function Ne(e,t,n){return(t??[]).flatMap(r=>[e,n!==void 0&&r.trim()==="-"?`${n}=-`:r])}function sr(e){let{options:t}=e,n=e.noteConflict??t.noteConflict;return[...oe(e.global),...e.guards.map(r=>`--expect-hash=${r}`),e.config.metadataKey,e.id,...Ne("--add",e.entries.map((r,o)=>o===e.position-1?e.rewritten:r),"path"),...Ne("--add-glob",e.resolved.addGlob,"pattern"),...Ne("--remove",e.resolved.remove,"path"),...Ne("--migrate",e.resolved.migrate),...t.note===void 0?[]:["--note",t.note],...n===void 0?[]:["--note-conflict",n],...e.config.supportsAppendStable&&t.appendStable===!0?["--append-stable"]:[],...t.validatePaths===!0?["--validate-paths"]:[],...t.fullHistory===!0?["--full-history"]:[],...t.author?["--author",t.author]:[],...t.message?["--message",t.message]:[],...t.force===!0?["--force"]:[]]}function As(e){return Ot.some(t=>t===e.toLowerCase())?`If "${e}" was meant as a key, give it once per entry.`:`If "${e}" was meant as a key, it is not one of: ${Ot.join(", ")}.`}function Ps(e){try{return Nt(e.entries,e.config.bareNoun)}catch(t){let n=e.entries,r=t,o=Ls(n,e.config.bareNoun),s=Cs(n[o-1],e.config.bareNoun);if(s===void 0)throw t;let i=ht(e.pmRoot),a=i===void 0?void 0:sr({...e,entries:n,position:o,rewritten:s.entry,guards:i});throw new l(`--add read the note segment "${s.segment}" as a new key "${s.key}", so the ${e.config.bareNoun} link was refused (${r.message})`,u.USAGE,{code:"linked_artifact_note_key_misread",flag:"--add",value:n[o-1],required:`Retry with the note quoted so its commas stay prose (${a===void 0?`as ${s.entry}; its revision guards cannot be replayed as typed, so no executable retry is offered`:"recovery.suggested_retry_args replays the whole invocation that way"}), or pass the prose through --note in a single-entry call. ${As(s.key)}`,why:"After a comma, an identifier followed by = or : opens a new key, so that a typo such as lable=main is refused instead of being stored as note text (GH-258).",...a===void 0?{}:{nextSteps:[E(a)]},details:{entry_index:o,misread_segment:s.segment,misread_key:s.key,note:s.note,rewritten_entry:s.entry,cause:r.context.code??"invalid_argument_value"},...a===void 0?{}:{recovery:{suggested_retry:E(a),suggested_retry_args:a}}})}}function Ue(e){return e===void 0?{counts:{},receipts:{}}:{counts:{total_count:e.total_count,returned_count:e.returned_count,has_more:e.has_more},receipts:{mutation_receipt:e.mutation_receipt,omission_receipt:e.omission_receipt}}}async function Rs(e){let{settings:t,config:n}=e,r=await je(e.pmRoot,e.id,t.id_prefix,t.item_format,e.typeToFolder);if(!r)throw new l(`Item ${e.id} not found`,u.NOT_FOUND);let s=(await $e(r,{schema:t.schema})).document.metadata[n.metadataKey]??[],i=e.writeRequested?xe({collectionKey:n.metadataKey,stored:s,written:[],removedCount:0,fullHistory:e.options.fullHistory===!0}):void 0;return or({id:r.id,artifacts:s,changed:!1,options:e.options,workspaceRoot:e.workspaceRoot,mutation:i})}async function Vc(e,t,n,r){let{metadataKey:o}=r,s=Oe(),i=B(process.cwd(),n.path),a=Pn(i),c=process.cwd();await ie(i);let d=await W(i),f=re(d,se()),m=await s.resolveList(t.add,"--add"),p=await s.resolveList(t.addGlob,"--add-glob"),g=await s.resolveList(t.remove,"--remove"),x=await s.resolveList(t.migrate,"--migrate"),h=Ps({id:e,pmRoot:i,entries:m,resolved:{addGlob:p,remove:g,migrate:x},options:t,global:n,config:r}).map(j=>({...j,path:jt(j.path,a,c)})),w=fs(p),L=await _s(w,a,c),R=h.length>0||w.length>0,b=gs([...h,...L],t.note,R),N=rs(t.noteConflict,R),k=ms(g).map(j=>jt(j,a,c)),v=ps(x);if(hs(b,k,v),!(b.length>0||k.length>0||v.length>0))return Rs({id:e,pmRoot:i,settings:d,typeToFolder:f.type_to_folder,options:t,workspaceRoot:a,config:r,writeRequested:w.length>0});let M=$(t.author,d.author_default),A=[],I=0,ct=[],Ce=await ae({pmRoot:i,settings:d,id:e,op:r.op,author:M,message:t.message,force:t.force,skipNoop:!0,mutate(j){let ut=j.metadata,Le=ut[o]??[],kn=[...Le],Ae=ys(kn,b,k,v),Pe=Ss(kn,Ae.adds,Ae.removes,r.supportsAppendStable&&t.appendStable===!0,N);if(Pe.conflicts.length>0){let yn=ht(i);throw ss({itemId:j.metadata.id,noun:r.bareNoun,conflicts:Pe.conflicts,retryArgs:Ro=>yn===void 0?void 0:sr({id:j.metadata.id,entries:m??[],position:0,rewritten:"",resolved:{addGlob:p,remove:g,migrate:x},options:t,global:n,config:r,guards:yn,noteConflict:Ro}),render:E})}let Re=Pe.entries;ct=Pe.outcomes,Re.length>0?ut[o]=Re:delete ut[o];let wn=!U(Le,Re);return A=Le,I=bs(Le,Re,v),{changedFields:wn?[o]:[],warnings:wn&&Ae.count>0?[`path_migrations_applied:${Ae.count}`]:[]}}}),dt=Ce.item[o]??[],xn=Ce.warnings.find(j=>j.startsWith("path_migrations_applied:")),Po=xn?Number(xn.slice(24)):0;return or({id:Ce.item.id,artifacts:dt,changed:Ce.changedFields.includes(o),migrationsApplied:Po,options:t,workspaceRoot:a,mutation:xe({collectionKey:o,stored:dt,written:Mt(A,dt),removedCount:I,fullHistory:t.fullHistory===!0,linkOutcomes:ct})})}function Xc(e,t){let n={};for(let[r,o]of Object.entries(e))n[r==="artifacts"?t:r]=o;return n}import{readFileSync as Os}from"node:fs";import Ge from"node:path";var Is=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),Ft=new Set(["--pm-path","--path","--author","--expect-hash"]),js={get:new Set(["--depth","--fields","--tree-depth","--tree_depth","--at","--format"]),history:new Set(["--limit","--field","--format"]),restore:new Set(["--message"]),update:new Set(["--title","-t","--description","-d","--body","-b","--status","-s","--close-reason","--close_reason","--priority","-p","--type","--tags","--add-tags","--add_tags","--remove-tags","--remove_tags","--deadline","--estimated-minutes","--estimate","--estimated_minutes","--acceptance-criteria","--ac","--acceptance_criteria","--definition-of-ready","--definition_of_ready","--order","--rank","--goal","--objective","--value","--impact","--outcome","--why-now","--why_now","--message","--assignee","--parent","--reviewer","--risk","--confidence","--sprint","--release","--blocked-by","--blocked_by","--blocked-reason","--blocked_reason","--unblock-note","--unblock_note","--reporter","--severity","--environment","--repro-steps","--repro_steps","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual","--affected-version","--affected_version","--fixed-version","--fixed_version","--component","--regression","--customer-impact","--customer_impact","--dep","--dep-remove","--dep_remove","--comment","--note","--learning","--file","--test","--doc","--reminder","--event","--type-option","--type_option","--field","--unset","--body-file"]),close:new Set(["--reason","-r","--close-reason","--duplicate-of","-d","--message","-m","--validate-close","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual"]),delete:new Set(["--message"]),append:new Set(["--body","--text","--message"]),claim:new Set(["--assignee","--message","--type","--tag","--priority","--assignee-filter","--parent","--sprint","--release","--max-attempts"]),release:new Set(["--assignee","--message"]),comments:new Set(["--add","--body","--comment","--file","--edit","--delete","--limit","--message"]),notes:new Set(["--add","--file","--edit","--delete","--limit","--message"]),learnings:new Set(["--add","--file","--edit","--delete","--limit","--message"]),files:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),docs:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),deps:new Set(["--format","--max-depth","--collapse","--node-limit","--edge-limit","--token-budget","--cursor","--direction","--kind"]),test:new Set(["--add","--add-json","--remove","--match","--only-index","--timeout","--env-set","--env-clear","--pm-context","--message"])},$s=new Set(["-p","--package"]),Ms=new Set(["-c","--call"]),Dt=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),Wt=new Set(["-C","--prefix","--userconfig","--cache"]),ir=new Set(["--cwd"]),ar=new Set(["--cwd"]),Ns=new Set(["exec","x"]),cr=new Set(["run","run-script"]),dr=new Set(["-C","--dir","--cwd","-w","--workspace","--filter"]);function Z(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function We(e,t=process.cwd()){let n=qe(e.split(" ").filter(i=>i.length>0));if(n.length===0)return null;let[r,...o]=n;if(Fe(r)||De(r,t))return o;if(r==="node"&&o[0]&&De(o[0],t))return o.slice(1);let s=r==="npx"||r==="bunx"?Q(o):r==="pnpm"?He(o):r==="npm"?Ke(o):null;return s&&(Fe(s.command)||ur(s.command))?s.args:null}var Us=(e,t="pm")=>{let n=t.trim().toLowerCase(),r=n.length;for(;r>0&&n[r-1]==="-";)r-=1;let o=n.slice(0,r);if(o.length===0)return[];let s=e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase(),i=new Set;for(let a of Z(s)){let c=We(a),d=c?qt(c):null,f=d&&Is.has(d.subcommand)?Fs(d.remaining,js[d.subcommand]):void 0,m=f?.trim().toLowerCase();m?.startsWith(`${o}-`)===!0&&m.length>o.length+1&&i.add(f)}return[...i].sort((a,c)=>a.localeCompare(c))};function qe(e){let t=0;for(e[t]==="env"&&(t+=1);t<e.length;){let n=e[t];if(/^(?:[a-z_][a-z0-9_]*|\$env:[a-z_][a-z0-9_]*)=.*/.test(n)){t+=1;continue}break}return e.slice(t)}function Gt(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(Ft.has(n)){t+=2;continue}t+=1;continue}return n}}function Fe(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function Gs(e){let t=e.trim();if(!t.startsWith("@")){let o=t.indexOf("@");return o===-1?t:t.slice(0,o)}let n=t.indexOf("/");if(n===-1)return t;let r=t.indexOf("@",n+1);return r===-1?t:t.slice(0,r)}function ur(e){let t=Gs(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function De(e,t=process.cwd()){let n=e.replaceAll("\\","/");if(n!=="dist/cli.js"&&n!=="./dist/cli.js"&&!n.endsWith("/dist/cli.js"))return!1;let r=Ge.resolve(t,e);try{return JSON.parse(Os(Ge.join(Ge.dirname(Ge.dirname(r)),"package.json"),"utf8")).name==="@unbrained/pm-cli"}catch{return!1}}function Q(e){let t=0;for(;t<e.length;){let r=e[t];if(r==="--"){t+=1;break}if(!r.startsWith("-"))break;let o=/^(?:-c|--call)=(.*)$/.exec(r);if(o){let s=o[1];return s?{command:s,args:e.slice(t+1)}:null}if(Ms.has(r)){t+=1;break}t+=$s.has(r)&&!r.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function H(e,t){let n=0;for(;n<e.length;){let r=e[n];if(r==="--"){n+=1;continue}if(r.startsWith("-")){if(r.includes("=")){n+=1;continue}if(t.has(r)){n+=2;continue}n+=1;continue}return{subcommand:r,args:e.slice(n+1)}}return null}function He(e){let t=H(e,Dt);return t?.subcommand!=="dlx"?null:Q(t.args)}function Ke(e){let t=H(e,Wt);return!t||!Ns.has(t.subcommand)?null:Q(t.args)}function qt(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(Ft.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function Fs(e,t=new Set){for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="--")return e[n+1];if(!r.startsWith("-"))return r;!r.includes("=")&&(Ft.has(r)||t.has(r))&&(n+=1)}}function Ut(e){return!e||!Fe(e.command)&&!ur(e.command)?!1:Gt(e.args)==="test-all"}var Ht=new Map([...["sh","bash","dash","zsh"].map(e=>[e,/^(?:-c|-[a-z]*c[a-z]*)$/u]),...["cmd","cmd.exe"].map(e=>[e,/^\/[ck]$/u]),...["powershell","powershell.exe","pwsh","pwsh.exe"].map(e=>[e,/^-(?:c|command)$/u])]),Ds=new Set(["npx","bunx"]);function Kt(e){let t=e.split(" ").filter(i=>i.length>0),n=qe(t);if(n.length===0)return!1;let[r,...o]=n,s=Ht.get(r);if(s){let i=o.findIndex(a=>s.test(a));return i>=0?Kt(o.slice(i+1).join(" ")):!1}return Fe(r)||De(r)?Gt(o)==="test-all":r==="node"&&o.length>0&&De(o[0])?Gt(o.slice(1))==="test-all":Ds.has(r)?Ut(Q(o)):r==="pnpm"?Ut(He(o)):r==="npm"?Ut(Ke(o)):!1}function Bt(e){let t=ue(e);return Z(t).some(n=>Kt(n))}function ke(e){if(Bt(e))throw new l('Linked test commands must not invoke "pm test-all"; this creates recursive orchestration.',u.USAGE)}function ue(e){return e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase()}import{execFile as Ws}from"node:child_process";import{readFile as qs}from"node:fs/promises";import fr from"node:path";import{promisify as Hs}from"node:util";var Ks=Hs(Ws),zt=1,Bs="linked-test-trust.json";function Jt(e){return fr.join(On(e),Bs)}function lr(){return{version:zt,acknowledged:{}}}async function Vt(e){try{let t=JSON.parse(await qs(Jt(e),"utf8"));return t.version!==zt||typeof t.acknowledged!="object"||t.acknowledged===null||Array.isArray(t.acknowledged)?lr():{version:zt,acknowledged:t.acknowledged}}catch{return lr()}}async function Xt(e=process.cwd()){let t=process.env.GITHUB_HEAD_REF?.trim()||process.env.GITHUB_REF_NAME?.trim();if(t&&t!=="merge")return t;try{let{stdout:n}=await Ks("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),r=n.trim();return r.length===0?void 0:r}catch{return}}function Yt(e=process.cwd()){return process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||e}function zs(e){return e===null||typeof e!="object"?!1:typeof e.author=="string"&&e.author.trim().length>0&&typeof e.created_at=="string"&&jn(e.created_at)&&(e.source_kind==="local_mutation"||e.source_kind==="merge_union")}function we(e,t){return{...e?{source_ref:e}:{},...t?{current_source_ref:t}:{}}}function Js(e,t,n,r){return e?.map(o=>o.command&&!o.provenance?{...o,provenance:{author:t,created_at:n,source_kind:"local_mutation",...r?{source_ref:r}:{}}}:o)}async function mr(e,t,n){if(!e||e.length===0)return e;for(let o of e)z(o);let r=Yt();return Js(e,t,n,await Xt(r))}function pr(e){return Tn(vn({command:e.command??null,path:e.path??null,scope:e.scope,pm_context_mode:e.pm_context_mode??null,workspace_context_mode:e.workspace_context_mode??null,env_set:e.env_set??null,env_clear:e.env_clear??null,shared_host_safe:e.shared_host_safe??null,provenance:e.provenance??null,provenance_invalid:e.provenance_invalid??null}))}async function Zt(e,t,n){let r=await Vt(e);return hr(t,n,r)}function hr(e,t,n){let r=pr(e),o=e.provenance?.source_ref;if(e.provenance===void 0&&e.provenance_invalid!==!0)return{fingerprint:r,trusted:!0,reason:"legacy"};let s=Object.hasOwn(n.acknowledged,r);return e.provenance_invalid===!0||!zs(e.provenance)?s?{fingerprint:r,trusted:!0,reason:"acknowledged",...we(void 0,t)}:{fingerprint:r,trusted:!1,reason:"invalid_provenance",...we(void 0,t)}:e.provenance.source_kind==="local_mutation"&&o===void 0?{fingerprint:r,trusted:!0,reason:"local_mutation",...we(void 0,t)}:e.provenance.source_kind==="local_mutation"&&o!==void 0&&o===t?{fingerprint:r,trusted:!0,reason:"local_source_ref",source_ref:o,current_source_ref:t}:s?{fingerprint:r,trusted:!0,reason:"acknowledged",...we(o,t)}:{fingerprint:r,trusted:!1,reason:"foreign_source_ref",...we(o,t)}}async function fd(e,t,n){let r=await Vt(e);return t.map(o=>hr(o,n,r))}async function _r(e,t,n){let r=await Vt(e),o=t.filter(s=>typeof s.command=="string"&&s.command.length>0).map(pr);for(let s of o)r.acknowledged[s]={acknowledged_at:n};return await Cn(fr.dirname(Jt(e))),await Ln(Jt(e),`${JSON.stringify(r,null,2)}
|
|
3
3
|
`),{acknowledged:o.length,fingerprints:o}}var Vs=["setup","test"];function P(e){return e.phase==="setup"}function Be(e,t){if(e===void 0)return;let n=typeof e=="string"?e.trim().toLowerCase():e;if(n==="setup")return"setup";if(!(n==="test"||n===""))throw new l(`${t} field "phase" must be one of: ${Vs.join(", ")}`,u.USAGE,{code:"invalid_argument_value",required:"Use phase=setup for a step that runs before the linked commands, or omit phase for a regular linked test.",examples:['pm test <id> --add "command=npm run build,phase=setup"']})}function gr(e){return[...e.filter(P),...e.filter(t=>!P(t))]}function xr(e,t){if(!e.selected.some(s=>!P(s)))return e;let n=t.flatMap((s,i)=>P(s)?[i+1]:[]);if(n.length===0)return e;let r=e.selected_indexes.filter(s=>!P(t[s-1])),o=n.filter(s=>!e.selected_indexes.includes(s));return{...e,selected:[...n,...r].map(s=>t[s-1]),selected_indexes:[...n,...r],selected_count:n.length+r.length,skipped_count:t.length-n.length-r.length,...o.length>0?{setup_indexes:o}:{}}}function kr(e,t,n){if(!P(e))return;let r=[...n].filter(o=>o!==t).sort();if(r.length!==0)return{command:e.command,path:e.path,status:"refused",exit_code:null,failure_category:"config_refusal",error:`Setup entry runs in the ${t} workspace, but linked commands it prepares run in ${r.join(", ")}, so its output would not reach them. Set workspace_context_mode on the setup entry and the linked commands to one mode.`}}function wr(){let e;return{blocked(t){if(e!==void 0)return{command:t.command,path:t.path,status:"skipped",...P(t)?{phase:"setup"}:{},error:`Skipped because setup entry "${e.label}" did not pass (${e.outcome}); no later linked command ran.`}},options(t,n){return!P(t)||n===void 0?n:{...n,failOnEmptyTestRun:!1,requireAssertionsForPm:!1}},record(t,n){if(!P(t))return n;if(n.status==="passed")return{...n,phase:"setup"};let o=n.status==="refused"||n.failure_category==="trust_refusal"||n.failure_category==="setup_failed"?{...n,phase:"setup"}:{...n,status:"failed",phase:"setup",failure_category:"setup_failed",...n.failure_category===void 0?{}:{setup_failure_cause:n.failure_category}};return e={label:t.command??t.path??"<no command>",outcome:o.failure_category??o.status},o}}}function Xs(){return{infra_collision:0,trust_refusal:0,config_refusal:0,assertion_failure:0,empty_run:0,timeout:0,max_buffer:0,spawn_error:0,signal:0,setup_failed:0}}function Qt(e){let t=Xs();for(let n of e)n.status!=="failed"&&n.status!=="refused"||!n.failure_category||(t[n.failure_category]+=1);return t}var ne=new Set(["PM_PATH","PM_GLOBAL_PATH","PM_SOURCE_PM_PATH","PM_SOURCE_WORKSPACE_ROOT","PM_BUILD_CONSUMER_LEASE","PM_BUILD_CONSUMER_LEASE_ROOT",ge,Fn,"FORCE_COLOR"]),Ve=/^[A-Za-z_][A-Za-z0-9_]*$/,te=["schema","tracker","auto","none"],yr=["source","isolated","snapshot"];function en(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new l(`${t} env_set must include at least one KEY=VALUE assignment`,u.USAGE);let r=Object.create(null);for(let o of n){let s=o.indexOf("=");if(s<=0)throw new l(`${t} env_set entries must use KEY=VALUE and be separated by semicolons. Example: env_set=PORT=0;PLAYWRIGHT_BASE_URL=http://127.0.0.1:4173`,u.USAGE);let i=o.slice(0,s).trim(),a=o.slice(s+1);if(!Ve.test(i))throw new l(`${t} env_set key "${i}" is invalid`,u.USAGE);if(ne.has(i.toUpperCase()))throw new l(`${t} env_set key "${i}" is reserved for sandbox safety`,u.USAGE);r[i]=a}return Object.keys(r).length>0?r:void 0}function tn(e,t){if(!e)return;let n=kt(e,{separators:/[;,\n]/});if(n.length===0)throw new l(`${t} env_clear must include at least one environment variable name`,u.USAGE);for(let r of n){if(!Ve.test(r))throw new l(`${t} env_clear key "${r}" is invalid`,u.USAGE);if(ne.has(r.toUpperCase()))throw new l(`${t} env_clear key "${r}" is reserved for sandbox safety`,u.USAGE)}return n}function Tr(e,t,n){if(!e)return;let r=e.trim().toLowerCase();if(r==="true"||r==="1"||r==="yes")return!0;if(r==="false"||r==="0"||r==="no")return!1;throw new l(`${t} ${n} must be one of true|false|1|0|yes|no`,u.USAGE)}function Er(e,t){if(!e)return;let n=e.trim().toLowerCase();if(te.includes(n))return n;throw new l(`${t} pm_context_mode must be one of: ${te.join(", ")}`,u.USAGE)}function ye(e,t){if(!e)return;let n=e.trim().toLowerCase();if(yr.includes(n))return n;throw new l(`${t} workspace_context_mode must be one of: ${yr.join(", ")}`,u.USAGE)}function Xe(e){if(!e)return;let t=kt(e,{separators:/[;\n]/});return t.length>0?t:void 0}function nn(e,t,n){let r=Xe(e);if(!(!r||r.length===0)){for(let o of r)try{new RegExp(o,"m")}catch(s){throw new l(`${t} ${n} includes invalid regex "${o}": ${s instanceof Error?s.message:String(s)}`,u.USAGE)}return r}}function Sr(e,t){if(!e)return;let n=pe(e,"assert_stdout_min_lines");if(!Number.isInteger(n)||n<0)throw new l(`${t} assert_stdout_min_lines must be an integer >= 0`,u.USAGE);return n}function br(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new l(`${t} assert_json_field_equals must include at least one path=value assignment`,u.USAGE);let r=Object.create(null);for(let o of n){let s=o.indexOf("=");if(s<=0)throw new l(`${t} assert_json_field_equals entries must use path=value and be separated by semicolons`,u.USAGE);let i=o.slice(0,s).trim(),a=o.slice(s+1).trim();if(i.length===0||a.length===0)throw new l(`${t} assert_json_field_equals entries must include non-empty path and value`,u.USAGE);r[i]=a}return Object.keys(r).length>0?r:void 0}function Cr(e,t){if(!e)return;let n=e.split(/[;\n]/).map(o=>o.trim()).filter(o=>o.length>0);if(n.length===0)throw new l(`${t} assert_json_field_gte must include at least one path=value assignment`,u.USAGE);let r=Object.create(null);for(let o of n){let s=o.indexOf("=");if(s<=0)throw new l(`${t} assert_json_field_gte entries must use path=value and be separated by semicolons`,u.USAGE);let i=o.slice(0,s).trim(),a=o.slice(s+1).trim();if(i.length===0||a.length===0)throw new l(`${t} assert_json_field_gte entries must include non-empty path and value`,u.USAGE);let c=Number(a);if(!Number.isFinite(c))throw new l(`${t} assert_json_field_gte value for "${i}" must be numeric`,u.USAGE);r[i]=c}return Object.keys(r).length>0?r:void 0}var Ys=new Set(J);function Ye(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Zs(e,t){let n={},r=[];for(let[o,s]of Object.entries(e)){let i=o.toLowerCase();if(!Ys.has(i)){r.push(o);continue}if(Object.hasOwn(n,i))throw t(`provides key "${o}" more than once after case normalization`);n[i]=s}if(r.length>0)throw t(`does not recognize key${r.length>1?"s":""} ${r.map(o=>`"${o}"`).join(", ")}. Allowed keys: ${J.join(", ")}.`);return n}function ee(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r!==void 0){if(typeof r!="string")throw n(`field "${t}" must be a JSON string`);return r}}function ze(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r===void 0)return;let o=typeof r=="string"?[r]:r;if(!Array.isArray(o)||o.some(i=>typeof i!="string"))throw n(`field "${t}" must be a string or an array of strings`);let s=o.filter(i=>i.length>0);return s.length>0?s:void 0}function vr(e,t,n){let r=ze(e,t,n);if(r){for(let o of r)try{new RegExp(o,"m")}catch(s){throw n(`field "${t}" includes invalid regex "${o}": ${s instanceof Error?s.message:String(s)}`)}return r}}function Je(e,t,n){let r=typeof e=="number"?e:typeof e=="string"&&e.trim().length>0?Number(e.trim()):Number.NaN;if(typeof e=="boolean"||!Number.isFinite(r))throw n(`field "${t}" must be a finite number (or numeric string)`);return r}function Qs(e,t){let n=e.timeout_seconds,r=e.timeout;if(n===void 0&&r===void 0)return;let o=n===void 0?void 0:Je(n,"timeout_seconds",t),s=r===void 0?void 0:Je(r,"timeout",t);if(o!==void 0&&s!==void 0&&o!==s)throw t("timeout and timeout_seconds must match when both are provided");let i=o??s;if(!Number.isInteger(i)||i<=0)throw t("timeout_seconds must be a positive integer");return i}function ei(e,t){let n=ee(e,"scope",t);if(n===void 0)return"project";if(!F.includes(n))throw t(`field "scope" must be one of: ${F.join(", ")}`);return n}function ti(e,t){if(!Object.hasOwn(e,"env_set"))return;let n=e.env_set;if(n===void 0)return;if(!Ye(n))throw t('field "env_set" must be a JSON object mapping environment names to string values');let r=Object.create(null);for(let[o,s]of Object.entries(n)){if(typeof s!="string")throw t(`field "env_set" value for "${o}" must be a string`);if(!Ve.test(o))throw t(`field "env_set" key "${o}" is invalid`);if(ne.has(o.toUpperCase()))throw t(`field "env_set" key "${o}" is reserved for sandbox safety`);r[o]=s}return Object.keys(r).length>0?r:void 0}function ni(e,t){let n=ze(e,"env_clear",t);if(n){for(let r of n){if(!Ve.test(r))throw t(`field "env_clear" key "${r}" is invalid`);if(ne.has(r.toUpperCase()))throw t(`field "env_clear" key "${r}" is reserved for sandbox safety`)}return n}}function ri(e,t,n){if(!Object.hasOwn(e,t))return;let r=e[t];if(r!==void 0){if(typeof r!="boolean")throw n(`field "${t}" must be a JSON boolean (true or false)`);return r}}function oi(e,t){if(!Object.hasOwn(e,"assert_stdout_min_lines"))return;let n=e.assert_stdout_min_lines;if(n===void 0)return;let r=Je(n,"assert_stdout_min_lines",t);if(!Number.isInteger(r)||r<0)throw t('field "assert_stdout_min_lines" must be an integer >= 0');return r}function si(e,t){if(!Object.hasOwn(e,"assert_json_field_equals"))return;let n=e.assert_json_field_equals;if(n===void 0)return;if(!Ye(n))throw t('field "assert_json_field_equals" must be a JSON object mapping field paths to expected values');let r=Object.create(null);for(let[o,s]of Object.entries(n)){if(o.trim().length===0)throw t('field "assert_json_field_equals" keys must be non-empty field paths');if(typeof s!="string"&&typeof s!="number"&&typeof s!="boolean")throw t(`field "assert_json_field_equals" value for "${o}" must be a string, number, or boolean`);r[o]=String(s)}return Object.keys(r).length>0?r:void 0}function ii(e,t){if(!Object.hasOwn(e,"assert_json_field_gte"))return;let n=e.assert_json_field_gte;if(n===void 0)return;if(!Ye(n))throw t('field "assert_json_field_gte" must be a JSON object mapping field paths to numeric minimums');let r=Object.create(null);for(let[o,s]of Object.entries(n)){if(o.trim().length===0)throw t('field "assert_json_field_gte" keys must be non-empty field paths');r[o]=Je(s,`assert_json_field_gte.${o}`,t)}return Object.keys(r).length>0?r:void 0}function ai(e,t,n){let r=p=>new l(`${n} ${t} ${p}`,u.USAGE);if(!Ye(e))throw r(`must be a JSON object with linked-test fields. Allowed keys: ${J.join(", ")}.`);let o=Zs(e,r),s=ee(o,"command",r),i=ee(o,"cmd",r);if(s!==void 0&&i!==void 0&&s!==i)throw r("command and cmd must match when both are provided");let a=s??i;if(a===void 0||a.trim().length===0)throw r('requires a non-empty "command" string');let c=ee(o,"path",r),d=ee(o,"pm_context_mode",r);if(d!==void 0&&!te.includes(d))throw r(`field "pm_context_mode" must be one of: ${te.join(", ")}`);let f=ye(ee(o,"workspace_context_mode",r),`${n} ${t}`),m=ee(o,"note",r);return{command:a,path:c!==void 0&&c.length>0?c:void 0,scope:ei(o,r),timeout_seconds:Qs(o,r),pm_context_mode:d,workspace_context_mode:f,env_set:ti(o,r),env_clear:ni(o,r),shared_host_safe:ri(o,"shared_host_safe",r),assert_stdout_contains:ze(o,"assert_stdout_contains",r),assert_stdout_regex:vr(o,"assert_stdout_regex",r),assert_stderr_contains:ze(o,"assert_stderr_contains",r),assert_stderr_regex:vr(o,"assert_stderr_regex",r),assert_stdout_min_lines:oi(o,r),assert_json_field_equals:si(o,r),assert_json_field_gte:ii(o,r),note:m!==void 0&&m.trim().length>0?m.trim():void 0,phase:Be(o.phase,`${n} ${t}`)}}function ve(e,t){let n=e.trim();if(n.length===0)throw new l(`${t} requires a JSON object or array of objects describing linked-test entries`,u.USAGE);let r;try{r=JSON.parse(n)}catch(s){throw new l(`${t} value is not valid JSON: ${s instanceof Error?s.message:String(s)}. Provide a JSON object or array of objects, e.g. '{"command":"node scripts/check.js --flag value, with commas","timeout_seconds":120}'.`,u.USAGE)}let o=Array.isArray(r)?r:[r];if(o.length===0)throw new l(`${t} array must include at least one linked-test entry object`,u.USAGE);return o.map((s,i)=>ai(s,o.length>1?`entry ${i+1}`:"entry",t))}var ci=32;function di(e){let t=[];for(let n of e??[]){let r=[];for(let o of n.split(",")){let s=o.slice(0,o.indexOf("=")).trim();r.length>0&&s!=="unit"&&s!=="threshold"&&(t.push(r.join(",")),r=[]),r.push(o)}t.push(r.join(","))}return t}function rn(e,t){let n=di(e).map(o=>{let[s,...i]=o.split(","),a=s.indexOf("="),c=s.slice(0,a).trim(),d=s.slice(a+1).trim(),f=Number(d);if(a<=0||c.length===0||d.length===0||!Number.isFinite(f))throw new l(`Invalid --measure "${o}"; expected name=value[,unit=...][,threshold=...]`,u.USAGE);let m,p;for(let g of i){let x=g.indexOf("="),h=g.slice(0,x).trim(),w=g.slice(x+1).trim();if(h==="unit"&&w.length>0)m=w;else if(h==="threshold"&&w.length>0&&Number.isFinite(Number(w)))p=Number(w);else throw new l(`Invalid --measure attribute "${g}"`,u.USAGE)}return{name:c,value:f,unit:m,threshold:p,recorded_at:t}});return[...new Map(n.map(o=>[o.name,o])).values()].sort((o,s)=>o.name.localeCompare(s.name)).slice(0,ci)}function Lr(e,t,n){return e.flatMap(r=>(r.measurements??[]).filter(o=>o.name===t&&o.value<n).map(o=>({...o,run_id:r.run_id})))}function Ar(e,t){let n=e.flatMap(s=>s.measurements??[]).filter(s=>s.name===t).sort((s,i)=>i.recorded_at.localeCompare(s.recorded_at)),r=n[0],o=n[1];return{name:t,latest:r?.value??null,previous:o?.value??null,delta:r!==void 0&&o!==void 0?r.value-o.value:null,unit:r?.unit}}var Pr=100;function le(e,t="--only-index"){let n=typeof e=="number"?e:Number(String(e).trim());if(!Number.isInteger(n)||n<1)throw new l(`${t} requires a 1-based integer index into the linked-test list (got "${e}"). Use pm test <id> --list to inspect positions.`,u.USAGE);return n}function ui(e){let n=(e.command??e.path??"<no command>").replaceAll(/\s+/g," ").trim()||"<no command>";return n.length<=Pr?n:`${n.slice(0,Pr-3)}...`}function Rr(e){return e.map((t,n)=>`${n+1}. ${ui(t)}`).join("; ")}function li(e){let t=[];return e.match!==void 0&&t.push("match"),e.onlyIndex!==void 0&&t.push("only-index"),e.onlyLast===!0&&t.push("only-last"),t}function fi(e,t){let n=e.command?.toLowerCase()??"",r=e.path?.toLowerCase()??"";return n.includes(t)||r.includes(t)}function Or(e,t){let n=li(t);if(n.length===0)return{selector:null,requested:null,selected:e,selected_indexes:e.map((o,s)=>s+1),selected_count:e.length,skipped_count:0};if(n.length>1)throw new l(`Combine at most one linked-test selector per run: ${n.map(o=>`--${o}`).join(" and ")} were provided. Pick one of --match, --only-index, --only-last.`,u.USAGE);let r=n[0];if(e.length===0)throw new l(`--${r} matched no linked tests because this item has none. Add one first with --add, --command, or --add-json.`,u.USAGE);if(r==="match"){let o=t.match.trim().toLowerCase();if(o.length===0)throw new l("--match requires a non-empty substring to match against linked-test command/path values",u.USAGE);let s=[],i=[];for(let a=0;a<e.length;a+=1)fi(e[a],o)&&(i.push(e[a]),s.push(a+1));if(i.length===0)throw new l(`--match "${t.match}" matched none of the ${e.length} linked test(s). Available entries: ${Rr(e)}`,u.USAGE);return{selector:"match",requested:t.match,selected:i,selected_indexes:s,selected_count:i.length,skipped_count:e.length-i.length}}if(r==="only-index"){let o=le(t.onlyIndex);if(o>e.length)throw new l(`--only-index ${o} is out of range: this item has ${e.length} linked test(s). Available entries: ${Rr(e)}`,u.USAGE);return{selector:"only-index",requested:String(o),selected:[e[o-1]],selected_indexes:[o],selected_count:1,skipped_count:e.length-1}}return{selector:"only-last",requested:"last",selected:[e[e.length-1]],selected_indexes:[e.length],selected_count:1,skipped_count:e.length-1}}var on=["command","cmd"],Te=Object.freeze(J.filter(e=>!["command","cmd","timeout"].includes(e)));function Ir(e){if(e.update===void 0&&e.updateIndex===void 0&&e.setJson===void 0)return;if(e.update===void 0==(e.updateIndex===void 0)||e.setJson===void 0)throw new l("Use exactly one --update or --update-index with --set-json",u.USAGE);let t;try{t=JSON.parse(e.setJson)}catch{throw new l("--set-json must contain a JSON object with explicit linked-test metadata fields",u.USAGE)}if(e.updateIndex!==void 0)return{selector:{index:le(e.updateIndex,"--update-index")},patch:t};let n=e.update,r=/^(command|path)=/u.exec(n);return{selector:r?.[1]==="path"?{path:n.slice(r[0].length)}:{command:r?n.slice(r[0].length):n},patch:t}}function jr(e){if([e.list,e.run,e.progress,e.timeout!==void 0,e.acknowledgeLinkedTests,e.metricBelow!==void 0,e.metricDiff!==void 0,(e.add?.length??0)>0,(e.addJson?.length??0)>0,(e.remove?.length??0)>0,(e.removeIndex?.length??0)>0].some(Boolean))throw new l("Edit linked-test metadata separately from listing, additions, removals, execution options, metric filters and trust acknowledgement",u.USAGE)}function mi(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new l("Select one linked test by index, command, or path",u.USAGE);let n=Object.keys(t);if(n.length!==1||!["index","command","path"].includes(n[0]))throw new l("Select one linked test by index, command, or path",u.USAGE);if("index"in t){let r=le(t.index,"--update-index");if(r<=e.length)return r-1}else{let r="command"in t?"command":"path",o="command"in t?t.command:t.path;if(typeof o!="string"||o.trim().length===0)throw new l("Linked-test selector must be a non-empty command or path",u.USAGE);let s=e.flatMap((i,a)=>i[r]===o?[a]:[]);if(s.length===1)return s[0];if(s.length>1)throw new l(`Linked-test selector is ambiguous; matching indexes: ${s.map(i=>i+1).join(", ")}`,u.USAGE,{code:"linked_test_update_ambiguous",required:"List linked tests and select one current --update-index."})}throw new l("No linked test matched the update selector",u.NOT_FOUND,{code:"linked_test_update_no_match",required:"List linked tests and select a current command, path, or --update-index."})}function $r(e,t){let n=Object.keys(e),r=n.filter(o=>!Te.includes(o));if(n.length===0&&!t||r.length>0)throw new l("Patch explicit linked-test metadata fields; command, aliases and provenance cannot be edited",u.USAGE,{code:"linked_test_patch_fields_unsupported",changed:!1,...r.length>0?{field:r[0]}:{},required:`Patch at least one editable field: ${Te.join(", ")}.`,recovery:{allowed_values:[...Te]},...r.length>0?{nextSteps:[`Remove unsupported field(s) from --set-json: ${r.join(", ")}.`]}:{}});if(e.scope===null)throw new l("scope is required and cannot be cleared",u.USAGE)}function pi(e,t,n){let r={};for(let o of Te){let s=t[o]!==void 0?t[o]:e[o];s!=null&&(r[o]=s)}return{command:n,...r}}function Ze(e){return{field:e,changed:!1,required:"Replace the entry instead: remove the selected linked test and add the new command in one pm test invocation, which records fresh provenance."}}function hi(e,t,n){let r=on.filter(s=>Object.hasOwn(e,s)).map(s=>e[s]),o=typeof e[t]=="string"?e[t].trim():"";if(r.length>1&&r.some(s=>typeof s!="string"||s.trim()!==o))throw new l("--set-json sets command and cmd to different values; send one command",u.USAGE,{code:"linked_test_command_immutable",...Ze(t),nextSteps:["Send the replacement command once, as command."]});if(o.length===0||o===n.command)throw new l(o.length===0?`--set-json cannot set ${t}: a linked test's command is its immutable identity`:`--set-json ${t} repeats the selected entry's command; omit it to edit only metadata`,u.USAGE,{code:"linked_test_command_immutable",...Ze(t),nextSteps:[`Patch only editable fields: ${Te.join(", ")}.`]});return ke(o),o}function _i(e){let{id:t,tests:n,index:r,identityKey:o,otherFields:s,requested:i,global:a}=e;$r(s,!0);let c=pi(n[r],s,i),d=ve(JSON.stringify(c),"--add-json")[0];z(d);let f=n.findIndex((m,p)=>p!==r&&_e(m,d));if(f>=0)throw new l(`--set-json cannot change ${o}: linked test ${f+1} already has the requested identity, so a replacement would merge into it`,u.USAGE,{code:"linked_test_command_immutable",...Ze(o),nextSteps:[`Edit linked test ${f+1} instead: ${E([...oe(a),"test",t,"--update-index",String(f+1),"--set-json","<editable fields>"])}`,`Or drop the selected entry: ${E([...oe(a),"test",t,"--remove-index",String(r+1)])}`]});return c}function gi(e){return[...e.author!==void 0?["--author",e.author]:[],...e.message!==void 0?["--message",e.message]:[],...e.force===!0?["--force"]:[]]}function xi(e){let{id:t,tests:n,index:r,patch:o,global:s,controls:i}=e;if(typeof o!="object"||o===null||Array.isArray(o))return;let a=o,c=on.find(h=>Object.hasOwn(a,h));if(c===void 0)return;let d=n[r],f=hi(a,c,d),m=Object.fromEntries(Object.entries(a).filter(([h])=>!on.includes(h))),p=_i({id:t,tests:n,index:r,identityKey:c,otherFields:m,requested:f,global:s}),g=d.command!==void 0&&n.filter(h=>h.command===d.command).length===1?["--remove",`command=${d.command}`]:["--remove-index",String(r+1)],x=[...oe(s),"test",t,...g,"--add-json",JSON.stringify(p),...gi(i)];throw new l(`--set-json cannot change ${c}: a linked test's command is its immutable identity; replace the entry instead`,u.USAGE,{code:"linked_test_command_immutable",...Ze(c),recovery:{suggested_retry:E(x),suggested_retry_args:x},nextSteps:["Run the suggested retry: it removes the selected entry and adds the new command in one history-recorded write. It selects the entry by its current command or list position, so list the linked tests again first if another writer may have changed them.",`SDK: runTest(${JSON.stringify(t)}, { ${g[0]==="--remove"?"remove":"removeIndex"}: [...], addJson: [...] }, { path: <the same tracker root> }) with the same values.`]})}function ki(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new l("Linked-test metadata patch must be a JSON object",u.USAGE);let n=Object.keys(t);$r(t,!1);let r=Object.fromEntries(Object.entries(e).filter(([a])=>J.includes(a))),o=Mn(ve(JSON.stringify({...r,command:e.command??"legacy-path-only",...Object.fromEntries(Object.entries(t).map(([a,c])=>[a,c===null?void 0:c]))}),"--set-json")[0]);z(o);let s=n.filter(a=>!U(e[a],o[a])),i={...e};for(let a of s){let c=o[a];Object.assign(i,{[a]:c}),c===void 0&&delete i[a]}if(!i.command?.trim()&&!i.path?.trim())throw new l("Linked-test entry must retain a command or path",u.USAGE);return{test:i,fields:s}}async function Mr(e,t,n={}){let r=B(process.cwd(),n.path);await ie(r);let o=await W(r),s=$(t.author,o.author_default),i=re(o,se()),a=0,c=[],d=await Nn({pmRoot:r,settings:o,id:e,author:s,op:"tests_update",message:t.message,force:t.force,skipNoop:!0,typeToFolder:i.type_to_folder,resolveHistoryContext:()=>({linked_test_update:{index:a,fields:c}}),mutate(m){let p=m.metadata.tests??[],g=mi(p,t.selector);xi({id:m.metadata.id,tests:p,index:g,patch:t.patch,global:n,controls:t});let x=ki(p[g],t.patch);return a=g+1,c=x.fields,x.fields.length===0?{changedFields:[]}:(m.metadata.tests=p.map((h,w)=>w===g?{...x.test,updated_by:s,updated_at:V()}:h),{changedFields:["tests"]})}}),f=d.item.tests;return{ok:!0,id:d.item.id,tests:f,count:f.length,changed:d.changedFields.length>0,updated_index:a,updated_fields:c}}var wi=[{code:"no_projects_matched_filters",regex:/\bNo projects matched the filters\b/i},{code:"no_test_files_found",regex:/\bNo test files found\b/i},{code:"no_tests_found",regex:/\bNo tests found\b/i},{code:"no_matching_tests",regex:/\bNo matching tests?\b/i},{code:"collected_zero_items",regex:/\bcollected 0 items?\b/i},{code:"reported_zero_tests",regex:/^\s*Ran 0 tests? across \d+ files?\./imu},{code:"reported_zero_passes",regex:/(?:^\s*(?:#|ℹ)?\s*tests\s+0\s*$[\s\S]*^\s*(?:#|ℹ)?\s*pass\s+0\s*$|^\s*(?:#|ℹ)?\s*pass\s+0\s*$[\s\S]*^\s*(?:#|ℹ)?\s*tests\s+0\s*$)/imu},{code:"reported_zero_tests",regex:/^\s*(?:#|ℹ)?\s*tests\s+0\s*$/imu}],yi=[{receiptCode:"reported_tests",regex:/^\s*(?:#|ℹ)?\s*tests\s+[1-9]\d*\s*$/imu},{receiptCode:"reported_passes",regex:/^\s*(?:#|ℹ)?\s*pass\s+[1-9]\d*\s*$/imu},{receiptCode:"tests_passed",regex:/\bTests?\s+[1-9]\d*\s+passed\b/iu},{receiptCode:"passed_count",regex:/\b[1-9]\d*\s+passed\b/iu},{receiptCode:"tests_summary",regex:/\bTests:\s+(?:.*\b)?[1-9]\d*\s+passed\b/iu},{receiptCode:"bun_pass_count",regex:/^\s*[1-9]\d* pass\s*$/imu},{receiptCode:"bun_executed_tests",regex:/^\s*Ran [1-9]\d* tests? across \d+ files?\./imu}];function Qe(e,t){let n=`${e}
|
|
4
4
|
${t}`;for(let r of wi)if(r.regex.test(n))return{code:r.code};return null}function Nr(e,t){for(let[n,r]of[["stdout",e],["stderr",t]]){let o=yi.find(s=>s.regex.test(r));if(o)return{code:o.receiptCode,stream:n}}}function Ur(e,t){return{trackerPath:e.path?.trim()||(process.env.PM_PATH?.trim()?t:void 0),noExtensions:e.noExtensions}}function Gr(e,t={}){let n=t.trackerPath?.trim();return E(["test",e,"--list",...t.noExtensions===!0?["--no-extensions"]:[],...n?["--pm-path",n]:[]],t.platform)}function Fr(e,t,n,r,o){if((t.measure?.length??0)===0||o.some(i=>i.phase!=="setup"&&typeof i.stdout=="string"&&i.failure_category!=="spawn_error"&&i.failure_category!=="empty_run"&&Qe(i.stdout,i.stderr??"")===null))return;let s=["--pm-path",r,...n.noExtensions?["--no-extensions"]:[],...n.author?["--author",n.author]:[],"test",e,"--list","--json"];throw new l("--measure requires an executed linked test",u.USAGE,{code:"test_measure_requires_execution",required:"Execute at least one linked command before recording measurement evidence.",why:"Empty, skipped and pre-execution refused runs cannot support measured evidence.",nextSteps:["Inspect the linked commands, adjust empty selections or missing commands, and resolve any trust refusal before retrying the measurement."],recovery:{suggested_retry:E(s),suggested_retry_args:s}})}function sn(e,t,n,r,o=!1){if((t.measure?.length??0)===0||t.run===!0)return;let s=["--pm-path",r,...n.noExtensions?["--no-extensions"]:[],...n.author?["--author",n.author]:[]],i=[...s,...Gn(e,t),...t.list?["--list"]:[],...o?["--background"]:[]],a=t.acknowledgeLinkedTests?[...s,"test",e,"--help"]:i,c=[...s,"test",e,"--acknowledge-linked-tests",...t.author?["--author",t.author]:[]];throw new l("--measure requires --run",u.USAGE,{code:"test_measure_requires_run",flag:"--measure",required:"Run the linked tests with --run to record measurement evidence.",why:"Measurements describe an executed linked-test run; recording them without execution would fabricate evidence.",...t.acknowledgeLinkedTests?{nextSteps:[`Review the linked commands and apply any requested link updates separately before acknowledging trust: ${E([...s,"test",e,"--list"])}`,`After review, acknowledge trust as a separate non-executing operation: ${E(c)}`,`Then run the measurement without --acknowledge-linked-tests: ${E(i)}`]}:{},recovery:{missing:["--run"],suggested_retry:E(a),suggested_retry_args:a}})}function Dr(e){if(!/^(?:[^.[\]]+|\[\d+\])(?:\.[^.[\]]+|\[\d+\])*$/u.test(e))return[];let t=[],n=e.matchAll(/[^.[\]]+|\[\d+\]/g);for(let[r]of n){if(r.startsWith("[")&&r.endsWith("]")){let o=Number.parseInt(r.slice(1,-1),10);if(!Number.isSafeInteger(o))return[];t.push(o);continue}t.push(r)}return t}function an(e,t){let n=t.trim();if(n.length===0)return{found:!1,value:void 0};let r=Dr(n);if(r.length===0)return{found:!1,value:void 0};let o=e;for(let s of r){if(typeof o!="object"||o===null)return{found:!1,value:void 0};if(typeof s=="number"&&(!Array.isArray(o)||s>=o.length))return{found:!1,value:void 0};let i=Object.getOwnPropertyDescriptor(o,s);if(!i||!Object.hasOwn(i,"value"))return{found:!1,value:void 0};o=i.value}return{found:!0,value:o}}import{cp as Ci,lstat as Li,mkdir as Ai,readlink as Pi,realpath as un,stat as Ri,symlink as Hr}from"node:fs/promises";import{execFile as Oi}from"node:child_process";import _ from"node:path";import{promisify as Ii}from"node:util";import{execFile as vi}from"node:child_process";import{readdir as Ti,realpath as Ei}from"node:fs/promises";import Si from"node:path";import{promisify as bi}from"node:util";var cn=bi(vi),Wr=".agents/pm/merge-receipts";async function qr(e,t,n){let r=Si.join(n,"merge-receipts"),o=(await Ti(r).catch(c=>{if(K(c))return[];throw c})).filter(c=>c.endsWith(".json")),{readIndexedReceiptBlobs:s}=await import("./indexed-receipt-blobs-DR3FDHND.js"),i=o.length===0?new Map:await s(e,r,o,Wn,await Ei(r),{failOnReadError:!0}),a={cwd:t,env:Dn(),timeout:1e4,maxBuffer:1024*1024,windowsHide:!0};await cn("git",["rm","-q","-r","--cached","--ignore-unmatch","--",Wr],a);for(let[c,d]of i){let f=cn("git",["hash-object","-w","--stdin"],a),m=f.child.stdin;m!==null&&(m.on("error",()=>{f.child.kill()}),m.end(d));let p=(await f).stdout.trim();if(!/^(?:[a-f\d]{40}|[a-f\d]{64})$/u.test(p))throw new Error("Invalid snapshot receipt object identity.");await cn("git",["update-index","--add","--cacheinfo","100644",p,`${Wr}/${c}`],a)}}var ji=new Set([".agents",".git",".nyc_output",".turbo","coverage"]),et=Ii(Oi);async function $i(e,t){let n=await tt(_.join(e,".git"));if(!n||n.isDirectory()&&!await tt(_.join(e,".git/HEAD")))return!1;let r=Object.fromEntries(Object.entries(process.env).filter(([o])=>!o.toUpperCase().startsWith("GIT_")));await et("git",["clone","--no-local","--no-checkout","--template=","--origin=origin","--",e,t],{env:r,timeout:12e4,maxBuffer:1024*1024,windowsHide:!0}),await et("git",["-C",t,"remote","remove","origin"],{env:r,timeout:1e4,windowsHide:!0});try{await et("git",["-C",t,"rev-parse","--verify","--quiet","HEAD"],{env:r,timeout:1e4,windowsHide:!0})}catch(o){if(o.code===1)return!0;throw o}return await et("git",["-C",t,"read-tree","HEAD"],{env:r,timeout:1e4,windowsHide:!0}),!0}async function Mi(e,t,n,r){await $i(e,t)&&n&&r!==!1&&await qr(e,t,n)}function dn(e){return e.split(_.sep).some(t=>ji.has(t.toLowerCase()))}function Ee(e){return e===".."||e.startsWith(`..${_.sep}`)||_.isAbsolute(e)}async function tt(e){try{return await Ri(e)}catch(t){if(!K(t))throw t;return}}async function nt(e){let t=[],n=e;for(;_.dirname(n)!==n;)try{return _.join(await un(n),...t)}catch(r){if(!K(r))throw r;t.unshift(_.basename(n)),n=_.dirname(n)}return _.join(await un(n),...t)}async function Ni(e,t,n){let r=_.relative(t,await nt(e));if(!Ee(r))return r;let o=[],s=e;for(;_.dirname(s)!==s;){let i=await nt(s),a=n.find(([,c])=>c===i);if(a)return _.join(a[0],...o);o.unshift(_.basename(s)),s=_.dirname(s)}return r}async function Kr(e,t,n,r){let o=[],s=[],i=await un(e),a=await nt(_.resolve(t));if(![_.relative(i,a),_.relative(a,i)].every(Ee))throw new Error("Snapshot destination must be disjoint from the source workspace; choose a temporary root outside the checkout.");await Ai(_.dirname(t),{recursive:!0}),await Mi(i,t,n,r),await Ci(i,t,{recursive:!0,force:!0,async filter(c){let d=_.relative(i,c);if(!d)return!0;if(dn(d))return!1;if(_.basename(c).toLowerCase()==="node_modules"){if((await tt(c))?.isDirectory()){let f=await nt(c),m=_.relative(i,f);if(!Ee(_.relative(f,i))||!Ee(m)&&(dn(m)||!m.split(_.sep).some(p=>p.toLowerCase()==="node_modules")))throw new Error(`Dependency symlink must target an included dependency directory or external installation: ${d}`);o.push([d,f])}return!1}return(await Li(c)).isSymbolicLink()?(s.push([d,_.resolve(_.dirname(c),await Pi(c)),(await tt(c))?.isDirectory()?"junction":"file"]),!1):!0}});for(let[c]of o)await Hr(_.resolve(i,c),_.join(t,c),"junction");for(let[c,d,f]of s){let m=await Ni(d,i,o);if(Ee(m)||dn(m))throw new Error(`Source symlink must target included workspace source: ${c}`);await Hr(_.resolve(t,m),_.join(t,c),f)}}import{execFile as Ui}from"node:child_process";import{constants as Br}from"node:fs";import{access as Gi,open as Fi}from"node:fs/promises";import zr from"node:path";import{promisify as Di}from"node:util";var Wi=Di(Ui);function qi(e){let t=e.match(/^\s*(?:"([^"\r\n]+)"|'([^'\r\n]+)'|([\w./\\:-]+))(?=\s|$)/u),n=t?.[1]??t?.[2]??t?.[3];return n&&!/[$`%&|<>^;]/u.test(n)?n:void 0}function Hi(e,t,n){return process.platform==="win32"?(t===1||t===9009)&&n.split(/\r?\n/u).some(r=>r.trim()===`'${e}' is not recognized as an internal or external command,`):t!==126&&t!==127?!1:n.split(/\r?\n/u).some(r=>t===127&&(r.endsWith(`: ${e}: not found`)||r.endsWith(`: ${e}: command not found`))||t===126&&r.includes(`: ${e}: `)&&r.endsWith(": bad interpreter: No such file or directory"))}async function Ki(e,t){let n=e.trim();if(!n||/[\r\n]/u.test(n))return!1;try{let r=await Fi(zr.resolve(t,n),Br.O_RDONLY|Br.O_NONBLOCK),o;try{let i=Buffer.alloc(256),{bytesRead:a}=await r.read(i,0,i.length,0);if(o=i.toString("utf8",0,a),a===i.length&&!o.includes(`
|
|
@@ -7,4 +7,4 @@ ${t}`;for(let r of wi)if(r.regex.test(n))return{code:r.code};return null}functio
|
|
|
7
7
|
[pm linked-test output truncated at ${st} bytes per stream; the child process continued to completion]
|
|
8
8
|
`:"";!x&&await Jr(e,{exitCode:R,stderr:k.text},n,s)&&(x="Linked test executable was not found. Install the tool or update the linked command before retrying.");let M={stdout:`${N.text}${O}`,stderr:k.text,exitCode:R,signal:b,timedOut:L,maxBufferExceeded:!1,outputTruncated:v,spawnError:x};return Ta(r,M,i,o),M}finally{await be(a,{recursive:!0,force:!0})}}function Aa(e,t){let n=[];e.maxBufferExceeded&&n.push(`Linked test output exceeded maxBuffer=${st} bytes. Reduce output volume or split the command.`),e.timedOut&&t>0&&n.push(`Linked test timed out after ${t}ms.`);let r=e.signal?`Linked test command terminated by signal ${e.signal}.`:void 0,o=e.spawnError?.trim()||r||"Linked test command failed.";return n.length===0?o:`${o} ${n.join(" ")}`}function Pa(e){let t=[e.spawnError??"",e.stderr,e.stdout].join(`
|
|
9
9
|
`);return ea.some(n=>n.test(t))||t.split(/\r?\n/u).some(n=>ta.test(n)&&na.test(n))}function Ra(e){return Pa(e)?"infra_collision":e.timedOut?"timeout":e.maxBufferExceeded?"max_buffer":e.spawnError?"spawn_error":e.signal?"signal":"assertion_failure"}function oo(e,t){for(let[n,r]of Object.entries(t.env_set))ne.has(n.toUpperCase())||(e[n]=r);for(let n of t.env_clear)ne.has(n.toUpperCase())||delete e[n]}function Oa(e){e.PORT===void 0&&(e.PORT="0"),e.HOST===void 0&&(e.HOST="127.0.0.1"),e.PM_SHARED_HOST_SAFE===void 0&&(e.PM_SHARED_HOST_SAFE="1"),e.PLAYWRIGHT_HTML_OPEN===void 0&&(e.PLAYWRIGHT_HTML_OPEN="never"),e.PW_TEST_HTML_REPORT_OPEN===void 0&&(e.PW_TEST_HTML_REPORT_OPEN="never")}function Ia(e,t){let n={...e.env_set,...t.env_set},r=[...new Set([...e.env_clear,...t.env_clear??[]])],o=t.shared_host_safe??e.shared_host_safe;return{env_set:n,env_clear:r,shared_host_safe:o}}function Co(e,t,n){return{env_set:ma(e,"--env-set"),env_clear:pa(t,"--env-clear"),shared_host_safe:n===!0}}async function Se(e,t,n=!1,r=hn){if(await he(e))try{await _t("seed_linked_test",async()=>{if(await r(y.dirname(t),{recursive:!0}),n){await Zr(e,t,{recursive:!0,force:!0});return}await Zr(e,t,{force:!0})},{why:"Linked tests need an isolated PM context without mutating the source tracker.",nextSteps:["Reclaim capacity on the filesystem that hosts the linked-test temporary directory."]})}catch(o){if(typeof o=="object"&&o!==null&&"code"in o&&K(o))return;throw o}}async function so(e,t,n,r=!1){for(let[o,s]of[[n.projectPmRoot,e],[n.globalPmRoot,t]])if(r){let i=await lt(D(o));if(i!==null){let a=await W(s);await xt({pmRoot:s,filePath:D(s),raw:i,op:"settings:write",author:$(void 0,a.author_default),lockTtlSeconds:a.locks.ttl_seconds,lockWaitMs:a.locks.wait_ms,recordCreation:!0,message:"Seed linked-test schema settings history"})}}else await Se(D(o),D(s));await Se(y.join(n.projectPmRoot,"extensions"),y.join(e,"extensions"),!0),await Se(y.join(n.globalPmRoot,"extensions"),y.join(t,"extensions"),!0)}async function io(e,t){if(!await he(e))return;let n=await mn(e,{withFileTypes:!0});for(let r of n){if(Zi.has(r.name))continue;let o=y.join(e,r.name),s=y.join(t,r.name);if(r.isDirectory()){await Se(o,s,!0);continue}r.isFile()&&await Se(o,s)}}async function ao(e,t){let n=await lt(D(e));if(n===null||await he(gt(e)))return;let r=await W(t);await be(gt(t),{force:!0}),await be(D(t),{force:!0}),await xt({pmRoot:t,filePath:D(t),raw:n,op:"settings:write",author:$(void 0,r.author_default),lockTtlSeconds:r.locks.ttl_seconds,lockWaitMs:r.locks.wait_ms,recordCreation:!0,message:"Seed linked-test tracker settings history"})}async function fe(e){if(!await he(e))return 0;let t=0,n=await mn(e,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||Qi.has(r.name))continue;let o=y.join(e,r.name),s;try{s=await mn(o,{withFileTypes:!0})}catch{continue}for(let i of s)i.isFile()&&An.some(a=>i.name.toLowerCase().endsWith(a))&&(t+=1)}return t}function ja(e){let t=typeof e.exitCode=="number"?e.exitCode:1;return(e.timedOut||e.maxBufferExceeded)&&t===0?1:t}function $a(e){let t=e.trim();if(t==="true")return!0;if(t==="false")return!1;if(t==="null")return null;let n=Number(t);if(t.length>0&&Number.isFinite(n))return n;if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch{}return t}function Ma(e,t){return typeof e=="object"&&e!==null&&typeof t=="object"&&t!==null?U(e,t):Object.is(e,t)}function Na(e,t,n){let r=[];r.push(...co("stdout",t,e.assert_stdout_contains)),r.push(...uo("stdout",t,e.assert_stdout_regex)),r.push(...co("stderr",n,e.assert_stderr_contains)),r.push(...uo("stderr",n,e.assert_stderr_regex)),r.push(...Ua(t,e.assert_stdout_min_lines));let o=e.assert_json_field_equals??{},s=e.assert_json_field_gte??{};if(!(Object.keys(o).length>0||Object.keys(s).length>0))return r;let a;try{a=JSON.parse(t)}catch(c){return r.push(`stdout is not valid JSON for assert_json_field_* checks: ${c instanceof Error?c.message:String(c)}`),r}for(let[c,d]of Object.entries(o)){let f=an(a,c);if(!f.found){r.push(`assert_json_field_equals missing path "${c}"`);continue}let m=$a(d);Ma(f.value,m)||r.push(`assert_json_field_equals mismatch at "${c}" (expected=${JSON.stringify(m)} actual=${JSON.stringify(f.value)})`)}for(let[c,d]of Object.entries(s)){let f=an(a,c);if(!f.found){r.push(`assert_json_field_gte missing path "${c}"`);continue}if(typeof f.value!="number"||!Number.isFinite(f.value)){r.push(`assert_json_field_gte path "${c}" resolved to non-numeric value`);continue}f.value<d&&r.push(`assert_json_field_gte failed at "${c}" (expected >= ${d}, actual ${f.value})`)}return r}function co(e,t,n){let r=[];for(let o of n??[])t.includes(o)||r.push(`${e} missing required text: "${o}"`);return r}function uo(e,t,n){let r=[];for(let o of n??[])try{new RegExp(o,"m").test(t)||r.push(`${e} failed regex assertion: /${o}/m`)}catch(s){r.push(`${e} regex assertion is invalid: /${o}/ (${s instanceof Error?s.message:String(s)})`)}return r}function Ua(e,t){if(typeof t!="number")return[];let n=e.split(/\r?\n/).map(r=>r.trim()).filter(r=>r.length>0).length;return n<t?[`stdout line count ${n} is below required minimum ${t}`]:[]}function Ga(e){let t=ue(e);return/(?:^|\s)(?:--test-name-pattern|--testnamepattern)(?:=|\s)/u.test(t)?!0:Z(t).some(n=>/(?:^|\s)-t(?:=|\s)/u.test(n)&&gn(n))}function Fa(e){return{root:e,schemaProjectPmPath:y.join(e,"schema","project",".agents","pm"),schemaGlobalPmPath:y.join(e,"schema","global"),trackerProjectPmPath:y.join(e,"tracker","project",".agents","pm"),trackerGlobalPmPath:y.join(e,"tracker","global"),workspaceSnapshotRoot:y.join(e,"workspace","project"),workspaceIsolatedRoot:y.join(e,"workspace","isolated")}}function Da(e,t,n){return e.some(r=>go(r,t,n)==="snapshot")}async function Wa(e,t){let n=y.join(e,".agents"),r=y.join(n,"pm");await hn(n,{recursive:!0}),await be(r,{recursive:!0,force:!0}),await Ji(t,r,process.platform==="win32"?"junction":"dir")}async function qa(e,t=yt,n=!0){let r={defaults:!0,agentGuidance:"skip"};await t(void 0,{path:e.schemaProjectPmPath},r),await t(void 0,{path:e.schemaGlobalPmPath},r),n&&(await t(void 0,{path:e.trackerProjectPmPath},r),await t(void 0,{path:e.trackerGlobalPmPath},r))}async function Ha(e,t,n){t&&(await so(e.schemaProjectPmPath,e.schemaGlobalPmPath,t,!0),n&&(await so(e.trackerProjectPmPath,e.trackerGlobalPmPath,t),await io(t.projectPmRoot,e.trackerProjectPmPath),await io(t.globalPmRoot,e.trackerGlobalPmPath),await ao(t.projectPmRoot,e.trackerProjectPmPath),await ao(t.globalPmRoot,e.trackerGlobalPmPath)))}function Ka(e,t,n){return e.some(r=>{let o=r.command??"",s=o.length>0&&wo(o),i=n?.autoPmContext===!0&&s?"auto":xo(r,t,n?.overrideLinkedPmContext===!0);return ko(i,s)==="tracker"})}async function Ba(e,t){return{sourceProjectItemCount:t?await fe(t.projectPmRoot):0,sourceGlobalItemCount:t?await fe(t.globalPmRoot):0,schemaProjectItemCount:await fe(e.schemaProjectPmPath),schemaGlobalItemCount:await fe(e.schemaGlobalPmPath),trackerProjectItemCount:await fe(e.trackerProjectPmPath),trackerGlobalItemCount:await fe(e.trackerGlobalPmPath)}}function za(e){let t=e.effectivePmContextMode==="tracker",n=t?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath,r=t?e.layout.trackerGlobalPmPath:e.layout.schemaGlobalPmPath,o=t?e.counts.trackerProjectItemCount:e.counts.schemaProjectItemCount,s=t?e.counts.trackerGlobalItemCount:e.counts.schemaGlobalItemCount,i=e.workspaceContextMode==="snapshot"?e.layout.workspaceSnapshotRoot:e.workspaceContextMode==="isolated"?e.layout.workspaceIsolatedRoot:e.sourceWorkspaceRoot,a=e.workspaceContextMode==="isolated"?"":i;return{requested_pm_context_mode:e.requestedPmContextMode,pm_context_mode:e.effectivePmContextMode,auto_pm_context_applied:e.autoPmContextApplied,is_pm_command:e.isPmCommand,is_pm_tracker_read_command:e.isPmTrackerReadCommand,source_project_pm_path:e.sourceRoots?.projectPmRoot??"",sandbox_project_pm_path:n,source_global_pm_path:e.sourceRoots?.globalPmRoot??"",sandbox_global_pm_path:r,source_project_item_count:e.counts.sourceProjectItemCount,sandbox_project_item_count:o,source_global_item_count:e.counts.sourceGlobalItemCount,sandbox_global_item_count:s,mismatch_detected:e.isPmCommand&&(e.counts.sourceProjectItemCount!==o||e.counts.sourceGlobalItemCount!==s),project_extensions_seeded:!!e.sourceRoots,global_extensions_seeded:!!e.sourceRoots,requested_workspace_context_mode:e.requestedWorkspaceContextMode,workspace_context_mode:e.workspaceContextMode,working_directory:i,source_workspace_root:a,trust:e.trust}}async function Ja(e){let t=typeof e.linkedTest.pm_context_mode=="string"&&e.linkedTest.pm_context_mode.trim().length>0?at(e.linkedTest.pm_context_mode):void 0,n=typeof e.linkedTest.command=="string"&&e.linkedTest.command.length>0?e.linkedTest.command:void 0,r=n?ha(n):!1,o=r&&n?wo(n):!1,s=e.options?.autoPmContext===!0&&o,i=s?"auto":xo(e.linkedTest,e.runLevelPmContextMode,e.options?.overrideLinkedPmContext===!0),a=ko(i,o),c=a==="tracker"?e.layout.trackerProjectPmPath:e.layout.schemaProjectPmPath;e.workspaceContextMode==="snapshot"&&await Wa(e.layout.workspaceSnapshotRoot,c);let d=e.options?.pmRoot?await Zt(e.options.pmRoot,e.linkedTest,e.currentSourceRef):await Zt(e.layout.root,e.linkedTest,e.currentSourceRef);return{linkedOverridePmContextMode:t,executionContext:za({layout:e.layout,counts:e.counts,sourceRoots:e.sourceRoots,isPmCommand:r,isPmTrackerReadCommand:o,requestedPmContextMode:i,effectivePmContextMode:a,autoPmContextApplied:s,requestedWorkspaceContextMode:e.requestedWorkspaceContextMode,workspaceContextMode:e.workspaceContextMode,sourceWorkspaceRoot:e.sourceWorkspaceRoot,trust:d})}}function lo(e,t,n){return{command:e.command,path:e.path,status:"skipped",execution_context:t,error:n}}function Va(e,t,n,r){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"assertion_failure",execution_context:t,...r?{stdout:r.stdout,stderr:r.stderr}:{},error:n}}function Xa(e,t,n){return{command:e.command,path:e.path,status:"failed",exit_code:1,failure_category:"trust_refusal",execution_context:t,error:n}}function Ya(e){if(e.executionContext.trust.trusted)return null;let t=e.options?.allowUntrustedLinkedTests===!0,n=e.options?.untrustedLinkedTestsPolicyEnabled===!0;if(t&&n)return null;let r=n?"Retry with --allow-untrusted-linked-tests for this invocation, or acknowledge the current commands with --acknowledge-linked-tests.":"Set testing.allow_untrusted_linked_tests=true, then retry with --allow-untrusted-linked-tests; alternatively acknowledge the current commands with --acknowledge-linked-tests.";return Xa(e.linkedTest,e.executionContext,`Linked test command is not trusted by this clone (source_ref=${e.executionContext.trust.source_ref??"unknown"}, current_ref=${e.executionContext.trust.current_source_ref??"unknown"}). ${r}`)}function Za(e){if(!e.linkedTest.command)return lo(e.linkedTest,e.executionContext,"No command configured for this linked test.");let t=xa(e.linkedTest.command);return t?lo(e.linkedTest,e.executionContext,t):null}function Qa(e){return e.executionContext.pm_context_mode!=="none"?null:e.executionContext.workspace_context_mode==="source"?it(e.linkedTest,e.executionContext,"pm_context_mode=none requires workspace_context_mode=isolated or snapshot so implicit tracker discovery cannot reach the source workspace."):e.executionContext.is_pm_command?it(e.linkedTest,e.executionContext,"pm_context_mode=none is for self-isolating SDK tests; direct PM commands require schema, tracker, or auto context."):null}function it(e,t,n){return{command:e.command,path:e.path,status:"refused",exit_code:null,failure_category:"config_refusal",execution_context:t,error:n}}function ec(e){let t=e.executionContext.pm_context_mode==="schema"&&e.executionContext.is_pm_tracker_read_command&&e.executionContext.mismatch_detected,n=e.options?.failOnContextMismatch===!0&&e.executionContext.is_pm_command&&e.executionContext.mismatch_detected;if(!t&&!n)return null;let r=fa({executionContext:e.executionContext,runLevelPmContextMode:e.runLevelPmContextMode,linkedOverridePmContextMode:e.linkedOverridePmContextMode}),o=e.options?.checkContext===!0?"Linked test preflight PM context mismatch detected":"Linked test PM context mismatch detected";return it(e.linkedTest,e.executionContext,`${o} (source_project_items=${e.executionContext.source_project_item_count}, sandbox_project_items=${e.executionContext.sandbox_project_item_count}).${r}`)}function tc(e){let t=Za(e);if(t)return t;let n=Ya(e);if(n)return n;let r=Qa(e);if(r)return r;let o=ec(e);return o||(e.options?.requireAssertionsForPm===!0&&e.executionContext.is_pm_command&&!la(e.linkedTest)?it(e.linkedTest,e.executionContext,"Linked PM command requires assertions when --require-assertions-for-pm is enabled."):null)}function nc(e){let t=Ia(e.runtimeDirectives,e.linkedTest),n={...process.env,SENTRY_ENVIRONMENT:"test"};return oo(n,e.runtimeDirectives),oo(n,{env_set:e.linkedTest.env_set??{},env_clear:e.linkedTest.env_clear??[]}),t.shared_host_safe&&Oa(n),n.FORCE_COLOR="0",e.executionContext.pm_context_mode==="none"?delete n.PM_PATH:n.PM_PATH=e.executionContext.sandbox_project_pm_path,n.PM_GLOBAL_PATH=e.executionContext.sandbox_global_pm_path,e.executionContext.workspace_context_mode!=="source"&&(delete n.PM_BUILD_CONSUMER_LEASE,delete n.PM_BUILD_CONSUMER_LEASE_ROOT),e.executionContext.workspace_context_mode==="isolated"?(delete n.PM_SOURCE_WORKSPACE_ROOT,delete n.PM_SOURCE_PM_PATH,delete n[ge]):(n.PM_SOURCE_WORKSPACE_ROOT=e.executionContext.source_workspace_root,n.PM_SOURCE_PM_PATH=e.executionContext.workspace_context_mode==="snapshot"?e.executionContext.sandbox_project_pm_path:e.executionContext.source_project_pm_path,n[ge]="read_only"),n}function rc(e,t,n,r){return{command:e.command,path:e.path,status:"passed",exit_code:0,execution_context:t,stdout:n.stdout,stderr:n.stderr,...r?{execution_receipt:r}:{}}}function fo(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:1,failure_category:"empty_run",execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:`Linked test reported an empty test run (${e.emptyRunSignal.code}). Update the test selection so at least one test executes; unfiltered commands may opt out by omitting --fail-on-empty-test-run.`}}function oc(e){return{command:e.linkedTest.command,path:e.linkedTest.path,status:"failed",exit_code:ja(e.execution),failure_category:Ra(e.execution),execution_context:e.executionContext,stdout:e.execution.stdout,stderr:e.execution.stderr,error:Aa(e.execution,e.timeoutMs)}}function sc(e){let t=Nr(e.execution.stdout,e.execution.stderr),n=e.linkedTest.phase!=="setup"&&Ga(e.linkedTest.command??"");if(e.options?.failOnEmptyTestRun===!0||n){let o=Qe(e.execution.stdout,e.execution.stderr);if(o)return fo({...e,emptyRunSignal:o});if(n&&!t)return fo({...e,emptyRunSignal:{code:"missing_positive_execution_receipt"}})}let r=Na(e.linkedTest,e.execution.stdout,e.execution.stderr);return r.length>0?Va(e.linkedTest,e.executionContext,`Linked test assertion(s) failed: ${r.join("; ")}`,e.execution):rc(e.linkedTest,e.executionContext,e.execution,t)}async function ic(e){let t=e.linkedTest.command??"",n=(e.linkedTest.timeout_seconds??e.defaultTimeoutSeconds??120)*1e3,r=await La(t,n,nc(e),{index:e.index+1,total:e.total,timeoutMs:n,command:t},e.progressMode,e.executionContext.working_directory);return r.exitCode===0&&!r.timedOut&&!r.maxBufferExceeded?sc({...e,execution:r}):oc({...e,execution:r,timeoutMs:n})}async function ac(e,t,n){let r=gr(e);for(let w of r)mt(w.command);let o=[],s=await po(y.join(ho(),"pm-linked-test-")),i=Fa(s),a=at(n?.pmContext),c=_o(n?.workspaceContext),d=n?.progress===!0?"always":"auto",f=Co(n?.envSet,n?.envClear,n?.sharedHostSafe),m=n?.sourceRoots,p=Yt(),g=Ka(r,a,n),x=Da(r,c,n?.overrideLinkedWorkspaceContext===!0),h=await Xt(p);try{await qa(i,yt,g),await hn(i.workspaceIsolatedRoot,{recursive:!0}),await Ha(i,m,g),x&&await Kr(p,i.workspaceSnapshotRoot,m?.projectPmRoot,g);let w=await Ba(i,m),L=wr(),R=k=>go(k,c,n?.overrideLinkedWorkspaceContext===!0),b=new Set(r.filter(k=>!P(k)).map(R)),N=async(k,v)=>{let O=L.options(k,n),M=R(k),A=kr(k,M,b);if(A)return A;let I=await Ja({linkedTest:k,layout:i,counts:w,sourceRoots:m,runLevelPmContextMode:a,options:n,requestedWorkspaceContextMode:c,workspaceContextMode:M,currentSourceRef:h,sourceWorkspaceRoot:p});return tc({linkedTest:k,executionContext:I.executionContext,runLevelPmContextMode:a,linkedOverridePmContextMode:I.linkedOverridePmContextMode,options:O})??await ic({linkedTest:k,index:v,total:r.length,defaultTimeoutSeconds:t,runtimeDirectives:f,progressMode:d,executionContext:I.executionContext,options:O})};for(let k=0;k<r.length;k+=1){let v=r[k];o.push(L.blocked(v)??L.record(v,await N(v,k)))}}finally{await be(i.root,{recursive:!0,force:!0,maxRetries:3,retryDelay:100})}return o}function cc(e,t){let n=[...t];return e.filter(r=>{let o=n.findIndex(s=>_e(s,r));return o>=0&&n.splice(o,1),o<0}).length}async function dc(e){let{id:t,pmRoot:n,settings:r,typeToFolder:o}=e,s=await je(n,t,r.id_prefix,r.item_format,o);if(!s)throw new l(`Item ${t} not found`,u.NOT_FOUND);let i=await $e(s,{schema:r.schema});return{itemId:s.id,tests:i.document.metadata.tests??[],testRuns:i.document.metadata.test_runs??[],changed:!1,removed:0}}function uc(e,t){let n=[...e];for(let r of t)n.some(o=>_e(o,r))||n.push(r);return n}function lc(e,t,n){if(t.length===0&&n.length===0)return{tests:e,removed:0};let r=new Set(n),o=e.filter((s,i)=>r.has(i+1)?!1:!t.some(a=>a.kind==="command"?s.command===a.value:a.kind==="path"?s.path===a.value:s.command===a.value||s.path===a.value));return{tests:o,removed:e.length-o.length}}function fc(e,t,n,r){return lc(uc(e,t),n,r)}function mc(e){return[e.timeout!==void 0,e.progress===!0,(e.envSet?.length??0)>0,(e.envClear?.length??0)>0,e.sharedHostSafe===!0,e.pmContext!==void 0,e.overrideLinkedPmContext===!0,e.failOnContextMismatch===!0,e.failOnSkipped===!0,e.failOnEmptyTestRun===!0,e.requireAssertionsForPm===!0,e.checkContext===!0,e.fullOutput===!0,e.autoPmContext===!0,e.workspaceContext!==void 0,e.overrideLinkedWorkspaceContext===!0,e.allowUntrustedLinkedTests===!0].some(Boolean)}function Lo(e){if(mc(e)&&e.run!==!0)throw new l("--timeout, --progress, --env-set, --env-clear, --shared-host-safe, --pm-context, --override-linked-pm-context, --workspace-context, --override-linked-workspace-context, --allow-untrusted-linked-tests, --fail-on-context-mismatch, --fail-on-skipped, --fail-on-empty-test-run, --require-assertions-for-pm, --check-context, --full-output, and --auto-pm-context require --run",u.USAGE);if(e.acknowledgeLinkedTests===!0&&e.run===!0)throw new l("--acknowledge-linked-tests records trust without executing commands; run it separately before --run",u.USAGE);if((e.match!==void 0||e.onlyIndex!==void 0||e.onlyLast===!0)&&e.run!==!0)throw new l("--match, --only-index, and --only-last require --run",u.USAGE)}async function pc(e){let{id:t,options:n,pmRoot:r,settings:o,typeToFolder:s,adds:i,removes:a,removeIndexes:c}=e;if(i.length===0&&a.length===0&&c.length===0)return dc({id:t,pmRoot:r,settings:o,typeToFolder:s});let d=0,f=[],m=await ae({pmRoot:r,settings:o,id:t,op:i.length>0?"tests_add":"tests_remove",author:$(n.author,o.author_default),message:n.message,force:n.force,skipNoop:!0,mutate(g){let x=g.metadata.tests??[],h=fc(x,i,a,c);if(ft(()=>Ao(n,h.tests)),d=h.removed,(a.length>0||c.length>0)&&d===0)throw new l("No linked tests matched the requested removal selector",u.NOT_FOUND,{code:"linked_test_remove_no_match",unmatched:[...a.map(w=>`${w.kind}=${w.value}`),...c.map(w=>`index=${w}`)],required:"List linked tests and retry with an exact command/path or a current 1-based --remove-index.",examples:[`pm test ${t} --list`,`pm test ${t} --remove-index 1`]});return g.metadata.tests=h.tests,f=x,{changedFields:U(x,h.tests)?[]:["tests"]}}}),p=m.item.tests??[];return{itemId:m.item.id,tests:p,testRuns:m.item.test_runs??[],changed:m.changedFields.length>0,removed:d,written:m.changedFields.length>0?Mt(f,p):[],storedRemoved:cc(f,p)}}function Ao(e,t){let n=at(e.pmContext);_o(e.workspaceContext),Co(e.envSet,e.envClear,e.sharedHostSafe);let r={match:e.match,onlyIndex:e.onlyIndex===void 0?void 0:le(e.onlyIndex),onlyLast:e.onlyLast},o=e.timeout===void 0?void 0:pe(e.timeout,"--timeout");if(o!==void 0&&o<=0)throw new l(`--timeout must be a positive number (got "${e.timeout}")`,u.USAGE);Lo(e);let s=e.run===!0?xr(Or(t,r),t):void 0;if(s)for(let i of s.selected)mt(i.command);return{defaultTimeoutSeconds:o,pmContextMode:n,runSelection:s,testsToRun:s?.selected??t}}async function hc(e){let{options:t,runOptions:n,pmRoot:r}=e;return t.run!==!0?[]:await ac(n.testsToRun,n.defaultTimeoutSeconds,{progress:t.progress,envSet:t.envSet,envClear:t.envClear,sharedHostSafe:t.sharedHostSafe,pmContext:n.pmContextMode,overrideLinkedPmContext:t.overrideLinkedPmContext,failOnContextMismatch:t.failOnContextMismatch,failOnEmptyTestRun:t.failOnEmptyTestRun===!0||(t.measure?.length??0)>0,requireAssertionsForPm:t.requireAssertionsForPm,checkContext:t.checkContext,autoPmContext:t.autoPmContext,workspaceContext:t.workspaceContext,overrideLinkedWorkspaceContext:t.overrideLinkedWorkspaceContext,pmRoot:r,allowUntrustedLinkedTests:t.allowUntrustedLinkedTests,untrustedLinkedTestsPolicyEnabled:e.untrustedLinkedTestsPolicyEnabled,sourceRoots:{projectPmRoot:r,globalPmRoot:Rn(process.cwd())}})}function _c(e,t){let n=[];if(e.run===!0&&e.checkContext===!0){let r=da(t);n.push(`context_preflight:checked_pm_commands=${r.checked_pm_commands};tracker_read_commands=${r.tracker_read_commands};mismatches=${r.mismatches};auto_remediated=${r.auto_remediated}`)}return n}function gc(e){let t=ca(e.runResults),n=Number.parseInt(process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim()??"",10),r=process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM?.trim(),o=V(),s=rn(e.options.measure,o);return{run_id:aa("test"),kind:"test",status:t.failed>0||e.failOnSkippedTriggered?"failed":"passed",started_at:e.runStartedAt,finished_at:o,recorded_at:o,attempt:Number.isFinite(n)&&n>=1?n:void 0,resumed_from:r&&r.length>0?r:void 0,passed:t.passed,failed:t.failed,skipped:t.skipped,fail_on_skipped_triggered:e.failOnSkippedTriggered?!0:void 0,measurements:s.length>0?s:void 0,executions:e.runResults.filter(i=>i.command?.trim()).slice(0,32).map(i=>({command:i.command.trim(),requested_pm_context_mode:i.execution_context?.requested_pm_context_mode,pm_context_mode:i.execution_context?.pm_context_mode,workspace_context_mode:i.execution_context?.workspace_context_mode,trust_reason:i.execution_context?.trust.reason}))}}async function xc(e){let{options:t,pmRoot:n,settings:r,itemId:o,runStartedAt:s,runResults:i,failOnSkippedTriggered:a,warnings:c}=e;if(t.run!==!0||!s)return;let d=gc({options:t,runStartedAt:s,runResults:i,failOnSkippedTriggered:a});if(r.testing.record_results_to_items!==!0)return{entry:d,receipt:{recorded:!1,reason:"tracking_disabled",run_id:d.run_id,recovery_command:"pm config project set test-result-tracking --policy enabled"}};try{return await Xr({pmRoot:n,settings:r,itemId:o,author:$(t.author,r.author_default),message:`Track test run summary (${d.run_id})`,entry:d}),{entry:d,receipt:{recorded:!0,reason:"recorded",run_id:d.run_id}}}catch(f){if(Un(f))throw f;return c.push(`test_result_tracking_failed:${o}:${f instanceof Error?f.message:String(f)}`),{entry:d,receipt:{recorded:!1,reason:"write_failed",run_id:d.run_id}}}}function mo(e,t,n){let r;if(e.metricBelow!==void 0){let o=e.metricBelow.indexOf("="),s=e.metricBelow.slice(0,o).trim(),i=e.metricBelow.slice(o+1).trim(),a=Number(i);if(o<=0||s.length===0||i.length===0||!Number.isFinite(a))throw new l("--metric-below must use name=value",u.USAGE);r=Lr(t,s,a)}return{measurements:n?.measurements,metric_below:r,metric_diff:e.metricDiff===void 0?void 0:Ar(t,e.metricDiff)}}async function kc(e,t,n){if(e.acknowledgeLinkedTests===!0)return _r(t,n,V())}function wc(e){let{item:t,runResults:n,failureCategories:r,runSelection:o,failOnSkippedTriggered:s,warnings:i,recording:a,measurementProjection:c,restoreScope:d}=e,f=vc(t,e.fullHistory),m=yc(t,o,f,d),{counts:p,receipts:g}=Ue(f);return{ok:n.every(x=>x.status!=="failed"&&x.status!=="refused")&&s!==!0,id:t.itemId,tests:m.tests,...m.omitted,run_results:n,...e.ran?{failure_categories:r}:{},selection:o?{selector:o.selector,requested:o.requested,selected_indexes:o.selected_indexes,selected_count:o.selected_count,skipped_count:o.skipped_count,...o.setup_indexes?{setup_indexes:o.setup_indexes}:{}}:void 0,fail_on_skipped_triggered:s?!0:void 0,warnings:i.length>0?i:void 0,changed:t.changed||a?.receipt.recorded===!0,...a?{evidence_recording:a.receipt}:{},count:m.count,...t.removed>0?{removed:t.removed}:{},...p,...c,...g}}function yc(e,t,n,r){return n!==void 0?{tests:n.entries,count:n.returned_count,omitted:{}}:t!==void 0&&t.selector!==null&&t.skipped_count>0?{tests:t.selected,count:e.tests.length,omitted:{tests_omitted:{count:e.tests.length-t.selected.length,restore_with:Gr(e.itemId,r)}}}:{tests:e.tests,count:e.tests.length,omitted:{}}}function vc(e,t){if(e.written!==void 0)return xe({collectionKey:"tests",stored:e.tests,written:e.written,removedCount:e.storedRemoved,fullHistory:t})}function Tc(e,t){let n=e.tests[e.updated_index-1],r=xe({collectionKey:"tests",stored:e.tests,written:e.changed&&n!==void 0?[n]:[],removedCount:0,fullHistory:t}),{counts:o,receipts:s}=Ue(r);return{...e,tests:r.entries,run_results:[],count:r.returned_count,...o,...s}}async function yl(e,t,n){let r=Ir(t);if(r){jr(t),Lo(t),sn(e,t,n,B(process.cwd(),n.path));let I=await Mr(e,{...r,author:t.author,message:t.message,force:t.force},n);return Tc(I,t.fullHistory===!0)}let o=Oe(),s=B(process.cwd(),n.path);await ie(s);let i=await W(s);sn(e,t,n,s),rn(t.measure,"validation"),mo(t,[],void 0);let a=re(i,se()),c=await o.resolveList(t.add,"--add"),d=await o.resolveList(t.addJson,"--add-json"),f=await o.resolveList(t.remove,"--remove"),m=[...yo(c),...vo(d)],p=await mr(m,$(t.author,i.author_default),V())??[],g=To(f),x=Eo(t.removeIndex),h=await pc({id:e,options:t,pmRoot:s,settings:i,typeToFolder:a.type_to_folder,adds:p,removes:g,removeIndexes:x}),w=ft(()=>Ao(t,h.tests)),L=await kc(t,s,h.tests),R=t.run===!0?V():void 0,b=await hc({options:t,runOptions:w,pmRoot:s,untrustedLinkedTestsPolicyEnabled:i.testing.allow_untrusted_linked_tests});Fr(e,t,n,s,b);let N=Qt(b),k=t.run===!0&&t.failOnSkipped===!0&&b.some(I=>I.status==="skipped"),v=_c(t,b);L&&v.push(`linked_test_trust_acknowledged:${L.acknowledged}`);let O=await xc({options:t,pmRoot:s,settings:i,itemId:h.itemId,runStartedAt:R,runResults:b,failOnSkippedTriggered:k,warnings:v}),M=O?.receipt.recorded?ln([...h.testRuns,O.entry]):h.testRuns,A=mo(t,M,O?.entry);return wc({item:h,runResults:b,failureCategories:N,runSelection:w.runSelection,failOnSkippedTriggered:k,warnings:v,recording:O,measurementProjection:A,restoreScope:Ur(n,s),ran:t.run===!0,fullHistory:t.fullHistory===!0})}export{Ct as a,Lt as b,os as c,Mt as d,xe as e,rr as f,Nt as g,fs as h,ms as i,ps as j,de as k,hs as l,At as m,_s as n,gs as o,$t as p,xs as q,ks as r,ws as s,Vc as t,Xc as u,Us as v,Xt as w,Yt as x,Js as y,mr as z,pr as A,Zt as B,fd as C,_r as D,P as E,Be as F,gr as G,wr as H,Qt as I,ne as J,Ve as K,te as L,yr as M,en as N,tn as O,Tr as P,Er as Q,ye as R,Xe as S,nn as T,Sr as U,br as V,Cr as W,ve as X,ci as Y,rn as Z,Lr as _,Ar as $,Xr as aa,Mr as ba,sn as ca,da,kl as ea,wl as fa,Ra as ga,ja as ha,ac as ia,yl as ja};
|
|
10
|
-
//# sourceMappingURL=chunk-
|
|
10
|
+
//# sourceMappingURL=chunk-GOEQXVOI.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as ct,b as Bn,c as vl,d as kl,g as Sl,i as Vl}from"./chunk-NA6D75V5.js";import{L as Ar,U as dd,a as Kl,c as Jl,d as Yl,e as Xl,k as Zl,l as Jt,m as vr,n as kr,u as Sr,w as ld}from"./chunk-SY5C3U32.js";import{$a as Cl,$b as Ce,Ac as hd,Cc as gd,Db as Kn,Dc as yd,Fa as Yc,Ga as Un,H as Vc,I as Kc,K as Jc,Kb as Bl,Mb as Wl,Oa as wl,Qa as xl,Ra as Il,Sb as Jn,Ub as Kt,Uc as xr,Wa as cr,Xa as lr,Xc as bd,Ya as dr,Yb as pr,Yc as vd,_a as El,ab as mr,ac as Ql,b as nr,d as Me,e as Cc,fc as fr,g as rt,ga as je,gc as _r,h as Rc,hc as ed,i as or,ic as td,j as Mn,jc as lt,kc as nd,lb as Ul,nc as id,o as it,ob as ql,oc as sd,pb as zl,pc as ad,qc as cd,rc as yr,sc as br,tc as wr,ub as Vt,wc as pd,x as Bc,xc as ud,y as Wc,yc as fd,zc as _d}from"./chunk-U7RBJGLF.js";import{$a as Ue,Ha as Rl,Jc as hr,Lb as od,Mb as rd,Oc as gr,Ra as Tl,Rc as md,Sa as Ol,Ta as $l,U as _e,Wa as Fl,Xa as Pl,Ya as Nl,Za as Ll,aa as Al,ab as Ml,b as bc,bb as Dl,db as jl,fb as Wn,hb as Gl,lb as Ee,mb as Hl,nb as Vn,rb as ur}from"./chunk-ZL6J6JYT.js";import{A as Bt,B as Dc,C as jc,D as ir,E as Wt,F as Dn,G as De,H as Gc,I as sr,J as U,K as ar,L as j,M as Uc,N as qc,O as jn,Q as zc,R as Gn,S as Hc,n as Ht,o as $c,p as Fc,q as Pc,s as rr,t as st,u as g,v as Nc,w as Lc,y as X,z as Mc}from"./chunk-L2ZSSMYY.js";import{ja as wd}from"./chunk-YSVOXCYH.js";import{A as nl,Ba as yl,C as ol,D as rl,E as il,Ea as bl,F as sl,G as al,H as cl,I as ll,J as dl,K as ml,L as pl,M as ul,N as fl,O as _l,P as hl,Q as gl,d as wc,ka as at,m as qn,o as Ge,p as Qc,q as zn,r as el,x as tl,xa as Hn}from"./chunk-4YQMQOUO.js";import{a as gc,b as yc}from"./chunk-3HKPVOAN.js";import{i as Xc,o as Zc}from"./chunk-Q6K7HWZ7.js";import{_ as Oc,a as Ic,b as Ec,l as Tc}from"./chunk-C6WM6ZN4.js";import{s as ot}from"./chunk-QDV7S2QS.js";import{A as pn,Aa as fe,Bb as Jo,C as ss,Da as sa,Ea as aa,Fb as ka,Ga as En,Gb as Sa,Ha as ca,Hb as Aa,Ib as xa,Jb as Ia,L as _n,Lb as Ea,M as hn,Mb as Ca,N as gn,Na as ua,Nb as Ra,O as yn,Oa as fa,Ob as zt,P as fs,Pb as Ta,Qb as Pn,R as ae,Rb as Oa,Rc as Na,Sb as Yo,T as Zs,Tb as Xo,Ub as $a,V as Qs,Va as Vo,W as ea,Y as ta,Z as na,a as Xi,ab as Tn,cb as On,ga as Ho,ha as Bo,i as $t,ib as ha,j as Zi,k as Qi,kb as ga,kd as Qo,l as es,lb as ya,lc as Zo,m as ts,mb as oe,md as er,na as In,nb as xe,pc as Fa,pd as La,qb as Ut,qc as Pa,qd as Ma,s as ns,sb as $n,t as xo,ta as ra,tb as Fn,u as os,ub as wa,v as le,wb as qt,x as rs,xa as ia,xb as va,y as is,zb as Ko}from"./chunk-CBUC4X7Q.js";import{B as _a,G as ba,H as P,f as oa,g as tt,k as la,l as nt,n as da,q as ma,r as Rn,s as Wo,u as I,v as pa}from"./chunk-OXC5KBIQ.js";import{b as Cn}from"./chunk-3AZOATC2.js";import{$f as Bs,Ad as Ts,Ae as Ds,Ea as Ne,Eg as kn,Ff as vn,Fg as Sn,Ga as Ze,Gg as An,Hb as Po,I as mn,Ib as C,Ig as Vs,Ja as ks,Kd as Os,Kf as et,Ma as Ss,Na as As,Nb as Cs,Nd as $s,Of as js,Og as Lo,P as ls,Q as ds,Qg as Mo,Rg as Do,Sg as jo,Tg as Go,Ua as wn,Ug as Uo,Va as Lt,Vg as qo,Wa as Mt,Wf as Gs,Wg as zo,X as ms,Xf as Us,Xg as T,Yb as No,Yf as qs,Zd as Fs,Zf as zs,_ as Ae,_f as Hs,a as dn,ae as Ps,ag as Ws,ba as Fo,cg as ue,ch as Ks,de as Ns,dh as Js,ea as Nt,fb as Le,gb as Dt,gd as Rs,gh as G,hf as jt,if as Gt,jh as xn,ke as Ls,nb as xs,nh as Ys,ob as Is,oh as Xs,pb as Es,te as Ms,u as Ki,v as Ji,we as Qe,y as Yi,zc as H}from"./chunk-NRQCBUYD.js";import{g as F,h as un,o as x,r as Se,s as $o,u as me}from"./chunk-GSLOAEY2.js";import{b as vc,d as kc,e as Sc,f as Ac,h as xc}from"./chunk-WSEIEDEK.js";import{$a as oc,Ba as Ja,C as ja,Ca as Ya,K as Ga,Ka as Xa,L as Nn,M as Ua,Ma as Za,Sa as Qa,Ta as ec,U as qa,Ua as tc,Xa as nc,Y as za,ab as rc,ba as Ha,bb as ic,ca as Ba,cb as sc,db as ac,ea as Wa,fb as cc,gb as lc,ha as Va,hb as dc,ib as mc,j as tr,jb as pc,kb as uc,nb as fc,ob as Ln,pb as _c,qb as hc,t as Da,vb as Ie,wb as E,ya as Ka}from"./chunk-A5ZEMOVR.js";import{D as cs,Q as S,U as ps,W as us,a as Ot,b as J,ha as vs,i as Y,k as Ao,m as Vi,v as as,x as fn}from"./chunk-I4SPJQQI.js";import{I as Ye,K as pe,L as _s,M as bn,N as hs,P as Fe,R as gs,V as ys,Z as Pe,_ as bs,a as Pt,ba as W,c as Eo,da as Xe,ea as ws,v as Co,w as Ro,x as To,y as Oo}from"./chunk-TE6FBDHP.js";import{A as u,C as p,E as ke,F as Je,G as Io,H as de,L as se,N as Ft,a as Ui,e as qi,f as zi,g as Hi,i as Bi,m as Wi}from"./chunk-K672XXGQ.js";import{AsyncLocalStorage as sb}from"node:async_hooks";import{realpathSync as ab}from"node:fs";import Mi from"node:path";import{readFile as xu}from"node:fs/promises";import Iu from"node:path";var Ir="context-intents.json";function Yn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Eu(e,t,n){if(!Yn(e))throw new TypeError(`${t} context intent at index ${String(n)} must be an object`);let o=e.included_field_groups;if(typeof e.command!="string"||typeof e.intent!="string"||typeof e.description!="string"||!Array.isArray(o)||!o.every(r=>typeof r=="string")||typeof e.token_budget!="number")throw new TypeError(`${t} context intent at index ${String(n)} has an invalid contract shape`);return{command:e.command,intent:e.intent,description:e.description,included_field_groups:o,token_budget:e.token_budget}}function kd(e,t){let n=Array.isArray(e)?e:Yn(e)&&Array.isArray(e.intents)?e.intents:void 0;if(!n)throw new TypeError(`${t} context intents must be an array or an object with an intents array`);return n.map((o,r)=>Eu(o,t,r))}async function Cu(e){let t=Iu.join(e,Ir),n;try{n=await xu(t,"utf8")}catch(r){if(Je(r))return[];throw await ba(e),r}let o;try{o=JSON.parse(n)}catch(r){let i=r instanceof Error?r.message:String(r);throw new TypeError(`Invalid ${Ir}: ${i}`,{cause:r})}return kd(o,Ir)}function Ru(e){if(!Yn(e))return;let t=e.contextIntents??e.context_intents;if(t!==void 0)return t;let n=e.default;return Yn(n)?n.contextIntents??n.context_intents:void 0}function Tu(e){return e.flatMap(t=>{let n=Ru(t.module);return n===void 0?[]:kd(n,`package ${t.name}`)})}async function Ou(e){let t=await Cu(e.pmRoot),n=Tu(e.packages??[]);return{workspaceContracts:t,packageContracts:n}}async function Er(e,t){let n=await Ou(e);return await Ms(n,t)}async function Sd(e,t,n=Ls){try{await n({pmRoot:e,result:t})}catch{if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let o=t,r=Array.isArray(o.warnings)?o.warnings.filter(i=>typeof i=="string"):[];o.warnings=[...new Set([...r,"context_usage_feedback_write_failed"])].sort()}}}import{createHash as Gu}from"node:crypto";var Yt=class extends RangeError{code;work;minimum_tokens;constructor(t,n,o){super(t),this.name="OutputEnvelopeFitError",this.code=t,this.work=Object.freeze({...n}),this.minimum_tokens=o}};function Cr(e,t){if(!Number.isSafeInteger(e)||e<1)throw new RangeError(`${t} must be a positive safe integer`)}function $u(e,t,n,o){return t.map(([r,i])=>{if(o.render_calls>=o.max_render_calls)throw new Yt("output_envelope_work_limit",o);o.render_calls+=1;let s=i(e);if(typeof s!="string")throw new TypeError("Envelope renderers must return strings");let a=n(s);if(!Number.isSafeInteger(a)||a<0)throw new RangeError("Envelope token estimates must be non-negative safe integers");return{name:r,text:s,bytes:Buffer.byteLength(s,"utf8"),estimated_tokens:a}})}function Ad(e,t,n,o){let r=t,i=Object.entries(n.renderers),s=n.estimateTokens??(a=>Rs(Buffer.byteLength(a,"utf8")));for(let a=0;a<(n.maxStabilizationPasses??16);a+=1){let c=Object.freeze({...r}),l={...n.buildEnvelope(e,c),output_fit:c},d=$u(l,i,s,o),m=Math.max(...d.map(h=>h.bytes)),f=Math.max(...d.map(h=>h.estimated_tokens));if(m===r.output_bytes&&f===r.estimated_tokens)return{envelope:l,renderings:d};r={...r,output_bytes:m,estimated_tokens:f}}throw new Yt("output_envelope_unstable",o)}function xd(e,t){Cr(t.tokenBudget,"tokenBudget"),Cr(t.maxRenderCalls??1e4,"maxRenderCalls"),Cr(t.maxStabilizationPasses??16,"maxStabilizationPasses");let n=t.policy??"prefix";if(n!=="prefix"&&n!=="skip")throw new TypeError("Unknown output envelope fit policy");if(Object.entries(t.renderers).length===0||Object.entries(t.renderers).some(([c,l])=>!c.trim()||typeof l!="function"))throw new TypeError("Envelope fitting requires named callable renderers");let o={evaluated_candidates:0,render_calls:0,max_render_calls:t.maxRenderCalls??1e4},r=[],i=[],s=c=>({version:1,policy:n,total_candidates:e.length,included_indices:Object.freeze([...c]),omitted_count:e.length-c.length,token_budget:t.tokenBudget,estimated_tokens:0,output_bytes:0}),a=Ad(r,s(i),t,o);if(a.envelope.output_fit.estimated_tokens>t.tokenBudget)throw new Yt("output_envelope_infeasible",o,a.envelope.output_fit.estimated_tokens);for(let[c,l]of e.entries()){o.evaluated_candidates+=1;let d=[...r,l],m=[...i,c],f=Ad(d,s(m),t,o);if(f.envelope.output_fit.estimated_tokens<=t.tokenBudget)r=d,i=m,a=f;else if(n==="prefix")break}return{rows:r,...a,complete:r.length===e.length,work:Object.freeze({...o})}}import{constants as Xt}from"node:fs";import{lstat as Id,mkdir as Tr,open as Ed}from"node:fs/promises";import he from"node:path";function Rr(e,t){if(typeof e!="string"||e.trim().length===0)throw new TypeError(`Relationship event ${t} must be non-empty`);return e.trim()}function Or(e,t){let n=t.require(e.kind),o=n.direction==="undirected"?[e.source,e.target].sort().join("\0"):`${e.source}\0${e.target}`;return`${n.kind}\0${o}`}function Fu(e){return Object.freeze({...e,...e.payload===void 0?{}:{payload:Object.freeze(structuredClone(e.payload))}})}function Pu(e,t,n,o){let r=n.require(e.kind),i=o.outgoingOne.get(`${r.kind}\0${e.source}`);if(i!==void 0&&i!==t)throw new TypeError(`Relationship outgoing cardinality exceeded for ${r.kind}`);let s=o.incomingOne.get(`${r.kind}\0${e.target}`);if(s!==void 0&&s!==t)throw new TypeError(`Relationship incoming cardinality exceeded for ${r.kind}`);let a=Or(e,n),c=o.identities.get(a);if(c!==void 0&&c!==t)throw new TypeError(`Relationship edge already active: ${a}`)}function Nu(e){let t=new Map;for(let n of e)n.action==="remove"?t.delete(n.relationshipId):t.set(n.relationshipId,n.edge);return t}function Lu(e,t,n){if(e.expectedVersion!==void 0&&e.expectedVersion!==t)throw new TypeError(`Relationship event version conflict: expected ${e.expectedVersion}, current ${t}`);let o=Rr(e.eventId,"eventId");if(n.has(o))throw new TypeError(`Relationship event already exists: ${o}`);if(e.action!=="add"&&e.action!=="remove"&&e.action!=="supersede")throw new TypeError(`Unknown relationship event action: ${e.action}`);if(!Number.isFinite(Date.parse(e.timestamp)))throw new TypeError("Relationship event timestamp must be valid");return{eventId:o,relationshipId:Rr(e.relationshipId,"relationshipId"),author:Rr(e.author,"author"),timestamp:new Date(e.timestamp).toISOString()}}function Mu(e,t,n,o,r,i){let s=n.has(t);if(e.action==="add"&&s)throw new TypeError(`Relationship is already active: ${t}`);if(e.action!=="add"&&!s)throw new TypeError(`Relationship is not active: ${t}`);if(e.action==="remove")return;if(!e.edge)throw new TypeError(`Relationship ${e.action} event requires an edge`);let a=typeof e.edge.source=="string"?e.edge.source.trim():"",c=typeof e.edge.target=="string"?e.edge.target.trim():"";if(!o.has(a)||!o.has(c))throw new TypeError(`Relationship endpoint not found: ${a} -> ${c}`);let l=new et([a,c],[e.edge],r).edges()[0];return Pu(l,t,r,i),Fu(l)}var Zt=class{#t;#n;#o=[];#i=new Set;#e=new Map;#r={identities:new Map,outgoingOne:new Map,incomingOne:new Map};constructor(t,n={}){this.#t=new Set([...t].filter(o=>typeof o=="string").map(o=>o.trim()).filter(Boolean)),this.#n=n.registry??vn()}get version(){return this.#o.length}events(){return Object.freeze([...this.#o])}*stream(t={}){let n=t.fromVersion??1,o=t.toVersion??this.version,r=t.batchSize??100;if(!Number.isInteger(n)||n<1)throw new TypeError("Relationship event stream fromVersion must be positive");if(!Number.isInteger(o)||o<0||o>this.version)throw new TypeError(`Relationship event stream toVersion out of range: ${o}`);if(!Number.isInteger(r)||r<1)throw new TypeError("Relationship event stream batchSize must be positive");if(n>o+1)throw new TypeError("Relationship event stream fromVersion exceeds the selected prefix");for(let i=n-1;i<o;i+=r)yield Object.freeze(this.#o.slice(i,Math.min(i+r,o)))}project(t,n,o={}){if(typeof n!="function")throw new TypeError("Relationship event projection requires a reducer");let r=t,i=0,s;for(let a of this.stream({...o,batchSize:256}))for(let c of a)r=n(r,c),i+=1,s=c;return Object.freeze({state:r,version:s?.sequence??Math.max(0,(o.fromVersion??1)-1),processed:i,...s===void 0?{}:{asOf:s.timestamp}})}#s(t,n){let o=this.#n.require(n.kind);this.#r.identities.set(Or(n,this.#n),t),o.outgoing==="one"&&this.#r.outgoingOne.set(`${o.kind}\0${n.source}`,t),o.incoming==="one"&&this.#r.incomingOne.set(`${o.kind}\0${n.target}`,t)}#a(t){let n=this.#n.require(t.kind);this.#r.identities.delete(Or(t,this.#n)),n.outgoing==="one"&&this.#r.outgoingOne.delete(`${n.kind}\0${t.source}`),n.incoming==="one"&&this.#r.incomingOne.delete(`${n.kind}\0${t.target}`)}append(t){let n=Lu(t,this.version,this.#i),o=this.#e.get(n.relationshipId),r=Mu(t,n.relationshipId,this.#e,this.#t,this.#n,this.#r),i=Object.freeze({eventId:n.eventId,relationshipId:n.relationshipId,action:t.action,...r===void 0?{}:{edge:r},author:n.author,timestamp:n.timestamp,...t.reason?.trim()?{reason:t.reason.trim()}:{},sequence:this.version+1});return this.#o.push(i),this.#i.add(n.eventId),o&&this.#a(o),t.action==="remove"?this.#e.delete(n.relationshipId):(this.#e.set(n.relationshipId,r),this.#s(n.relationshipId,r)),i}snapshot(t={}){if(t.atVersion!==void 0&&t.atTimestamp!==void 0)throw new TypeError("Relationship snapshot accepts one target");let n;if(t.atTimestamp!==void 0){let i=Date.parse(t.atTimestamp);if(!Number.isFinite(i))throw new TypeError("Relationship snapshot timestamp must be valid");n=this.#o.filter(s=>Date.parse(s.timestamp)<=i)}else{let i=t.atVersion??this.version;if(!Number.isInteger(i)||i<0||i>this.version)throw new TypeError(`Relationship snapshot version out of range: ${i}`);n=this.#o.slice(0,i)}let o=Nu(n),r=new et(this.#t,o.values(),this.#n);return Object.freeze({version:n.at(-1)?.sequence??0,...n.at(-1)?{asOf:n.at(-1).timestamp}:{},edges:r.edges(),graph:r})}page(t){if(!Number.isInteger(t.limit)||t.limit<1)throw new TypeError("Relationship event page limit must be positive");let n=Fs("relationship-events",{order:"append-sequence"}),o=t.cursor===void 0?this.version:Number(Ps(t.cursor,n).snapshot);if(!Number.isSafeInteger(o)||o<0||o>this.version)throw new TypeError("Relationship event cursor snapshot version is invalid");let r=Ns(this.#o.slice(0,o),{cursor:t.cursor,fingerprint:n,limit:t.limit,readId:i=>i.eventId,snapshot:String(o)});return{version:o,events:r.rows,hasMore:r.has_more,...r.next_cursor?{nextCursor:r.next_cursor}:{}}}},Du="relationship-event-store",Cd=Xt.O_NOFOLLOW;function Xn(e){return Le(e,Du,30,`relationship-store:${process.pid}`,!1,!1,3e3)}async function qe(e,t="relationships/events.jsonl"){let n=he.resolve(e),o=he.resolve(n,t),r=he.relative(n,o);if(r.length===0)throw new TypeError("Relationship event path must name a file within the tracker root");if(r===".."||r.startsWith(`..${he.sep}`)||he.isAbsolute(r))throw new TypeError("Relationship event path must stay within the tracker root");if(await Tr(n,{recursive:!0}),(await Id(n)).isSymbolicLink())throw new TypeError("Relationship event tracker root must not be a symbolic link");let s=n;for(let a of r.split(he.sep)){s=he.join(s,a);try{if((await Id(s)).isSymbolicLink())throw new TypeError("Relationship event path must not contain symbolic links")}catch(c){if(Io(c))break;throw c}}return o}async function Zn(e,t,n){let o=new Zt(t,{registry:n}),r,i;try{i=await Ed(e,Xt.O_RDONLY|Cd),r=await i.readFile("utf8")}catch(a){if(Io(a))return{log:o,raw:""};throw a}finally{await i?.close()}let s=r.split(`
|
|
1
|
+
import{a as ct,b as Bn,c as vl,d as kl,g as Sl,i as Vl}from"./chunk-G6TARHFK.js";import{L as Ar,U as dd,a as Kl,c as Jl,d as Yl,e as Xl,k as Zl,l as Jt,m as vr,n as kr,u as Sr,w as ld}from"./chunk-SY5C3U32.js";import{$a as Cl,$b as Ce,Ac as hd,Cc as gd,Db as Kn,Dc as yd,Fa as Yc,Ga as Un,H as Vc,I as Kc,K as Jc,Kb as Bl,Mb as Wl,Oa as wl,Qa as xl,Ra as Il,Sb as Jn,Ub as Kt,Uc as xr,Wa as cr,Xa as lr,Xc as bd,Ya as dr,Yb as pr,Yc as vd,_a as El,ab as mr,ac as Ql,b as nr,d as Me,e as Cc,fc as fr,g as rt,ga as je,gc as _r,h as Rc,hc as ed,i as or,ic as td,j as Mn,jc as lt,kc as nd,lb as Ul,nc as id,o as it,ob as ql,oc as sd,pb as zl,pc as ad,qc as cd,rc as yr,sc as br,tc as wr,ub as Vt,wc as pd,x as Bc,xc as ud,y as Wc,yc as fd,zc as _d}from"./chunk-SDXCJZKB.js";import{$a as Ue,Ha as Rl,Jc as hr,Lb as od,Mb as rd,Oc as gr,Ra as Tl,Rc as md,Sa as Ol,Ta as $l,U as _e,Wa as Fl,Xa as Pl,Ya as Nl,Za as Ll,aa as Al,ab as Ml,b as bc,bb as Dl,db as jl,fb as Wn,hb as Gl,lb as Ee,mb as Hl,nb as Vn,rb as ur}from"./chunk-ZL6J6JYT.js";import{A as Bt,B as Dc,C as jc,D as ir,E as Wt,F as Dn,G as De,H as Gc,I as sr,J as U,K as ar,L as j,M as Uc,N as qc,O as jn,Q as zc,R as Gn,S as Hc,n as Ht,o as $c,p as Fc,q as Pc,s as rr,t as st,u as g,v as Nc,w as Lc,y as X,z as Mc}from"./chunk-L2ZSSMYY.js";import{ja as wd}from"./chunk-GOEQXVOI.js";import{A as nl,Ba as yl,C as ol,D as rl,E as il,Ea as bl,F as sl,G as al,H as cl,I as ll,J as dl,K as ml,L as pl,M as ul,N as fl,O as _l,P as hl,Q as gl,d as wc,ka as at,m as qn,o as Ge,p as Qc,q as zn,r as el,x as tl,xa as Hn}from"./chunk-7V65VACG.js";import{a as gc,b as yc}from"./chunk-3HKPVOAN.js";import{i as Xc,o as Zc}from"./chunk-Q6K7HWZ7.js";import{_ as Oc,a as Ic,b as Ec,l as Tc}from"./chunk-C6WM6ZN4.js";import{s as ot}from"./chunk-QDV7S2QS.js";import{A as pn,Aa as fe,Bb as Jo,C as ss,Da as sa,Ea as aa,Fb as ka,Ga as En,Gb as Sa,Ha as ca,Hb as Aa,Ib as xa,Jb as Ia,L as _n,Lb as Ea,M as hn,Mb as Ca,N as gn,Na as ua,Nb as Ra,O as yn,Oa as fa,Ob as zt,P as fs,Pb as Ta,Qb as Pn,R as ae,Rb as Oa,Rc as Na,Sb as Yo,T as Zs,Tb as Xo,Ub as $a,V as Qs,Va as Vo,W as ea,Y as ta,Z as na,a as Xi,ab as Tn,cb as On,ga as Ho,ha as Bo,i as $t,ib as ha,j as Zi,k as Qi,kb as ga,kd as Qo,l as es,lb as ya,lc as Zo,m as ts,mb as oe,md as er,na as In,nb as xe,pc as Fa,pd as La,qb as Ut,qc as Pa,qd as Ma,s as ns,sb as $n,t as xo,ta as ra,tb as Fn,u as os,ub as wa,v as le,wb as qt,x as rs,xa as ia,xb as va,y as is,zb as Ko}from"./chunk-CBUC4X7Q.js";import{B as _a,G as ba,H as P,f as oa,g as tt,k as la,l as nt,n as da,q as ma,r as Rn,s as Wo,u as I,v as pa}from"./chunk-OXC5KBIQ.js";import{b as Cn}from"./chunk-3AZOATC2.js";import{$f as Bs,Ad as Ts,Ae as Ds,Ea as Ne,Eg as kn,Ff as vn,Fg as Sn,Ga as Ze,Gg as An,Hb as Po,I as mn,Ib as C,Ig as Vs,Ja as ks,Kd as Os,Kf as et,Ma as Ss,Na as As,Nb as Cs,Nd as $s,Of as js,Og as Lo,P as ls,Q as ds,Qg as Mo,Rg as Do,Sg as jo,Tg as Go,Ua as wn,Ug as Uo,Va as Lt,Vg as qo,Wa as Mt,Wf as Gs,Wg as zo,X as ms,Xf as Us,Xg as T,Yb as No,Yf as qs,Zd as Fs,Zf as zs,_ as Ae,_f as Hs,a as dn,ae as Ps,ag as Ws,ba as Fo,cg as ue,ch as Ks,de as Ns,dh as Js,ea as Nt,fb as Le,gb as Dt,gd as Rs,gh as G,hf as jt,if as Gt,jh as xn,ke as Ls,nb as xs,nh as Ys,ob as Is,oh as Xs,pb as Es,te as Ms,u as Ki,v as Ji,we as Qe,y as Yi,zc as H}from"./chunk-NRQCBUYD.js";import{g as F,h as un,o as x,r as Se,s as $o,u as me}from"./chunk-GSLOAEY2.js";import{b as vc,d as kc,e as Sc,f as Ac,h as xc}from"./chunk-WSEIEDEK.js";import{$a as oc,Ba as Ja,C as ja,Ca as Ya,K as Ga,Ka as Xa,L as Nn,M as Ua,Ma as Za,Sa as Qa,Ta as ec,U as qa,Ua as tc,Xa as nc,Y as za,ab as rc,ba as Ha,bb as ic,ca as Ba,cb as sc,db as ac,ea as Wa,fb as cc,gb as lc,ha as Va,hb as dc,ib as mc,j as tr,jb as pc,kb as uc,nb as fc,ob as Ln,pb as _c,qb as hc,t as Da,vb as Ie,wb as E,ya as Ka}from"./chunk-A5ZEMOVR.js";import{D as cs,Q as S,U as ps,W as us,a as Ot,b as J,ha as vs,i as Y,k as Ao,m as Vi,v as as,x as fn}from"./chunk-I4SPJQQI.js";import{I as Ye,K as pe,L as _s,M as bn,N as hs,P as Fe,R as gs,V as ys,Z as Pe,_ as bs,a as Pt,ba as W,c as Eo,da as Xe,ea as ws,v as Co,w as Ro,x as To,y as Oo}from"./chunk-TE6FBDHP.js";import{A as u,C as p,E as ke,F as Je,G as Io,H as de,L as se,N as Ft,a as Ui,e as qi,f as zi,g as Hi,i as Bi,m as Wi}from"./chunk-K672XXGQ.js";import{AsyncLocalStorage as sb}from"node:async_hooks";import{realpathSync as ab}from"node:fs";import Mi from"node:path";import{readFile as xu}from"node:fs/promises";import Iu from"node:path";var Ir="context-intents.json";function Yn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Eu(e,t,n){if(!Yn(e))throw new TypeError(`${t} context intent at index ${String(n)} must be an object`);let o=e.included_field_groups;if(typeof e.command!="string"||typeof e.intent!="string"||typeof e.description!="string"||!Array.isArray(o)||!o.every(r=>typeof r=="string")||typeof e.token_budget!="number")throw new TypeError(`${t} context intent at index ${String(n)} has an invalid contract shape`);return{command:e.command,intent:e.intent,description:e.description,included_field_groups:o,token_budget:e.token_budget}}function kd(e,t){let n=Array.isArray(e)?e:Yn(e)&&Array.isArray(e.intents)?e.intents:void 0;if(!n)throw new TypeError(`${t} context intents must be an array or an object with an intents array`);return n.map((o,r)=>Eu(o,t,r))}async function Cu(e){let t=Iu.join(e,Ir),n;try{n=await xu(t,"utf8")}catch(r){if(Je(r))return[];throw await ba(e),r}let o;try{o=JSON.parse(n)}catch(r){let i=r instanceof Error?r.message:String(r);throw new TypeError(`Invalid ${Ir}: ${i}`,{cause:r})}return kd(o,Ir)}function Ru(e){if(!Yn(e))return;let t=e.contextIntents??e.context_intents;if(t!==void 0)return t;let n=e.default;return Yn(n)?n.contextIntents??n.context_intents:void 0}function Tu(e){return e.flatMap(t=>{let n=Ru(t.module);return n===void 0?[]:kd(n,`package ${t.name}`)})}async function Ou(e){let t=await Cu(e.pmRoot),n=Tu(e.packages??[]);return{workspaceContracts:t,packageContracts:n}}async function Er(e,t){let n=await Ou(e);return await Ms(n,t)}async function Sd(e,t,n=Ls){try{await n({pmRoot:e,result:t})}catch{if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let o=t,r=Array.isArray(o.warnings)?o.warnings.filter(i=>typeof i=="string"):[];o.warnings=[...new Set([...r,"context_usage_feedback_write_failed"])].sort()}}}import{createHash as Gu}from"node:crypto";var Yt=class extends RangeError{code;work;minimum_tokens;constructor(t,n,o){super(t),this.name="OutputEnvelopeFitError",this.code=t,this.work=Object.freeze({...n}),this.minimum_tokens=o}};function Cr(e,t){if(!Number.isSafeInteger(e)||e<1)throw new RangeError(`${t} must be a positive safe integer`)}function $u(e,t,n,o){return t.map(([r,i])=>{if(o.render_calls>=o.max_render_calls)throw new Yt("output_envelope_work_limit",o);o.render_calls+=1;let s=i(e);if(typeof s!="string")throw new TypeError("Envelope renderers must return strings");let a=n(s);if(!Number.isSafeInteger(a)||a<0)throw new RangeError("Envelope token estimates must be non-negative safe integers");return{name:r,text:s,bytes:Buffer.byteLength(s,"utf8"),estimated_tokens:a}})}function Ad(e,t,n,o){let r=t,i=Object.entries(n.renderers),s=n.estimateTokens??(a=>Rs(Buffer.byteLength(a,"utf8")));for(let a=0;a<(n.maxStabilizationPasses??16);a+=1){let c=Object.freeze({...r}),l={...n.buildEnvelope(e,c),output_fit:c},d=$u(l,i,s,o),m=Math.max(...d.map(h=>h.bytes)),f=Math.max(...d.map(h=>h.estimated_tokens));if(m===r.output_bytes&&f===r.estimated_tokens)return{envelope:l,renderings:d};r={...r,output_bytes:m,estimated_tokens:f}}throw new Yt("output_envelope_unstable",o)}function xd(e,t){Cr(t.tokenBudget,"tokenBudget"),Cr(t.maxRenderCalls??1e4,"maxRenderCalls"),Cr(t.maxStabilizationPasses??16,"maxStabilizationPasses");let n=t.policy??"prefix";if(n!=="prefix"&&n!=="skip")throw new TypeError("Unknown output envelope fit policy");if(Object.entries(t.renderers).length===0||Object.entries(t.renderers).some(([c,l])=>!c.trim()||typeof l!="function"))throw new TypeError("Envelope fitting requires named callable renderers");let o={evaluated_candidates:0,render_calls:0,max_render_calls:t.maxRenderCalls??1e4},r=[],i=[],s=c=>({version:1,policy:n,total_candidates:e.length,included_indices:Object.freeze([...c]),omitted_count:e.length-c.length,token_budget:t.tokenBudget,estimated_tokens:0,output_bytes:0}),a=Ad(r,s(i),t,o);if(a.envelope.output_fit.estimated_tokens>t.tokenBudget)throw new Yt("output_envelope_infeasible",o,a.envelope.output_fit.estimated_tokens);for(let[c,l]of e.entries()){o.evaluated_candidates+=1;let d=[...r,l],m=[...i,c],f=Ad(d,s(m),t,o);if(f.envelope.output_fit.estimated_tokens<=t.tokenBudget)r=d,i=m,a=f;else if(n==="prefix")break}return{rows:r,...a,complete:r.length===e.length,work:Object.freeze({...o})}}import{constants as Xt}from"node:fs";import{lstat as Id,mkdir as Tr,open as Ed}from"node:fs/promises";import he from"node:path";function Rr(e,t){if(typeof e!="string"||e.trim().length===0)throw new TypeError(`Relationship event ${t} must be non-empty`);return e.trim()}function Or(e,t){let n=t.require(e.kind),o=n.direction==="undirected"?[e.source,e.target].sort().join("\0"):`${e.source}\0${e.target}`;return`${n.kind}\0${o}`}function Fu(e){return Object.freeze({...e,...e.payload===void 0?{}:{payload:Object.freeze(structuredClone(e.payload))}})}function Pu(e,t,n,o){let r=n.require(e.kind),i=o.outgoingOne.get(`${r.kind}\0${e.source}`);if(i!==void 0&&i!==t)throw new TypeError(`Relationship outgoing cardinality exceeded for ${r.kind}`);let s=o.incomingOne.get(`${r.kind}\0${e.target}`);if(s!==void 0&&s!==t)throw new TypeError(`Relationship incoming cardinality exceeded for ${r.kind}`);let a=Or(e,n),c=o.identities.get(a);if(c!==void 0&&c!==t)throw new TypeError(`Relationship edge already active: ${a}`)}function Nu(e){let t=new Map;for(let n of e)n.action==="remove"?t.delete(n.relationshipId):t.set(n.relationshipId,n.edge);return t}function Lu(e,t,n){if(e.expectedVersion!==void 0&&e.expectedVersion!==t)throw new TypeError(`Relationship event version conflict: expected ${e.expectedVersion}, current ${t}`);let o=Rr(e.eventId,"eventId");if(n.has(o))throw new TypeError(`Relationship event already exists: ${o}`);if(e.action!=="add"&&e.action!=="remove"&&e.action!=="supersede")throw new TypeError(`Unknown relationship event action: ${e.action}`);if(!Number.isFinite(Date.parse(e.timestamp)))throw new TypeError("Relationship event timestamp must be valid");return{eventId:o,relationshipId:Rr(e.relationshipId,"relationshipId"),author:Rr(e.author,"author"),timestamp:new Date(e.timestamp).toISOString()}}function Mu(e,t,n,o,r,i){let s=n.has(t);if(e.action==="add"&&s)throw new TypeError(`Relationship is already active: ${t}`);if(e.action!=="add"&&!s)throw new TypeError(`Relationship is not active: ${t}`);if(e.action==="remove")return;if(!e.edge)throw new TypeError(`Relationship ${e.action} event requires an edge`);let a=typeof e.edge.source=="string"?e.edge.source.trim():"",c=typeof e.edge.target=="string"?e.edge.target.trim():"";if(!o.has(a)||!o.has(c))throw new TypeError(`Relationship endpoint not found: ${a} -> ${c}`);let l=new et([a,c],[e.edge],r).edges()[0];return Pu(l,t,r,i),Fu(l)}var Zt=class{#t;#n;#o=[];#i=new Set;#e=new Map;#r={identities:new Map,outgoingOne:new Map,incomingOne:new Map};constructor(t,n={}){this.#t=new Set([...t].filter(o=>typeof o=="string").map(o=>o.trim()).filter(Boolean)),this.#n=n.registry??vn()}get version(){return this.#o.length}events(){return Object.freeze([...this.#o])}*stream(t={}){let n=t.fromVersion??1,o=t.toVersion??this.version,r=t.batchSize??100;if(!Number.isInteger(n)||n<1)throw new TypeError("Relationship event stream fromVersion must be positive");if(!Number.isInteger(o)||o<0||o>this.version)throw new TypeError(`Relationship event stream toVersion out of range: ${o}`);if(!Number.isInteger(r)||r<1)throw new TypeError("Relationship event stream batchSize must be positive");if(n>o+1)throw new TypeError("Relationship event stream fromVersion exceeds the selected prefix");for(let i=n-1;i<o;i+=r)yield Object.freeze(this.#o.slice(i,Math.min(i+r,o)))}project(t,n,o={}){if(typeof n!="function")throw new TypeError("Relationship event projection requires a reducer");let r=t,i=0,s;for(let a of this.stream({...o,batchSize:256}))for(let c of a)r=n(r,c),i+=1,s=c;return Object.freeze({state:r,version:s?.sequence??Math.max(0,(o.fromVersion??1)-1),processed:i,...s===void 0?{}:{asOf:s.timestamp}})}#s(t,n){let o=this.#n.require(n.kind);this.#r.identities.set(Or(n,this.#n),t),o.outgoing==="one"&&this.#r.outgoingOne.set(`${o.kind}\0${n.source}`,t),o.incoming==="one"&&this.#r.incomingOne.set(`${o.kind}\0${n.target}`,t)}#a(t){let n=this.#n.require(t.kind);this.#r.identities.delete(Or(t,this.#n)),n.outgoing==="one"&&this.#r.outgoingOne.delete(`${n.kind}\0${t.source}`),n.incoming==="one"&&this.#r.incomingOne.delete(`${n.kind}\0${t.target}`)}append(t){let n=Lu(t,this.version,this.#i),o=this.#e.get(n.relationshipId),r=Mu(t,n.relationshipId,this.#e,this.#t,this.#n,this.#r),i=Object.freeze({eventId:n.eventId,relationshipId:n.relationshipId,action:t.action,...r===void 0?{}:{edge:r},author:n.author,timestamp:n.timestamp,...t.reason?.trim()?{reason:t.reason.trim()}:{},sequence:this.version+1});return this.#o.push(i),this.#i.add(n.eventId),o&&this.#a(o),t.action==="remove"?this.#e.delete(n.relationshipId):(this.#e.set(n.relationshipId,r),this.#s(n.relationshipId,r)),i}snapshot(t={}){if(t.atVersion!==void 0&&t.atTimestamp!==void 0)throw new TypeError("Relationship snapshot accepts one target");let n;if(t.atTimestamp!==void 0){let i=Date.parse(t.atTimestamp);if(!Number.isFinite(i))throw new TypeError("Relationship snapshot timestamp must be valid");n=this.#o.filter(s=>Date.parse(s.timestamp)<=i)}else{let i=t.atVersion??this.version;if(!Number.isInteger(i)||i<0||i>this.version)throw new TypeError(`Relationship snapshot version out of range: ${i}`);n=this.#o.slice(0,i)}let o=Nu(n),r=new et(this.#t,o.values(),this.#n);return Object.freeze({version:n.at(-1)?.sequence??0,...n.at(-1)?{asOf:n.at(-1).timestamp}:{},edges:r.edges(),graph:r})}page(t){if(!Number.isInteger(t.limit)||t.limit<1)throw new TypeError("Relationship event page limit must be positive");let n=Fs("relationship-events",{order:"append-sequence"}),o=t.cursor===void 0?this.version:Number(Ps(t.cursor,n).snapshot);if(!Number.isSafeInteger(o)||o<0||o>this.version)throw new TypeError("Relationship event cursor snapshot version is invalid");let r=Ns(this.#o.slice(0,o),{cursor:t.cursor,fingerprint:n,limit:t.limit,readId:i=>i.eventId,snapshot:String(o)});return{version:o,events:r.rows,hasMore:r.has_more,...r.next_cursor?{nextCursor:r.next_cursor}:{}}}},Du="relationship-event-store",Cd=Xt.O_NOFOLLOW;function Xn(e){return Le(e,Du,30,`relationship-store:${process.pid}`,!1,!1,3e3)}async function qe(e,t="relationships/events.jsonl"){let n=he.resolve(e),o=he.resolve(n,t),r=he.relative(n,o);if(r.length===0)throw new TypeError("Relationship event path must name a file within the tracker root");if(r===".."||r.startsWith(`..${he.sep}`)||he.isAbsolute(r))throw new TypeError("Relationship event path must stay within the tracker root");if(await Tr(n,{recursive:!0}),(await Id(n)).isSymbolicLink())throw new TypeError("Relationship event tracker root must not be a symbolic link");let s=n;for(let a of r.split(he.sep)){s=he.join(s,a);try{if((await Id(s)).isSymbolicLink())throw new TypeError("Relationship event path must not contain symbolic links")}catch(c){if(Io(c))break;throw c}}return o}async function Zn(e,t,n){let o=new Zt(t,{registry:n}),r,i;try{i=await Ed(e,Xt.O_RDONLY|Cd),r=await i.readFile("utf8")}catch(a){if(Io(a))return{log:o,raw:""};throw a}finally{await i?.close()}let s=r.split(`
|
|
2
2
|
`);for(let a=0;a<s.length;a+=1){let c=s[a].trim();if(!c)continue;let l;try{l=JSON.parse(c)}catch{throw new TypeError(`Invalid relationship event JSONL at line ${a+1}`)}if(l.sequence!==o.version+1)throw new TypeError(`Invalid relationship event sequence at line ${a+1}`);o.append({eventId:l.eventId,relationshipId:l.relationshipId,action:l.action,...l.edge===void 0?{}:{edge:l.edge},author:l.author,timestamp:l.timestamp,...l.reason===void 0?{}:{reason:l.reason},expectedVersion:o.version})}return{log:o,raw:r}}function ju(e,t,n,o){let r=Date.parse(t.timestamp),i;return t.action!=="remove"&&t.edge!==void 0&&(i=new et(n,[t.edge],o).edges()[0]),e.eventId===t.eventId.trim()&&e.relationshipId===t.relationshipId.trim()&&e.action===t.action&&e.author===t.author.trim()&&Number.isFinite(r)&&e.timestamp===new Date(r).toISOString()&&e.reason===(t.reason?.trim()||void 0)&&Ot(e.edge)===Ot(i)}var Qn=class e{#t;#n;#o;#i;#e;constructor(t,n,o,r){this.#t=t.pmRoot,this.#n=n,this.#o=t.registry,this.#i=o,this.#e=r}static async open(t){let n=Object.freeze([...t.nodes]),o=await qe(t.pmRoot,t.relativePath),r=await Xn(t.pmRoot);try{await qe(t.pmRoot,o);let{log:i}=await Zn(o,n,t.registry);return new e(t,n,o,i)}finally{await r()}}get path(){return this.#i}async currentVersion(){return this.#e=await this.#r(),this.#e.version}async append(t){let n=await Xn(this.#t);try{let o=await qe(this.#t,this.#i),{log:r}=await Zn(o,this.#n,this.#o),i=r.append(t);await Tr(he.dirname(o),{recursive:!0}),await qe(this.#t,o);let s=await Ed(o,Xt.O_APPEND|Xt.O_CREAT|Xt.O_WRONLY|Cd);try{await s.appendFile(`${JSON.stringify(i)}
|
|
3
3
|
`,"utf8")}finally{await s.close()}return this.#e=r,i}finally{await n()}}async appendBatch(t,n={}){let o=await Xn(this.#t);try{let r=await qe(this.#t,this.#i),{log:i,raw:s}=await Zn(r,this.#n,this.#o),a=i.version,c=new Map(i.events().map(m=>[m.eventId,m])),l=[],d=[];for(let m of t){let f=m.eventId.trim(),h=c.get(f);if(h!==void 0){if(n.existingEventPolicy==="skip_identical"&&ju(h,m,this.#n,this.#o)){d.push(h.eventId);continue}if(n.existingEventPolicy==="skip_identical")throw new TypeError(`Relationship event id collision with different content: ${f}`)}let y=i.append(m);c.set(y.eventId,y),l.push(y)}if(l.length>0){let m=s.length===0||s.endsWith(`
|
|
4
4
|
`)?s:`${s}
|
|
@@ -2285,5 +2285,5 @@ compdef _pm pm`}var fu=["bash","zsh","fish"],Fy={bash:'Add to ~/.bashrc or ~/.ba
|
|
|
2285
2285
|
`)}catch{}}function Dy(e){let t=(e??"keyword").trim().toLowerCase();if(t==="keyword")return"keyword";if(t==="semantic"||t==="hybrid")return t;throw new p("Reindex mode must be one of keyword|semantic|hybrid",u.USAGE)}async function jy(e,t,n,o){let r=[];return{candidates:await ya(e,t,n,r,o),warnings:r}}async function Ni(e,t,n,o,r){let i=ue(T()),s=[];for(let a of t)if(!(r&&!r.has(a.metadata.id))){if(typeof a.body=="string"){s.push({metadata:a.metadata,body:a.body});continue}try{let c=await Ny.readFile(a.item_path,"utf8"),l=wn(c,{format:a.item_format,schema:n,extensionFieldNames:i,onWarning:d=>o.push(d)});s.push({metadata:a.metadata,body:l.body})}catch{o.push(`item_list_item_read_failed:${an.relative(e,a.item_path)}`),s.push({metadata:a.metadata,body:""})}}return s}function Gy(e,t,n){let o=e.metadata;return{id:o.id,mode:t,updated_at:o.updated_at,corpus:ka(e,{fields:n})}}var Et=ms;function Uy(e){let t=T(),n=Et(e.search?.provider);if(!n)return null;let o=Qs(t,n);if(!o)return null;let r=o.runtime_definition??o.definition,i=Et(r.name)??Et(o.definition.name);if(!i)return null;let s=r.embedBatch,a=r.embed_batch,c=r.embed,l=typeof s=="function"?s:typeof a=="function"?a:void 0,d=typeof c=="function"?c:void 0;return!l&&!d?null:{name:i,embedBatch:l,embed:d}}function qy(e){let t=T(),n=Et(e.vector_store?.adapter);if(!n)return null;let o=ea(t,n);if(!o)return null;let r=o.runtime_definition??o.definition,i=Et(r.name)??Et(o.definition.name);if(!i)return null;let s=r.upsert,a=r.delete;return{adapterName:i,...typeof s=="function"?{upsert:s}:{},...typeof a=="function"?{delete:a}:{}}}function Pi(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="number"||!Number.isFinite(n)))throw new p(`Invalid vector returned by ${t}`,u.GENERIC_FAILURE);return e}async function zy(e,t,n){let o=t.search?.embedding_model?.trim()||"text-embedding-3-small";if(e.embedBatch){let i=await Promise.resolve(e.embedBatch({inputs:n,settings:t,model:o}));if(!Array.isArray(i))throw new p(`Extension search provider "${e.name}" embedBatch must return an array of vectors`,u.GENERIC_FAILURE);return i.map((s,a)=>Pi(s,`extension search provider "${e.name}" embedBatch output at index ${a}`))}if(!e.embed)throw new p(`Extension search provider "${e.name}" does not implement embed/embedBatch`,u.GENERIC_FAILURE);let r=[];for(let[i,s]of n.entries()){let a=await Promise.resolve(e.embed({input:s,settings:t,model:o}));r.push(Pi(a,`extension search provider "${e.name}" embed output at index ${i}`))}return r}function _u(e){return e.search?.embedding_model?.trim()||"text-embedding-3-small"}function hu(e,t,n){let o=n?zt(n.name,_u(e)):t?zt(t.name,t.model):null;if(!o)throw new p("No embedding identity available for semantic reindex mode",u.USAGE);return o}function Hy(e,t){return Object.keys(e).filter(n=>!t.has(n)).sort((n,o)=>n.localeCompare(o))}async function gu(e,t,n,o,r,i,s,a){let c=o?.name??n?.name,l=Sa(c,e.search.embedding_corpus_max_characters).maxCharacters,d=Jo(e),m=r.map(y=>Aa(y,{providerName:c,maxCharacters:l,fields:d})),f=[],h=null;if(o)try{f=await zy(o,e,m),h=zt(o.name,_u(e))}catch(y){if(!n)throw new p(`Extension search provider "${o.name}" failed to generate embeddings: ${y instanceof Error?y.message:String(y)}`,u.GENERIC_FAILURE);i.push(`Extension search provider "${o.name}" failed; falling back to built-in provider (${y instanceof Error?y.message:String(y)})`)}if(f.length===0){if(!n)throw new p(`No embedding executor available for reindex mode '${t}'`,u.USAGE);let y=await xa(n,e,m,{onProgress:k=>{k.phase==="complete"&&(s.batches_completed=k.batch_index),D(a,`embedding_batch_${k.phase} batch=${k.batch_index}/${k.batch_total} size=${k.batch_size} completed_inputs=${k.completed_inputs}/${k.total_inputs}`)}});i.push(...y.warnings),s.batching=y.receipt,f=y.vectors,h=zt(n.name,n.model)}if(D(a,`embedding_complete vectors=${f.length}`),f.length!==r.length)throw new p(`Embedding output size mismatch (expected ${r.length}, received ${f.length})`,u.GENERIC_FAILURE);if(!h)throw new p(`No embedding identity available for reindex mode '${t}'`,u.USAGE);return{vectors:f,embeddingIdentity:h}}async function By(e,t,n,o,r,i){let s=Object.keys(n);if(t){if(s.length>0&&t.delete)try{await Promise.resolve(t.delete({ids:s.sort((a,c)=>a.localeCompare(c)),settings:o}))}catch(a){throw new p(`Extension vector adapter "${t.adapterName}" failed to delete vectors during reindex reset: ${a instanceof Error?a.message:String(a)}`,u.GENERIC_FAILURE)}else s.length>0&&r.push(`search_semantic_reindex_reset_skipped:adapter=${t.adapterName}:known_ids=${s.length}`);if(!e)return}e&&await Ra(e,s,{},i)}async function yu(e,t,n,o,r){if(n.length!==0){if(t){if(t.delete)try{await Promise.resolve(t.delete({ids:n,settings:o}))}catch(i){throw new p(`Extension vector adapter "${t.adapterName}" failed to delete orphan vectors during reindex: ${i instanceof Error?i.message:String(i)}`,u.GENERIC_FAILURE)}else r.push(`search_semantic_reindex_orphan_prune_skipped:adapter=${t.adapterName}:count=${n.length}`);if(!e)return}e&&await Ca(e,n)}}function Wy(e){return{enabled:e!=="keyword",stale_items:0,unchanged_items:0,embedded_items:0,vector_upserted:0,batches_completed:0}}function Vy(e,t,n){return{version:1,mode:e,generated_at:t,total_items:n.length,items:n.map(o=>({id:o.metadata.id,type:o.metadata.type,status:o.metadata.status,priority:o.metadata.priority,updated_at:o.metadata.updated_at}))}}function Ky(e){if(e.requestedMode==="keyword")return{activeEmbeddingProvider:null,activeVectorStore:null};let t=Ko(e.settings);if(!t.active&&!e.extensionEmbedding)throw new p(`Reindex mode '${e.requestedMode}' requires a configured embedding provider in settings.providers.openai/settings.providers.ollama or an extension provider selected by settings.search.provider`,u.USAGE);let n=Ia(e.settings,e.pmRoot);if(!n.active&&!e.extensionVectorAdapter)throw new p(`Reindex mode '${e.requestedMode}' requires a configured vector store in settings.vector_store.qdrant/settings.vector_store.lancedb or an extension adapter selected by settings.vector_store.adapter`,u.USAGE);return{activeEmbeddingProvider:t.active,activeVectorStore:n.active}}async function Jy(e){let t=F(e.settings,T()),n=await jy(e.pmRoot,e.settings.item_format,t.type_to_folder,e.settings.schema);return{documentCandidates:n.candidates,warnings:[...n.warnings],metadataDocuments:n.candidates.map(o=>({metadata:o.metadata,body:typeof o.body=="string"?o.body:""}))}}async function Yy(e){let t=await Xo(e.pmRoot);if(e.reindexWarnings.push(...t.warnings),e.forceFullSemantic&&e.reindexWarnings.push("search_semantic_reindex_full_ignored:mode_keyword"),!t.embedding)return;let n=(()=>{try{return hu(e.settings,Ko(e.settings).active,e.extensionEmbedding)}catch{return null}})();n&&Pn(t.embedding,n)&&(e.reindexWarnings.push("search_semantic_reindex_requires_rebuild:embedding_identity_changed"),e.reindexWarnings.push(Ly))}async function Xy(e){let t=await Xo(e.pmRoot);e.semanticWarnings.push(...t.warnings);let n=hu(e.settings,e.activeEmbeddingProvider,e.extensionEmbedding),o=new Set(e.metadataDocuments.map(l=>l.metadata.id)),r=Hy(t.entries,o),i=Pn(t.embedding,n);e.forceFullSemantic&&!i&&e.semanticWarnings.push("search_semantic_reindex_full_rebuild_forced");let s=e.forceFullSemantic||i?e.metadataDocuments:e.metadataDocuments.filter(l=>t.entries[l.metadata.id]!==l.metadata.updated_at),a=new Set(s.map(l=>l.metadata.id)),c=a.size>0?await Ni(e.pmRoot,e.documentCandidates,e.settings.schema,e.reindexWarnings,a):[];return{ledgerEntries:t.entries,ledgerEmbedding:t.embedding,orphanIds:r,resetRequired:i,staleDocuments:c,freshDocuments:e.metadataDocuments.length-c.length}}async function Zy(e){let t=new Set(e.metadataDocuments.map(r=>r.metadata.id)),n=await Ni(e.pmRoot,e.documentCandidates,e.settings.schema,e.reindexWarnings,t);e.semanticSummary.stale_items=n.length,e.semanticSummary.unchanged_items=0,D(e.progressEnabled,`embedding_dimension_changed reset_items=${n.length}`);let o=await gu(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,n,e.semanticWarnings,e.semanticSummary,e.progressEnabled);return{...o,staleDocuments:n,vectorDimension:Yo(o.vectors,"Reindex embeddings")}}async function Qy(e){let t=await gu(e.settings,e.requestedMode,e.activeEmbeddingProvider,e.extensionEmbedding,e.staleDocuments,e.semanticWarnings,e.semanticSummary,e.progressEnabled),n=t.vectors,o=t.embeddingIdentity,r=Yo(n,"Reindex embeddings");if(!(!e.resetRequired&&(Pn(e.ledgerEmbedding,o)||Oa(e.ledgerEmbedding,r))))return{vectors:n,embeddingIdentity:o,staleDocuments:e.staleDocuments,vectorDimension:r,resetRequired:e.resetRequired};let s=await Zy(e);return n=s.vectors,o=s.embeddingIdentity,r=s.vectorDimension,{vectors:n,embeddingIdentity:o,staleDocuments:s.staleDocuments,vectorDimension:r,resetRequired:!0}}async function eb(e){if(e.extensionVectorAdapter)try{let t=e.extensionVectorAdapter.adapterName;if(D(e.progressEnabled,`vector_upsert_start adapter=${t} points=${e.points.length}`),typeof e.extensionVectorAdapter.upsert!="function")throw new p(`Extension vector adapter "${t}" does not support upserting vectors.`,u.USAGE);await Promise.resolve(e.extensionVectorAdapter.upsert({points:e.points,settings:e.settings})),e.semanticSummary.vector_upserted=e.points.length,D(e.progressEnabled,`vector_upsert_complete adapter=${t}`);return}catch(t){if(t instanceof p)throw t;if(!e.activeVectorStore)throw new p(`Extension vector adapter "${e.extensionVectorAdapter.adapterName}" failed to upsert vectors: ${t instanceof Error?t.message:String(t)}`,u.GENERIC_FAILURE);e.semanticWarnings.push(`Extension vector adapter "${e.extensionVectorAdapter.adapterName}" failed; falling back to built-in vector store (${t instanceof Error?t.message:String(t)})`),D(e.progressEnabled,"vector_upsert_fallback built_in_store")}if(e.activeVectorStore){D(e.progressEnabled,`vector_upsert_start adapter=${e.activeVectorStore.name} points=${e.points.length}`),await Ea(e.activeVectorStore,e.points),e.semanticSummary.vector_upserted=e.points.length,D(e.progressEnabled,`vector_upsert_complete adapter=${e.activeVectorStore.name}`);return}throw new p(`No vector upsert executor available for reindex mode '${e.requestedMode}'`,u.USAGE)}function tb(e,t){return e.map((n,o)=>({id:n.metadata.id,vector:Pi(t[o],`reindex embeddings output at index ${o}`),payload:{id:n.metadata.id,type:n.metadata.type,status:n.metadata.status,priority:n.metadata.priority,updated_at:n.metadata.updated_at}}))}async function nb(e){D(e.progressEnabled,`embedding_start items=${e.plan.staleDocuments.length} unchanged_items=${e.plan.freshDocuments}`);let t=await Qy({pmRoot:e.pmRoot,settings:e.settings,requestedMode:e.requestedMode,activeEmbeddingProvider:e.activeEmbeddingProvider,extensionEmbedding:e.extensionEmbedding,documentCandidates:e.documentCandidates,metadataDocuments:e.metadataDocuments,staleDocuments:e.plan.staleDocuments,ledgerEmbedding:e.plan.ledgerEmbedding,resetRequired:e.plan.resetRequired,semanticWarnings:e.semanticWarnings,reindexWarnings:e.reindexWarnings,semanticSummary:e.semanticSummary,progressEnabled:e.progressEnabled});t.resetRequired?(D(e.progressEnabled,"vector_reset_start"),await By(e.activeVectorStore,e.extensionVectorAdapter,e.plan.ledgerEntries,e.settings,e.semanticWarnings,e.plan.ledgerEmbedding?t.vectorDimension:void 0),D(e.progressEnabled,"vector_reset_complete")):await yu(e.activeVectorStore,e.extensionVectorAdapter,e.plan.orphanIds,e.settings,e.semanticWarnings);let n=tb(t.staleDocuments,t.vectors);return e.semanticSummary.embedded_items=t.vectors.length,await eb({requestedMode:e.requestedMode,activeVectorStore:e.activeVectorStore,extensionVectorAdapter:e.extensionVectorAdapter,settings:e.settings,points:n,semanticWarnings:e.semanticWarnings,semanticSummary:e.semanticSummary,progressEnabled:e.progressEnabled}),{staleDocuments:t.staleDocuments,embeddingMetadata:Ta(t.embeddingIdentity,t.vectorDimension)}}async function ob(e){let t=await Xy(e);e.semanticSummary.stale_items=t.staleDocuments.length,e.semanticSummary.unchanged_items=t.freshDocuments;let n=Object.fromEntries(e.metadataDocuments.map(i=>[i.metadata.id,i.metadata.updated_at]));if(D(e.progressEnabled,`semantic_stale_items stale=${t.staleDocuments.length} total=${e.metadataDocuments.length} unchanged=${t.freshDocuments} full=${e.forceFullSemantic||t.resetRequired}`),t.staleDocuments.length===0)return D(e.progressEnabled,`embedding_skipped unchanged_items=${t.freshDocuments}`),e.semanticWarnings.push(`search_semantic_reindex_skipped_unchanged:count=${t.freshDocuments}`),await yu(e.activeVectorStore,e.extensionVectorAdapter,t.orphanIds,e.settings,e.semanticWarnings),{documentsForKeywordArtifacts:e.documentsForKeywordArtifacts,vectorizationLedgerEntries:n,vectorizationEmbeddingMetadata:t.ledgerEmbedding};let o=await nb({...e,plan:t});t.freshDocuments>0&&e.semanticWarnings.push(`search_semantic_reindex_skipped_unchanged:count=${t.freshDocuments}`);let r=new Map(o.staleDocuments.map(i=>[i.metadata.id,i]));return{documentsForKeywordArtifacts:e.metadataDocuments.map(i=>r.get(i.metadata.id)??i),vectorizationLedgerEntries:n,vectorizationEmbeddingMetadata:o.embeddingMetadata}}async function rb(e){let t=an.join(e.pmRoot,$i),n=an.join(e.pmRoot,Fi),o=Jo(e.settings),r=e.documentsForKeywordArtifacts.map(s=>JSON.stringify(Gy(s,e.mode,o))).join(`
|
|
2286
2286
|
`);D(e.progressEnabled,"writing keyword artifacts"),await se(t,`${JSON.stringify(e.manifest,null,2)}
|
|
2287
2287
|
`),await se(n,`${r}
|
|
2288
|
-
`);let i=[];if(e.mode!=="keyword")try{D(e.progressEnabled,"writing vectorization status ledger"),await $a(e.pmRoot,e.vectorizationLedgerEntries,e.vectorizationEmbeddingMetadata)}catch(s){i.push(`search_vectorization_status_ledger_write_failed:${s instanceof Error?s.message:String(s)}`)}return i}async function ib(e,t){let n=Dy(e.mode),o=My(e),r=e.full===!0;D(o,`start mode=${n}`);let i=x(process.cwd(),t.path);await P(i);let s=ua(await I(i)).settings,a=null;try{a=await Le(i,fa,s.locks.ttl_seconds,C(void 0,"pm-reindex"),!1,s.governance.force_required_for_stale_lock,s.locks.wait_ms)}catch(c){throw c instanceof p&&c.exitCode===u.CONFLICT?new p("Another pm reindex run is already active for this project. Wait for it to finish before starting a new keyword, semantic, or hybrid reindex.",u.CONFLICT,{code:"reindex_already_running",type:"urn:pm-cli:error:reindex_already_running",why:"Semantic reindex can be expensive and duplicate runs compete for the same local embedding model and vector store.",nextSteps:["Check active pm reindex processes before starting another reindex.","Rerun with --progress when you need non-interactive visibility."]}):c}try{let c=Uy(s),l=qy(s),d=Ky({requestedMode:n,pmRoot:i,settings:s,extensionEmbedding:c,extensionVectorAdapter:l}),m=n;D(o,"loading item corpus");let f=await Jy({pmRoot:i,settings:s}),h=f.warnings,{documentCandidates:y,metadataDocuments:k}=f;D(o,`loaded_items=${k.length}`);let b=S(),v=Vy(m,b,k),_=an.join(i,$i),A=an.join(i,Fi),N=m==="keyword"?await Ni(i,y,s.schema,h):k,O=[],B={},$=null,R=Wy(m);if(m==="keyword"&&await Yy({pmRoot:i,settings:s,forceFullSemantic:r,extensionEmbedding:c,reindexWarnings:h}),m!=="keyword"){let ne=await ob({pmRoot:i,settings:s,requestedMode:n,activeEmbeddingProvider:d.activeEmbeddingProvider,activeVectorStore:d.activeVectorStore,extensionEmbedding:c,extensionVectorAdapter:l,documentCandidates:y,metadataDocuments:k,documentsForKeywordArtifacts:N,forceFullSemantic:r,reindexWarnings:h,semanticWarnings:O,semanticSummary:R,progressEnabled:o});N=ne.documentsForKeywordArtifacts,B=ne.vectorizationLedgerEntries,$=ne.vectorizationEmbeddingMetadata}let ie=await rb({pmRoot:i,mode:m,manifest:v,documentsForKeywordArtifacts:N,settings:s,vectorizationLedgerEntries:B,vectorizationEmbeddingMetadata:$,progressEnabled:o}),Tt=[...await G({path:_,scope:"project",op:"reindex:manifest"}),...await G({path:A,scope:"project",op:"reindex:embeddings"}),...await Ys({mode:m,total_items:k.length})];return D(o,"done"),{ok:!0,mode:m,total_items:k.length,semantic:R,artifacts:{manifest:$i,embeddings:Fi},warnings:[...h,...O,...ie,...Tt],generated_at:b}}finally{await a?.()}}var cn=Symbol("pm.active-extension-host-context");function ee(e){return{fullChangedFields:!0,options:e}}var w=class e{defaults;constructor(t={}){this.defaults={...t.pmRoot===void 0?{}:{path:t.pmRoot},...t.cwd===void 0?{}:{cwd:t.cwd},...t.author===void 0?{}:{author:t.author},...t.noExtensions===void 0?{}:{noExtensions:t.noExtensions}}}static forActiveExtensionHost(t){let n=new e({...t,noExtensions:!0});return n.defaults[cn]=!0,n}run(t,n={}){return ub({...this.defaults,...n,action:t})}runTyped(t,n={}){return this.run(t,n)}async withItemTransactionContext(t,n=!1){let o=x(this.defaults.cwd??process.cwd(),this.defaults.path),r=async()=>{let c=await nt(o,()=>I(o));return t({pmRoot:o,author:C(this.defaults.author,c.author_default)})};if(this.defaults[cn]===!0){let c=process.cwd(),l=()=>vu(o,Bt({path:o}),void 0,c,r);return n?nt(o,l):l()}let i=Rt()!==void 0;i&&Di(this.defaults.cwd);let s=i?void 0:this.defaults.cwd,a=()=>ku({...this.defaults,cwd:s,path:o},r);return n?nt(o,a):a()}previewItemMutations(t){return this.withItemTransactionContext(async n=>(await import("./item-transaction-66RDV7PH.js")).previewItemMutations({...t,...n}),!0)}commitItemMutations(t){return this.withItemTransactionContext(async n=>(await import("./item-transaction-66RDV7PH.js")).commitItemMutations({...t,...n}))}get itemTransactions(){let t=(n,o)=>this.withItemTransactionContext(async r=>(await import("./item-transaction-66RDV7PH.js")).abandonItemTransaction({...o,...r,transactionId:n}));return{status:n=>this.withItemTransactionContext(async o=>(await import("./item-transaction-66RDV7PH.js")).readItemTransaction(o.pmRoot,n),!0),abandon:t,supersede:(n,o,r)=>t(n,{...r,supersededBy:o})}}readItemRevision(t){return this.withItemTransactionContext(async({pmRoot:n})=>(await import("./item-revision-3LENTXYF.js")).readItemRevision(t,{pmRoot:n}))}async withExpectedItemRevisions(t,n){let o=await import("./item-revision-3LENTXYF.js"),r="",i=await this.withItemTransactionContext(({pmRoot:a})=>(r=a,o.bindExpectedItemRevisions(t,{pmRoot:a}))),s=this.defaults.noExtensions===!0&&this.defaults[cn]!==!0;return o.runWithBoundItemRevisionScope(i,n,{scopeArgs:["--pm-path",r,...s?["--no-extensions"]:[]]})}context(t={}){return this.runTyped("context",{options:t})}listAllItemMetadataLight(){return Fd(this.defaults.path,this.defaults.cwd)}list(t={}){return this.runTyped("list",{options:t})}async listAllComplete(t={}){return to(await this.list(Fr(t)),t)}search(t,n={}){return this.runTyped("search",{query:t,options:n})}get(t,n={}){return this.runTyped("get",{id:t,options:n})}next(t={}){return this.runTyped("next",{options:t})}aggregate(t={}){return this.runTyped("aggregate",{options:t})}stats(t={}){return this.runTyped("stats",{options:t})}duplicates(t={}){return this.runTyped("duplicates",{options:t})}comments(t,n={}){return this.runTyped("comments",{id:t,options:n})}notes(t,n={}){return this.runTyped("notes",{id:t,options:n})}learnings(t,n={}){return this.runTyped("learnings",{id:t,options:n})}files(t,n={}){return this.runTyped("files",{id:t,options:n})}filesDiscover(t,n={}){return this.runTyped("files-discover",{id:t,options:n})}filesLookup(t){return this.runTyped("files-lookup",{options:t})}docs(t,n={}){return this.runTyped("docs",{id:t,options:n})}deps(t,n={}){return this.runTyped("deps",{id:t,options:n})}graph(t,n={},o={}){return this.runTyped("graph",{subcommand:t,...n,options:o})}async append(t,n,o={}){return $c(o,"append"),await this.runTyped("append",{id:t,...ee(st(o,{body:n}))})}init(t,n={}){return this.runTyped("init",{...t===void 0?{}:{prefix:t},options:n})}config(t,n,o,r,i={}){return this.runTyped("config",{scope:t,configAction:n,...o===void 0?{}:{key:o},...r===void 0?{}:{value:r},options:i})}schema(t,n={}){return this.runTyped("schema",{options:{...n,subcommand:t}})}workflowPolicy(t,n,o={}){return this.runTyped("schema",{name:n,options:{...o,subcommand:t}})}schemaList(){return this.runTyped("schema",{options:{subcommand:"list"}})}schemaShow(t){return this.runTyped("schema",{name:t,options:{subcommand:"show"}})}schemaAddType(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-type"}})}schemaRemoveType(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-type"}})}schemaAddStatus(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-status"}})}schemaRemoveStatus(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-status"}})}schemaAddField(t,n={}){let{type:o,...r}=n;return this.runTyped("schema",{name:t,options:{...r,fieldType:o,subcommand:"add-field"}})}schemaRemoveField(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-field"}})}schemaListFields(){return this.runTyped("schema",{options:{subcommand:"list-fields"}})}schemaShowField(t){return this.runTyped("schema",{name:t,options:{subcommand:"show-field"}})}schemaApplyPreset(t,n={}){return this.runTyped("schema",{typePreset:t,options:{...n,subcommand:"apply-preset"}})}schemaInferTypes(t={}){return this.runTyped("schema",{options:{...t,subcommand:"add-type",infer:!0}})}schemaRenameType(t,n,o){return this.runTyped("schema",{name:t,options:{...o,subcommand:"rename-type",to:n}})}schemaRenameField(t,n,o,r){return this.runTyped("schema",{name:t,options:{...o,subcommand:"rename-field",to:n,...r?{fieldTypeScope:r}:{}}})}schemaRemapStatus(t,n,o){return this.runTyped("schema",{name:t,options:{...o,subcommand:"remap-status",to:n}})}schemaShowStatus(t){return this.runTyped("schema",{name:t,options:{subcommand:"show-status"}})}profile(t,n={}){return this.runTyped("profile",{options:{...n,subcommand:t}})}profileList(){return this.runTyped("profile",{options:{subcommand:"list"}})}profileShow(t){return this.runTyped("profile",{name:t,options:{subcommand:"show"}})}profileApply(t,n={}){return this.runTyped("profile",{name:t,options:{...n,subcommand:"apply"}})}profileLint(t){return this.runTyped("profile",{name:t,options:{subcommand:"lint"}})}validate(t={}){return this.runTyped("validate",{options:t})}health(t={}){return this.runTyped("health",{options:t})}gc(t={}){return this.runTyped("gc",{options:t})}assurance(t){return this.runTyped("assurance",{options:{...t,subcommand:t.action}})}historyRedact(t,n){return this.runTyped("history-redact",{id:t,options:n})}historyRepair(t,n={}){return this.runTyped("history-repair",{id:t,options:n})}historyRepairAll(t={}){return this.runTyped("history-repair",{options:{...t,all:!0}})}historyAttest(t={}){return this.runTyped("history-attest",{options:t})}historyCompact(t,n={}){return this.runTyped("history-compact",{id:t,options:n})}historyCompactBulk(t){return this.runTyped("history-compact",{options:t})}historyAuthorAcknowledge(t){return this.runTyped("history-author-acknowledge",{historyEvent:(t.events??[]).map(n=>`${n.item_id}:${String(n.line)}`),allActionable:t.all_actionable===!0,dryRun:t.dry_run===!0,planFingerprint:t.plan_fingerprint,limit:t.coordinate_limit,attributedAuthor:t.attributed_author,reviewer:t.reviewer,reason:t.reason})}plan(t,n,o={},r,i){return this.runTyped("plan",{fullChangedFields:!0,...n===void 0?{}:{id:n},...r===void 0?{}:{stepRef:r},...i===void 0?{}:{reorderTo:i},options:st(o,{subcommand:t})})}planCreate(t){return this.plan("create",void 0,t)}planShow(t,n={}){return this.plan("show",t,n)}planAddStep(t,n){return this.plan("add-step",t,n)}planUpdateStep(t,n,o){return this.plan("update-step",t,o,n)}planCompleteStep(t,n,o={}){return this.plan("complete-step",t,o,n)}planBlockStep(t,n,o){return this.plan("block-step",t,o,n)}planReorderStep(t,n,o,r={}){return this.plan("reorder-step",t,r,n,o)}planRemoveStep(t,n,o={}){return this.plan("remove-step",t,o,n)}planLink(t,n,o){return this.plan("link",t,o,n)}planUnlink(t,n,o){return this.plan("unlink",t,o,n)}planDecision(t,n){return this.plan("decision",t,n)}planDiscovery(t,n){return this.plan("discovery",t,n)}planValidation(t,n){return this.plan("validation",t,n)}planResume(t,n){return this.plan("resume",t,n)}planApprove(t,n={}){return this.plan("approve",t,n)}planMaterialize(t,n){return this.plan("materialize",t,n)}create(t={}){return this.runTyped("create",ee(t))}update(t,n={}){return this.runTyped("update",{id:t,...ee(n)})}reopen(t,n,o={}){return this.runTyped("item-reopen",{id:t,reason:n,fullChangedFields:!0,options:o})}close(t,n,o={}){return this.runTyped("close",{id:t,reason:n,...ee(o)})}claim(t,n={}){return this.runTyped("claim",{id:t,...ee(n)})}claimNext(t={}){return this.runTyped("claim",{next:!0,...ee(t)})}release(t,n={}){return this.runTyped("release",{id:t,...ee(n)})}copy(t,n={}){return this.runTyped("copy",{id:t,...ee(n)})}delete(t,n={}){return this.runTyped("delete",{id:t,...ee(n)})}restore(t,n,o={}){return this.runTyped("restore",{fullChangedFields:!0,id:t,options:{...o,target:n}})}focus(t,n={}){return this.runTyped("focus",{...t===void 0?{}:{id:t},...ee(n)})}startTask(t,n={}){return this.runTyped("start-task",{id:t,...ee(n)})}pauseTask(t,n={}){return this.runTyped("pause-task",{id:t,...ee(n)})}closeTask(t,n,o={}){return this.runTyped("close-task",{id:t,reason:n,...ee(o)})}extension(t,n={}){return this.runTyped("extension",{...t===void 0?{}:{target:t},options:n})}extensionList(t={}){return this.extension("list",t)}extensionActivate(t,n={}){return this.runTyped("extension-activate",{target:t,options:n})}extensionDeactivate(t,n={}){return this.runTyped("extension-deactivate",{target:t,options:n})}package(t,n={}){return this.runTyped("package",{...t===void 0?{}:{target:t},options:{...n,vocabulary:"package"}})}packageList(t={}){return this.package("list",t)}packageInstall(t,n={}){return this.runTyped("package-install",{target:t,options:n})}packageUninstall(t,n={}){return this.runTyped("package-uninstall",{target:t,options:n})}packageDoctor(t={}){return this.runTyped("package-doctor",{options:t})}packageManage(t,n={}){return this.runTyped("package-manage",{...t===void 0?{}:{target:t},options:n})}packageDescribe(t,n={}){return this.runTyped("package-describe",{...t===void 0?{}:{target:t},options:n})}packageReload(t={}){return this.runTyped("package-reload",{options:t})}packageCatalog(t={}){return this.runTyped("package-catalog",{options:t})}packageActivate(t,n={}){return this.runTyped("package-activate",{target:t,options:n})}packageDeactivate(t,n={}){return this.runTyped("package-deactivate",{target:t,options:n})}packageMigrate(t={}){return this.package(void 0,{...t,migrate:!0})}upgrade(t,n={}){return this.runTyped("upgrade",{...t===void 0?{}:{target:t},options:n})}};function iR(e={},t={}){return new w(t).context(e)}function sR(e={},t={}){return new w(t).list(e)}function aR(e={},t={}){return new w(t).listAllComplete(e)}function cR(e,t={},n={}){return new w(n).search(e,t)}function lR(e,t={},n={}){return new w(n).get(e,t)}function dR(e={},t={}){return new w(t).next(e)}function mR(e={},t={}){return new w(t).aggregate(e)}function pR(e={},t={}){return new w(t).stats(e)}function uR(e={},t={}){return new w(t).duplicates(e)}function fR(e,t={},n={}){return new w(n).comments(e,t)}function _R(e,t={},n={}){return new w(n).notes(e,t)}function hR(e,t={},n={}){return new w(n).learnings(e,t)}function gR(e,t={},n={}){return new w(n).files(e,t)}function yR(e,t={},n={}){return new w(n).filesDiscover(e,t)}function bR(e,t={}){return new w(t).filesLookup(e)}function wR(e,t={},n={}){return new w(n).docs(e,t)}function vR(e,t={},n={}){return new w(n).deps(e,t)}function kR(e,t={},n={},o={}){return new w(o).graph(e,t,n)}function SR(e,t,n={},o={}){return new w(o).append(e,t,n)}function AR(e,t={},n={}){return new w(n).init(e,t)}function xR(e,t,n,o,r={},i={}){return new w(i).config(e,t,n,o,r)}function IR(e,t={},n={}){return new w(n).schema(e,t)}function ER(e={}){return new w(e).schemaList()}function CR(e,t={}){return new w(t).schemaShow(e)}function RR(e,t={},n={}){return new w(n).schemaAddType(e,t)}function TR(e,t={},n={}){return new w(n).schemaRemoveType(e,t)}function OR(e,t={},n={}){return new w(n).schemaAddStatus(e,t)}function $R(e,t={},n={}){return new w(n).schemaRemoveStatus(e,t)}function FR(e,t={},n={}){return new w(n).schemaAddField(e,t)}function PR(e,t={},n={}){return new w(n).schemaRemoveField(e,t)}function NR(e={}){return new w(e).schemaListFields()}function LR(e,t={}){return new w(t).schemaShowField(e)}function MR(e,t={},n={}){return new w(n).schemaApplyPreset(e,t)}function DR(e={},t={}){return new w(t).schemaInferTypes(e)}function jR(e,t,n,o={}){return new w(o).schemaRenameType(e,t,n)}function GR(e,t,n,o,r={}){return new w(r).schemaRenameField(e,t,n,o)}function UR(e,t,n,o={}){return new w(o).schemaRemapStatus(e,t,n)}function qR(e,t={}){return new w(t).schemaShowStatus(e)}function zR(e,t={},n={}){return new w(n).profile(e,t)}function HR(e={}){return new w(e).profileList()}function BR(e,t={}){return new w(t).profileShow(e)}function WR(e,t={},n={}){return new w(n).profileApply(e,t)}function VR(e,t={}){return new w(t).profileLint(e)}function KR(e={},t={}){return new w(t).validate(e)}function JR(e={},t={}){return new w(t).health(e)}function YR(e={},t={}){return new w(t).gc(e)}function XR(e,t,n={}){return new w(n).historyRedact(e,t)}function ZR(e,t={},n={}){return new w(n).historyRepair(e,t)}function QR(e={},t={}){return new w(t).historyRepairAll(e)}function eT(e,t={},n={}){return new w(n).historyCompact(e,t)}function tT(e,t={}){return new w(t).historyCompactBulk(e)}function nT(e={},t={}){return new w(t).create(e)}function oT(e,t={},n={}){return new w(n).update(e,t)}function rT(e,t,n={},o={}){return new w(o).reopen(e,t,n)}function iT(e,t,n={},o={}){return new w(o).close(e,t,n)}function sT(e,t={},n={}){return new w(n).claim(e,t)}function aT(e={},t={}){return new w(t).claimNext(e)}function cT(e,t={},n={}){return new w(n).release(e,t)}function lT(e,t={},n={}){return new w(n).copy(e,t)}function dT(e,t={},n={}){return new w(n).delete(e,t)}function mT(e,t,n={},o={}){return new w(o).restore(e,t,n)}function pT(e,t={},n={}){return new w(n).focus(e,t)}function uT(e,t={},n={}){return new w(n).startTask(e,t)}function fT(e,t={},n={}){return new w(n).pauseTask(e,t)}function _T(e,t,n={},o={}){return new w(o).closeTask(e,t,n)}function hT(e,t={},n={}){return new w(n).extension(e,t)}function gT(e={},t={}){return new w(t).extensionList(e)}function yT(e,t={},n={}){return new w(n).extensionActivate(e,t)}function bT(e,t={},n={}){return new w(n).extensionDeactivate(e,t)}function wT(e,t={},n={}){return new w(n).package(e,t)}function vT(e={},t={}){return new w(t).packageList(e)}function kT(e,t={},n={}){return new w(n).packageInstall(e,t)}function ST(e,t={},n={}){return new w(n).packageUninstall(e,t)}function AT(e={},t={}){return new w(t).packageDoctor(e)}function xT(e,t={},n={}){return new w(n).packageManage(e,t)}function IT(e,t={},n={}){return new w(n).packageDescribe(e,t)}function ET(e={},t={}){return new w(t).packageReload(e)}function CT(e={},t={}){return new w(t).packageCatalog(e)}function RT(e,t={},n={}){return new w(n).packageActivate(e,t)}function TT(e,t={},n={}){return new w(n).packageDeactivate(e,t)}function OT(e,t={},n={}){return new w(n).upgrade(e,t)}async function $T(e,t={}){let n=typeof e=="string"?{...t,pmRoot:e}:e??t,o={json:!0,quiet:n.quiet??!0,noExtensions:n.noExtensions??!1,noPager:!0,profile:n.profile??!1,path:n.pmRoot};return Un(n,o)}var bu=Vs(),So=new sb;function ln(e){try{return ab(e)}catch{return Mi.resolve(e)}}function Rt(){let e=So.getStore();for(;e!==void 0&&!e.live;)e=e.parent;return e}async function Ct(e,t,n,o=!0){let r={root:ln(e),active:t,live:!0,parent:Rt(),ready:o};try{return await So.run(r,n)}finally{r.live=!1}}function Di(e){if(e===void 0||ln(e)===ln(process.cwd()))return;let t="Omit cwd inside an open extension scope and address the tracker with path, or make the call outside the scope.";throw new p(`A nested SDK call cannot change the working directory to "${e}" while its caller's extension scope is open. ${t}`,u.USAGE,{code:"invalid_argument_value",reason:"nested_cwd_unavailable",changed:!1,field:"cwd",required:t,nextSteps:[t]})}function ji(e,t,n,o){let r=Rt();if(r===void 0)return;let i=r===So.getStore(),s=r.root===ln(e);if(s&&!r.ready){let a="Do the work from a command or hook handler, after the tracker's extensions have activated.";throw new p(`An extension lifecycle callback cannot run SDK work for tracker ${r.root} while its extensions activate or deactivate. ${a}`,u.USAGE,{code:"invalid_argument_value",reason:"extension_scope_not_ready",changed:!1,required:a,nextSteps:[a]})}return i&&s&&t.noExtensions!==!0?o(r.active):Lo(()=>Ct(e,null,()=>Li(t,n,a=>Ct(e,a,()=>o(a))),!1))}function vu(e,t,n,o,r){let i=So.getStore();if(i===void 0)return r(null);let s=Rt(),a={...t,noExtensions:!1};return s===void 0?Ct(e,null,()=>Gi(a,n===void 0?void 0:o,o,c=>Ct(e,c,()=>r(c))),!1):s===i&&s.ready&&s.root===ln(e)?r(null):ji(e,a,o,r)}function ko(){Mo(Gs()),Do(Us()),jo(qs()),Go(zs()),Uo(Hs()),qo(Bs()),zo(Ws())}async function Gi(e,t,n,o){return Lo(()=>t===void 0?bu.read(()=>Li(e,n,o)):bu.write(()=>db(t,()=>Li(e,n,o))))}async function ku(e,t){let n=e.cwd,o=n===void 0?process.cwd():Mi.resolve(n),r=x(o,e.path),i=Bt({path:r,noExtensions:e.noExtensions});Rt()!==void 0&&Di(n);let s=ji(r,i,o,()=>t());return s!==void 0?s:Gi(i,n===void 0?void 0:o,o,a=>Ct(r,a,t))}function FT(e,t){return ku({path:e},t)}function cb(e){try{let t=e instanceof Error?e.stack:void 0,n=typeof t=="string"?t:Pa(e);return typeof n=="string"?n:"Unknown failure"}catch{return"Unknown failure"}}async function Li(e,t,n){let o=x(t,e.path);if(e.noExtensions)return ko(),Er({pmRoot:o},()=>n(null));if(!await ke(Se(o)))return ko(),n(null);let r=null,i;try{let s=await I(o),a=await kn({pmRoot:o,settings:s,cwd:t,noExtensions:!1}),c=await An({...a,loaded:a.loaded});i={loadResult:a,activationResult:c},Mo(c.hooks),Do(c.commands),jo(c.parsers),Go(c.preflight),Uo(c.services),qo(c.renderers),zo(c.registrations),r={registrations:c.registrations,commands:c.commands,pmRoot:o,packages:a.loaded}}catch(s){ko(),console.error("[pm-sdk] extension activation failed; continuing without active extensions:",cb(s))}try{return await Er({pmRoot:o,packages:r?.packages},()=>n(r))}finally{ko(),i&&await Sn(i.loadResult,i.activationResult).catch(()=>{})}}function Su(e,t){let n=De(e);return t?.registrations.commands.find(o=>De(o.action)===n)?.command??t?.commands.handlers.find(o=>De(o.command)===n)?.command}async function lb(e,t,n,o,r){if(!r)throw new p(`Unsupported native pm action: ${e}`,u.USAGE);let i=Su(e,r);if(!i)throw new p(`Unsupported native pm action: ${e}`,u.USAGE);let s=typeof n.author=="string"?n.author:o.author,a=sr(i),c=Wc(ar(t,n),Bc(r.registrations,a),a,Od(a)),l=await Xs({command:a,args:U(n.args??t.args),options:c,global:{...o,author:s},pm_root:r.pmRoot,sdk:Td(r.pmRoot,w.forActiveExtensionHost({pmRoot:r.pmRoot,author:s}),s,a)});if(!l.handled){if(Object.hasOwn(l,"cause"))throw Fa(i,l);let d=l.warnings.length>0?` (${l.warnings.join(", ")})`:"";throw new p(`Unsupported native pm action: ${e}${d}`,u.USAGE)}return l.result}async function db(e,t){let n=process.cwd();process.chdir(e);try{return await t()}finally{process.chdir(n)}}function mb(e){let t=K(e,"action"),n=De(t),o=be(Pr,n),r=o?.action??n,i={...e,action:r};return o?.options!==void 0&&(i.options={...o.options,...Nt(e.options)}),r==="package"&&(i.options={...Nt(i.options),vocabulary:"package"}),{action:r,args:i}}function pb(e,t,n,o){let r=e[cn]===!0,i=t.noExtensions===!0&&!r?["--no-extensions"]:[];if(n!==void 0)return["--pm-path",x(o,t.path),...i];let s=ds(t,o);return[...t.noExtensions===!0?s.slice(0,-1):s,...i]}async function ub(e){let t=mb(e),n=Bt(t.args);ls(n);let o=Gc(t.action),r=g(t.args,"cwd"),i=r===void 0?process.cwd():Mi.resolve(r);t.action==="init"&&(n[yl]=i),(t.action!=="init"||n.path!==void 0||(process.env.PM_PATH?.trim().length??0)>0)&&(n.path=x(i,n.path));let{expectHash:s,dispatchArgs:a}=Hc(t.args),c=async l=>{if(s===void 0)return wu(t.action,a,n,l);let{dispatchWithExpectedItemRevisions:d}=await import("./item-revision-3LENTXYF.js");return d({action:t.action,expectHash:s,defaultId:g(a,"id")??g(Nt(a.options),"id"),options:Nt(a.options),background:a.background,pmRoot:x(i,n.path),invocation:{scopeArgs:pb(e,n,r,i),...n.outputFormat===void 0?{}:{outputArgs:["--output-format",n.outputFormat]}},run:()=>wu(t.action,a,n,l)})};try{if(t.action==="history-attest")return await c(null);let l=x(i,n.path);if(Rt()!==void 0&&Di(r),e[cn]===!0)return await vu(l,n,r,i,c);let d=ji(l,n,i,c);return d!==void 0?await d:await Gi(n,r===void 0?void 0:i,i,m=>Ct(l,m,()=>c(m)))}finally{o&&yi()}}function PT(e=Yi){return e.map(t=>{let n=De(t),o=be(Pr,n),r=o?.action??n,i=be(gi,r)!==void 0;return{action:t,resolved_action:r,covered:i,route:i?o?"alias":"native":"missing"}})}async function wu(e,t,n,o){let r=be(gi,e),i=ir(t,e,{nativeAction:r!==void 0});if(e==="create"||e==="update"){let{assertNativeMutationOptions:d}=await import("./mutation-admission-PGKJTCG6.js");await d(e,t,i,n.path,Dc[e])}if(e==="update-many"){let{assertNativeUpdateManyOptions:d}=await import("./mutation-admission-PGKJTCG6.js");await d(t,i,n.path)}let s=r?void 0:Su(e,o),a=s===void 0?e:`extension:${s}`;Os(a,i),$s(a,i);let c={action:e,args:t,options:i,id:g(t,"id"),force:t.force===!0||i.force===!0,global:n,activeExtensions:o},l=r?await r(c):await lb(e,t,i,n,o);if(e==="history-attest")return l;{let d=Ds(a,i,l);return await Sd(x(process.cwd(),n.path),d),d}}var fb={closeManyOptionsFromFlat:jn,extensionOptionsFromArgs:ar,globalOptions:Bt,mutationListOptions:Uc,normalizeActionName:De,normalizeCommandPath:sr,normalizeMcpUpdateOptions:zc,normalizeMcpOptionsArrays:jc,optionsWithAuthor:ir,readRequiredString:K,readScalarString:Nc,readScalarStringAllowBlank:Lc,readStringArray:U,updateManyOptionsFromFlat:Gn,withAddNoteOption:Wt,withFilesDiscoveryOptions:Dn,withMutationCompaction:j};(process.env.NODE_ENV==="test"||process.env.VITEST!==void 0||process.env.VITEST_WORKER_ID!==void 0)&&(globalThis.__pmCliActionRunnerTestHooks=fb);export{Ir as a,kd as b,Cu as c,Tu as d,Ou as e,Er as f,Yt as g,xd as h,Zt as i,Qn as j,Td as k,Od as l,Bu as m,eo as n,Fr as o,$d as p,to as q,Qu as r,Ld as s,jd as t,Ud as u,Bd as v,Dr as w,jr as x,Gr as y,Ur as z,$f as A,Vr as B,cm as C,um as D,_m as E,pt as F,ii as G,ah as H,mk as I,pk as J,ci as K,gm as L,Rk as M,Tk as N,bm as O,km as P,Yk as Q,Ah as R,_i as S,Ih as T,Eh as U,Nm as V,Lm as W,Mm as X,Dm as Y,jm as Z,kS as _,SS as $,AS as aa,xS as ba,Gm as ca,zm as da,mo as ea,Km as fa,Jm as ga,Ym as ha,K as ia,yi as ja,eI as ka,tI as la,nI as ma,oI as na,rI as oa,ap as pa,iI as qa,Og as ra,Pg as sa,Dg as ta,jg as ua,Gg as va,z as wa,Ug as xa,qg as ya,zg as za,Hg as Aa,wi as Ba,mp as Ca,_t as Da,bi as Ea,pp as Fa,Bg as Ga,up as Ha,Wg as Ia,Vg as Ja,Kg as Ka,Jg as La,Yg as Ma,Xg as Na,ry as Oa,gp as Pa,sy as Qa,uy as Ra,wy as Sa,ky as Ta,Py as Ua,ib as Va,w as Wa,iR as Xa,sR as Ya,aR as Za,cR as _a,lR as $a,dR as ab,mR as bb,pR as cb,uR as db,fR as eb,_R as fb,hR as gb,gR as hb,yR as ib,bR as jb,wR as kb,vR as lb,kR as mb,SR as nb,AR as ob,xR as pb,IR as qb,ER as rb,CR as sb,RR as tb,TR as ub,OR as vb,$R as wb,FR as xb,PR as yb,NR as zb,LR as Ab,MR as Bb,DR as Cb,jR as Db,GR as Eb,UR as Fb,qR as Gb,zR as Hb,HR as Ib,BR as Jb,WR as Kb,VR as Lb,KR as Mb,JR as Nb,YR as Ob,XR as Pb,ZR as Qb,QR as Rb,eT as Sb,tT as Tb,nT as Ub,oT as Vb,rT as Wb,iT as Xb,sT as Yb,aT as Zb,cT as _b,lT as $b,dT as ac,mT as bc,pT as cc,uT as dc,fT as ec,_T as fc,hT as gc,gT as hc,yT as ic,bT as jc,wT as kc,vT as lc,kT as mc,ST as nc,AT as oc,xT as pc,IT as qc,ET as rc,CT as sc,RT as tc,TT as uc,OT as vc,$T as wc,ku as xc,FT as yc,ub as zc,PT as Ac};
|
|
2289
|
-
//# sourceMappingURL=chunk-
|
|
2288
|
+
`);let i=[];if(e.mode!=="keyword")try{D(e.progressEnabled,"writing vectorization status ledger"),await $a(e.pmRoot,e.vectorizationLedgerEntries,e.vectorizationEmbeddingMetadata)}catch(s){i.push(`search_vectorization_status_ledger_write_failed:${s instanceof Error?s.message:String(s)}`)}return i}async function ib(e,t){let n=Dy(e.mode),o=My(e),r=e.full===!0;D(o,`start mode=${n}`);let i=x(process.cwd(),t.path);await P(i);let s=ua(await I(i)).settings,a=null;try{a=await Le(i,fa,s.locks.ttl_seconds,C(void 0,"pm-reindex"),!1,s.governance.force_required_for_stale_lock,s.locks.wait_ms)}catch(c){throw c instanceof p&&c.exitCode===u.CONFLICT?new p("Another pm reindex run is already active for this project. Wait for it to finish before starting a new keyword, semantic, or hybrid reindex.",u.CONFLICT,{code:"reindex_already_running",type:"urn:pm-cli:error:reindex_already_running",why:"Semantic reindex can be expensive and duplicate runs compete for the same local embedding model and vector store.",nextSteps:["Check active pm reindex processes before starting another reindex.","Rerun with --progress when you need non-interactive visibility."]}):c}try{let c=Uy(s),l=qy(s),d=Ky({requestedMode:n,pmRoot:i,settings:s,extensionEmbedding:c,extensionVectorAdapter:l}),m=n;D(o,"loading item corpus");let f=await Jy({pmRoot:i,settings:s}),h=f.warnings,{documentCandidates:y,metadataDocuments:k}=f;D(o,`loaded_items=${k.length}`);let b=S(),v=Vy(m,b,k),_=an.join(i,$i),A=an.join(i,Fi),N=m==="keyword"?await Ni(i,y,s.schema,h):k,O=[],B={},$=null,R=Wy(m);if(m==="keyword"&&await Yy({pmRoot:i,settings:s,forceFullSemantic:r,extensionEmbedding:c,reindexWarnings:h}),m!=="keyword"){let ne=await ob({pmRoot:i,settings:s,requestedMode:n,activeEmbeddingProvider:d.activeEmbeddingProvider,activeVectorStore:d.activeVectorStore,extensionEmbedding:c,extensionVectorAdapter:l,documentCandidates:y,metadataDocuments:k,documentsForKeywordArtifacts:N,forceFullSemantic:r,reindexWarnings:h,semanticWarnings:O,semanticSummary:R,progressEnabled:o});N=ne.documentsForKeywordArtifacts,B=ne.vectorizationLedgerEntries,$=ne.vectorizationEmbeddingMetadata}let ie=await rb({pmRoot:i,mode:m,manifest:v,documentsForKeywordArtifacts:N,settings:s,vectorizationLedgerEntries:B,vectorizationEmbeddingMetadata:$,progressEnabled:o}),Tt=[...await G({path:_,scope:"project",op:"reindex:manifest"}),...await G({path:A,scope:"project",op:"reindex:embeddings"}),...await Ys({mode:m,total_items:k.length})];return D(o,"done"),{ok:!0,mode:m,total_items:k.length,semantic:R,artifacts:{manifest:$i,embeddings:Fi},warnings:[...h,...O,...ie,...Tt],generated_at:b}}finally{await a?.()}}var cn=Symbol("pm.active-extension-host-context");function ee(e){return{fullChangedFields:!0,options:e}}var w=class e{defaults;constructor(t={}){this.defaults={...t.pmRoot===void 0?{}:{path:t.pmRoot},...t.cwd===void 0?{}:{cwd:t.cwd},...t.author===void 0?{}:{author:t.author},...t.noExtensions===void 0?{}:{noExtensions:t.noExtensions}}}static forActiveExtensionHost(t){let n=new e({...t,noExtensions:!0});return n.defaults[cn]=!0,n}run(t,n={}){return ub({...this.defaults,...n,action:t})}runTyped(t,n={}){return this.run(t,n)}async withItemTransactionContext(t,n=!1){let o=x(this.defaults.cwd??process.cwd(),this.defaults.path),r=async()=>{let c=await nt(o,()=>I(o));return t({pmRoot:o,author:C(this.defaults.author,c.author_default)})};if(this.defaults[cn]===!0){let c=process.cwd(),l=()=>vu(o,Bt({path:o}),void 0,c,r);return n?nt(o,l):l()}let i=Rt()!==void 0;i&&Di(this.defaults.cwd);let s=i?void 0:this.defaults.cwd,a=()=>ku({...this.defaults,cwd:s,path:o},r);return n?nt(o,a):a()}previewItemMutations(t){return this.withItemTransactionContext(async n=>(await import("./item-transaction-56J5OCHA.js")).previewItemMutations({...t,...n}),!0)}commitItemMutations(t){return this.withItemTransactionContext(async n=>(await import("./item-transaction-56J5OCHA.js")).commitItemMutations({...t,...n}))}get itemTransactions(){let t=(n,o)=>this.withItemTransactionContext(async r=>(await import("./item-transaction-56J5OCHA.js")).abandonItemTransaction({...o,...r,transactionId:n}));return{status:n=>this.withItemTransactionContext(async o=>(await import("./item-transaction-56J5OCHA.js")).readItemTransaction(o.pmRoot,n),!0),abandon:t,supersede:(n,o,r)=>t(n,{...r,supersededBy:o})}}readItemRevision(t){return this.withItemTransactionContext(async({pmRoot:n})=>(await import("./item-revision-3LENTXYF.js")).readItemRevision(t,{pmRoot:n}))}async withExpectedItemRevisions(t,n){let o=await import("./item-revision-3LENTXYF.js"),r="",i=await this.withItemTransactionContext(({pmRoot:a})=>(r=a,o.bindExpectedItemRevisions(t,{pmRoot:a}))),s=this.defaults.noExtensions===!0&&this.defaults[cn]!==!0;return o.runWithBoundItemRevisionScope(i,n,{scopeArgs:["--pm-path",r,...s?["--no-extensions"]:[]]})}context(t={}){return this.runTyped("context",{options:t})}listAllItemMetadataLight(){return Fd(this.defaults.path,this.defaults.cwd)}list(t={}){return this.runTyped("list",{options:t})}async listAllComplete(t={}){return to(await this.list(Fr(t)),t)}search(t,n={}){return this.runTyped("search",{query:t,options:n})}get(t,n={}){return this.runTyped("get",{id:t,options:n})}next(t={}){return this.runTyped("next",{options:t})}aggregate(t={}){return this.runTyped("aggregate",{options:t})}stats(t={}){return this.runTyped("stats",{options:t})}duplicates(t={}){return this.runTyped("duplicates",{options:t})}comments(t,n={}){return this.runTyped("comments",{id:t,options:n})}notes(t,n={}){return this.runTyped("notes",{id:t,options:n})}learnings(t,n={}){return this.runTyped("learnings",{id:t,options:n})}files(t,n={}){return this.runTyped("files",{id:t,options:n})}filesDiscover(t,n={}){return this.runTyped("files-discover",{id:t,options:n})}filesLookup(t){return this.runTyped("files-lookup",{options:t})}docs(t,n={}){return this.runTyped("docs",{id:t,options:n})}deps(t,n={}){return this.runTyped("deps",{id:t,options:n})}graph(t,n={},o={}){return this.runTyped("graph",{subcommand:t,...n,options:o})}async append(t,n,o={}){return $c(o,"append"),await this.runTyped("append",{id:t,...ee(st(o,{body:n}))})}init(t,n={}){return this.runTyped("init",{...t===void 0?{}:{prefix:t},options:n})}config(t,n,o,r,i={}){return this.runTyped("config",{scope:t,configAction:n,...o===void 0?{}:{key:o},...r===void 0?{}:{value:r},options:i})}schema(t,n={}){return this.runTyped("schema",{options:{...n,subcommand:t}})}workflowPolicy(t,n,o={}){return this.runTyped("schema",{name:n,options:{...o,subcommand:t}})}schemaList(){return this.runTyped("schema",{options:{subcommand:"list"}})}schemaShow(t){return this.runTyped("schema",{name:t,options:{subcommand:"show"}})}schemaAddType(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-type"}})}schemaRemoveType(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-type"}})}schemaAddStatus(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"add-status"}})}schemaRemoveStatus(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-status"}})}schemaAddField(t,n={}){let{type:o,...r}=n;return this.runTyped("schema",{name:t,options:{...r,fieldType:o,subcommand:"add-field"}})}schemaRemoveField(t,n={}){return this.runTyped("schema",{name:t,options:{...n,subcommand:"remove-field"}})}schemaListFields(){return this.runTyped("schema",{options:{subcommand:"list-fields"}})}schemaShowField(t){return this.runTyped("schema",{name:t,options:{subcommand:"show-field"}})}schemaApplyPreset(t,n={}){return this.runTyped("schema",{typePreset:t,options:{...n,subcommand:"apply-preset"}})}schemaInferTypes(t={}){return this.runTyped("schema",{options:{...t,subcommand:"add-type",infer:!0}})}schemaRenameType(t,n,o){return this.runTyped("schema",{name:t,options:{...o,subcommand:"rename-type",to:n}})}schemaRenameField(t,n,o,r){return this.runTyped("schema",{name:t,options:{...o,subcommand:"rename-field",to:n,...r?{fieldTypeScope:r}:{}}})}schemaRemapStatus(t,n,o){return this.runTyped("schema",{name:t,options:{...o,subcommand:"remap-status",to:n}})}schemaShowStatus(t){return this.runTyped("schema",{name:t,options:{subcommand:"show-status"}})}profile(t,n={}){return this.runTyped("profile",{options:{...n,subcommand:t}})}profileList(){return this.runTyped("profile",{options:{subcommand:"list"}})}profileShow(t){return this.runTyped("profile",{name:t,options:{subcommand:"show"}})}profileApply(t,n={}){return this.runTyped("profile",{name:t,options:{...n,subcommand:"apply"}})}profileLint(t){return this.runTyped("profile",{name:t,options:{subcommand:"lint"}})}validate(t={}){return this.runTyped("validate",{options:t})}health(t={}){return this.runTyped("health",{options:t})}gc(t={}){return this.runTyped("gc",{options:t})}assurance(t){return this.runTyped("assurance",{options:{...t,subcommand:t.action}})}historyRedact(t,n){return this.runTyped("history-redact",{id:t,options:n})}historyRepair(t,n={}){return this.runTyped("history-repair",{id:t,options:n})}historyRepairAll(t={}){return this.runTyped("history-repair",{options:{...t,all:!0}})}historyAttest(t={}){return this.runTyped("history-attest",{options:t})}historyCompact(t,n={}){return this.runTyped("history-compact",{id:t,options:n})}historyCompactBulk(t){return this.runTyped("history-compact",{options:t})}historyAuthorAcknowledge(t){return this.runTyped("history-author-acknowledge",{historyEvent:(t.events??[]).map(n=>`${n.item_id}:${String(n.line)}`),allActionable:t.all_actionable===!0,dryRun:t.dry_run===!0,planFingerprint:t.plan_fingerprint,limit:t.coordinate_limit,attributedAuthor:t.attributed_author,reviewer:t.reviewer,reason:t.reason})}plan(t,n,o={},r,i){return this.runTyped("plan",{fullChangedFields:!0,...n===void 0?{}:{id:n},...r===void 0?{}:{stepRef:r},...i===void 0?{}:{reorderTo:i},options:st(o,{subcommand:t})})}planCreate(t){return this.plan("create",void 0,t)}planShow(t,n={}){return this.plan("show",t,n)}planAddStep(t,n){return this.plan("add-step",t,n)}planUpdateStep(t,n,o){return this.plan("update-step",t,o,n)}planCompleteStep(t,n,o={}){return this.plan("complete-step",t,o,n)}planBlockStep(t,n,o){return this.plan("block-step",t,o,n)}planReorderStep(t,n,o,r={}){return this.plan("reorder-step",t,r,n,o)}planRemoveStep(t,n,o={}){return this.plan("remove-step",t,o,n)}planLink(t,n,o){return this.plan("link",t,o,n)}planUnlink(t,n,o){return this.plan("unlink",t,o,n)}planDecision(t,n){return this.plan("decision",t,n)}planDiscovery(t,n){return this.plan("discovery",t,n)}planValidation(t,n){return this.plan("validation",t,n)}planResume(t,n){return this.plan("resume",t,n)}planApprove(t,n={}){return this.plan("approve",t,n)}planMaterialize(t,n){return this.plan("materialize",t,n)}create(t={}){return this.runTyped("create",ee(t))}update(t,n={}){return this.runTyped("update",{id:t,...ee(n)})}reopen(t,n,o={}){return this.runTyped("item-reopen",{id:t,reason:n,fullChangedFields:!0,options:o})}close(t,n,o={}){return this.runTyped("close",{id:t,reason:n,...ee(o)})}claim(t,n={}){return this.runTyped("claim",{id:t,...ee(n)})}claimNext(t={}){return this.runTyped("claim",{next:!0,...ee(t)})}release(t,n={}){return this.runTyped("release",{id:t,...ee(n)})}copy(t,n={}){return this.runTyped("copy",{id:t,...ee(n)})}delete(t,n={}){return this.runTyped("delete",{id:t,...ee(n)})}restore(t,n,o={}){return this.runTyped("restore",{fullChangedFields:!0,id:t,options:{...o,target:n}})}focus(t,n={}){return this.runTyped("focus",{...t===void 0?{}:{id:t},...ee(n)})}startTask(t,n={}){return this.runTyped("start-task",{id:t,...ee(n)})}pauseTask(t,n={}){return this.runTyped("pause-task",{id:t,...ee(n)})}closeTask(t,n,o={}){return this.runTyped("close-task",{id:t,reason:n,...ee(o)})}extension(t,n={}){return this.runTyped("extension",{...t===void 0?{}:{target:t},options:n})}extensionList(t={}){return this.extension("list",t)}extensionActivate(t,n={}){return this.runTyped("extension-activate",{target:t,options:n})}extensionDeactivate(t,n={}){return this.runTyped("extension-deactivate",{target:t,options:n})}package(t,n={}){return this.runTyped("package",{...t===void 0?{}:{target:t},options:{...n,vocabulary:"package"}})}packageList(t={}){return this.package("list",t)}packageInstall(t,n={}){return this.runTyped("package-install",{target:t,options:n})}packageUninstall(t,n={}){return this.runTyped("package-uninstall",{target:t,options:n})}packageDoctor(t={}){return this.runTyped("package-doctor",{options:t})}packageManage(t,n={}){return this.runTyped("package-manage",{...t===void 0?{}:{target:t},options:n})}packageDescribe(t,n={}){return this.runTyped("package-describe",{...t===void 0?{}:{target:t},options:n})}packageReload(t={}){return this.runTyped("package-reload",{options:t})}packageCatalog(t={}){return this.runTyped("package-catalog",{options:t})}packageActivate(t,n={}){return this.runTyped("package-activate",{target:t,options:n})}packageDeactivate(t,n={}){return this.runTyped("package-deactivate",{target:t,options:n})}packageMigrate(t={}){return this.package(void 0,{...t,migrate:!0})}upgrade(t,n={}){return this.runTyped("upgrade",{...t===void 0?{}:{target:t},options:n})}};function iR(e={},t={}){return new w(t).context(e)}function sR(e={},t={}){return new w(t).list(e)}function aR(e={},t={}){return new w(t).listAllComplete(e)}function cR(e,t={},n={}){return new w(n).search(e,t)}function lR(e,t={},n={}){return new w(n).get(e,t)}function dR(e={},t={}){return new w(t).next(e)}function mR(e={},t={}){return new w(t).aggregate(e)}function pR(e={},t={}){return new w(t).stats(e)}function uR(e={},t={}){return new w(t).duplicates(e)}function fR(e,t={},n={}){return new w(n).comments(e,t)}function _R(e,t={},n={}){return new w(n).notes(e,t)}function hR(e,t={},n={}){return new w(n).learnings(e,t)}function gR(e,t={},n={}){return new w(n).files(e,t)}function yR(e,t={},n={}){return new w(n).filesDiscover(e,t)}function bR(e,t={}){return new w(t).filesLookup(e)}function wR(e,t={},n={}){return new w(n).docs(e,t)}function vR(e,t={},n={}){return new w(n).deps(e,t)}function kR(e,t={},n={},o={}){return new w(o).graph(e,t,n)}function SR(e,t,n={},o={}){return new w(o).append(e,t,n)}function AR(e,t={},n={}){return new w(n).init(e,t)}function xR(e,t,n,o,r={},i={}){return new w(i).config(e,t,n,o,r)}function IR(e,t={},n={}){return new w(n).schema(e,t)}function ER(e={}){return new w(e).schemaList()}function CR(e,t={}){return new w(t).schemaShow(e)}function RR(e,t={},n={}){return new w(n).schemaAddType(e,t)}function TR(e,t={},n={}){return new w(n).schemaRemoveType(e,t)}function OR(e,t={},n={}){return new w(n).schemaAddStatus(e,t)}function $R(e,t={},n={}){return new w(n).schemaRemoveStatus(e,t)}function FR(e,t={},n={}){return new w(n).schemaAddField(e,t)}function PR(e,t={},n={}){return new w(n).schemaRemoveField(e,t)}function NR(e={}){return new w(e).schemaListFields()}function LR(e,t={}){return new w(t).schemaShowField(e)}function MR(e,t={},n={}){return new w(n).schemaApplyPreset(e,t)}function DR(e={},t={}){return new w(t).schemaInferTypes(e)}function jR(e,t,n,o={}){return new w(o).schemaRenameType(e,t,n)}function GR(e,t,n,o,r={}){return new w(r).schemaRenameField(e,t,n,o)}function UR(e,t,n,o={}){return new w(o).schemaRemapStatus(e,t,n)}function qR(e,t={}){return new w(t).schemaShowStatus(e)}function zR(e,t={},n={}){return new w(n).profile(e,t)}function HR(e={}){return new w(e).profileList()}function BR(e,t={}){return new w(t).profileShow(e)}function WR(e,t={},n={}){return new w(n).profileApply(e,t)}function VR(e,t={}){return new w(t).profileLint(e)}function KR(e={},t={}){return new w(t).validate(e)}function JR(e={},t={}){return new w(t).health(e)}function YR(e={},t={}){return new w(t).gc(e)}function XR(e,t,n={}){return new w(n).historyRedact(e,t)}function ZR(e,t={},n={}){return new w(n).historyRepair(e,t)}function QR(e={},t={}){return new w(t).historyRepairAll(e)}function eT(e,t={},n={}){return new w(n).historyCompact(e,t)}function tT(e,t={}){return new w(t).historyCompactBulk(e)}function nT(e={},t={}){return new w(t).create(e)}function oT(e,t={},n={}){return new w(n).update(e,t)}function rT(e,t,n={},o={}){return new w(o).reopen(e,t,n)}function iT(e,t,n={},o={}){return new w(o).close(e,t,n)}function sT(e,t={},n={}){return new w(n).claim(e,t)}function aT(e={},t={}){return new w(t).claimNext(e)}function cT(e,t={},n={}){return new w(n).release(e,t)}function lT(e,t={},n={}){return new w(n).copy(e,t)}function dT(e,t={},n={}){return new w(n).delete(e,t)}function mT(e,t,n={},o={}){return new w(o).restore(e,t,n)}function pT(e,t={},n={}){return new w(n).focus(e,t)}function uT(e,t={},n={}){return new w(n).startTask(e,t)}function fT(e,t={},n={}){return new w(n).pauseTask(e,t)}function _T(e,t,n={},o={}){return new w(o).closeTask(e,t,n)}function hT(e,t={},n={}){return new w(n).extension(e,t)}function gT(e={},t={}){return new w(t).extensionList(e)}function yT(e,t={},n={}){return new w(n).extensionActivate(e,t)}function bT(e,t={},n={}){return new w(n).extensionDeactivate(e,t)}function wT(e,t={},n={}){return new w(n).package(e,t)}function vT(e={},t={}){return new w(t).packageList(e)}function kT(e,t={},n={}){return new w(n).packageInstall(e,t)}function ST(e,t={},n={}){return new w(n).packageUninstall(e,t)}function AT(e={},t={}){return new w(t).packageDoctor(e)}function xT(e,t={},n={}){return new w(n).packageManage(e,t)}function IT(e,t={},n={}){return new w(n).packageDescribe(e,t)}function ET(e={},t={}){return new w(t).packageReload(e)}function CT(e={},t={}){return new w(t).packageCatalog(e)}function RT(e,t={},n={}){return new w(n).packageActivate(e,t)}function TT(e,t={},n={}){return new w(n).packageDeactivate(e,t)}function OT(e,t={},n={}){return new w(n).upgrade(e,t)}async function $T(e,t={}){let n=typeof e=="string"?{...t,pmRoot:e}:e??t,o={json:!0,quiet:n.quiet??!0,noExtensions:n.noExtensions??!1,noPager:!0,profile:n.profile??!1,path:n.pmRoot};return Un(n,o)}var bu=Vs(),So=new sb;function ln(e){try{return ab(e)}catch{return Mi.resolve(e)}}function Rt(){let e=So.getStore();for(;e!==void 0&&!e.live;)e=e.parent;return e}async function Ct(e,t,n,o=!0){let r={root:ln(e),active:t,live:!0,parent:Rt(),ready:o};try{return await So.run(r,n)}finally{r.live=!1}}function Di(e){if(e===void 0||ln(e)===ln(process.cwd()))return;let t="Omit cwd inside an open extension scope and address the tracker with path, or make the call outside the scope.";throw new p(`A nested SDK call cannot change the working directory to "${e}" while its caller's extension scope is open. ${t}`,u.USAGE,{code:"invalid_argument_value",reason:"nested_cwd_unavailable",changed:!1,field:"cwd",required:t,nextSteps:[t]})}function ji(e,t,n,o){let r=Rt();if(r===void 0)return;let i=r===So.getStore(),s=r.root===ln(e);if(s&&!r.ready){let a="Do the work from a command or hook handler, after the tracker's extensions have activated.";throw new p(`An extension lifecycle callback cannot run SDK work for tracker ${r.root} while its extensions activate or deactivate. ${a}`,u.USAGE,{code:"invalid_argument_value",reason:"extension_scope_not_ready",changed:!1,required:a,nextSteps:[a]})}return i&&s&&t.noExtensions!==!0?o(r.active):Lo(()=>Ct(e,null,()=>Li(t,n,a=>Ct(e,a,()=>o(a))),!1))}function vu(e,t,n,o,r){let i=So.getStore();if(i===void 0)return r(null);let s=Rt(),a={...t,noExtensions:!1};return s===void 0?Ct(e,null,()=>Gi(a,n===void 0?void 0:o,o,c=>Ct(e,c,()=>r(c))),!1):s===i&&s.ready&&s.root===ln(e)?r(null):ji(e,a,o,r)}function ko(){Mo(Gs()),Do(Us()),jo(qs()),Go(zs()),Uo(Hs()),qo(Bs()),zo(Ws())}async function Gi(e,t,n,o){return Lo(()=>t===void 0?bu.read(()=>Li(e,n,o)):bu.write(()=>db(t,()=>Li(e,n,o))))}async function ku(e,t){let n=e.cwd,o=n===void 0?process.cwd():Mi.resolve(n),r=x(o,e.path),i=Bt({path:r,noExtensions:e.noExtensions});Rt()!==void 0&&Di(n);let s=ji(r,i,o,()=>t());return s!==void 0?s:Gi(i,n===void 0?void 0:o,o,a=>Ct(r,a,t))}function FT(e,t){return ku({path:e},t)}function cb(e){try{let t=e instanceof Error?e.stack:void 0,n=typeof t=="string"?t:Pa(e);return typeof n=="string"?n:"Unknown failure"}catch{return"Unknown failure"}}async function Li(e,t,n){let o=x(t,e.path);if(e.noExtensions)return ko(),Er({pmRoot:o},()=>n(null));if(!await ke(Se(o)))return ko(),n(null);let r=null,i;try{let s=await I(o),a=await kn({pmRoot:o,settings:s,cwd:t,noExtensions:!1}),c=await An({...a,loaded:a.loaded});i={loadResult:a,activationResult:c},Mo(c.hooks),Do(c.commands),jo(c.parsers),Go(c.preflight),Uo(c.services),qo(c.renderers),zo(c.registrations),r={registrations:c.registrations,commands:c.commands,pmRoot:o,packages:a.loaded}}catch(s){ko(),console.error("[pm-sdk] extension activation failed; continuing without active extensions:",cb(s))}try{return await Er({pmRoot:o,packages:r?.packages},()=>n(r))}finally{ko(),i&&await Sn(i.loadResult,i.activationResult).catch(()=>{})}}function Su(e,t){let n=De(e);return t?.registrations.commands.find(o=>De(o.action)===n)?.command??t?.commands.handlers.find(o=>De(o.command)===n)?.command}async function lb(e,t,n,o,r){if(!r)throw new p(`Unsupported native pm action: ${e}`,u.USAGE);let i=Su(e,r);if(!i)throw new p(`Unsupported native pm action: ${e}`,u.USAGE);let s=typeof n.author=="string"?n.author:o.author,a=sr(i),c=Wc(ar(t,n),Bc(r.registrations,a),a,Od(a)),l=await Xs({command:a,args:U(n.args??t.args),options:c,global:{...o,author:s},pm_root:r.pmRoot,sdk:Td(r.pmRoot,w.forActiveExtensionHost({pmRoot:r.pmRoot,author:s}),s,a)});if(!l.handled){if(Object.hasOwn(l,"cause"))throw Fa(i,l);let d=l.warnings.length>0?` (${l.warnings.join(", ")})`:"";throw new p(`Unsupported native pm action: ${e}${d}`,u.USAGE)}return l.result}async function db(e,t){let n=process.cwd();process.chdir(e);try{return await t()}finally{process.chdir(n)}}function mb(e){let t=K(e,"action"),n=De(t),o=be(Pr,n),r=o?.action??n,i={...e,action:r};return o?.options!==void 0&&(i.options={...o.options,...Nt(e.options)}),r==="package"&&(i.options={...Nt(i.options),vocabulary:"package"}),{action:r,args:i}}function pb(e,t,n,o){let r=e[cn]===!0,i=t.noExtensions===!0&&!r?["--no-extensions"]:[];if(n!==void 0)return["--pm-path",x(o,t.path),...i];let s=ds(t,o);return[...t.noExtensions===!0?s.slice(0,-1):s,...i]}async function ub(e){let t=mb(e),n=Bt(t.args);ls(n);let o=Gc(t.action),r=g(t.args,"cwd"),i=r===void 0?process.cwd():Mi.resolve(r);t.action==="init"&&(n[yl]=i),(t.action!=="init"||n.path!==void 0||(process.env.PM_PATH?.trim().length??0)>0)&&(n.path=x(i,n.path));let{expectHash:s,dispatchArgs:a}=Hc(t.args),c=async l=>{if(s===void 0)return wu(t.action,a,n,l);let{dispatchWithExpectedItemRevisions:d}=await import("./item-revision-3LENTXYF.js");return d({action:t.action,expectHash:s,defaultId:g(a,"id")??g(Nt(a.options),"id"),options:Nt(a.options),background:a.background,pmRoot:x(i,n.path),invocation:{scopeArgs:pb(e,n,r,i),...n.outputFormat===void 0?{}:{outputArgs:["--output-format",n.outputFormat]}},run:()=>wu(t.action,a,n,l)})};try{if(t.action==="history-attest")return await c(null);let l=x(i,n.path);if(Rt()!==void 0&&Di(r),e[cn]===!0)return await vu(l,n,r,i,c);let d=ji(l,n,i,c);return d!==void 0?await d:await Gi(n,r===void 0?void 0:i,i,m=>Ct(l,m,()=>c(m)))}finally{o&&yi()}}function PT(e=Yi){return e.map(t=>{let n=De(t),o=be(Pr,n),r=o?.action??n,i=be(gi,r)!==void 0;return{action:t,resolved_action:r,covered:i,route:i?o?"alias":"native":"missing"}})}async function wu(e,t,n,o){let r=be(gi,e),i=ir(t,e,{nativeAction:r!==void 0});if(e==="create"||e==="update"){let{assertNativeMutationOptions:d}=await import("./mutation-admission-PGKJTCG6.js");await d(e,t,i,n.path,Dc[e])}if(e==="update-many"){let{assertNativeUpdateManyOptions:d}=await import("./mutation-admission-PGKJTCG6.js");await d(t,i,n.path)}let s=r?void 0:Su(e,o),a=s===void 0?e:`extension:${s}`;Os(a,i),$s(a,i);let c={action:e,args:t,options:i,id:g(t,"id"),force:t.force===!0||i.force===!0,global:n,activeExtensions:o},l=r?await r(c):await lb(e,t,i,n,o);if(e==="history-attest")return l;{let d=Ds(a,i,l);return await Sd(x(process.cwd(),n.path),d),d}}var fb={closeManyOptionsFromFlat:jn,extensionOptionsFromArgs:ar,globalOptions:Bt,mutationListOptions:Uc,normalizeActionName:De,normalizeCommandPath:sr,normalizeMcpUpdateOptions:zc,normalizeMcpOptionsArrays:jc,optionsWithAuthor:ir,readRequiredString:K,readScalarString:Nc,readScalarStringAllowBlank:Lc,readStringArray:U,updateManyOptionsFromFlat:Gn,withAddNoteOption:Wt,withFilesDiscoveryOptions:Dn,withMutationCompaction:j};(process.env.NODE_ENV==="test"||process.env.VITEST!==void 0||process.env.VITEST_WORKER_ID!==void 0)&&(globalThis.__pmCliActionRunnerTestHooks=fb);export{Ir as a,kd as b,Cu as c,Tu as d,Ou as e,Er as f,Yt as g,xd as h,Zt as i,Qn as j,Td as k,Od as l,Bu as m,eo as n,Fr as o,$d as p,to as q,Qu as r,Ld as s,jd as t,Ud as u,Bd as v,Dr as w,jr as x,Gr as y,Ur as z,$f as A,Vr as B,cm as C,um as D,_m as E,pt as F,ii as G,ah as H,mk as I,pk as J,ci as K,gm as L,Rk as M,Tk as N,bm as O,km as P,Yk as Q,Ah as R,_i as S,Ih as T,Eh as U,Nm as V,Lm as W,Mm as X,Dm as Y,jm as Z,kS as _,SS as $,AS as aa,xS as ba,Gm as ca,zm as da,mo as ea,Km as fa,Jm as ga,Ym as ha,K as ia,yi as ja,eI as ka,tI as la,nI as ma,oI as na,rI as oa,ap as pa,iI as qa,Og as ra,Pg as sa,Dg as ta,jg as ua,Gg as va,z as wa,Ug as xa,qg as ya,zg as za,Hg as Aa,wi as Ba,mp as Ca,_t as Da,bi as Ea,pp as Fa,Bg as Ga,up as Ha,Wg as Ia,Vg as Ja,Kg as Ka,Jg as La,Yg as Ma,Xg as Na,ry as Oa,gp as Pa,sy as Qa,uy as Ra,wy as Sa,ky as Ta,Py as Ua,ib as Va,w as Wa,iR as Xa,sR as Ya,aR as Za,cR as _a,lR as $a,dR as ab,mR as bb,pR as cb,uR as db,fR as eb,_R as fb,hR as gb,gR as hb,yR as ib,bR as jb,wR as kb,vR as lb,kR as mb,SR as nb,AR as ob,xR as pb,IR as qb,ER as rb,CR as sb,RR as tb,TR as ub,OR as vb,$R as wb,FR as xb,PR as yb,NR as zb,LR as Ab,MR as Bb,DR as Cb,jR as Db,GR as Eb,UR as Fb,qR as Gb,zR as Hb,HR as Ib,BR as Jb,WR as Kb,VR as Lb,KR as Mb,JR as Nb,YR as Ob,XR as Pb,ZR as Qb,QR as Rb,eT as Sb,tT as Tb,nT as Ub,oT as Vb,rT as Wb,iT as Xb,sT as Yb,aT as Zb,cT as _b,lT as $b,dT as ac,mT as bc,pT as cc,uT as dc,fT as ec,_T as fc,hT as gc,gT as hc,yT as ic,bT as jc,wT as kc,vT as lc,kT as mc,ST as nc,AT as oc,xT as pc,IT as qc,ET as rc,CT as sc,RT as tc,TT as uc,OT as vc,$T as wc,ku as xc,FT as yc,ub as zc,PT as Ac};
|
|
2289
|
+
//# sourceMappingURL=chunk-ROTEELDL.js.map
|