@unbrained/pm-cli 2026.11.24 → 2026.11.25

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.
Files changed (150) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/cli/error-guidance.js +5 -5
  3. package/dist/cli-bundle/bundle-manifest.json +1 -1
  4. package/dist/cli-bundle/chunks/{chunk-I2OJ5B4A.js → chunk-4FZH5BTV.js} +2 -2
  5. package/dist/cli-bundle/chunks/{chunk-YYT3MIRF.js → chunk-6OIHST4I.js} +1 -1
  6. package/dist/cli-bundle/chunks/{chunk-ZYCOM4MS.js → chunk-7EPYCU7U.js} +2 -2
  7. package/dist/cli-bundle/chunks/{chunk-TVIJ2VCU.js → chunk-BVJMVU4Z.js} +5 -5
  8. package/dist/cli-bundle/chunks/{chunk-23K6DQQY.js → chunk-C4KIZQHW.js} +2 -2
  9. package/dist/cli-bundle/chunks/{chunk-FXJYZBWV.js → chunk-CNUFU454.js} +40 -40
  10. package/dist/cli-bundle/chunks/{chunk-PQUBVRV5.js → chunk-CONBVY2O.js} +2 -2
  11. package/dist/cli-bundle/chunks/{chunk-HNKK2UG6.js → chunk-CZEMEPPQ.js} +3 -3
  12. package/dist/cli-bundle/chunks/{chunk-Z7MFVRDV.js → chunk-DF6A7C32.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-ZOX4SWRL.js → chunk-FHLOGAGA.js} +2 -2
  14. package/dist/cli-bundle/chunks/chunk-FVY7U3SU.js +125 -0
  15. package/dist/cli-bundle/chunks/{chunk-VJSGUXGU.js → chunk-GBVF2ZB3.js} +2 -2
  16. package/dist/cli-bundle/chunks/{chunk-TKRY22SO.js → chunk-GZI7ZAB7.js} +2 -2
  17. package/dist/cli-bundle/chunks/{chunk-PW7U7WCE.js → chunk-K34FR5CO.js} +2 -2
  18. package/dist/cli-bundle/chunks/{chunk-D6PDUKUG.js → chunk-KHFUHGL3.js} +2 -2
  19. package/dist/cli-bundle/chunks/{chunk-DQDRA3SW.js → chunk-L6VS7F3R.js} +2 -2
  20. package/dist/cli-bundle/chunks/chunk-LOX3VY4T.js +2 -0
  21. package/dist/cli-bundle/chunks/{chunk-WWTPNIC2.js → chunk-LPW7S5KA.js} +2 -2
  22. package/dist/cli-bundle/chunks/{chunk-5DUP4AZA.js → chunk-MGJMQSN4.js} +2 -2
  23. package/dist/cli-bundle/chunks/{chunk-MXUSC5RS.js → chunk-OS5W4ZG2.js} +31 -31
  24. package/dist/cli-bundle/chunks/{chunk-37UDIJ2K.js → chunk-OWK2JL4I.js} +2 -2
  25. package/dist/cli-bundle/chunks/{chunk-SSALO4DB.js → chunk-SCIPT7WF.js} +2 -2
  26. package/dist/cli-bundle/chunks/{chunk-7X253M6Z.js → chunk-SX76UGEY.js} +2 -2
  27. package/dist/cli-bundle/chunks/{chunk-YW2HBHRO.js → chunk-VA4T37Q4.js} +2 -2
  28. package/dist/cli-bundle/chunks/{chunk-STOOTHZZ.js → chunk-WQOEVGLQ.js} +2 -2
  29. package/dist/cli-bundle/chunks/chunk-XHCIOLJP.js +3 -0
  30. package/dist/cli-bundle/chunks/{chunk-XFADNMGD.js → chunk-XKWJONAO.js} +2 -2
  31. package/dist/cli-bundle/chunks/chunk-YIGBEY7K.js +2 -0
  32. package/dist/cli-bundle/chunks/{chunk-7VRFEURZ.js → chunk-ZBOQEZ2H.js} +25 -25
  33. package/dist/cli-bundle/chunks/{chunk-PLIUU37C.js → chunk-ZLICQPRG.js} +2 -2
  34. package/dist/cli-bundle/chunks/{field-option-collisions-W66HSWMK.js → field-option-collisions-QE65APSD.js} +2 -2
  35. package/dist/cli-bundle/chunks/{indexed-receipt-blobs-BPYKN5Q7.js → indexed-receipt-blobs-H3MMNXXG.js} +2 -2
  36. package/dist/cli-bundle/chunks/{item-revision-D3LSBNIR.js → item-revision-INDHJV6X.js} +2 -2
  37. package/dist/cli-bundle/chunks/item-transaction-LCKK4XXB.js +2 -0
  38. package/dist/cli-bundle/chunks/{mutation-actor-OKL3CQVX.js → mutation-actor-KU7BMLUN.js} +2 -2
  39. package/dist/cli-bundle/chunks/mutation-admission-3OMCTQD4.js +2 -0
  40. package/dist/cli-bundle/chunks/{register-list-query-3LBV6CS2.js → register-list-query-3GV3LBOT.js} +2 -2
  41. package/dist/cli-bundle/chunks/{register-mutation-72AGTMNE.js → register-mutation-GZLF47SX.js} +2 -2
  42. package/dist/cli-bundle/chunks/{register-operations-XERFG2SH.js → register-operations-PBJZGCAL.js} +2 -2
  43. package/dist/cli-bundle/chunks/{register-setup-W22L34Z4.js → register-setup-ZLJEF6NZ.js} +2 -2
  44. package/dist/cli-bundle/chunks/{runtime-schema-JP2KBHBY.js → runtime-schema-Y4SHTEXL.js} +2 -2
  45. package/dist/cli-bundle/chunks/{settlement-hook-6MR32OOC.js → settlement-hook-ESAAEBRM.js} +2 -2
  46. package/dist/cli-bundle/chunks/{stage-T2LKWN7C.js → stage-3WIZBD4N.js} +2 -2
  47. package/dist/cli-bundle/focused-chunks/chunk-3Y5PTQ2F.js +27 -0
  48. package/dist/cli-bundle/focused-chunks/{chunk-XDBHD4CY.js → chunk-4LQL4EO6.js} +3 -3
  49. package/dist/cli-bundle/focused-chunks/{chunk-RIE3SJSE.js → chunk-4SX2BN4V.js} +2 -2
  50. package/dist/cli-bundle/focused-chunks/{chunk-B6BNHKUW.js → chunk-5RBC4WSE.js} +39 -39
  51. package/dist/cli-bundle/focused-chunks/chunk-7SSGTGZO.js +91 -0
  52. package/dist/cli-bundle/focused-chunks/{chunk-LMFIAQ2V.js → chunk-A4R57E4K.js} +2 -2
  53. package/dist/cli-bundle/focused-chunks/{chunk-46MP7IZN.js → chunk-BOIMP2AR.js} +2 -2
  54. package/dist/cli-bundle/focused-chunks/{chunk-GXP7Q4XM.js → chunk-BYQK5DGH.js} +2 -2
  55. package/dist/cli-bundle/focused-chunks/chunk-C3FEDTSD.js +44 -0
  56. package/dist/cli-bundle/focused-chunks/{chunk-REFMQY47.js → chunk-IAOKVKWW.js} +2 -2
  57. package/dist/cli-bundle/focused-chunks/{chunk-YD66IRSL.js → chunk-JOKRDFMQ.js} +2 -2
  58. package/dist/cli-bundle/focused-chunks/{chunk-HL47UQZJ.js → chunk-MB56Y4M6.js} +2 -2
  59. package/dist/cli-bundle/focused-chunks/{chunk-A6VEMCRR.js → chunk-NGFDPEP7.js} +1 -1
  60. package/dist/cli-bundle/focused-chunks/{chunk-RIQUIHYU.js → chunk-OCKKIECS.js} +2 -2
  61. package/dist/cli-bundle/focused-chunks/{chunk-24VRBNKE.js → chunk-PKX2EHE3.js} +2 -2
  62. package/dist/cli-bundle/focused-chunks/{chunk-C7WHWI7K.js → chunk-SXC2EO3E.js} +2 -2
  63. package/dist/cli-bundle/focused-chunks/{chunk-3ELVASVA.js → chunk-TQIKDFOD.js} +2 -2
  64. package/dist/cli-bundle/focused-chunks/{chunk-OZOCEB2Q.js → chunk-TRL4JDWX.js} +2 -2
  65. package/dist/cli-bundle/focused-chunks/{chunk-3OCDKITJ.js → chunk-UWWAVXG4.js} +2 -2
  66. package/dist/cli-bundle/focused-chunks/chunk-VMYVN36N.js +13 -0
  67. package/dist/cli-bundle/focused-chunks/{chunk-LMU7DDOA.js → chunk-VU2PH4PF.js} +2 -2
  68. package/dist/cli-bundle/focused-chunks/{chunk-EUQGZPGO.js → chunk-WL2R7T5G.js} +2 -2
  69. package/dist/cli-bundle/focused-chunks/chunk-WVA5KOXF.js +3 -0
  70. package/dist/cli-bundle/focused-chunks/{chunk-RLO2HCZT.js → chunk-X4EWD6TL.js} +2 -2
  71. package/dist/cli-bundle/focused-chunks/{chunk-SMMOZ3H3.js → chunk-XKLBTDJ7.js} +37 -37
  72. package/dist/cli-bundle/focused-chunks/{chunk-UVTUX54T.js → chunk-YYEWIKNI.js} +2 -2
  73. package/dist/cli-bundle/focused-chunks/{chunk-Z7W2RQIB.js → chunk-ZLRRII55.js} +2 -2
  74. package/dist/cli-bundle/focused-chunks/{field-option-collisions-UODPSV6W.js → field-option-collisions-5ROXGUME.js} +2 -2
  75. package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-EGEJMG3G.js → indexed-receipt-blobs-PG2VJ3MB.js} +2 -2
  76. package/dist/cli-bundle/focused-chunks/{item-revision-QH7RNBX4.js → item-revision-KYMSQVZE.js} +2 -2
  77. package/dist/cli-bundle/focused-chunks/{item-transaction-ZO72OINF.js → item-transaction-I4HLVHEJ.js} +2 -2
  78. package/dist/cli-bundle/focused-chunks/{mutation-actor-PHVLKG4I.js → mutation-actor-GGOQKAE6.js} +2 -2
  79. package/dist/cli-bundle/focused-chunks/{mutation-admission-ZSG5OECH.js → mutation-admission-OS36ZCMH.js} +2 -2
  80. package/dist/cli-bundle/focused-chunks/{runtime-schema-6RQMIDTN.js → runtime-schema-YXPYDD2C.js} +2 -2
  81. package/dist/cli-bundle/focused-chunks/{settlement-hook-FMLGKG7J.js → settlement-hook-4MGRERCT.js} +2 -2
  82. package/dist/cli-bundle/focused-chunks/{stage-AQMKRVX4.js → stage-4ZFWJUKO.js} +2 -2
  83. package/dist/cli-bundle/main.js +18 -18
  84. package/dist/cli-bundle/sdk-authoring.js +1 -1
  85. package/dist/cli-bundle/sdk-contracts.js +1 -1
  86. package/dist/cli-bundle/sdk-core.js +1 -1
  87. package/dist/cli-bundle/sdk-governance.js +1 -1
  88. package/dist/cli-bundle/sdk-graph.js +1 -1
  89. package/dist/cli-bundle/sdk-merge.js +61 -61
  90. package/dist/cli-bundle/sdk-query.js +1 -1
  91. package/dist/cli-bundle/sdk-runtime.js +1 -1
  92. package/dist/cli-bundle/sdk-testing.js +1 -1
  93. package/dist/cli-bundle/sdk.js +12 -12
  94. package/dist/core/shared/command-line.d.ts +54 -4
  95. package/dist/core/shared/command-line.js +1 -1
  96. package/dist/core/shared/errors.d.ts +9 -0
  97. package/dist/core/shared/secret-rules.js +5 -5
  98. package/dist/core/shared/url-credentials.d.ts +16 -3
  99. package/dist/core/shared/url-credentials.js +1 -1
  100. package/dist/core/store/item-store.d.ts +26 -4
  101. package/dist/core/store/item-store.js +1 -1
  102. package/dist/sdk/command-line.d.ts +1 -1
  103. package/dist/sdk/command-line.js +1 -1
  104. package/dist/sdk/context-intent-contracts.js +1 -1
  105. package/dist/sdk/governance/tracked-runtime-cache.js +1 -1
  106. package/dist/sdk/index.d.ts +1 -1
  107. package/dist/sdk/lifecycle/claim.d.ts +21 -1
  108. package/dist/sdk/lifecycle/claim.js +1 -1
  109. package/dist/sdk/lifecycle/task-composition.js +1 -1
  110. package/dist/sdk/ownership-source.d.ts +15 -1
  111. package/dist/sdk/ownership-source.js +1 -1
  112. package/dist/sdk/public-surface.json +1 -1
  113. package/dist/sdk/runtime-primitives.d.ts +1 -1
  114. package/docs/AGENT_GUIDE.md +2 -2
  115. package/docs/CONFIGURATION.md +1 -0
  116. package/docs/MUTATION_INTEGRITY.md +97 -8
  117. package/docs/SDK.md +40 -3
  118. package/docs/WORKSPACE_POSITION_AND_LIFECYCLE.md +17 -4
  119. package/marketplace.json +1 -1
  120. package/package.json +1 -1
  121. package/packages/pm-beads/package.json +1 -1
  122. package/packages/pm-calendar/package.json +1 -1
  123. package/packages/pm-command-kit/package.json +1 -1
  124. package/packages/pm-digital-twin/package.json +1 -1
  125. package/packages/pm-governance-audit/package.json +1 -1
  126. package/packages/pm-guide-shell/package.json +1 -1
  127. package/packages/pm-kanban/package.json +1 -1
  128. package/packages/pm-lifecycle-hooks/package.json +1 -1
  129. package/packages/pm-linked-test-adapters/package.json +1 -1
  130. package/packages/pm-search-advanced/package.json +1 -1
  131. package/packages/pm-templates/package.json +1 -1
  132. package/packages/pm-todos/package.json +1 -1
  133. package/packages/pm-vcs/package.json +1 -1
  134. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  135. package/plugins/pm-claude/package.json +1 -1
  136. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  137. package/plugins/pm-codex/package.json +1 -1
  138. package/plugins/pm-codex/plugin.json +1 -1
  139. package/runtime-dependencies.json +1 -1
  140. package/dist/cli-bundle/chunks/chunk-7IROAPWI.js +0 -3
  141. package/dist/cli-bundle/chunks/chunk-AWB5KBJS.js +0 -2
  142. package/dist/cli-bundle/chunks/chunk-I3BFCKZR.js +0 -2
  143. package/dist/cli-bundle/chunks/chunk-YOPTAIBD.js +0 -125
  144. package/dist/cli-bundle/chunks/item-transaction-M6NTBYH3.js +0 -2
  145. package/dist/cli-bundle/chunks/mutation-admission-EKPEOZMF.js +0 -2
  146. package/dist/cli-bundle/focused-chunks/chunk-3GT4A3ZN.js +0 -44
  147. package/dist/cli-bundle/focused-chunks/chunk-3Z7MCUJM.js +0 -3
  148. package/dist/cli-bundle/focused-chunks/chunk-5LDBS6MS.js +0 -91
  149. package/dist/cli-bundle/focused-chunks/chunk-FDZPRJXJ.js +0 -27
  150. package/dist/cli-bundle/focused-chunks/chunk-Q2HY44LV.js +0 -13
@@ -1,10 +1,60 @@
1
1
  /**
2
2
  * @module core/shared/command-line
3
- * Quotes tokenized recovery commands for the current platform shell.
3
+ * Quotes tokenized recovery commands for a declared shell dialect.
4
+ *
5
+ * Every rendered pm command (recovery `suggested_retry`, `restore_with`,
6
+ * next-step hints) is written for one shell. `posix` is the default outside
7
+ * Windows; on Windows the default is `cmd`, the cmd.exe / CreateProcess
8
+ * dialect settled in pm-b24b, and `PM_COMMAND_SHELL=powershell` switches to
9
+ * PowerShell literal quoting (pm-kjoudp, GH-1774).
4
10
  */
11
+ /** Shell a rendered pm command is quoted for. */
12
+ export type CommandShellDialect="posix"|"cmd"|"powershell";
13
+ /** Environment variable that declares the shell rendered pm commands are pasted into. */
14
+ export declare const COMMAND_SHELL_ENV="PM_COMMAND_SHELL";
15
+ /**
16
+ * The shell dialect rendered commands use: a recognized `PM_COMMAND_SHELL`
17
+ * value wins, otherwise `cmd` on Windows and `posix` elsewhere. An empty or
18
+ * unrecognized value keeps the platform default, so a typo never yields a
19
+ * dialect the caller did not choose.
20
+ */
21
+ export declare const resolveCommandShellDialect:(platform?:NodeJS.Platform,env?:Readonly<Record<string,string|undefined>>)=> CommandShellDialect;
5
22
  /** Quote one Windows argument with the linear CommandLineToArgvW escaping algorithm. */
6
23
  export declare const quoteWindowsCommandArg:(arg:string)=> string;
7
- /** Quote one command argument only when platform shell-significant characters require it. */
8
- export declare const quoteCommandArg:(arg:string,platform?:NodeJS.Platform)=> string;
24
+ /**
25
+ * Caret-escape a CommandLineToArgvW-quoted argument for cmd.exe. Every quote
26
+ * is escaped, so cmd.exe never enters a quoted region and removes each caret
27
+ * exactly once, handing CreateProcess the exact CommandLineToArgvW spelling.
28
+ * Every `%` is immediately followed by a caret (its own, or the one escaping
29
+ * the next metacharacter), so each text cmd.exe could read as a `%name%` or
30
+ * `%name:modifier%` reference names a variable starting with `^`, which no
31
+ * defined variable does; interactive and `cmd /c` percent expansion then
32
+ * leaves it intact.
33
+ */
34
+ export declare const escapeCmdMetacharacters:(quoted:string)=> string;
35
+ /**
36
+ * Quote one argument for cmd.exe: CommandLineToArgvW quoting, caret-escaped
37
+ * when cmd.exe would otherwise expand or split it. cmd.exe ends a command at
38
+ * a line break and no escape carries one, so each line break is rendered as
39
+ * a space: a pasted retry can never run the text after the break as another
40
+ * command (GH-1774).
41
+ */
42
+ export declare const quoteCmdCommandArg:(arg:string)=> string;
43
+ /** Double every single quote, including the typographic ones PowerShell also accepts, for a single-quoted PowerShell string. */
44
+ export declare const escapePowerShellSingleQuotes:(text:string)=> string;
45
+ /**
46
+ * Quote one argument as a PowerShell literal (single-quoted) string, where
47
+ * `$`, `$(...)`, backticks and `%` never expand.
48
+ */
49
+ export declare const quotePowerShellCommandArg:(arg:string)=> string;
50
+ /** Quote one command argument for `dialect` (default: the declared shell for `platform`) only when its shell-significant characters require it. */
51
+ export declare const quoteCommandArg:(arg:string,platform?:NodeJS.Platform,dialect?:CommandShellDialect)=> string;
52
+ /**
53
+ * Quote one argument for a POSIX shell. Double quotes with `"`, `\`, `$` and
54
+ * backticks escaped are exact for `sh -c` and scripts; an argument holding
55
+ * `!` is single-quoted instead, because interactive bash and zsh
56
+ * history-expand `!` inside double quotes (pm-oq893h).
57
+ */
58
+ export declare const quotePosixCommandArg:(arg:string)=> string;
9
59
  /** Render a complete pm command from already-tokenized arguments. */
10
- export declare const renderPmCommand:(argv:string[],platform?:NodeJS.Platform)=> string;
60
+ export declare const renderPmCommand:(argv:string[],platform?:NodeJS.Platform,dialect?:CommandShellDialect)=> string;
@@ -1,2 +1,2 @@
1
- const o=t=>{let n='"',e=0;for(const r of t){if(r==="\\"){e+=1;continue}n+="\\".repeat(r==='"'?e*2+1:e),n+=r,e=0}return`${n}${"\\".repeat(e*2)}"`},s=(t,n=process.platform)=>(n==="win32"?/^[A-Za-z0-9._:/\\@=-]+$/:/^[A-Za-z0-9._:/@=-]+$/).test(t)?t:n==="win32"?o(t):`"${t.replace(/(["\\$`])/g,"\\$1")}"`,a=(t,n=process.platform)=>{const e=t.map(r=>s(r,n)).join(" ");return e.length>0?`pm ${e}`:"pm"};export{s as quoteCommandArg,o as quoteWindowsCommandArg,a as renderPmCommand};
1
+ const l="PM_COMMAND_SHELL",a=new Map([["posix","posix"],["sh","posix"],["bash","posix"],["zsh","posix"],["cmd","cmd"],["cmd.exe","cmd"],["powershell","powershell"],["pwsh","powershell"]]),r=(e=process.platform,t=process.env)=>{const o=t[l]?.trim().toLowerCase(),n=o===void 0?void 0:a.get(o);return n!==void 0?n:e==="win32"?"cmd":"posix"},d=e=>{let t='"',o=0;for(const n of e){if(n==="\\"){o+=1;continue}t+="\\".repeat(n==='"'?o*2+1:o),t+=n,o=0}return`${t}${"\\".repeat(o*2)}"`},c=new Set(["(",")","!","^",'"',"<",">","&","|"]),i=e=>{let t="";for(let o=0;o<e.length;o+=1){const n=e[o];if(c.has(n)){t+=`^${n}`;continue}t+=n,n==="%"&&!c.has(e.charAt(o+1))&&(t+="^")}return t},u=/["%]/u,m=/\r\n|[\r\n]/gu,h=e=>{const t=e.replace(m," "),o=d(t);return u.test(t)?i(o):o},A=/['\u2018\u2019\u201A\u201B]/gu,_=e=>e.replace(A,"$&$&"),x=e=>`'${_(e)}'`,E={posix:/^(?!=)[A-Za-z0-9._:/@=-]+$/u,cmd:/^[A-Za-z0-9._:/\\@=-]+$/u,powershell:/^(?!--$)[A-Za-z0-9._:/\\=-][A-Za-z0-9._:/\\@=-]*$/u},C=(e,t=process.platform,o)=>{const n=o??r(t);return E[n].test(e)?e:n==="cmd"?h(e):n==="powershell"?x(e):f(e)},f=e=>e.includes("!")?`'${e.replaceAll("'","'\\''")}'`:`"${e.replace(/(["\\$`])/g,"\\$1")}"`,S=(e,t=process.platform,o)=>{const n=o??r(t),s=e.map(p=>C(p,t,n)).join(" ");return s.length>0?`pm ${s}`:"pm"};export{l as COMMAND_SHELL_ENV,i as escapeCmdMetacharacters,_ as escapePowerShellSingleQuotes,h as quoteCmdCommandArg,C as quoteCommandArg,f as quotePosixCommandArg,x as quotePowerShellCommandArg,d as quoteWindowsCommandArg,S as renderPmCommand,r as resolveCommandShellDialect};
2
2
  //# sourceMappingURL=command-line.js.map
@@ -280,6 +280,15 @@ last_activity_at:string|null;
280
280
  history_unreadable?:true;
281
281
  /** Present when the readable stream cannot prove the holder's idleness: no original record sets the holder, or after it a salvage discarded, a repair, redaction or merge reconcile rewrote, or a workspace restore replaced records. The claim is then never judged stale. */
282
282
  unproven_activity?:"claim_record_unavailable"|"discarded_history_tail"|"rewritten_history"|"workspace_restored";
283
+ /**
284
+ * Holder activity under the stale-work policy: `stale` when idleness is
285
+ * proven past the threshold, `active` when recorded activity is recent,
286
+ * and `unknown` when the history is unreadable, cannot prove idleness, or
287
+ * no valid activity time is recorded (GH-1774). pm always sets it;
288
+ * evidence built by an older producer may omit it, and readers then
289
+ * derive it from the other fields.
290
+ */
291
+ state?:"active"|"stale"|"unknown";
283
292
  /** Whole hours since `claimed_at`, or null when the claim time is unknown. */
284
293
  claim_age_hours:number|null;
285
294
  /** Whole hours since `last_activity_at`, or null when the activity time is unknown. */
@@ -1,6 +1,6 @@
1
- const A=`[^\\s/\\\\<>"'\\x60()\\[\\]{},;?=:#*]+`,d="[/\\\\]+",Ae="[\\p{L}\\p{N}._@-]+",R=Ae+"(?:"+d+A+")*",w="(?:(?:home|users)"+d+R+"|root"+d+R+")",Re="[/\\\\]"+w,$e="[/\\\\]{2,}"+w,me="/?[a-z]:"+d+"users"+d+R,he=A+"(?: +"+A+")*",x="(?:"+he+d+")?users"+d+R,we="[/\\\\]{2,}"+A+d+x,Se="(?:[a-z]:|volume\\{[a-f0-9-]+\\}|"+A+")",P="[/\\\\]{2}[?.]"+d+"(?:unc"+d+A+d+x+"|"+Se+d+"users"+d+R+")",ye="file:(?:"+P+"|(?:[/\\\\](?![/\\\\])|[/\\\\]{3,}|[/\\\\]{2}localhost"+d+")(?:"+w+"|[a-z]:"+d+"users"+d+R+")|[/\\\\]{2}(?:[a-z]:"+d+"users"+d+R+"|"+A+d+"(?:"+w+"|"+x+")))",Ne=new RegExp("(?:^|[^\\p{L}\\p{N}_./\\\\~])(?:"+Re+"|"+me+"|"+ye+")|(?:^|[^\\p{L}\\p{N}_:./\\\\~])(?:"+$e+"|"+we+"|"+P+")","giu"),Z=4,xe=/%[a-f0-9]{2}|\\(?:u[a-f0-9]{4}|x[a-f0-9]{2}|\/)/iu,Ie=new TextDecoder("utf-8");function Le(e){return e.replace(/(?:%[a-f0-9]{2})+/giu,n=>Ie.decode(Uint8Array.from(n.matchAll(/%([a-f0-9]{2})/giu),t=>Number.parseInt(t[1],16)))).replace(/%(?![a-f0-9]{2})[a-z0-9]{0,2}/giu,"\uFFFD")}function be(e){return e.replace(/\\+(?:u([a-f0-9]{4})|x([a-f0-9]{2})|(\/))?/giu,(n,t,r,s)=>{const i=t??r;return i===void 0?s??n:String.fromCharCode(Number.parseInt(i,16))})}function Te(e){return e.normalize("NFKC").replace(/[\p{Bidi_Control}\u200b-\u200f\u2060-\u206f\ufeff]/gu,"").replace(/[\u2215\u2044]/gu,"/").replace(/[\u043e\u041e]/gu,"o").replace(/[\u0455\u0405]/gu,"s")}function Oe(e,n){for(const[t,r]of[["percent_decode",Le],["json_unescape",be],["unicode_fold",Te]]){const s=r(e);s!==e&&!n.includes(t)&&n.push(t),e=s}return e}function*ke(e,n,t){let r=e;const s=[];for(let i=0;i<Z;i+=1){const o=r;if(r=Oe(r,s),!t){n.lastIndex=0;for(const a of r.matchAll(n))t=!0,yield{index:0,normalizations:[...s]}}if(r===o)break;i===Z-1&&xe.test(r)&&(yield{index:0,normalizations:[...s],normalization_incomplete:!0})}}function*Ce(e,n){let t=0;for(const r of e.split(`
2
- `)){n.lastIndex=0;let s=!1;for(const i of r.matchAll(n))s=!0,yield{index:t+i.index};for(const i of ke(r,n,s))yield{...i,index:t};t+=r.length+1}}const M="password|passphrase",S=4,g=4096,m=e=>`${e}+(?!${e})`,D=String.raw`'[^'\r\n]*'|"[^"\\\r\n]*(?:\\.[^"\\\r\n]*){0,${g}}"`,ze=String.raw`\$\{(?:${m(String.raw`[^{}$'"\\\r\n]`)}|\\[^\r\n]|${D}|\$(?!\{)|\$\{[^{}\r\n]*\}){0,${g}}\}`+String.raw`|\$\((?:${m(String.raw`[^()$'"\\\r\n]`)}|\\[^\r\n]|${D}|\$(?!\()|\$\([^()\r\n]*\)){0,${g}}\)`,U=String.raw`${ze}|<[^<>\r\n]*>|${m(String.raw`[A-Za-z0-9!@#%^&*._+\-=]`)}|\$(?![{(])`,Pe=String.raw`"[^"]*"|'[^']*'`,v=String.raw`(?:"[^"\s]*"|'[^'\s]*')(?:${U}){0,${g}}`,V=new RegExp(String.raw`(?!config\.auth\.password\s*(?:\|\|\s*(?:''|"")|\?\s*unescape\(encodeURIComponent\(config\.auth\.password\)\)\s*:\s*(?:''|""))(?=[ \t]*(?:\/\*(?:[^*]|\*(?!\/))*\*\/[ \t]*)*(?:;|$|\/\/[^\r\n\u2028\u2029]*(?:\r\n)?$)))`+`((?:${U}){1,${g}}(?:${v}){0,${S}}|(?:${v}){1,${S}}|${Pe})`),Ze=8,F="token|secret|password|passwd|api[_-]?key",I="(?<![a-z0-9_]|[a-z0-9_]-)(?:(?:[a-z0-9]+_)+(?:password|passphrase)|(?:[a-z0-9]+[_-])*(?:secret|token|(?:api|secret|private|access)[_-]?key|client[_-]?secret|passwd|pwd))",E=4096,H=String.raw`"(?=[^"\s]{8}[^"\s]*")|'(?=[^'\s]{8}[^'\s]*')|(?!["'])`,B=String.raw`(?![<[$/]|~\/|\.\.?\/|[A-Za-z][\w+.-]*:\/\/|%[A-Za-z_]\w*%|[A-Za-z]:[\\/]|(?<=")(?:(?:[A-Za-z_]\w*\.){1,${E}}[A-Za-z_]\w*|[A-Za-z]+(?:-[A-Za-z]+){0,${E}}|(?:[\w.-]+\/){1,${E}}[\w.-]+\.[A-Za-z][A-Za-z0-9]{0,4})"|(?<=')(?:(?:[A-Za-z_]\w*\.){1,${E}}[A-Za-z_]\w*|[A-Za-z]+(?:-[A-Za-z]+){0,${E}}|(?:[\w.-]+\/){1,${E}}[\w.-]+\.[A-Za-z][A-Za-z0-9]{0,4})'|(?<!["'])[A-Za-z]+(?:-[A-Za-z]+){0,${E}}(?![\w!@#$%^&*.+\-=/~])|(?<!["'])(?:[A-Za-z_]\w*\.){1,${E}}[A-Za-z_]\w*(?![\w!@#$%^&*.+\-=/~])|(?<!["'])(?:[\w.-]+\/){1,${E}}[\w.-]+\.[A-Za-z][A-Za-z0-9]{0,4}(?=[\s,;)}\]]|$)|(?<!["'])[\w$.]+\()(?:(?<=")[^\s"]{8}[^\s"]*|(?<=')[^\s']{8}[^\s']*|(?<==)[A-Za-z0-9!@#$%^&*._+\-=/~?:|]{8,}|(?<!["'=])[A-Za-z0-9!@#$%^&*._+\-=/~]{8,})`,L=new RegExp(`(?:${H})(${B})`,"iy"),Me=8,De=String.raw`[A-Za-z0-9!@#%^*._+\-=/~]`,q=String.raw`&(?!&)`,Ue=64,W=String.raw`'[^'\s]*'|"[^"\\\s]*(?:\\\S[^"\\\s]*){0,${g}}"`,K=String.raw`\$\{(?:${m(String.raw`[^{}$'"\\\s]`)}|\\\S|${W}|\$(?!\{)|\$\{[^{}\s]*\}){0,${g}}\}`+String.raw`|\$\((?:${m(String.raw`[^()$'"\\\s]`)}|\\\S|${W}|\$(?!\()|\$\([^()\s]*\)){0,${g}}\)`+String.raw`|<[^<>\s]*>|\$[A-Za-z_]\w*(?!\w)`,j=e=>String.raw`${K}|${m(e)}|${q}|\$(?![{(A-Za-z_])`,Q=e=>String.raw`(?:"[^"\s]*"|'[^'\s]*')(?:${j(e)}){0,${g}}`,ve=e=>String.raw`(?:(?:${e}|${q}){1,${Ue}}(?=[$<]))?(?:${K})`+String.raw`(?:${j(e)}){0,${g}}(?:${Q(e)}){0,${S}}`,Ve=e=>String.raw`(?:${Q(e)}){1,${S}}`,G=e=>String.raw`(?<!["'])(?:${e(De)})`,Y=String.raw`(?:[\w@#~]|!(?![.+\-*/%=^!(]))`,Fe=String.raw`(?=(?:"[^"\s]*"|'[^'\s]*')[$<"']`+String.raw`|"(?=[^"\s]*[$<])[^"\s]*"${Y}|'(?=[^'\s]*[$<])[^'\s]*'${Y})`,He=String.raw`(?<=")(?=[^"\s]*[$<])[^"\s]+|(?<=')(?=[^'\s]*[$<])[^'\s]+`,X=new RegExp(`(?:${Fe}|${H})((?=["'])(?:${G(Ve)})|${He}|${G(ve)}|${B})`),J=/["']?([A-Za-z0-9+/=_-]{24,})/,tt=[{name:"private-key",mutationRule:"private_key",category:"credential",regex:/-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/g},{name:"github-token",mutationRule:"github_token",category:"credential",regex:/\b(?:gh[opsru]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})\b/g},{name:"npm-token",mutationRule:"npm_token",category:"credential",regex:/\bnpm_[A-Za-z0-9]{20,}\b/g},{name:"aws-access-key",mutationRule:"aws_access_key",category:"credential",regex:/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g},{name:"google-api-key",mutationRule:"google_api_key",category:"credential",regex:/\bAIza[0-9A-Za-z_-]{35}\b/g},{name:"slack-token",mutationRule:"slack_token",category:"credential",regex:/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g},{name:"anthropic-api-key",mutationRule:"anthropic_api_key",category:"credential",regex:/\bsk-ant-[A-Za-z0-9_-]{20,}\b/g},{name:"openai-api-key",mutationRule:"openai_api_key",category:"credential",regex:/\bsk-(?!ant-)[A-Za-z0-9_-]{20,}\b/g},{name:"gitlab-token",mutationRule:"gitlab_token",category:"credential",regex:/\bglpat-[A-Za-z0-9_.-]{20,}\b/g},{name:"jwt-like-token",mutationRule:"jwt_like_token",category:"credential",regex:/\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g},{name:"npm-auth-token-assignment",mutationRule:"npm_auth_token_assignment",category:"credential",regex:/_authToken\s*=\s*\S+/g},{name:"sentry-user-token",mutationRule:"sentry_user_token",category:"credential",regex:/\bsntryu_[A-Za-z0-9]{20,}\b/g},{name:"sentry-org-token",mutationRule:"sentry_org_token",category:"credential",regex:/\bsntrys_[A-Za-z0-9_-]{20,}\b/g},{name:"private-ip",mutationRule:"private_ip",category:"network",regex:/\b(?:10\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|172\.(?:1[6-9]|2\d|3[01])\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|192\.168\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d))\b/g},{name:"private-ssh-target",mutationRule:"private_ssh_target",category:"network",regex:/\b(?:ssh|scp|rsync)\s+[A-Za-z0-9._-]+@(?:10\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|172\.(?:1[6-9]|2\d|3[01])\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|192\.168\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d))\b/g},{name:"sshpass-inline-password",mutationRule:"sshpass_inline_password",category:"credential",regex:/\bsshpass\s+-p\s+["'][^"']{6,}["']/g},{name:"password-assignment",mutationRule:"password_assignment",category:"credential",regex:new RegExp(String.raw`\b(?:${M})\s*[:=]\s*`+V.source,"gi"),structured:{keys:M,value:V.source,element:!0},minimumLiteralLength:Ze},{name:"absolute-home-path",mutationRule:"absolute_home_path",category:"path",regex:Ne,excludeFiles:/^(?:tests\/|examples\/)/},{name:"user-at-private-host",mutationRule:"user_at_private_host",category:"network",regex:/(?<![A-Za-z0-9._-])[A-Za-z0-9._-]+@(?:10\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|172\.(?:1[6-9]|2\d|3[01])\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|192\.168\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d))\b/g,excludeFiles:/^(?:tests\/|examples\/)/},{name:"high-entropy-assignment",mutationRule:"high_entropy_assignment",category:"credential",regex:new RegExp(String.raw`\b(?:${F})\s*[:=]\s*`+J.source,"gi"),structured:{keys:F,value:J.source},mutationOnlyReason:"Generic assignments in source code are not credentials; preserve the existing mutation heuristic without treating source identifiers as secrets.",minimumEntropy:3.5},{name:"credential-key-assignment",mutationRule:"credential_key_assignment",category:"credential",regex:new RegExp(String.raw`\b(?:${I})\s*[:=]\s*`+X.source,"gi"),structured:{keys:I,value:X.source,element:!0,elementValue:!0},mutationOnlyReason:"Key-named assignments in source code and test fixtures are identifiers and synthetic data; repository scans keep the token-format rules, which recognize real credentials there.",minimumEntropy:3,minimumLiteralLength:Me,literalValue:L,baseline:{regex:new RegExp(String.raw`\b(?:${I})\s*[:=]\s*`+L.source,"gi"),value:L.source},rejectValue:/^(?:[\w.-]+\/)*id_(?:rsa|dsa|ecdsa|ed25519)(?:_sk)?(?:\.pub)?$/u,rejectStatementReference:/^[A-Z]+(?:_[A-Z]+)+$/u}];function*rt(e,n){if(e.mutationRule==="absolute_home_path"){yield*Ce(n,e.regex);return}for(const t of ne(e))yield*Ge(t,n),t.structured&&(yield*Pn(t,t.structured,n))}const ee=new WeakMap;function ne(e){const n=e.baseline;if(n===void 0)return[e];let t=ee.get(e);return t===void 0&&(t={...e,regex:n.regex,minimumLiteralLength:void 0,literalValue:void 0,baseline:void 0},e.structured&&(t.structured={...e.structured,value:n.value}),ee.set(e,t)),[e,t]}function Be(e,n){const t=e[n-1]==="#"||e[n-1]==="!"?n-1:n;return e[t-1]==="{"&&e[t-2]==="$"}const b=new WeakSet,te=new WeakMap,qe=4096;function We(e,n,t){const r=[],s=[],i=n+t.length;return re(e,n,i,s,r),re(e,i,Math.min(e.length,i+qe),s),r}function re(e,n,t,r,s){for(let i=n;i<t&&(s!==void 0||r.length>0);i+=1){const o=r.at(-1);if(e[i]==="$"&&(e[i+1]==="{"||e[i+1]==="(")&&o?.quoted!=="'"){const a={open:i,close:t,command:e[i+1]==="(",quoted:[]};s?.push(a),r.push({span:a,closer:e[i+1]==="{"?"}":")"}),i+=1}else o!==void 0&&(i=Ke(e,i,r))}}function Ke(e,n,t){const r=t.at(-1),s=e[n];return s==="\\"&&r.quoted!=="'"?n+1:(r.quoted!==void 0?s===r.quoted&&(r.span.quoted.push([r.quoteStart,n]),r.quoted=void 0):s==="'"||s==='"'?(r.quoted=s,r.quoteStart=n):s===r.closer&&(t.pop().span.close=n),n)}function je(e){const n=[];let t=0;return r=>{for(;t<e.length&&e[t].open<r;t+=1){for(;n.length>0&&n.at(-1).close<e[t].open;)n.pop();n.push(e[t])}for(;n.length>0&&n.at(-1).close<r;)n.pop();return n.at(-1)}}function Qe(e,n){let t=0,r=e.quoted.length-1;for(;t<=r;){const s=t+r>>1,[i,o]=e.quoted[s];if(n<i)r=s-1;else if(n>o)t=s+1;else return!0}return!1}const se=/\$[({A-Za-z_]|</u;function*Ge(e,n){const t=e.regex;t.lastIndex=0;const r=Ye(e);let s;for(const i of n.matchAll(t))N(e,i)?yield{index:i.index}:r!==void 0&&se.test(i[1])&&(s??=new RegExp(t),yield*Xe(e,s,n,i,r==="deep"))}function Ye(e){return e.minimumLiteralLength===void 0?void 0:e.minimumEntropy===void 0&&e.literalValue===void 0&&e.rejectValue===void 0?"deep":"shallow"}function*Xe(e,n,t,r,s){const i=r.index+r[0].length;n.lastIndex=i-r[1].length;let o;for(let a=n.exec(t);a!==null&&a.index<i;a=n.exec(t)){if(Be(t,a.index)){n.lastIndex=a.index+1;continue}o??=je(We(t,i-r[1].length,r[1]));const u=o(a.index);u!==void 0&&(te.set(a,u.close),u.command&&!Qe(u,a.index)&&b.add(a)),N(e,a)?yield{index:a.index}:s&&se.test(a[1])&&(n.lastIndex=a.index+a[0].length-a[1].length)}}const ie=new Map,oe=/[\r\n\u2028\u2029]/u;function T(e){const n=`${e.keys}\0${e.value}\0${e.element===!0}`;let t=ie.get(n);return t||(t={key:new RegExp(String.raw`\b(?:${e.keys})(["']?)\s*[:=]\s*`,"gi"),value:new RegExp(e.value,"iyd"),...e.element?{element:{open:new RegExp(String.raw`<(?:${e.keys})(?:\s[^<>]*)?>`,"gi"),close:new RegExp(String.raw`<\/(?:${e.keys})\s*>`,"iy"),span:new RegExp(String.raw`<(?!\/?(?:${e.keys})\b)[^<>]*>`,"iy")}}:{}},ie.set(n,t)),t}function ae(e,n){const t=e[n];for(let r=n+1;r<e.length;r+=1){const s=e[r];if(s==="\\")r+=1;else if(s===t)return{end:r+1,terminated:!0}}return{end:e.length,terminated:!1}}function Je(e,n){return ae(e,n).end}function en(e,n,t){return e.at(-1)==="}"?t:n}function nn(e,n,t,r=t){const s=[];let i=!1;for(let o=n;o<e.length;o+=1){const a=e[o];switch(a){case"[":case"{":s.push(a==="["?"]":"}"),i=a==="{";break;case"]":case"}":if(s.pop()!==a||s.length===0)return{found:!1,end:o+1};i=!1;break;case",":i=s.at(-1)==="}";break;case":":i=!1;break;case'"':case"'":if(!i&&en(s,t,r)(o))return{found:!0,end:o};o=Je(e,o)-1;break;default:break}}return{found:!1,end:e.length}}const tn=/\\(?:U[0-9a-fA-F]{8}|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}|[0-7]{1,3}|[\s\S])/gu,rn={n:`
3
- `,r:"\r",t:" ",b:"\b",f:"\f",v:"\v"};function sn(e,n){const t=e[0],r=e.slice(1,n?-1:void 0).replaceAll(tn,o=>{const a=o[1];if((a==="u"||a==="x")&&o.length>2)return String.fromCharCode(Number.parseInt(o.slice(2),16));if(/^[0-7]$/u.test(a))return String.fromCharCode(Number.parseInt(o.slice(1),8));if(a==="U"&&o.length===10){const u=Number.parseInt(o.slice(2),16);return u<=1114111?String.fromCodePoint(u):"\uFFFD"}return rn[a]??a}),s=r.replaceAll(t,t==='"'?"'":'"').replaceAll(/[\r\n\u2028\u2029]/gu," "),i=n?t:"";return{reading:`${t}${s}${i}`,...ue(`${t}${r}${i}`,n)}}function ue(e,n){return{original:e,bodyStart:1,bodyEnd:e.length-(n?1:0)}}const on=64;function ce(e,n,t){const r=e[n-1];if(!t)return r!==void 0&&/[\p{L}\p{N}_.-]/u.test(r)?"prefixed":"exact";if(r===t)return"exact";const s=Math.max(0,n-on);for(let i=n-1;i>=s;i-=1){const o=e[i];if(o===t)return"prefixed";if(o===`
4
- `||o==="\r"||o==='"'||o==="'")return"malformed"}return"malformed"}function le(e,n,t,r=!1){const s=(a,u,c)=>{n.lastIndex=u;const l=n.exec(a);if(l===null||oe.test(l[0]))return null;const f=l.indices?.[1];return c!==void 0&&f!==void 0&&(l[1]=c.original.slice(Math.max(f[0],c.bodyStart),Math.min(f[1],c.bodyEnd)),O.add(l)),N(e,l)?l:null},i=a=>{if(t[a]!=='"'&&t[a]!=="'")return;const{end:u,terminated:c}=ae(t,a),l=t.slice(a,u);if(!r&&!l.includes("\\"))return;if(oe.test(l))return[];const f=sn(l,c);return(t[a]==="'"?[f,{reading:l,...ue(l,c)}]:[f]).map(_=>s(_.reading,0,_)).filter(_=>_!==null)},o=a=>{const u=i(a);if(u!==void 0)return u;const c=s(t,a);return c===null?[]:[c]};return{direct:a=>s(t,a)!==null,escaped:a=>(i(a)?.length??0)>0,accepts:a=>u=>o(u).some(c=>!(a&&/\s/u.test(an(e,c))))}}function an(e,n){return e.minimumLiteralLength===void 0?n[0]:de(n)}const O=new WeakSet;function de(e){const n=b.has(e)&&!$(h(e))?un(e[1]):void 0,t=n??e[1],r=n!==void 0||ln(e);return O.has(e)||$(h(e))?_e(t,r):nt(t,r)}function un(e){for(let n=0;n<e.length;n+=1){const t=e[n];if(t==="'"||t==='"')n=ge(e,n);else if(t==="$"&&(e[n+1]==="{"||e[n+1]==="("))n=Math.max(n,k(e,n)-1);else if(/[|&;<>]/u.test(t))return e.slice(0,n)}}const cn=/^[;,)}\]]{0,64}/u;function ln(e){const n=e.input,t=e.index+e[0].length,r=$(h(e))&&$(n[t])?t+1:$(e[0].at(-1))?t:-1,s=r===-1?t:r,i=cn.exec(n.slice(s,s+An))[0].length,o=s+i;if(o===n.length||/\s/u.test(n[o])||te.get(e)===s||b.has(e)&&/[|&;<>]/u.test(n[s]))return!0;if(r===-1||i===0)return!1;const a=dn(e,r===t+1),u=n.slice(o,o+40),c=/[}\]]/u.test(n.slice(s,o));return a!==void 0&&(pn.test(u)||(a==="element"||c)&&_n.test(u))}function dn(e,n){const t=e.input,r=e.index+e[0].length-e[1].length-(n?1:0),s=t.slice(Math.max(0,r-fn),r);return En.test(s)?"element":gn.test(s)?"key":void 0}const fn=512,gn=/[{,]\s*(["'])[^"'\r\n]{1,256}\1\s*[:=]\s*$/u,En=/[[,]\s*$/u,pn=/^(?:["'`]|[{[](?:[\s"'`{[\]}]|$|(?:-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null)[\s,\]}]))/u,_n=/^(?:-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null)[\s,\]}]/u,An=64,Rn=/^\s{0,16}\(/u,$n=/(?<![=!<>])=[ \t]{0,16}$/u;function h(e){return e.input[e.index+e[0].length-e[1].length-1]}function $(e){return e==='"'||e==="'"}const mn=/[$<"']/u;function hn(e){if(O.has(e)||$(h(e))||!/^[$<]/u.test(e[1]))return!1;const n=e.index+e[0].length,t=n-e[1].length,r=e.input.slice(n,n+18);if(e[1][0]==="<"&&(In(e[1])||$n.test(e.input.slice(Math.max(0,t-18),t))||bn.test(r)))return!0;const s=fe(e[1]),i=e[1][s]==="!"?e[1][s+1]:e[1][s];return Ln.test(i??"")||Rn.test(r)}function fe(e){let n=0;for(let t=k(e,n);t!==-1;t=k(e,n))n=t;return n}function k(e,n){const t=e[n];if(t==="<")return wn(e,n);if(t!=="$")return-1;const r=e[n+1];if(r==="{"||r==="(")return Sn(e,n+1,r);y.lastIndex=n;const s=y.exec(e)?.[0];return s===void 0?-1:n+s.length}function wn(e,n){const t=e.indexOf(">",n+1),r=e.indexOf("<",n+1);return t!==-1&&(r===-1||t<r)?t+1:-1}function Sn(e,n,t){const r=t==="{"?"}":")";let s=0;for(let i=n;i<e.length;i+=1){const o=e[i];if(o==="\\")i+=1;else if(o==="'"||o==='"')i=ge(e,i);else if(o===t)s+=1;else if(o===r&&--s===0)return i+1}return-1}function ge(e,n){const t=e[n];for(let r=n+1;r<e.length;r+=1){if(e[r]===t)return r;t==='"'&&e[r]==="\\"&&(r+=1)}return e.length}const yn=/^[\w$.[\]|&,{}:;?]+$/u,Nn=/^(?:"[^"]*"|'[^']*'|-?\d+(?:\.\d+)?)(?:\|(?:"[^"]*"|'[^']*'|-?\d+(?:\.\d+)?|[A-Za-z_$][\w$.]*))*$/u,xn=/\b(?:string|number|boolean|bigint|symbol|any|unknown|object|never|void|undefined|null)\b/u;function In(e){const n=e.slice(1,e.indexOf(">"));return Nn.test(n)?!0:yn.test(n)?xn.test(n)||/[.|&[{]/u.test(n)||/^[A-Z][\w$]*$/u.test(n)&&(n.length===1||/[a-z]/u.test(n)):!1}const Ln=/[.+\-*/%=^&]/u,bn=/^\s{0,16}(?:\?\.|\?\?|\|\||&&|[([])/u;function Tn(e,n,t){if(t)return!1;const r=n.replaceAll('"',"'");return e.lastIndex=0,e.exec(`"${r}"`)?.[1]===r}function st(e,n){if(!e.structured)return;const t=`${JSON.stringify(n)}:`,r=T(e.structured).key;r.lastIndex=0;for(let s=r.exec(t);s;s=r.exec(t)){if(s.index+s[0].length!==t.length)continue;const i=ce(t,s.index,s[1]);if(i!=="malformed")return i}}function it(e,n,t){if(!e.structured)return!1;const r=JSON.stringify(n).replaceAll("\u2028","\\u2028").replaceAll("\u2029","\\u2029");return ne(e).some(s=>le(s,T(s.structured).value,r,!0).accepts(t)(0))}function*On(e,n,t){const r=new RegExp(e.open);for(let s=r.exec(n);s;s=r.exec(n)){const i=s.index+s[0].length,o=kn(e,n,i);if(o===void 0){r.lastIndex=s.index+1;continue}t(n.slice(i,o.start).trim())&&(yield{index:s.index}),r.lastIndex=o.end}}function kn(e,n,t){for(let r=n.indexOf("<",t);r!==-1;){e.close.lastIndex=r;const s=e.close.exec(n);if(s!==null)return{start:r,end:r+s[0].length};e.span.lastIndex=r;const i=e.span.exec(n);if(i===null)return;r=n.indexOf("<",r+i[0].length)}}function Cn(e,n,t){return n<e.exact||t&&n<e.compact}function zn(e,n,t,r){return(t||e.escaped(r)&&!e.direct(r))&&n(r)}function*Pn(e,n,t){const r=T(n),s=le(e,r.value,t),i=new RegExp(r.key),o={exact:0,compact:0};for(let a=i.exec(t);a;a=i.exec(t)){const u=a[1],c=ce(t,a.index,u);if(c==="malformed")continue;const l=c==="prefixed",f=s.accepts(l),p=a.index+a[0].length,_=t[p];if(_==="["||_==="{"){if(Cn(o,p,l))continue;const z=nn(t,p,f,s.accepts(!0));o[l?"compact":"exact"]=z.end,z.found&&(yield{index:a.index})}else zn(s,f,u,p)&&(yield{index:a.index})}r.element&&(yield*On(r.element,t,Mn(e,n,r)))}const Zn=8;function Mn(e,n,t){if(!n.elementValue){const r=e.minimumLiteralLength??Zn;return s=>_e(s).length>=r}return r=>{const s=r.replaceAll('"',"'");t.value.lastIndex=0;const i=t.value.exec(`"${s}"`);return i===null||i[1]!==s?!1:(i[1]=r,N(e,i))}}function Dn(e,n,t){const r=n.index+n[0].length;return/^[ \t]*;/u.test(n.input.slice(r,r+64))&&!$(h(n))&&e.test(t)}function Un(e,n){for(let t=n+1;t<e.length;t+=1){if(e[t]===">")return t;if(e[t]==="<")return-1}return-1}function C(e,n){e.raw+=n,e.literal+=n}function vn(e,n,t){const r=e[n+1];if(e[n]!=="$"||r!=="{"&&r!=="(")return-1;const s=r==="{"?e.slice(n+2,n+2+jn(e,n+2)):"",i=t[0],o=t.length===1&&i.quote!==void 0&&i.literal.length===i.pieceStart;return t.push({close:r==="{"?"}":")",keep:s!=="",raw:`$${r}${s}`,literal:"",opensPiece:o}),n+2+s.length}const Vn=/[A-Za-z_]/u,Fn=/\w/u,Hn=/[{(A-Za-z_]/u,y=/\$[A-Za-z_]\w*/y,Bn=/^_*[A-Z][A-Z0-9_]*$/u,qn=/^\$[A-Za-z_]\w*$/u,Wn=/^(["'])\$[A-Za-z_]\w*\1$/u;function Kn(e,n,t){y.lastIndex=n;const r=y.exec(e)?.[0];return r===void 0?-1:(t.literal===""&&Bn.test(r.slice(1))?t.raw+=r:C(t,r),n+r.length)}function jn(e,n){if(!Vn.test(e[n]??""))return 0;let t=n+1;for(;t<e.length&&Fn.test(e[t]);)t+=1;e[t]===":"&&(t+=1);const r=e[t];return r==="-"||r==="="||r==="+"?t+1-n:0}function Qn(e,n){const t=e.pop(),r=e.at(-1);r.raw+=`${t.raw}${n}`,t.keep&&(r.literal+=t.literal)}const Ee=/[^$<"'\\})]+/y,Gn='$`"\\\n';function Yn(e,n){return e===`
5
- `?"":n==='"'&&!Gn.includes(e)?`\\${e}`:e}function Xn(e,n,t){const r=e[n],s=t.quote;if(s==='"'&&r==="$"&&Hn.test(e[n+1]??""))return-1;let i=1,o=r;if(r==="\\"&&s!=="'"&&n+1<e.length)i=2,o=Yn(e[n+1],s);else if(s===void 0){if(r!=='"'&&r!=="'")return-1;t.quote=r,o=""}else r===s&&(t.quote=void 0,o="");return t.raw+=e.slice(n,n+i),t.keep&&(t.literal+=o),n+i}function Jn(e,n,t,r,s){const i=t.at(-1);Ee.lastIndex=n;const o=Ee.exec(e)?.[0];if(o!==void 0)return C(i,o),n+o.length;if(t.length>1){const p=Xn(e,n,i);if(p!==-1)return p}else if(r&&et(e[n],i))return n+1;const a=vn(e,n,t);if(a!==-1)return a;const u=t.at(-1),c=e[n],l=s&&c==="$"?Kn(e,n,u):-1;if(l!==-1)return l;if(t.length>1&&c===u.close)return Qn(t,c),n+1;const f=c==="<"?Un(e,n):-1;return f!==-1?(u.raw+=e.slice(n,f+1),f+1):(C(u,c),n+1)}function et(e,n){return e!=='"'&&e!=="'"?!1:n.quote===void 0?(n.quote=e,n.pieceStart=n.literal.length,!0):e!==n.quote?!1:(n.quote=void 0,!0)}function pe(e,n,t){if(t&&(qn.test(e)||n&&Wn.test(e)))return"";const r={close:"}",keep:!0,raw:"",literal:""},s=[r];for(let i=0;i<e.length;)i=Jn(e,i,s,n,t);for(let i=s.length-1;i>0;i-=1){const o=s[i],a=s[i-1];a.raw+=o.raw,n&&i===1&&o.opensPiece===!0||(a.literal+=o.raw)}return r.literal}function _e(e,n=!0){return pe(e,!1,n)}function nt(e,n=!0){return pe(e,!0,n)}function N(e,n){const t=e.minimumLiteralLength===void 0?n[1]:de(n);if(e.minimumLiteralLength!==void 0&&t.length<e.minimumLiteralLength||e.literalValue&&mn.test(n[1])&&!Tn(e.literalValue,t,hn(n))||e.rejectValue?.test(t)===!0||e.rejectStatementReference&&Dn(e.rejectStatementReference,n,t))return!1;if(e.minimumEntropy===void 0)return!0;const r=[...t],s=new Map;for(const o of r)s.set(o,(s.get(o)??0)+1);let i=0;for(const o of s.values()){const a=o/r.length;i-=a*Math.log2(a)}return i>=e.minimumEntropy}const ot={leadingReferencesEnd:fe};export{Ne as PRIVATE_HOME_PATH_PATTERN,tt as SECRET_RULES,ot as _testOnly,N as acceptsSecretMatch,it as acceptsStructuredValue,_e as expandRuntimeReferences,Ce as findPrivateHomePathMatches,rt as findSecretRuleMatches,nt as literalAfterReferences,st as structuredKeyShape};
1
+ const R=`[^\\s/\\\\<>"'\\x60()\\[\\]{},;?=:#*]+`,d="[/\\\\]+",xe="[\\p{L}\\p{N}._@-]+",h=xe+"(?:"+d+R+")*",m="(?:(?:home|users)"+d+h+"|root"+d+h+")",Ie="[/\\\\]"+m,Ce="[/\\\\]{2,}"+m,be="/?[a-z]:"+d+"users"+d+h,ke=R+"(?: +"+R+")*",x="(?:"+ke+d+")?users"+d+h,ze="[/\\\\]{2,}"+R+d+x,Me="(?:[a-z]:|volume\\{[a-f0-9-]+\\}|"+R+")",U="[/\\\\]{2}[?.]"+d+"(?:unc"+d+R+d+x+"|"+Me+d+"users"+d+h+")",De="file:(?:"+U+"|(?:[/\\\\](?![/\\\\])|[/\\\\]{3,}|[/\\\\]{2}localhost"+d+")(?:"+m+"|[a-z]:"+d+"users"+d+h+")|[/\\\\]{2}(?:[a-z]:"+d+"users"+d+h+"|"+R+d+"(?:"+m+"|"+x+")))",Pe=new RegExp("(?:^|[^\\p{L}\\p{N}_./\\\\~])(?:"+Ie+"|"+be+"|"+De+")|(?:^|[^\\p{L}\\p{N}_:./\\\\~])(?:"+Ce+"|"+ze+"|"+U+")","giu"),v=4,Ze=/%[a-f0-9]{2}|\\(?:u[a-f0-9]{4}|x[a-f0-9]{2}|\/)/iu,Ue=new TextDecoder("utf-8");function ve(e){return e.replace(/(?:%[a-f0-9]{2})+/giu,n=>Ue.decode(Uint8Array.from(n.matchAll(/%([a-f0-9]{2})/giu),t=>Number.parseInt(t[1],16)))).replace(/%(?![a-f0-9]{2})[a-z0-9]{0,2}/giu,"\uFFFD")}function Ve(e){return e.replace(/\\+(?:u([a-f0-9]{4})|x([a-f0-9]{2})|(\/))?/giu,(n,t,r,s)=>{const i=t??r;return i===void 0?s??n:String.fromCharCode(Number.parseInt(i,16))})}function Fe(e){return e.normalize("NFKC").replace(/[\p{Bidi_Control}\u200b-\u200f\u2060-\u206f\ufeff]/gu,"").replace(/[\u2215\u2044]/gu,"/").replace(/[\u043e\u041e]/gu,"o").replace(/[\u0455\u0405]/gu,"s")}function Be(e,n){for(const[t,r]of[["percent_decode",ve],["json_unescape",Ve],["unicode_fold",Fe]]){const s=r(e);s!==e&&!n.includes(t)&&n.push(t),e=s}return e}function*He(e,n,t){let r=e;const s=[];for(let i=0;i<v;i+=1){const u=r;if(r=Be(r,s),!t){n.lastIndex=0;for(const o of r.matchAll(n))t=!0,yield{index:0,normalizations:[...s]}}if(r===u)break;i===v-1&&Ze.test(r)&&(yield{index:0,normalizations:[...s],normalization_incomplete:!0})}}function*We(e,n){let t=0;for(const r of e.split(`
2
+ `)){n.lastIndex=0;let s=!1;for(const i of r.matchAll(n))s=!0,yield{index:t+i.index};for(const i of He(r,n,s))yield{...i,index:t};t+=r.length+1}}const V="password|passphrase",N=4,g=4096,$=e=>`${e}+(?!${e})`,F=String.raw`'[^'\r\n]*'|"[^"\\\r\n]*(?:\\.[^"\\\r\n]*){0,${g}}"`,qe=String.raw`\$\{(?:${$(String.raw`[^{}$'"\\\r\n]`)}|\\[^\r\n]|${F}|\$(?!\{)|\$\{[^{}\r\n]*\}){0,${g}}\}`+String.raw`|\$\((?:${$(String.raw`[^()$'"\\\r\n]`)}|\\[^\r\n]|${F}|\$(?!\()|\$\([^()\r\n]*\)){0,${g}}\)`,B=String.raw`${qe}|<[^<>\r\n]*>|${$(String.raw`[A-Za-z0-9!@#%^&*._+\-=]`)}|\$(?![{(])`,Ge=String.raw`"[^"]*"|'[^']*'`,H=String.raw`(?:"[^"\s]*"|'[^'\s]*')(?:${B}){0,${g}}`,W=new RegExp(String.raw`(?!config\.auth\.password\s*(?:\|\|\s*(?:''|"")|\?\s*unescape\(encodeURIComponent\(config\.auth\.password\)\)\s*:\s*(?:''|""))(?=[ \t]*(?:\/\*(?:[^*]|\*(?!\/))*\*\/[ \t]*)*(?:;|$|\/\/[^\r\n\u2028\u2029]*(?:\r\n)?$)))`+`((?:${B}){1,${g}}(?:${H}){0,${N}}|(?:${H}){1,${N}}|${Ge})`),Ke=8,q="token|secret|password|passwd|api[_-]?key",I="(?<![a-z0-9_]|[a-z0-9_]-)(?:(?:[a-z0-9]+_)+(?:password|passphrase)|(?:[a-z0-9]+[_-])*(?:secret|token|(?:api|secret|private|access)[_-]?key|client[_-]?secret|passwd|pwd))",p=4096,G=String.raw`"(?=[^"\s]{8}[^"\s]*")|'(?=[^'\s]{8}[^'\s]*')|(?!["'])`,K=String.raw`(?![<[$/]|~\/|\.\.?\/|[A-Za-z][\w+.-]*:\/\/|%[A-Za-z_]\w*%(?=$|[\s"',;)}\]<>&|\\])|[A-Za-z]:[\\/]|(?<=")(?:(?:[A-Za-z_]\w*\.){1,${p}}[A-Za-z_]\w*|[A-Za-z]+(?:-[A-Za-z]+){0,${p}}|(?:[\w.-]+\/){1,${p}}[\w.-]+\.[A-Za-z][A-Za-z0-9]{0,4})"|(?<=')(?:(?:[A-Za-z_]\w*\.){1,${p}}[A-Za-z_]\w*|[A-Za-z]+(?:-[A-Za-z]+){0,${p}}|(?:[\w.-]+\/){1,${p}}[\w.-]+\.[A-Za-z][A-Za-z0-9]{0,4})'|(?<!["'])[A-Za-z]+(?:-[A-Za-z]+){0,${p}}(?![\w!@#$%^&*.+\-=/~])|(?<!["'])(?:[A-Za-z_]\w*\.){1,${p}}[A-Za-z_]\w*(?![\w!@#$%^&*.+\-=/~])|(?<!["'])(?:[\w.-]+\/){1,${p}}[\w.-]+\.[A-Za-z][A-Za-z0-9]{0,4}(?=[\s,;)}\]]|$)|(?<!["'])[\w$.]+\()(?:(?<=")[^\s"]{8}[^\s"]*|(?<=')[^\s']{8}[^\s']*|(?<==)[A-Za-z0-9!@#$%^&*._+\-=/~?:|]{8,}|(?<!["'=])[A-Za-z0-9!@#$%^&*._+\-=/~]{8,})`,C=new RegExp(`(?:${G})(${K})`,"iy"),Qe=8,je=String.raw`[A-Za-z0-9!@#%^*._+\-=/~]`,Q=String.raw`&(?!&)`,Ye=64,j=String.raw`'[^'\s]*'|"[^"\\\s]*(?:\\\S[^"\\\s]*){0,${g}}"`,Y=String.raw`\$\{(?:${$(String.raw`[^{}$'"\\\s]`)}|\\\S|${j}|\$(?!\{)|\$\{[^{}\s]*\}){0,${g}}\}`+String.raw`|\$\((?:${$(String.raw`[^()$'"\\\s]`)}|\\\S|${j}|\$(?!\()|\$\([^()\s]*\)){0,${g}}\)`+String.raw`|<[^<>\s]*>|\$[A-Za-z_]\w*(?!\w)`,X=e=>String.raw`${Y}|${$(e)}|${Q}|\$(?![{(A-Za-z_])`,J=e=>String.raw`(?:"[^"\s]*"|'[^'\s]*')(?:${X(e)}){0,${g}}`,Xe=e=>String.raw`(?:(?:${e}|${Q}){1,${Ye}}(?=[$<]))?(?:${Y})`+String.raw`(?:${X(e)}){0,${g}}(?:${J(e)}){0,${N}}`,Je=e=>String.raw`(?:${J(e)}){1,${N}}`,ee=e=>String.raw`(?<!["'])(?:${e(je)})`,ne=String.raw`(?:[\w@#~]|!(?![.+\-*/%=^!(]))`,en=String.raw`(?=(?:"[^"\s]*"|'[^'\s]*')[$<"']`+String.raw`|"(?=[^"\s]*[$<])[^"\s]*"${ne}|'(?=[^'\s]*[$<])[^'\s]*'${ne})`,nn=String.raw`(?<=")(?=[^"\s]*[$<])[^"\s]+|(?<=')(?=[^'\s]*[$<])[^'\s]+`,te=new RegExp(`(?:${en}|${G})((?=["'])(?:${ee(Je)})|${nn}|${ee(Xe)}|${K})`),re=/["']?([A-Za-z0-9+/=_-]{24,})/,zt=[{name:"private-key",mutationRule:"private_key",category:"credential",regex:/-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/g},{name:"github-token",mutationRule:"github_token",category:"credential",regex:/\b(?:gh[opsru]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})\b/g},{name:"npm-token",mutationRule:"npm_token",category:"credential",regex:/\bnpm_[A-Za-z0-9]{20,}\b/g},{name:"aws-access-key",mutationRule:"aws_access_key",category:"credential",regex:/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g},{name:"google-api-key",mutationRule:"google_api_key",category:"credential",regex:/\bAIza[0-9A-Za-z_-]{35}\b/g},{name:"slack-token",mutationRule:"slack_token",category:"credential",regex:/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g},{name:"anthropic-api-key",mutationRule:"anthropic_api_key",category:"credential",regex:/\bsk-ant-[A-Za-z0-9_-]{20,}\b/g},{name:"openai-api-key",mutationRule:"openai_api_key",category:"credential",regex:/\bsk-(?!ant-)[A-Za-z0-9_-]{20,}\b/g},{name:"gitlab-token",mutationRule:"gitlab_token",category:"credential",regex:/\bglpat-[A-Za-z0-9_.-]{20,}\b/g},{name:"jwt-like-token",mutationRule:"jwt_like_token",category:"credential",regex:/\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g},{name:"npm-auth-token-assignment",mutationRule:"npm_auth_token_assignment",category:"credential",regex:/_authToken\s*=\s*\S+/g},{name:"sentry-user-token",mutationRule:"sentry_user_token",category:"credential",regex:/\bsntryu_[A-Za-z0-9]{20,}\b/g},{name:"sentry-org-token",mutationRule:"sentry_org_token",category:"credential",regex:/\bsntrys_[A-Za-z0-9_-]{20,}\b/g},{name:"private-ip",mutationRule:"private_ip",category:"network",regex:/\b(?:10\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|172\.(?:1[6-9]|2\d|3[01])\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|192\.168\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d))\b/g},{name:"private-ssh-target",mutationRule:"private_ssh_target",category:"network",regex:/\b(?:ssh|scp|rsync)\s+[A-Za-z0-9._-]+@(?:10\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|172\.(?:1[6-9]|2\d|3[01])\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|192\.168\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d))\b/g},{name:"sshpass-inline-password",mutationRule:"sshpass_inline_password",category:"credential",regex:/\bsshpass\s+-p\s+["'][^"']{6,}["']/g},{name:"password-assignment",mutationRule:"password_assignment",category:"credential",regex:new RegExp(String.raw`\b(?:${V})\s*[:=]\s*`+W.source,"gi"),structured:{keys:V,value:W.source,element:!0},minimumLiteralLength:Ke},{name:"absolute-home-path",mutationRule:"absolute_home_path",category:"path",regex:Pe,excludeFiles:/^(?:tests\/|examples\/)/},{name:"user-at-private-host",mutationRule:"user_at_private_host",category:"network",regex:/(?<![A-Za-z0-9._-])[A-Za-z0-9._-]+@(?:10\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|172\.(?:1[6-9]|2\d|3[01])\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|192\.168\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d))\b/g,excludeFiles:/^(?:tests\/|examples\/)/},{name:"high-entropy-assignment",mutationRule:"high_entropy_assignment",category:"credential",regex:new RegExp(String.raw`\b(?:${q})\s*[:=]\s*`+re.source,"gi"),structured:{keys:q,value:re.source},mutationOnlyReason:"Generic assignments in source code are not credentials; preserve the existing mutation heuristic without treating source identifiers as secrets.",minimumEntropy:3.5},{name:"credential-key-assignment",mutationRule:"credential_key_assignment",category:"credential",regex:new RegExp(String.raw`\b(?:${I})\s*[:=]\s*`+te.source,"gi"),structured:{keys:I,value:te.source,element:!0,elementValue:!0},mutationOnlyReason:"Key-named assignments in source code and test fixtures are identifiers and synthetic data; repository scans keep the token-format rules, which recognize real credentials there.",minimumEntropy:3,minimumLiteralLength:Qe,literalValue:C,baseline:{regex:new RegExp(String.raw`\b(?:${I})\s*[:=]\s*`+C.source,"gi"),value:C.source},rejectValue:/^(?:[\w.-]+\/)*id_(?:rsa|dsa|ecdsa|ed25519)(?:_sk)?(?:\.pub)?$/u,rejectStatementReference:/^[A-Z]+(?:_[A-Z]+)+$/u}];function*Mt(e,n){if(e.mutationRule==="absolute_home_path"){yield*We(n,e.regex);return}for(const t of ie(e))yield*cn(t,n),t.structured&&(yield*gt(t,t.structured,n))}const se=new WeakMap;function ie(e){const n=e.baseline;if(n===void 0)return[e];let t=se.get(e);return t===void 0&&(t={...e,regex:n.regex,minimumLiteralLength:void 0,literalValue:void 0,baseline:void 0},e.structured&&(t.structured={...e.structured,value:n.value}),se.set(e,t)),[e,t]}function tn(e,n){const t=e[n-1]==="#"||e[n-1]==="!"?n-1:n;return e[t-1]==="{"&&e[t-2]==="$"}const b=new WeakSet,ue=new WeakMap,rn=4096;function sn(e,n,t){const r=[],s=[],i=n+t.length;return oe(e,n,i,s,r),oe(e,i,Math.min(e.length,i+rn),s),r}function oe(e,n,t,r,s){for(let i=n;i<t&&(s!==void 0||r.length>0);i+=1){const u=r.at(-1);if(e[i]==="$"&&(e[i+1]==="{"||e[i+1]==="(")&&u?.quoted!=="'"){const o={open:i,close:t,command:e[i+1]==="(",quoted:[]};s?.push(o),r.push({span:o,closer:e[i+1]==="{"?"}":")"}),i+=1}else u!==void 0&&(i=un(e,i,r))}}function un(e,n,t){const r=t.at(-1),s=e[n];return s==="\\"&&r.quoted!=="'"?n+1:(r.quoted!==void 0?s===r.quoted&&(r.span.quoted.push([r.quoteStart,n]),r.quoted=void 0):s==="'"||s==='"'?(r.quoted=s,r.quoteStart=n):s===r.closer&&(t.pop().span.close=n),n)}function on(e){const n=[];let t=0;return r=>{for(;t<e.length&&e[t].open<r;t+=1){for(;n.length>0&&n.at(-1).close<e[t].open;)n.pop();n.push(e[t])}for(;n.length>0&&n.at(-1).close<r;)n.pop();return n.at(-1)}}function an(e,n){let t=0,r=e.quoted.length-1;for(;t<=r;){const s=t+r>>1,[i,u]=e.quoted[s];if(n<i)r=s-1;else if(n>u)t=s+1;else return!0}return!1}const ae=/\$[({A-Za-z_]|</u,k=new WeakMap;function*cn(e,n){const t=new RegExp(e.regex),r=ln(e);let s,i;for(let u=t.exec(n);u!==null;u=t.exec(n)){let o=u;if(e.minimumLiteralLength!==void 0){i??=bn(n);const a=u.index+u[0].length,c=a-u[1].length,l=Bn(i,c,a);l>c&&(l<a&&(o=Qn(u,l),t.lastIndex=l),k.set(o,l))}L(e,o)?yield{index:o.index}:r!==void 0&&ae.test(o[1])&&(s??=new RegExp(t),yield*dn(e,s,n,o,r==="deep"))}}function ln(e){return e.minimumLiteralLength===void 0?void 0:e.minimumEntropy===void 0&&e.literalValue===void 0&&e.rejectValue===void 0?"deep":"shallow"}function*dn(e,n,t,r,s){const i=r.index+r[0].length;n.lastIndex=i-r[1].length;let u;for(let o=n.exec(t);o!==null&&o.index<i;o=n.exec(t)){if(tn(t,o.index)){n.lastIndex=o.index+1;continue}u??=on(sn(t,i-r[1].length,r[1]));const a=u(o.index);a!==void 0&&(ue.set(o,a.close),a.command&&!an(a,o.index)&&b.add(o)),L(e,o)?yield{index:o.index}:s&&ae.test(o[1])&&(n.lastIndex=o.index+o[0].length-o[1].length)}}const ce=new Map,y=/[\r\n\u2028\u2029]/u;function z(e){const n=`${e.keys}\0${e.value}\0${e.element===!0}`;let t=ce.get(n);return t||(t={key:new RegExp(String.raw`\b(?:${e.keys})(["']?)\s*[:=]\s*`,"gi"),value:new RegExp(e.value,"iyd"),...e.element?{element:{open:new RegExp(String.raw`<(?:${e.keys})(?:\s[^<>]*)?>`,"gi"),close:new RegExp(String.raw`<\/(?:${e.keys})\s*>`,"iy"),span:new RegExp(String.raw`<(?!\/?(?:${e.keys})\b)[^<>]*>`,"iy")}}:{}},ce.set(n,t)),t}function le(e,n){const t=e[n];for(let r=n+1;r<e.length;r+=1){const s=e[r];if(s==="\\")r+=1;else if(s===t)return{end:r+1,terminated:!0}}return{end:e.length,terminated:!1}}function fn(e,n){return le(e,n).end}function gn(e,n,t){return e.at(-1)==="}"?t:n}function pn(e,n,t,r=t){const s=[];let i=!1;for(let u=n;u<e.length;u+=1){const o=e[u];switch(o){case"[":case"{":s.push(o==="["?"]":"}"),i=o==="{";break;case"]":case"}":if(s.pop()!==o||s.length===0)return{found:!1,end:u+1};i=!1;break;case",":i=s.at(-1)==="}";break;case":":i=!1;break;case'"':case"'":if(!i&&gn(s,t,r)(u))return{found:!0,end:u};u=fn(e,u)-1;break;default:break}}return{found:!1,end:e.length}}const En=/\\(?:U[0-9a-fA-F]{8}|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}|[0-7]{1,3}|[\s\S])/gu,_n={n:`
3
+ `,r:"\r",t:" ",b:"\b",f:"\f",v:"\v"};function An(e,n){const t=e[0],r=e.slice(1,n?-1:void 0).replaceAll(En,u=>{const o=u[1];if((o==="u"||o==="x")&&u.length>2)return String.fromCharCode(Number.parseInt(u.slice(2),16));if(/^[0-7]$/u.test(o))return String.fromCharCode(Number.parseInt(u.slice(1),8));if(o==="U"&&u.length===10){const a=Number.parseInt(u.slice(2),16);return a<=1114111?String.fromCodePoint(a):"\uFFFD"}return _n[o]??o}),s=r.replaceAll(t,t==='"'?"'":'"').replaceAll(/[\r\n\u2028\u2029]/gu," "),i=n?t:"";return{reading:`${t}${s}${i}`,...de(`${t}${r}${i}`,n)}}function de(e,n){return{original:e,bodyStart:1,bodyEnd:e.length-(n?1:0)}}const Rn=64;function fe(e,n,t){const r=e[n-1];if(!t)return r!==void 0&&/[\p{L}\p{N}_.-]/u.test(r)?"prefixed":"exact";if(r===t)return"exact";const s=Math.max(0,n-Rn);for(let i=n-1;i>=s;i-=1){const u=e[i];if(u===t)return"prefixed";if(u===`
4
+ `||u==="\r"||u==='"'||u==="'")return"malformed"}return"malformed"}function ge(e,n,t,r=!1){const s=(o,a,c)=>{n.lastIndex=a;const l=n.exec(o);if(l===null||y.test(l[0]))return null;const f=l.indices?.[1];return c!==void 0&&f!==void 0&&(l[1]=c.original.slice(Math.max(f[0],c.bodyStart),Math.min(f[1],c.bodyEnd)),O.add(l)),L(e,l)?l:null},i=o=>{if(t[o]!=='"'&&t[o]!=="'")return;const{end:a,terminated:c}=le(t,o),l=t.slice(o,a);if(!r&&!l.includes("\\"))return;if(y.test(l))return[];const f=An(l,c);return(t[o]==="'"?[f,{reading:l,...de(l,c)}]:[f]).map(A=>s(A.reading,0,A)).filter(A=>A!==null)},u=o=>{const a=i(o);if(a!==void 0)return a;const c=s(t,o);return c===null?[]:[c]};return{direct:o=>s(t,o)!==null,escaped:o=>(i(o)?.length??0)>0,accepts:o=>a=>u(a).some(c=>!(o&&/\s/u.test(hn(e,c))))}}function hn(e,n){return e.minimumLiteralLength===void 0?n[0]:pe(n)}const O=new WeakSet;function pe(e){const n=b.has(e)&&!_(w(e))?yn(e[1]):void 0,t=n??e[1];if(n===void 0&&wn(e,t))return"";const r=n!==void 0||Tn(e);return O.has(e)||_(w(e))?Le(t,r):kt(t,r)}const $n=/^%[A-Za-z_]\w*%$/u,Sn=/^(["']?)%[A-Za-z_]\w*%\1$/u;function wn(e,n){if(!Sn.test(n))return!1;if(O.has(e))return!0;const t=e.input,r=e.index+e[0].length;if(k.get(e)===r)return!0;let s=r;for(;s<t.length&&(t[s]===" "||t[s]===" ");)s+=1;return s===t.length||y.test(t[s])?!0:_(n[0])&&/[,;)}\]]/u.test(t[s])&&Nn(e)}const mn=/(?:^|[\s{,[])(["'])[^"'\r\n]{1,256}\1\s*[:=]\s*$/u;function Nn(e){if(Ee(e,!1)!==void 0)return!0;const n=e.input,t=e.index+e[0].length-e[1].length,r=n.slice(Math.max(0,t-_e),t);return mn.test(r)||/:[ \t]*$/u.test(r)}function yn(e){for(let n=0;n<e.length;n+=1){const t=e[n];if(t==="'"||t==='"')n=ye(e,n);else if(t==="$"&&(e[n+1]==="{"||e[n+1]==="("))n=Math.max(n,D(e,n)-1);else if(/[|&;<>]/u.test(t))return e.slice(0,n)}}const On=/^[;,)}\]]{0,64}/u;function Tn(e){const n=e.input,t=e.index+e[0].length,r=_(w(e))&&_(n[t])?t+1:_(e[0].at(-1))?t:-1,s=r===-1?t:r,i=On.exec(n.slice(s,s+he))[0].length,u=s+i;if(u===n.length||/\s/u.test(n[u])||Ln(e,s,t))return!0;if(r===-1||i===0)return!1;const o=Ee(e,r===t+1),a=n.slice(u,u+40),c=/[}\]]/u.test(n.slice(s,u));return o!==void 0&&(Ae.test(a)||(o==="element"||c)&&Re.test(a))}function Ln(e,n,t){return ue.get(e)===n||b.has(e)&&/[|&;<>]/u.test(e.input[n])?!0:k.get(e)===t}function Ee(e,n){const t=e.input,r=e.index+e[0].length-e[1].length-(n?1:0),s=t.slice(Math.max(0,r-_e),r);return In.test(s)?"element":xn.test(s)?"key":void 0}const _e=512,xn=/[{,]\s*(["'])[^"'\r\n]{1,256}\1\s*[:=]\s*$/u,In=/[[,]\s*$/u,Ae=/^(?:["'`]|[{[](?:[\s"'`{[\]}]|$|(?:-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null)[\s,\]}]))/u,Re=/^(?:-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null)[\s,\]}]/u,he=64,S=0,M=1,Cn=2,$e=/[\p{L}\p{N}_]/u;function Se(e){return e===10||e===13}function bn(e){return{content:e,index:0,state:S,opener:-1,escapes:!0}}function we(e){const{content:n}=e,t=e.index,r=n.charCodeAt(t);if(e.index=t+1,Se(r))return e.state=S,-1;if(r===92)return e.escapes&&t+1<n.length&&!Se(n.charCodeAt(t+1))&&(e.index=t+2),-1;if(r!==34&&r!==39)return-1;const s=r===34?M:Cn;return e.state===s?(e.state=S,t):(e.state===S&&!(t>0&&$e.test(n[t-1]))&&(e.state=s,e.opener=t,e.escapes=s===M||Mn(n,t)),-1)}function kn(e,n){for(;e.index<n;)we(e)}function zn(e,n){const t=me(e,n),r=e[t];return{inContainer:r!==void 0&&/[[{,:]/u.test(r),attribute:r==="="&&Pn(e,t)}}function me(e,n){let t=n-1;for(;t>=0&&/\s/u.test(e[t]);)t-=1;return t}function Mn(e,n){return/[[{,:]/u.test(e.charAt(me(e,n)))}const Dn=8192;function Pn(e,n){const t=Math.max(0,n-Dn);for(let r=n-1;r>=t;r-=1){const s=e[r];if(s===">")return!1;if(s==="<")return/[A-Za-z]/u.test(e.charAt(r+1));if(s==='"'||s==="'"){const i=e.lastIndexOf(s,r-1);if(i<t)return!1;r=i}}return!1}const Zn=/[,:;)}\]]/u;function Un(e,n,t){let r=n+1;if(vn(e,r,t))return!0;const s=Math.min(e.length,r+he);for(;r<s&&Zn.test(e[r]);)r+=1;if(r===n+1)return!1;for(;r<e.length&&(e[r]===" "||e[r]===" ");)r+=1;if(r===e.length||y.test(e[r]))return!0;if(!t.inContainer)return!1;const i=e.slice(r,r+Vn);return Ae.test(i)||Re.test(i)||Fn.test(i)}function vn(e,n,t){return n===e.length||/\s/u.test(e[n])?!0:t.attribute&&(e[n]===">"||e.startsWith("/>",n))}const Vn=512,Fn=/^[A-Za-z_][\w.-]{0,480}:(?:\s|$)/u;function Bn(e,n,t){kn(e,n);const r=e.state;if(r===S)return-1;const{content:s}=e,i=e.opener,u=r===M?"'":'"',o={open:!1,placeholder:!1,references:[]},a=Math.min(t,s.length-1);for(;e.index<=a;){qn(o,s,e.index,u);const c=we(e);if(c!==-1){const l=o.open||o.placeholder||o.references.length>0;return Kn(s,c,t,l)&&Un(s,c,zn(s,i))?c:-1}if(e.state!==r)return-1}return-1}const Hn=/^<[^<>\s]{0,254}>/u,Wn=256;function qn(e,n,t,r){const s=n[t];e.open?s===r&&(e.open=!1):e.placeholder?s===">"&&(e.placeholder=!1):s==="$"&&(n[t+1]==="{"||n[t+1]==="(")?e.references.push(n[t+1]==="{"?"}":")"):s===e.references.at(-1)?e.references.pop():s==="<"&&Hn.test(n.slice(t,t+Wn))?e.placeholder=!0:s===r&&(e.open=Gn(n,t))}function Gn(e,n){return e[n]==='"'||!$e.test(e[n-1])}function Kn(e,n,t,r){return n>=t||!(r||/\s/u.test(e.charAt(n+1)))}function Qn(e,n){const t=e.index+e[0].length-e[1].length,r=[e.input.slice(e.index,n),e.input.slice(t,n)];return Object.assign(r,{index:e.index,input:e.input,groups:void 0})}const jn=/^\s{0,16}\(/u,Yn=/(?<![=!<>])=[ \t]{0,16}$/u;function w(e){return e.input[e.index+e[0].length-e[1].length-1]}function _(e){return e==='"'||e==="'"}const Xn=/[$<"']/u;function Jn(e){if(O.has(e)||_(w(e))||!/^[$<]/u.test(e[1]))return!1;const n=e.index+e[0].length,t=n-e[1].length,r=e.input.slice(n,n+18);if(e[1][0]==="<"&&(it(e[1])||Yn.test(e.input.slice(Math.max(0,t-18),t))||ot.test(r)))return!0;const s=Ne(e[1]),i=e[1][s]==="!"?e[1][s+1]:e[1][s];return ut.test(i??"")||jn.test(r)}function Ne(e){let n=0;for(let t=D(e,n);t!==-1;t=D(e,n))n=t;return n}function D(e,n){const t=e[n];if(t==="<")return et(e,n);if(t!=="$")return-1;const r=e[n+1];if(r==="{"||r==="(")return nt(e,n+1,r);T.lastIndex=n;const s=T.exec(e)?.[0];return s===void 0?-1:n+s.length}function et(e,n){const t=e.indexOf(">",n+1),r=e.indexOf("<",n+1);return t!==-1&&(r===-1||t<r)?t+1:-1}function nt(e,n,t){const r=t==="{"?"}":")";let s=0;for(let i=n;i<e.length;i+=1){const u=e[i];if(u==="\\")i+=1;else if(u==="'"||u==='"')i=ye(e,i);else if(u===t)s+=1;else if(u===r&&--s===0)return i+1}return-1}function ye(e,n){const t=e[n];for(let r=n+1;r<e.length;r+=1){if(e[r]===t)return r;t==='"'&&e[r]==="\\"&&(r+=1)}return e.length}const tt=/^[\w$.[\]|&,{}:;?]+$/u,rt=/^(?:"[^"]*"|'[^']*'|-?\d+(?:\.\d+)?)(?:\|(?:"[^"]*"|'[^']*'|-?\d+(?:\.\d+)?|[A-Za-z_$][\w$.]*))*$/u,st=/\b(?:string|number|boolean|bigint|symbol|any|unknown|object|never|void|undefined|null)\b/u;function it(e){const n=e.slice(1,e.indexOf(">"));return rt.test(n)?!0:tt.test(n)?st.test(n)||/[.|&[{]/u.test(n)||/^[A-Z][\w$]*$/u.test(n)&&(n.length===1||/[a-z]/u.test(n)):!1}const ut=/[.+\-*/%=^&]/u,ot=/^\s{0,16}(?:\?\.|\?\?|\|\||&&|[([])/u;function at(e,n,t){if(t)return!1;const r=n.replaceAll('"',"'");return e.lastIndex=0,e.exec(`"${r}"`)?.[1]===r}function Dt(e,n){if(!e.structured)return;const t=`${JSON.stringify(n)}:`,r=z(e.structured).key;r.lastIndex=0;for(let s=r.exec(t);s;s=r.exec(t)){if(s.index+s[0].length!==t.length)continue;const i=fe(t,s.index,s[1]);if(i!=="malformed")return i}}function Pt(e,n,t){if(!e.structured)return!1;const r=JSON.stringify(n).replaceAll("\u2028","\\u2028").replaceAll("\u2029","\\u2029");return ie(e).some(s=>ge(s,z(s.structured).value,r,!0).accepts(t)(0))}function*ct(e,n,t){const r=new RegExp(e.open);for(let s=r.exec(n);s;s=r.exec(n)){const i=s.index+s[0].length,u=lt(e,n,i);if(u===void 0){r.lastIndex=s.index+1;continue}t(n.slice(i,u.start).trim())&&(yield{index:s.index}),r.lastIndex=u.end}}function lt(e,n,t){for(let r=n.indexOf("<",t);r!==-1;){e.close.lastIndex=r;const s=e.close.exec(n);if(s!==null)return{start:r,end:r+s[0].length};e.span.lastIndex=r;const i=e.span.exec(n);if(i===null)return;r=n.indexOf("<",r+i[0].length)}}function dt(e,n,t){return n<e.exact||t&&n<e.compact}function ft(e,n,t,r){return(t||e.escaped(r)&&!e.direct(r))&&n(r)}function*gt(e,n,t){const r=z(n),s=ge(e,r.value,t),i=new RegExp(r.key),u={exact:0,compact:0};for(let o=i.exec(t);o;o=i.exec(t)){const a=o[1],c=fe(t,o.index,a);if(c==="malformed")continue;const l=c==="prefixed",f=s.accepts(l),E=o.index+o[0].length,A=t[E];if(A==="["||A==="{"){if(dt(u,E,l))continue;const Z=pn(t,E,f,s.accepts(!0));u[l?"compact":"exact"]=Z.end,Z.found&&(yield{index:o.index})}else ft(s,f,a,E)&&(yield{index:o.index})}r.element&&(yield*ct(r.element,t,Et(e,n,r)))}const pt=8;function Et(e,n,t){if(!n.elementValue){const r=e.minimumLiteralLength??pt;return s=>!$n.test(s.trim())&&Le(s).length>=r}return r=>{const s=r.replaceAll('"',"'");t.value.lastIndex=0;const i=t.value.exec(`"${s}"`);return i===null||i[1]!==s?!1:(i[1]=r,L(e,i))}}function _t(e,n,t){const r=n.index+n[0].length;return/^[ \t]*;/u.test(n.input.slice(r,r+64))&&!_(w(n))&&e.test(t)}function At(e,n){for(let t=n+1;t<e.length;t+=1){if(e[t]===">")return t;if(e[t]==="<")return-1}return-1}function P(e,n){e.raw+=n,e.literal+=n}function Rt(e,n,t){const r=e[n+1];if(e[n]!=="$"||r!=="{"&&r!=="(")return-1;const s=r==="{"?e.slice(n+2,n+2+Ot(e,n+2)):"",i=t[0],u=t.length===1&&i.quote!==void 0&&i.literal.length===i.pieceStart;return t.push({close:r==="{"?"}":")",keep:s!=="",raw:`$${r}${s}`,literal:"",opensPiece:u}),n+2+s.length}const ht=/[A-Za-z_]/u,$t=/\w/u,St=/[{(A-Za-z_]/u,T=/\$[A-Za-z_]\w*/y,wt=/^_*[A-Z][A-Z0-9_]*$/u,mt=/^\$[A-Za-z_]\w*$/u,Nt=/^(["'])\$[A-Za-z_]\w*\1$/u;function yt(e,n,t){T.lastIndex=n;const r=T.exec(e)?.[0];return r===void 0?-1:(t.literal===""&&wt.test(r.slice(1))?t.raw+=r:P(t,r),n+r.length)}function Ot(e,n){if(!ht.test(e[n]??""))return 0;let t=n+1;for(;t<e.length&&$t.test(e[t]);)t+=1;e[t]===":"&&(t+=1);const r=e[t];return r==="-"||r==="="||r==="+"?t+1-n:0}function Tt(e,n){const t=e.pop(),r=e.at(-1);r.raw+=`${t.raw}${n}`,t.keep&&(r.literal+=t.literal)}const Oe=/[^$<"'\\})]+/y,Lt='$`"\\\n';function xt(e,n){return e===`
5
+ `?"":n==='"'&&!Lt.includes(e)?`\\${e}`:e}function It(e,n,t){const r=e[n],s=t.quote;if(s==='"'&&r==="$"&&St.test(e[n+1]??""))return-1;let i=1,u=r;if(r==="\\"&&s!=="'"&&n+1<e.length)i=2,u=xt(e[n+1],s);else if(s===void 0){if(r!=='"'&&r!=="'")return-1;t.quote=r,u=""}else r===s&&(t.quote=void 0,u="");return t.raw+=e.slice(n,n+i),t.keep&&(t.literal+=u),n+i}function Ct(e,n,t,r,s){const i=t.at(-1);Oe.lastIndex=n;const u=Oe.exec(e)?.[0];if(u!==void 0)return P(i,u),n+u.length;if(t.length>1){const E=It(e,n,i);if(E!==-1)return E}else if(r&&bt(e[n],i))return n+1;const o=Rt(e,n,t);if(o!==-1)return o;const a=t.at(-1),c=e[n],l=s&&c==="$"?yt(e,n,a):-1;if(l!==-1)return l;if(t.length>1&&c===a.close)return Tt(t,c),n+1;const f=c==="<"?At(e,n):-1;return f!==-1?(a.raw+=e.slice(n,f+1),f+1):(P(a,c),n+1)}function bt(e,n){return e!=='"'&&e!=="'"?!1:n.quote===void 0?(n.quote=e,n.pieceStart=n.literal.length,!0):e!==n.quote?!1:(n.quote=void 0,!0)}function Te(e,n,t){if(t&&(mt.test(e)||n&&Nt.test(e)))return"";const r={close:"}",keep:!0,raw:"",literal:""},s=[r];for(let i=0;i<e.length;)i=Ct(e,i,s,n,t);for(let i=s.length-1;i>0;i-=1){const u=s[i],o=s[i-1];o.raw+=u.raw,n&&i===1&&u.opensPiece===!0||(o.literal+=u.raw)}return r.literal}function Le(e,n=!0){return Te(e,!1,n)}function kt(e,n=!0){return Te(e,!0,n)}function L(e,n){const t=e.minimumLiteralLength===void 0?n[1]:pe(n);if(e.minimumLiteralLength!==void 0&&t.length<e.minimumLiteralLength||e.literalValue&&Xn.test(n[1])&&!at(e.literalValue,t,Jn(n))||e.rejectValue?.test(t)===!0||e.rejectStatementReference&&_t(e.rejectStatementReference,n,t))return!1;if(e.minimumEntropy===void 0)return!0;const r=[...t],s=new Map;for(const u of r)s.set(u,(s.get(u)??0)+1);let i=0;for(const u of s.values()){const o=u/r.length;i-=o*Math.log2(o)}return i>=e.minimumEntropy}const Zt={leadingReferencesEnd:Ne};export{Pe as PRIVATE_HOME_PATH_PATTERN,zt as SECRET_RULES,Zt as _testOnly,L as acceptsSecretMatch,Pt as acceptsStructuredValue,Le as expandRuntimeReferences,We as findPrivateHomePathMatches,Mt as findSecretRuleMatches,kt as literalAfterReferences,Dt as structuredKeyShape};
6
6
  //# sourceMappingURL=secret-rules.js.map
@@ -57,9 +57,22 @@ export declare function redactOptionalIdentityCredentials<T>(value:T):T;
57
57
  export declare function runWithUrlCredentialInvocation<T>(argv:readonly string[],run:()=> T):T;
58
58
  /** Whether the running invocation carried any possible URL userinfo. */
59
59
  export declare function invocationCarriesUrlCredentials():boolean;
60
+ /**
61
+ * Authority text with every escaped quote of the opening's kind replaced by
62
+ * neutral characters (GH-1774): inside a URL opened by `'`, POSIX's escaped
63
+ * apostrophe (`'\\''`, or `'\\\\''` in JSON); inside one opened by `'` or `"`,
64
+ * a quote an odd run of backslashes escapes (`\\"`, cmd's caret form `\\^"`,
65
+ * or either as JSON encodes it). Their backslashes
66
+ * are then not read as a special scheme's path delimiter, nor their quotes
67
+ * as the closer. Positions are kept, so every index read from the result
68
+ * fits the original.
69
+ */
70
+ declare function neutralizeEscapedQuotes(text:string,closer:string|undefined):string;
60
71
  /**
61
72
  * Apply {@link redactUrlCredentialsInToken} to every whitespace-delimited word
62
- * of free text, after removing the running invocation's registered
63
- * fragments.
73
+ * of free text, after removing the running invocation's registered fragments
74
+ * and joining each URL userinfo that holds blanks into one word.
64
75
  */
65
- export declare function redactUrlCredentialsInText(text:string):string;
76
+ export declare function redactUrlCredentialsInText(text:string):string;
77
+ /** Test-only access to the position-keeping escape neutralization (GH-1774). */
78
+ export declare const urlCredentialsTestOnly:{neutralizeEscapedQuotes:typeof neutralizeEscapedQuotes;};export{};
@@ -1,2 +1,2 @@
1
- import{AsyncLocalStorage as x}from"node:async_hooks";import{quoteWindowsCommandArg as A}from"./command-line.js";import{EXIT_CODE as C}from"./constants.js";import{PmCliError as T}from"./errors.js";const p="[redacted]";function L(t,e){if(/[\t\n\r]/u.test(t)||!/(?:^|[^A-Za-z0-9+.-])(?:https?|wss?|ftp)$/iu.test(t.slice(0,e)))return!1;let n=e+1;for(;t[n]==="/"||t[n]==="\\";)n+=1;const r=t.indexOf("/",n)-n;if(r<0)return!1;const i=n+r;return!/[:@%]/u.test(t.slice(n,i))&&!/[:%]|[/\\][/\\]/u.test(t.slice(i))}function u(t){const e=Math.max(t.lastIndexOf("@"),t.toLowerCase().lastIndexOf("%40")),n=t.indexOf(":");if(e<0||n<0||n>e)return;let r=n+1;for(;r<e&&r<n+3&&(t[r]==="/"||t[r]==="\\");)r+=1;return r===e||L(t,n)?void 0:[r,e]}function m(t){const e=u(t);return e?`${t.slice(0,e[0])}${p}${t.slice(e[1])}`:t}function y(t){return m(t)}const I=["author","assignee","claim_principal"];function j(t){const e={...t};for(const n of I)typeof e[n]=="string"&&(e[n]=y(e[n]));return e}function E(t,e){if(!(typeof t!="string"||u(t.trim())===void 0))throw new T(`${e} must not carry URL credentials: an identity is a name, never a credential.`,C.USAGE,{code:"invalid_argument_value",field:e,required:`Set ${e} to a plain name such as agent-a, with no URL userinfo (no user, password or token before the host).`,nextSteps:[`Rerun with ${e} set to a plain name.`],url_credentials_rejected:{source:e}})}function G(t,e){return E(t,e),t}const O=[["comments","author"],["notes","author"],["learnings","author"],["dependencies","author"],["plan_decisions","author"],["plan_discoveries","author"],["plan_steps","owner"],["tests","provenance","author"],["tests","updated_by"]],U=4;function h(t,e,n=0){if(typeof t=="string"){E(t,e);return}if(!(n>=U||typeof t!="object"||t===null))for(const r of Object.values(t))h(r,e,n+1)}function N(t,e){let n=t;for(const r of e){if(typeof n!="object"||n===null||Array.isArray(n))return;n=n[r]}return n}function H(t){const e=t;for(const n of I)h(e[n],n);for(const[n,...r]of O){const i=e[n];Array.isArray(i)&&i.forEach((a,l)=>{h(N(a,r),`${n}[${l}].${r.join(".")}`)})}}function q(t){return typeof t=="string"?y(t):t}const d=6,$=65536,w={carried:!1,fragments:new Set,fragmentLength:d,shortSpellings:[]},g=new x;function S(t){const e=t.toLowerCase();if(e.length===t.length)return e;let n="";for(const r of t){const i=r.toLowerCase();n+=i.length===r.length?i:r}return n}function R(t){return[t,t.replaceAll(/(["\\$`])/gu,"\\$1"),A(`${t}@`).slice(1,-2),JSON.stringify(t).slice(1,-1)]}function D(t){const e=t.indexOf(":");return e>=0&&e<t.length-1?t.slice(e+1):t}function b(t){const e=new Set;let n=!1;for(const s of t){const c=u(s);if(c){n=!0;for(const _ of R(D(s.slice(c[0],c[1]))))e.add(S(_))}}const r=[...e],i=r.reduce((s,c)=>s+Math.max(0,c.length-d+1)+1,0),a=Math.max(1,Math.ceil(i/$)),l=Math.max(d,a),o=new Set,f=new Set;for(const s of r){if(s.length<l){(s.length>=d||/\s/u.test(s))&&f.add(s);continue}for(let c=0;c+l<=s.length;c+=a)o.add(s.slice(c,c+l));o.add(s.slice(-l))}return{carried:n,fragments:o,fragmentLength:l,shortSpellings:[...f]}}function M(t,e){const n=S(t),r=new Uint8Array(t.length);let i=!1;const a=e.fragmentLength;for(let o=0;o+a<=n.length;o+=1)e.fragments.has(n.slice(o,o+a))&&(r.fill(1,o,o+a),i=!0);for(const o of e.shortSpellings)for(let f=n.indexOf(o);f>=0;f=n.indexOf(o,f+1))r.fill(1,f,f+o.length),i=!0;if(!i)return t;let l="";for(let o=0;o<t.length;o+=1)r[o]?(o===0||!r[o-1])&&(l+=p):l+=t[o];return l}function V(t,e){return g.run(b(t),e)}function Y(){return(g.getStore()??w).carried}function X(t){const e=g.getStore()??w,n=e.carried?M(t,e):t;return/@|%40/iu.test(n)?n.replaceAll(/\S+/gu,m):n}export{p as URL_CREDENTIAL_PLACEHOLDER,H as assertIdentityFieldsWithoutUrlCredentials,E as assertIdentityWithoutUrlCredentials,Y as invocationCarriesUrlCredentials,G as parseIdentityOption,y as redactIdentityCredentials,j as redactIdentityFields,q as redactOptionalIdentityCredentials,X as redactUrlCredentialsInText,m as redactUrlCredentialsInToken,V as runWithUrlCredentialInvocation};
1
+ import{AsyncLocalStorage as H}from"node:async_hooks";import{escapeCmdMetacharacters as F,escapePowerShellSingleQuotes as j,quoteWindowsCommandArg as z}from"./command-line.js";import{EXIT_CODE as B}from"./constants.js";import{PmCliError as G}from"./errors.js";const y="[redacted]",X=/%\^?40/giu,g=/@|%\^?40/iu;function C(e,t=e.length){let n=-1;for(const r of e.matchAll(X)){if(r.index>t)break;n=r.index}return n}function v(e,t){if(/[\t\n\r]/u.test(e)||!/(?:^|[^A-Za-z0-9+.-])(?:https?|wss?|ftp)$/iu.test(e.slice(0,t)))return!1;let n=t+1;for(;e[n]==="/"||e[n]==="\\";)n+=1;const r=e.indexOf("/",n)-n;if(r<0)return!1;const s=n+r;return!/[:@%]/u.test(e.slice(n,s))&&!/[:%]|[/\\][/\\]/u.test(e.slice(s))}function S(e){const t=Math.max(e.lastIndexOf("@"),C(e)),n=e.indexOf(":");if(t<0||n<0||n>t)return;let r=n+1;for(;r<t&&r<n+3&&(e[r]==="/"||e[r]==="\\");)r+=1;return r===t||v(e,n)?void 0:[r,t]}function _(e){const t=S(e);return t?`${e.slice(0,t[0])}${y}${e.slice(t[1])}`:e}function I(e){return _(e)}const T=["author","assignee","claim_principal"];function ye(e){const t={...e};for(const n of T)typeof t[n]=="string"&&(t[n]=I(t[n]));return t}function w(e,t){if(!(typeof e!="string"||S(e.trim())===void 0))throw new G(`${t} must not carry URL credentials: an identity is a name, never a credential.`,B.USAGE,{code:"invalid_argument_value",field:t,required:`Set ${t} to a plain name such as agent-a, with no URL userinfo (no user, password or token before the host).`,nextSteps:[`Rerun with ${t} set to a plain name.`],url_credentials_rejected:{source:t}})}function Ce(e,t){return w(e,t),e}const Z=[["comments","author"],["notes","author"],["learnings","author"],["dependencies","author"],["plan_decisions","author"],["plan_discoveries","author"],["plan_steps","owner"],["tests","provenance","author"],["tests","updated_by"]],x=4;function m(e,t,n=0){if(typeof e=="string"){w(e,t);return}if(!(n>=x||typeof e!="object"||e===null))for(const r of Object.values(e))m(r,t,n+1)}function Q(e,t){let n=e;for(const r of t){if(typeof n!="object"||n===null||Array.isArray(n))return;n=n[r]}return n}function Ie(e){const t=e;for(const n of T)m(t[n],n);for(const[n,...r]of Z){const s=t[n];Array.isArray(s)&&s.forEach((i,o)=>{m(Q(i,r),`${n}[${o}].${r.join(".")}`)})}}function Te(e){return typeof e=="string"?I(e):e}const h=6,q=65536,P={carried:!1,fragments:new Set,fragmentLength:h,shortSpellings:[]},A=new H;function R(e){const t=e.toLowerCase();if(t.length===e.length)return t;let n="";for(const r of e){const s=r.toLowerCase();n+=s.length===r.length?s:r}return n}function k(e){const t=z(`${e}@`),n=[e,e.replaceAll(/(["\\$`])/gu,"\\$1"),e.replaceAll("'","'\\''"),t.slice(1,-2),F(t).slice(2,-3),j(e)];return[...n,...n.map(r=>JSON.stringify(r).slice(1,-1))]}function V(e){const t=e.indexOf(":");return t>=0&&t<e.length-1?e.slice(t+1):e}function Y(e){const t=new Set;let n=!1;for(const u of e){const c=S(u);if(c){n=!0;for(const f of k(V(u.slice(c[0],c[1]))))t.add(R(f))}}const r=[...t],s=r.reduce((u,c)=>u+Math.max(0,c.length-h+1)+1,0),i=Math.max(1,Math.ceil(s/q)),o=Math.max(h,i),l=new Set,a=new Set;for(const u of r){if(u.length<o){(u.length>=h||/\s/u.test(u))&&a.add(u);continue}for(let c=0;c+o<=u.length;c+=i)l.add(u.slice(c,c+o));l.add(u.slice(-o))}return{carried:n,fragments:l,fragmentLength:o,shortSpellings:[...a]}}function J(e,t){const n=R(e),r=new Uint8Array(e.length);let s=!1;const i=t.fragmentLength;for(let l=0;l+i<=n.length;l+=1)t.fragments.has(n.slice(l,l+i))&&(r.fill(1,l,l+i),s=!0);for(const l of t.shortSpellings)for(let a=n.indexOf(l);a>=0;a=n.indexOf(l,a+1))r.fill(1,a,a+l.length),s=!0;if(!s)return e;let o="";for(let l=0;l<e.length;l+=1)r[l]?(l===0||!r[l-1])&&(o+=y):o+=e[l];return o}function we(e,t){return A.run(Y(e),t)}function Pe(){return(A.getStore()??P).carried}const K=16,U=512,ee=/^(?:(?:[A-Za-z0-9-]+\.)+[A-Za-z0-9-]+|localhost):\d+$/iu,ne=260,te={'"':'"',"'":"'","`":"`","<":">","(":")","[":"]"},re=new Set(["http","https","ws","wss","ftp","file"]);function $(e,t=!1){const n=ae(e);if(n<0)return;const r=O(e,n);if(n-r<2)return;const s=te[e[r-1]??""],i=re.has(e.slice(r,n).toLowerCase());let o=n+1;for(;o<e.length&&(e[o]==="/"||e[o]==="\\");)o+=1;if(o===e.length)return{kind:"pending",closer:s,special:i};const l=p(e.slice(o),s);if(l.startsWith("[")||i&&/[/\\?#]/u.test(l)||E(l,s)>=0)return;const a=ue(l,t);return a===void 0?void 0:{kind:a,closer:s,special:i}}const se=new Set([")","]"]),ie="'\\''",oe="'\\\\''";function p(e,t){return t==="'"?D(e.replaceAll(oe,"_____").replaceAll(ie,"____")):t==='"'?D(e):e}function L(e,t){let n=t;for(;e[n]==="\\";)n+=1;return n}function le(e,t,n){const r=(n-t)%2===1;if(e[n]==='"')return r?n:-1;if(e[n]!=="^")return-1;if(e[n+1]==='"')return r?n+1:-1;const s=L(e,n+1);return e[s]==='"'&&(s-n-1)%2===1?s:-1}function D(e){const t=[];let n=0;for(let r=e.indexOf("\\");r>=0;r=e.indexOf("\\",r)){const s=L(e,r),i=le(e,r,s);i>=0&&(t.push(e.slice(n,r),"_".repeat(i+1-r)),n=i+1),r=i>=0?i+1:s}return n===0?e:`${t.join("")}${e.slice(n)}`}function E(e,t){if(t===void 0)return-1;if(!se.has(t))return ce(e,t);let n=e.length;for(;n>0&&/[.,;:!?*_~`]/u.test(e[n-1]);)n-=1;return n>0&&e[n-1]===t?n-1:-1}function ce(e,t){for(let n=e.indexOf(t);n>=0;n=e.indexOf(t,n+1)){if(t==="'"&&e[n+1]==="'"){n+=1;continue}let r=0;for(;n-r>0&&e[n-r-1]==="\\";)r+=1;if(r%2===0)return n}return-1}function ae(e){let t=-1;for(let n=e.length-2;n>=0;n-=1){if(e[n]!==":"||e[n+1]!=="/"&&e[n+1]!=="\\")continue;const r=O(e,n);if(r===0||/[=?&#"'`(<[{,]/u.test(e[r-1]))return n;t=n}return t}function O(e,t){let n=t;for(;n>0&&/[A-Za-z0-9+.-]/u.test(e[n-1]);)n-=1;return n}function ue(e,t){return e.includes(":")?!t&&e.length<=ne&&ee.test(e)?void 0:"user":g.test(e)?void 0:"label"}function fe(e,t,n,r=-1){const s=Math.min(e.length,t+U);let i=t,o=r,l=n.kind==="user",a=!1;for(let u=0;u<K&&i<s;u+=1){const c=M(e,i,s);if(c===void 0)break;const f=pe(e.slice(c[0],Math.min(c[1],s+3)),s-c[0],n);if(f.startsUrl)break;de(f,l,a)&&(o=c[1]);const d=/[\t\r\n]/u.test(e[c[1]]??"");if(l||=f.colon||f.trailingColon&&d,a||=f.trailingColon,f.endsAuthority)break;i=c[1]}return o}function de(e,t,n){return e.separator?t||e.colonBeforeSeparator||n&&(e.hasPath||e.closedByOpener):!1}function M(e,t,n){let r=t;for(;r<n&&/\s/u.test(e[r]);)r+=1;if(r===n)return;let s=r;for(;s<e.length&&!/\s/u.test(e[s]);)s+=1;return[r,s]}function N(e){const t=e.indexOf(":");return t>=0&&t<e.length-1&&!he.test(e)}const he=/^\d{1,2}:\d{2}(?::\d{2})?(?:\.\d+)?(?:Z|[AaPp][Mm])?[.,;:!?)]*$/u;function pe(e,t,n){const r=p(e,n.closer),s=n.special?r.search(/[/\\?#]/u):-1,i=s<0?r:r.slice(0,s),o=E(i,n.closer),l=r.search(/:[/\\]/u),a=o<0?i:i.slice(0,o),u=Math.min(a.length,t)-1,c=u<0?-1:Math.max(a.lastIndexOf("@",u),C(a,u));return{startsUrl:l>=0&&o<0&&ge(r.slice(0,l+1)),separator:c>=0,colonBeforeSeparator:c>0&&(N(a.slice(0,c))||a[c-1]===":"),colon:N(a),trailingColon:a.endsWith(":"),hasPath:o<0&&c>=0&&/[/\\]/u.test(r.slice(c+1)),closedByOpener:o>=0,endsAuthority:s>=0||o>=0}}function ge(e){const t=O(e,e.length-1);return t<e.length-2&&/[A-Za-z]/u.test(e[t])&&(t===0||t===1&&/["'`(<[]/u.test(e[0]))}function Se(e,t,n){const r=$(t,/[\t\r\n]/u.test(e.charAt(n)));if(r?.kind!=="pending")return r===void 0?void 0:{opening:r,from:n,seed:-1,final:!1};const s=M(e,n,Math.min(e.length,n+U));if(s===void 0)return;const i=p(e.slice(s[0],s[1]),r.closer),o=/^[/\\]*/u.exec(i)[0],l=i.slice(o.length),a=r.special?l.split(/[/\\?#]/u,1)[0]:l,u=E(a,r.closer),c=`${o}${u<0?a:a.slice(0,u)}`,f=g.test(c),d=f?{...r,kind:"user"}:$(`${t}${c}`);if(d===void 0||d.kind==="pending")return;const W=f?s[1]:-1;return{opening:d,from:s[1],seed:W,final:c.length<i.length}}function _e(e){if(!/:[/\\]/u.test(e))return e;const t=/\S+/gu;let n="",r=0;for(let s=t.exec(e);s!==null;s=t.exec(e)){const i=Se(e,s[0],s.index+s[0].length);if(i===void 0)continue;const o=i.final?i.seed:fe(e,i.from,i.opening,i.seed);o!==-1&&(n+=`${e.slice(r,s.index)}${_(e.slice(s.index,o))}`,r=o,t.lastIndex=o)}return r===0?e:`${n}${e.slice(r)}`}function Re(e){const t=A.getStore()??P,n=b(e);return t.carried?b(J(n,t)):n}function b(e){return g.test(e)?_e(e).replaceAll(/\S+/gu,_):e}const Ue={neutralizeEscapedQuotes:p};export{y as URL_CREDENTIAL_PLACEHOLDER,Ie as assertIdentityFieldsWithoutUrlCredentials,w as assertIdentityWithoutUrlCredentials,Pe as invocationCarriesUrlCredentials,Ce as parseIdentityOption,I as redactIdentityCredentials,ye as redactIdentityFields,Te as redactOptionalIdentityCredentials,Re as redactUrlCredentialsInText,_ as redactUrlCredentialsInToken,we as runWithUrlCredentialInvocation,Ue as urlCredentialsTestOnly};
2
2
  //# sourceMappingURL=url-credentials.js.map
@@ -47,20 +47,42 @@ export interface ItemMutationLocation{
47
47
  * `document.metadata.id` (for example in case on a case-sensitive
48
48
  * filesystem), so any read of this item's history inside the mutation must use it.
49
49
  */
50
- storageId:string;}
50
+ storageId:string;
51
+ /**
52
+ * True when another principal holds the item and the mutation's
53
+ * `callerClaimScope` scoped it to the caller's own ended claim: the
54
+ * callback must leave the holder's ownership unchanged. A scoped mutation
55
+ * that changes nothing writes nothing.
56
+ */
57
+ callerClaimScoped?:true;}
58
+ /**
59
+ * Decide, under the item lock, whether a mutation by a caller who does not
60
+ * hold the item acts only on the caller's own ended claim. When it resolves
61
+ * true the assignee-conflict policy and `--force` do not apply, and the
62
+ * callback receives `callerClaimScoped`.
63
+ */
64
+ export type CallerClaimScope=(input:{
65
+ /** The item as read under the lock. */
66
+ document:ItemDocument;
67
+ /** Storage id that keys the item's lock and history stream. */
68
+ storageId:string;
69
+ /** The caller's claim principal, compared exactly as the ownership guard compares it. */
70
+ callerPrincipal:string;})=> Promise<boolean>;
51
71
  /** The locked edit a single-item mutation applies; it receives the document and where the lock acts. */
52
72
  export type ItemMutationCallback=(document:ItemDocument,mutation:ItemMutationLocation)=>{changedFields:string[];warnings?:string[];}|Promise<{changedFields:string[];warnings?:string[];}>;interface ItemMutationResult{item:ItemMetadata;body:string;changedFields:string[];warnings:string[];}
53
73
  interface ItemMutationParams{pmRoot:string;settings:PmSettings;id:string;op:string;author:string;message?:string;
54
74
  /** Structured immutable context attached to the appended history entry. */
55
- historyContext?:Record<string,unknown>;force?:boolean;bypassAssigneeConflict?:boolean;skipNoop?:boolean;extensionFieldNames?:readonly string[];typeToFolder?:Record<string,string>;mutate:ItemMutationCallback;}
75
+ historyContext?:Record<string,unknown>;force?:boolean;bypassAssigneeConflict?:boolean;
76
+ /** Scope a non-holder's mutation to its own ended claim; see {@link CallerClaimScope}. */
77
+ callerClaimScope?:CallerClaimScope;skipNoop?:boolean;extensionFieldNames?:readonly string[];typeToFolder?:Record<string,string>;mutate:ItemMutationCallback;}
56
78
  /** Mutate one item while attaching structured context to its immutable history event. */
57
79
  export declare function mutateItemWithHistoryContext(params:{pmRoot:string;settings:PmSettings;id:string;op:string;author:string;message?:string;
58
80
  /** Structured immutable context attached to the appended history entry. */
59
- historyContext?:Record<string,unknown>;force?:boolean;bypassAssigneeConflict?:boolean;skipNoop?:boolean;extensionFieldNames?:readonly string[];typeToFolder?:Record<string,string>;mutate:ItemMutationCallback;}):Promise<{item:ItemMetadata;body:string;changedFields:string[];warnings:string[];}>;
81
+ historyContext?:Record<string,unknown>;force?:boolean;bypassAssigneeConflict?:boolean;callerClaimScope?:CallerClaimScope;skipNoop?:boolean;extensionFieldNames?:readonly string[];typeToFolder?:Record<string,string>;mutate:ItemMutationCallback;}):Promise<{item:ItemMetadata;body:string;changedFields:string[];warnings:string[];}>;
60
82
  /** Mutate one item while resolving structured history context after its locked mutation. */
61
83
  export declare function mutateItemWithHistoryContextResolver(params:Omit<ItemMutationParams,"historyContext">&{resolveHistoryContext:()=> Record<string,unknown>|undefined;}):Promise<ItemMutationResult>;
62
84
  /** Implements mutate item for the public runtime surface of this module. */
63
- export declare function mutateItem(params:{pmRoot:string;settings:PmSettings;id:string;op:string;author:string;message?:string;force?:boolean;bypassAssigneeConflict?:boolean;skipNoop?:boolean;extensionFieldNames?:readonly string[];typeToFolder?:Record<string,string>;mutate:ItemMutationCallback;}):Promise<{item:ItemMetadata;body:string;changedFields:string[];warnings:string[];}>;
85
+ export declare function mutateItem(params:{pmRoot:string;settings:PmSettings;id:string;op:string;author:string;message?:string;force?:boolean;bypassAssigneeConflict?:boolean;callerClaimScope?:CallerClaimScope;skipNoop?:boolean;extensionFieldNames?:readonly string[];typeToFolder?:Record<string,string>;mutate:ItemMutationCallback;}):Promise<{item:ItemMetadata;body:string;changedFields:string[];warnings:string[];}>;
64
86
  /** Public contract for item store test only, shared by SDK and presentation-layer consumers. */
65
87
  export declare const itemStoreTestOnly:{appendWarning:typeof appendWarning;bypassesAssigneeConflict:typeof bypassesAssigneeConflict;buildDidYouMeanSuggestions:typeof buildDidYouMeanSuggestions;isErrno:typeof isErrno;};
66
88
  /** Implements delete item for the public runtime surface of this module. */
@@ -1,2 +1,2 @@
1
- import I from"node:fs/promises";import{buildDeletedItemError as bt}from"../history/tombstone.js";import{normalizeHistoryOperationForWrite as Pt}from"../history/operation-contract.js";import{enforceWorkflowMutation as B}from"../policy/workflow-policy-store.js";import{recordItemMetadataEnumeration as L}from"./item-metadata-read-work.js";import{advanceItemMutationPreconditions as G,assertItemMutationPreconditions as V,itemMutationPreconditionHistoryContext as kt,transactionCompensationHistoryContext as Y}from"./item-mutation-precondition.js";import{checkpointMutationHistoryContext as Ct}from"../checkpoint/mutation-context.js";import M from"node:path";import{getActiveExtensionRegistrations as K,projectAfterCommandItemSnapshot as E,recordAfterCommandAffectedItem as X,runActiveOnReadHooks as Nt,runActiveBeforeMutationHooks as J,runActiveOnWriteHooks as D,runActiveServiceOverride as Q}from"../extensions/index.js";import{collectRegisteredItemFieldNames as Tt}from"../extensions/item-fields.js";import{EMPTY_CANONICAL_DOCUMENT as Z,EXIT_CODE as C,TYPE_TO_FOLDER as O}from"../shared/constants.js";import{PmCliError as y}from"../shared/errors.js";import{levenshteinDistanceWithinLimit as Dt}from"../shared/levenshtein.js";import{appendHistoryEntry as tt,createHistoryEntry as et}from"../history/history.js";import{enforceHistoryStreamPolicyForItem as ot}from"../history/history-stream-policy.js";import{canonicalDocument as W,parseItemDocument as it,serializeItemDocument as Ot}from"../item/item-format.js";import{resolveItemTypeRegistry as Wt}from"../item/type-registry.js";import{effectiveItemFormatVersion as At,requiredItemFormatVersion as nt}from"../item/item-format-version.js";import{assertProjectRuntimeFormatGuard as St}from"../../sdk/environment/project-runtime-compatibility.js";import{acquireLockLease as Lt}from"../lock/lock.js";import{isFileMissingError as Mt,writeFileAtomic as A}from"../fs/fs-utils.js";import{isUtf8 as Et}from"node:buffer";import{normalizeItemId as rt,normalizeRawItemId as jt}from"../item/id.js";import{acquireItemMetadataDerivedIndexLock as at,listAllDocumentCandidatesCached as $t,listAllDocumentsCached as Ht,listAllDocumentsCachedLight as zt,refreshItemMetadataDerivedIndex as st}from"./item-metadata-cache.js";import{getHistoryPath as dt,getItemPath as ct,ITEM_FILE_EXTENSIONS as qt,resolveWorkspaceRoot as Ut}from"./paths.js";import{resolveGovernanceKnobs as Bt}from"./settings.js";import{assertReadableTrackerRoot as j}from"./tracker-preflight.js";import{resolveClaimPrincipal as Gt}from"../shared/author.js";import{pruneResolvedDeferredFields as Vt}from"../item/deferred-fields.js";import{nowIso as mt}from"../shared/time.js";import{redactOptionalIdentityCredentials as Yt}from"../shared/url-credentials.js";async function Kt(t){try{return await I.access(t),!0}catch{return!1}}function Xt(t,o){return typeof t=="object"&&t!==null&&"code"in t&&t.code===o}function lt(t,o){t&&(t.includes(o)||t.push(o))}function $(t){return t??Tt(K())}function Jt(t){return t==="toon"?["toon","json_markdown"]:t==="json_markdown"?["json_markdown","toon"]:["toon","json_markdown"]}async function H(t,o,e="pm-",i,a=O){const n=o.trim(),d=n.startsWith("#")?n.slice(1):n;if(d.length===0)return null;const l=rt(o,e),m=jt(o),r=[...new Set([d,l,m])].filter(h=>h.length>0),f=Object.entries(a),c=Jt(i);for(const h of r){const u=new Map;for(const[s]of f)for(const g of c){const p=ct(t,s,h,g,a);await Kt(p)&&u.set(p,u.get(p)??{id:h,type:s,itemPath:p,item_format:g})}if(u.size>1){const s=[...u.keys()].map(g=>M.relative(t,g).split(M.sep).join("/")).sort();throw new y(`Item ${h} has ambiguous identity across ${s.join(", ")}. Preserve both documents and inspect pm ops validate --check-storage-integrity before resolving the collision.`,C.CONFLICT,{code:"item_identity_ambiguous",item_id:h,paths:s})}for(const s of u.values())return s}return null}async function ft(t,o={}){const e=await Qt(t,o);if(e.error!==null)throw e.error;return{raw:e.raw,document:e.document}}async function Qt(t,o={}){const e=await I.readFile(t.itemPath);if(!Et(e))throw new y("Item contains invalid UTF-8; preserve a binary backup before recovering it.",C.CONFLICT,{code:"item_document_encoding_invalid",item_id:t.id,item_path:t.itemPath,byte_length:e.length,empty:!1});const i=e.toString("utf8");await Nt({path:t.itemPath,scope:"project"});let a;try{a=it(i,{format:t.item_format,requireSupportedFormat:!0,schema:o.schema,extensionFieldNames:$(o.extensionFieldNames),onWarning:n=>lt(o.warnings,n)})}catch(n){if(n instanceof y&&n.code==="item_format_version_unsupported")throw new y(`Item ${t.id}: ${n.message}`,n.exitCode,{...n.context,item_id:t.id,item_path:t.itemPath});if(n instanceof y&&n.code==="item_document_invalid")return{raw:i,document:null,error:new y(`Cannot read ${t.id} at ${t.itemPath}${e.length===0?" (zero-length file)":""}: ${n.message}`,n.exitCode,{...n.context,item_id:t.id,item_path:t.itemPath,byte_length:e.length,empty:e.length===0,nextSteps:[`Run pm history ${t.id} --full, then pm restore ${t.id} <version> to recover a recorded state.`]})};throw n}return{raw:i,document:a,error:null}}async function Zt(t,o,e=O,i,a){await j(t);const n=await Ht(t,o,e,i,a);return L(n.length),n.map(d=>d.metadata)}async function Me(t,o,e=O,i,a){await j(t);const n=await zt(t,o,e,i,a);return L(n.length),n.map(d=>d.metadata)}async function Ee(t,o,e=O,i,a,n={}){await j(t);const d=await $t(t,o,e,i,a,{includeBody:!0,forceSourceScan:n.forceSourceScan});return L(d.length),d.map(l=>({...l.metadata,body:l.body}))}function ut(t){return{async get(o){const e=await H(t.pmRoot,o,t.settings.id_prefix,t.settings.item_format,t.typeToFolder);if(!e)return null;const{document:i}=await ft(e,{schema:t.settings.schema});return{item:i.metadata,body:i.body}},list:()=>Zt(t.pmRoot,t.settings.item_format,t.typeToFolder,void 0,t.settings.schema)}}async function te(t,o){const e=new Set(Object.values(o)),i=[];return await Promise.all([...e].map(async a=>{try{const n=await I.readdir(M.join(t,a));for(const d of n)for(const l of qt)if(d.toLowerCase().endsWith(l)){i.push(d.slice(0,-l.length));break}}catch{}})),i}async function ht(t,o,e,i){const a=rt(o,e),n=await te(t,i);if(n.length===0)return[];const d=Math.max(3,Math.floor(a.length/2));return n.map(m=>({id:m,distance:Dt(m,a,d)})).filter(m=>m.distance!==null).sort((m,r)=>m.distance-r.distance).slice(0,3).map(m=>m.id)}async function ee(t,o,e,i){const a=await bt(t,o,e);if(a)return a;const n=await ht(t,o,e,i),d=["Confirm the active --path/PM_PATH scope, then retry with a valid id."];return n.length>0&&d.unshift(`Did you mean one of: ${n.join(", ")}?`),new y(`Item ${o} not found`,C.NOT_FOUND,{code:"item_not_found",id:o,nextSteps:d})}function gt(t,o){return t==="claim"||o===!0&&(t==="comment_add"||t==="comment_edit"||t==="comment_delete"||t==="note_add"||t==="learning_add"||t==="release"||t==="update"||t==="update_ownership_bypass"||t==="update_audit")}async function wt(t){const o=t.typeToFolder??Wt(t.settings,K()).type_to_folder,e=await H(t.pmRoot,t.id,t.settings.id_prefix,t.settings.item_format,o);if(!e)throw await ee(t.pmRoot,t.id,t.settings.id_prefix,o);const i=await Lt(t.pmRoot,e.id,t.settings.locks.ttl_seconds,t.author,!!t.force,t.settings.governance.force_required_for_stale_lock,t.settings.locks.wait_ms,{waitPolicy:"progress"}),a=i.release;try{const n=[],{raw:d,document:l}=await ft(e,{schema:t.settings.schema,extensionFieldNames:t.extensionFieldNames,warnings:n}),m=l.metadata.assignee?.trim(),r=Yt(m),f=l.metadata.claim_principal?.trim()||m,c=Gt(t.author),h=Bt(t.settings);if(r&&f!==c&&!t.force&&!gt(t.op,t.bypassAssigneeConflict)){if(h.ownership_enforcement==="strict")throw new y(`Item ${e.id} is assigned to ${r}. Use --force to override.`,C.CONFLICT);h.ownership_enforcement==="warn"&&n.push(`ownership_warning:assignee_conflict:${e.id}:${r}`)}return{typeToFolder:o,located:e,originalRaw:d,document:l,warnings:n,releaseLock:a,lease:i}}catch(n){throw await a(),n}}function pt(t){return Object.keys(t).length===0?void 0:t}async function yt(t,o,e,i){return t.fence(async()=>{let a;try{a=await I.readFile(o.itemPath,"utf8")}catch(n){if(!Mt(n))throw n;a=null}if(a!==e)throw new y(`Item ${o.id} changed after this mutation read it; refusing to overwrite the newer revision. Nothing was written.`,C.CONFLICT,{code:"stale_revision",item_id:o.id,reason:a===null?"item_removed":"item_revision_changed",required:"Re-read the item and apply the mutation again; the newer stored revision was kept."});return i()})}function oe(t,o,e){if(!t.handled||typeof t.result!="object"||t.result===null)return{effectiveTargetItemPath:o,effectiveSerializedAfter:e,skipItemWrite:!1};const i=t.result;return{effectiveTargetItemPath:typeof i.target_item_path=="string"&&i.target_item_path.trim().length>0?i.target_item_path:o,effectiveSerializedAfter:typeof i.contents=="string"?i.contents:e,skipItemWrite:i.skip_write===!0}}async function _t(t){try{const o=await H(t.pmRoot,t.id,t.settings.id_prefix,t.settings.item_format,t.typeToFolder);if(!o)return{document:Z};const e=it(await I.readFile(o.itemPath,"utf8"),{format:o.item_format,requireSupportedFormat:!0,schema:t.settings.schema,extensionFieldNames:$(t.extensionFieldNames)});return e.metadata.id===t.embeddedId?{document:e}:{document:t.fallback,revision:It}}catch{return{document:t.fallback,revision:It}}}const It="unreadable-after-storage-override";async function ie(t){const o=await Q("item_store_delete",t),e=o.handled&&typeof o.result=="object"&&o.result!==null?o.result:{};return{effectiveItemPath:typeof e.item_path=="string"&&e.item_path.trim().length>0?e.item_path:t.item_path,skipDelete:e.skip_delete===!0,warnings:o.warnings}}async function ne(t){if(!t.skipItemWrite){if(t.effectiveTargetItemPath!==t.originalItemPath){await A(t.originalItemPath,t.originalRaw),await I.rm(t.effectiveTargetItemPath,{force:!0});return}await A(t.originalItemPath,t.originalRaw)}}function re(t,o){Vt(t.metadata)&&o.push("deferred_fields")}async function z(t){Pt(t.op);const o=await wt({pmRoot:t.pmRoot,settings:t.settings,id:t.id,op:t.op,author:t.author,force:t.force,bypassAssigneeConflict:t.bypassAssigneeConflict,extensionFieldNames:t.extensionFieldNames,typeToFolder:t.typeToFolder}),{typeToFolder:e,located:i,originalRaw:a,document:n,warnings:d,releaseLock:l,lease:m}=o;try{V(t.pmRoot,n,i.id);const r=W(n,{schema:t.settings.schema,extensionFieldNames:t.extensionFieldNames}),f=W(structuredClone(n),{schema:t.settings.schema,extensionFieldNames:t.extensionFieldNames}),c=await t.mutate(f,{storageId:i.id});if(re(f,c.changedFields),t.skipNoop===!0&&c.changedFields.length===0)return{item:r.metadata,body:r.body,changedFields:[],warnings:[...d,...c.warnings??[]]};const h={...t.resolveHistoryContext?.(),...Ct(t.pmRoot,i.id),...kt(t.pmRoot,[i.id,n.metadata.id])},u=Math.max(nt(r.metadata),nt(f.metadata));St(Ut(t.pmRoot),u),u>At(f.metadata)&&(f.metadata.pm_format_version=u,c.changedFields.push("pm_format_version")),f.metadata.updated_at=mt();const s=W(f,{schema:t.settings.schema,extensionFieldNames:t.extensionFieldNames}),g=await B({pmRoot:t.pmRoot,settings:t.settings,operation:t.op,author:t.author,before:r,after:s});await J({pm_root:t.pmRoot,operation:t.op,before:r,after:s,changed_fields:c.changedFields,author:t.author,sdk:ut({pmRoot:t.pmRoot,settings:t.settings,typeToFolder:e})});const p=await ot({pmRoot:t.pmRoot,settings:t.settings,itemId:i.id,commandLabel:t.op}),v="toon",x=Ot(s,{format:v,schema:t.settings.schema,extensionFieldNames:t.extensionFieldNames}),b=ct(t.pmRoot,s.metadata.type,i.id,v,e),F=dt(t.pmRoot,i.id),N=await yt(m,i,a,async()=>{const P=await Q("item_store_write",{op:t.op,pm_root:t.pmRoot,item_id:i.id,source_item_path:i.itemPath,target_item_path:b,history_path:F,item_format:v,before:r,after:s,contents:x}),{effectiveTargetItemPath:_,effectiveSerializedAfter:q,skipItemWrite:k}=oe(P,b,x),vt=await at(t.pmRoot,t.author);let U=[];try{k||await A(_,q),!k&&_!==i.itemPath&&await I.rm(i.itemPath);const Rt=et({nowIso:s.metadata.updated_at,author:t.author,op:t.op,before:r,after:s,message:t.message,context:pt({...h,...g.decisions.length===0?{}:{workflow_policies:g.decisions},...Y(t.pmRoot,[i.id,n.metadata.id],t.op)})});try{await tt(F,Rt)}catch(xt){throw await ne({skipItemWrite:k,effectiveTargetItemPath:_,originalItemPath:i.itemPath,originalRaw:a}),xt}k||(U=await st({pmRoot:t.pmRoot,preferredFormat:t.settings.item_format,typeToFolder:e,schema:t.settings.schema,itemPath:_,previousItemPath:i.itemPath,document:s}))}finally{await vt()}const Ft=k||_!==b||q!==x;return{derivedIndexWarnings:U,effectiveTargetItemPath:_,overrideWarnings:P.warnings,stored:Ft?await _t({pmRoot:t.pmRoot,settings:t.settings,id:i.id,typeToFolder:e,extensionFieldNames:t.extensionFieldNames,fallback:s,embeddedId:s.metadata.id}):{document:s}}}),{derivedIndexWarnings:w,effectiveTargetItemPath:R,stored:T}=N;G(t.pmRoot,T.document,i.id,[s.metadata.id],T.revision);const S=[...await D({path:R,scope:"project",op:t.op,item_id:s.metadata.id,item_type:s.metadata.type,before:r,after:s,changed_fields:c.changedFields}),...await D({path:F,scope:"project",op:`${t.op}:history`,item_id:s.metadata.id,item_type:s.metadata.type,before:r,after:s,changed_fields:c.changedFields})];return X({id:s.metadata.id,op:t.op,item_type:s.metadata.type,previous_status:r.metadata.status,status:s.metadata.status,previous:E(r.metadata,c.changedFields),current:E(s.metadata,c.changedFields),changed_fields:c.changedFields}),{item:s.metadata,body:s.body,changedFields:c.changedFields,warnings:[...d,...c.warnings??[],...g.warnings,...p.warnings,...N.overrideWarnings,...w,...S]}}finally{await l()}}async function je(t){const{historyContext:o,...e}=t;return z({...e,resolveHistoryContext:()=>o})}async function $e(t){return z(t)}async function He(t){return z(t)}const ze={appendWarning:lt,bypassesAssigneeConflict:gt,buildDidYouMeanSuggestions:ht,isErrno:Xt};async function qe(t){const o=await wt({pmRoot:t.pmRoot,settings:t.settings,id:t.id,op:"delete",author:t.author,force:t.force}),{located:e,originalRaw:i,document:a,warnings:n,releaseLock:d,lease:l}=o;try{V(t.pmRoot,a,e.id);const m=$(void 0),r=W(a,{schema:t.settings.schema,extensionFieldNames:m}),f=await B({pmRoot:t.pmRoot,settings:t.settings,operation:"delete",author:t.author,before:r,after:null,dryRun:t.dryRun});await J({pm_root:t.pmRoot,operation:"delete",before:r,after:null,changed_fields:["deleted"],author:t.author,dry_run:t.dryRun===!0,sdk:ut({pmRoot:t.pmRoot,settings:t.settings,typeToFolder:o.typeToFolder})});const c=await ot({pmRoot:t.pmRoot,settings:t.settings,itemId:e.id,commandLabel:"delete"}),h=mt(),u=Z,s=et({nowIso:h,author:t.author,op:"delete",before:r,after:u,message:t.message,context:pt({...f.decisions.length===0?{}:{workflow_policies:f.decisions},...Y(t.pmRoot,[e.id,a.metadata.id],"delete")})}),g=dt(t.pmRoot,e.id),p=()=>ie({op:"delete",pm_root:t.pmRoot,item_id:e.id,item_path:e.itemPath,history_path:g,before:r});if(t.dryRun===!0){const w=await p();return{item:r.metadata,changedFields:["deleted"],targetPath:w.effectiveItemPath,warnings:[...n,...f.warnings,...c.warnings,...w.warnings]}}const v=await yt(l,e,i,async()=>{const{effectiveItemPath:w,skipDelete:R,warnings:T}=await p(),S=await at(t.pmRoot,t.author);let P=[];try{R||await I.rm(w);try{await tt(g,s)}catch(_){throw R||await A(w,i),_}R||(P=await st({pmRoot:t.pmRoot,preferredFormat:t.settings.item_format,typeToFolder:o.typeToFolder,schema:t.settings.schema,itemPath:w,document:null}))}finally{await S()}return{derivedIndexWarnings:P,effectiveItemPath:w,overrideWarnings:T,stored:R||w!==e.itemPath?await _t({pmRoot:t.pmRoot,settings:t.settings,id:e.id,typeToFolder:o.typeToFolder,fallback:u,embeddedId:a.metadata.id}):{document:u}}}),{derivedIndexWarnings:x,effectiveItemPath:b,stored:F}=v;G(t.pmRoot,F.document,e.id,[a.metadata.id],F.revision);const N=[...await D({path:b,scope:"project",op:"delete",item_id:r.metadata.id,item_type:r.metadata.type,before:r,after:u,changed_fields:["deleted"]}),...await D({path:g,scope:"project",op:"delete:history",item_id:r.metadata.id,item_type:r.metadata.type,before:r,after:u,changed_fields:["deleted"]})];return X({id:r.metadata.id,op:"delete",item_type:r.metadata.type,previous_status:r.metadata.status,previous:E(r.metadata,Object.keys(r.metadata)),changed_fields:["deleted"]}),{item:r.metadata,changedFields:["deleted"],warnings:[...n,...f.warnings,...c.warnings,...v.overrideWarnings,...x,...N]}}finally{await d()}}export{ee as buildItemNotFoundError,ut as createMutationGuardSdk,qe as deleteItem,ze as itemStoreTestOnly,Zt as listAllItemMetadata,Me as listAllItemMetadataLight,Ee as listAllItemMetadataWithBody,H as locateItem,He as mutateItem,je as mutateItemWithHistoryContext,$e as mutateItemWithHistoryContextResolver,ft as readLocatedItem,Qt as readLocatedItemSnapshot};
1
+ import _ from"node:fs/promises";import{buildDeletedItemError as Pt}from"../history/tombstone.js";import{normalizeHistoryOperationForWrite as kt}from"../history/operation-contract.js";import{enforceWorkflowMutation as G}from"../policy/workflow-policy-store.js";import{recordItemMetadataEnumeration as M}from"./item-metadata-read-work.js";import{advanceItemMutationPreconditions as V,assertItemMutationPreconditions as Y,itemMutationPreconditionHistoryContext as Ct,transactionCompensationHistoryContext as K}from"./item-mutation-precondition.js";import{checkpointMutationHistoryContext as Nt}from"../checkpoint/mutation-context.js";import E from"node:path";import{getActiveExtensionRegistrations as X,projectAfterCommandItemSnapshot as j,recordAfterCommandAffectedItem as J,runActiveOnReadHooks as Tt,runActiveBeforeMutationHooks as Q,runActiveOnWriteHooks as D,runActiveServiceOverride as Z}from"../extensions/index.js";import{collectRegisteredItemFieldNames as St}from"../extensions/item-fields.js";import{EMPTY_CANONICAL_DOCUMENT as tt,EXIT_CODE as k,TYPE_TO_FOLDER as O}from"../shared/constants.js";import{PmCliError as y}from"../shared/errors.js";import{levenshteinDistanceWithinLimit as Dt}from"../shared/levenshtein.js";import{appendHistoryEntry as et,createHistoryEntry as ot}from"../history/history.js";import{enforceHistoryStreamPolicyForItem as it}from"../history/history-stream-policy.js";import{canonicalDocument as W,parseItemDocument as nt,serializeItemDocument as Ot}from"../item/item-format.js";import{resolveItemTypeRegistry as Wt}from"../item/type-registry.js";import{effectiveItemFormatVersion as At,requiredItemFormatVersion as rt}from"../item/item-format-version.js";import{assertProjectRuntimeFormatGuard as Lt}from"../../sdk/environment/project-runtime-compatibility.js";import{acquireLockLease as Mt}from"../lock/lock.js";import{isFileMissingError as Et,writeFileAtomic as A}from"../fs/fs-utils.js";import{isUtf8 as jt}from"node:buffer";import{normalizeItemId as at,normalizeRawItemId as $t}from"../item/id.js";import{acquireItemMetadataDerivedIndexLock as st,listAllDocumentCandidatesCached as Ht,listAllDocumentsCached as zt,listAllDocumentsCachedLight as Ut,refreshItemMetadataDerivedIndex as dt}from"./item-metadata-cache.js";import{getHistoryPath as ct,getItemPath as mt,ITEM_FILE_EXTENSIONS as qt,resolveWorkspaceRoot as Bt}from"./paths.js";import{resolveGovernanceKnobs as Gt}from"./settings.js";import{assertReadableTrackerRoot as $}from"./tracker-preflight.js";import{resolveClaimPrincipal as Vt}from"../shared/author.js";import{pruneResolvedDeferredFields as Yt}from"../item/deferred-fields.js";import{nowIso as lt}from"../shared/time.js";import{redactOptionalIdentityCredentials as Kt}from"../shared/url-credentials.js";async function Xt(t){try{return await _.access(t),!0}catch{return!1}}function Jt(t,e){return typeof t=="object"&&t!==null&&"code"in t&&t.code===e}function ft(t,e){t&&(t.includes(e)||t.push(e))}function H(t){return t??St(X())}function Qt(t){return t==="toon"?["toon","json_markdown"]:t==="json_markdown"?["json_markdown","toon"]:["toon","json_markdown"]}async function z(t,e,o="pm-",i,r=O){const n=e.trim(),d=n.startsWith("#")?n.slice(1):n;if(d.length===0)return null;const l=at(e,o),f=$t(e),s=[...new Set([d,l,f])].filter(c=>c.length>0),m=Object.entries(r),g=Qt(i);for(const c of s){const u=new Map;for(const[h]of m)for(const a of g){const p=mt(t,h,c,a,r);await Xt(p)&&u.set(p,u.get(p)??{id:c,type:h,itemPath:p,item_format:a})}if(u.size>1){const h=[...u.keys()].map(a=>E.relative(t,a).split(E.sep).join("/")).sort();throw new y(`Item ${c} has ambiguous identity across ${h.join(", ")}. Preserve both documents and inspect pm ops validate --check-storage-integrity before resolving the collision.`,k.CONFLICT,{code:"item_identity_ambiguous",item_id:c,paths:h})}for(const h of u.values())return h}return null}async function ut(t,e={}){const o=await Zt(t,e);if(o.error!==null)throw o.error;return{raw:o.raw,document:o.document}}async function Zt(t,e={}){const o=await _.readFile(t.itemPath);if(!jt(o))throw new y("Item contains invalid UTF-8; preserve a binary backup before recovering it.",k.CONFLICT,{code:"item_document_encoding_invalid",item_id:t.id,item_path:t.itemPath,byte_length:o.length,empty:!1});const i=o.toString("utf8");await Tt({path:t.itemPath,scope:"project"});let r;try{r=nt(i,{format:t.item_format,requireSupportedFormat:!0,schema:e.schema,extensionFieldNames:H(e.extensionFieldNames),onWarning:n=>ft(e.warnings,n)})}catch(n){if(n instanceof y&&n.code==="item_format_version_unsupported")throw new y(`Item ${t.id}: ${n.message}`,n.exitCode,{...n.context,item_id:t.id,item_path:t.itemPath});if(n instanceof y&&n.code==="item_document_invalid")return{raw:i,document:null,error:new y(`Cannot read ${t.id} at ${t.itemPath}${o.length===0?" (zero-length file)":""}: ${n.message}`,n.exitCode,{...n.context,item_id:t.id,item_path:t.itemPath,byte_length:o.length,empty:o.length===0,nextSteps:[`Run pm history ${t.id} --full, then pm restore ${t.id} <version> to recover a recorded state.`]})};throw n}return{raw:i,document:r,error:null}}async function te(t,e,o=O,i,r){await $(t);const n=await zt(t,e,o,i,r);return M(n.length),n.map(d=>d.metadata)}async function He(t,e,o=O,i,r){await $(t);const n=await Ut(t,e,o,i,r);return M(n.length),n.map(d=>d.metadata)}async function ze(t,e,o=O,i,r,n={}){await $(t);const d=await Ht(t,e,o,i,r,{includeBody:!0,forceSourceScan:n.forceSourceScan});return M(d.length),d.map(l=>({...l.metadata,body:l.body}))}function ht(t){return{async get(e){const o=await z(t.pmRoot,e,t.settings.id_prefix,t.settings.item_format,t.typeToFolder);if(!o)return null;const{document:i}=await ut(o,{schema:t.settings.schema});return{item:i.metadata,body:i.body}},list:()=>te(t.pmRoot,t.settings.item_format,t.typeToFolder,void 0,t.settings.schema)}}async function ee(t,e){const o=new Set(Object.values(e)),i=[];return await Promise.all([...o].map(async r=>{try{const n=await _.readdir(E.join(t,r));for(const d of n)for(const l of qt)if(d.toLowerCase().endsWith(l)){i.push(d.slice(0,-l.length));break}}catch{}})),i}async function gt(t,e,o,i){const r=at(e,o),n=await ee(t,i);if(n.length===0)return[];const d=Math.max(3,Math.floor(r.length/2));return n.map(f=>({id:f,distance:Dt(f,r,d)})).filter(f=>f.distance!==null).sort((f,s)=>f.distance-s.distance).slice(0,3).map(f=>f.id)}async function oe(t,e,o,i){const r=await Pt(t,e,o);if(r)return r;const n=await gt(t,e,o,i),d=["Confirm the active --path/PM_PATH scope, then retry with a valid id."];return n.length>0&&d.unshift(`Did you mean one of: ${n.join(", ")}?`),new y(`Item ${e} not found`,k.NOT_FOUND,{code:"item_not_found",id:e,nextSteps:d})}function pt(t,e){return t==="claim"||e===!0&&(t==="comment_add"||t==="comment_edit"||t==="comment_delete"||t==="note_add"||t==="learning_add"||t==="release"||t==="update"||t==="update_ownership_bypass"||t==="update_audit")}async function wt(t){const e=t.typeToFolder??Wt(t.settings,X()).type_to_folder,o=await z(t.pmRoot,t.id,t.settings.id_prefix,t.settings.item_format,e);if(!o)throw await oe(t.pmRoot,t.id,t.settings.id_prefix,e);const i=await Mt(t.pmRoot,o.id,t.settings.locks.ttl_seconds,t.author,!!t.force,t.settings.governance.force_required_for_stale_lock,t.settings.locks.wait_ms,{waitPolicy:"progress"}),r=i.release;try{const n=[],{raw:d,document:l}=await ut(o,{schema:t.settings.schema,extensionFieldNames:t.extensionFieldNames,warnings:n}),f=l.metadata.assignee?.trim(),s=Kt(f),m=l.metadata.claim_principal?.trim()||f,g=Vt(t.author),c=Gt(t.settings),u=!!s&&m!==g,h=u&&t.callerClaimScope!==void 0&&await t.callerClaimScope({document:l,storageId:o.id,callerPrincipal:g});if(u&&!h&&!t.force&&!pt(t.op,t.bypassAssigneeConflict)){if(c.ownership_enforcement==="strict")throw new y(`Item ${o.id} is assigned to ${s}. Use --force to override.`,k.CONFLICT);c.ownership_enforcement==="warn"&&n.push(`ownership_warning:assignee_conflict:${o.id}:${s}`)}return{typeToFolder:e,located:o,originalRaw:d,document:l,warnings:n,releaseLock:r,lease:i,callerClaimScoped:h}}catch(n){throw await r(),n}}function yt(t){return Object.keys(t).length===0?void 0:t}async function _t(t,e,o,i){return t.fence(async()=>{let r;try{r=await _.readFile(e.itemPath,"utf8")}catch(n){if(!Et(n))throw n;r=null}if(r!==o)throw new y(`Item ${e.id} changed after this mutation read it; refusing to overwrite the newer revision. Nothing was written.`,k.CONFLICT,{code:"stale_revision",item_id:e.id,reason:r===null?"item_removed":"item_revision_changed",required:"Re-read the item and apply the mutation again; the newer stored revision was kept."});return i()})}function ie(t,e,o){if(!t.handled||typeof t.result!="object"||t.result===null)return{effectiveTargetItemPath:e,effectiveSerializedAfter:o,skipItemWrite:!1};const i=t.result;return{effectiveTargetItemPath:typeof i.target_item_path=="string"&&i.target_item_path.trim().length>0?i.target_item_path:e,effectiveSerializedAfter:typeof i.contents=="string"?i.contents:o,skipItemWrite:i.skip_write===!0}}async function It(t){try{const e=await z(t.pmRoot,t.id,t.settings.id_prefix,t.settings.item_format,t.typeToFolder);if(!e)return{document:tt};const o=nt(await _.readFile(e.itemPath,"utf8"),{format:e.item_format,requireSupportedFormat:!0,schema:t.settings.schema,extensionFieldNames:H(t.extensionFieldNames)});return o.metadata.id===t.embeddedId?{document:o}:{document:t.fallback,revision:vt}}catch{return{document:t.fallback,revision:vt}}}const vt="unreadable-after-storage-override";async function ne(t){const e=await Z("item_store_delete",t),o=e.handled&&typeof e.result=="object"&&e.result!==null?e.result:{};return{effectiveItemPath:typeof o.item_path=="string"&&o.item_path.trim().length>0?o.item_path:t.item_path,skipDelete:o.skip_delete===!0,warnings:e.warnings}}async function re(t){if(!t.skipItemWrite){if(t.effectiveTargetItemPath!==t.originalItemPath){await A(t.originalItemPath,t.originalRaw),await _.rm(t.effectiveTargetItemPath,{force:!0});return}await A(t.originalItemPath,t.originalRaw)}}function ae(t,e){Yt(t.metadata)&&e.push("deferred_fields")}function se(t,e){return e?{storageId:t,callerClaimScoped:!0}:{storageId:t}}function de(t,e,o){o&&e.length===0||ae(t,e)}function ce(t,e){return t===!0||e}async function U(t){kt(t.op);const e=await wt({pmRoot:t.pmRoot,settings:t.settings,id:t.id,op:t.op,author:t.author,force:t.force,bypassAssigneeConflict:t.bypassAssigneeConflict,callerClaimScope:t.callerClaimScope,extensionFieldNames:t.extensionFieldNames,typeToFolder:t.typeToFolder}),{typeToFolder:o,located:i,originalRaw:r,document:n,warnings:d,releaseLock:l,lease:f,callerClaimScoped:s}=e;try{Y(t.pmRoot,n,i.id);const m=W(n,{schema:t.settings.schema,extensionFieldNames:t.extensionFieldNames}),g=W(structuredClone(n),{schema:t.settings.schema,extensionFieldNames:t.extensionFieldNames}),c=await t.mutate(g,se(i.id,s));if(de(g,c.changedFields,s),ce(t.skipNoop,s)&&c.changedFields.length===0)return{item:m.metadata,body:m.body,changedFields:[],warnings:[...d,...c.warnings??[]]};const u={...t.resolveHistoryContext?.(),...Nt(t.pmRoot,i.id),...Ct(t.pmRoot,[i.id,n.metadata.id])},h=Math.max(rt(m.metadata),rt(g.metadata));Lt(Bt(t.pmRoot),h),h>At(g.metadata)&&(g.metadata.pm_format_version=h,c.changedFields.push("pm_format_version")),g.metadata.updated_at=lt();const a=W(g,{schema:t.settings.schema,extensionFieldNames:t.extensionFieldNames}),p=await G({pmRoot:t.pmRoot,settings:t.settings,operation:t.op,author:t.author,before:m,after:a});await Q({pm_root:t.pmRoot,operation:t.op,before:m,after:a,changed_fields:c.changedFields,author:t.author,sdk:ht({pmRoot:t.pmRoot,settings:t.settings,typeToFolder:o})});const C=await it({pmRoot:t.pmRoot,settings:t.settings,itemId:i.id,commandLabel:t.op}),R="toon",x=Ot(a,{format:R,schema:t.settings.schema,extensionFieldNames:t.extensionFieldNames}),I=mt(t.pmRoot,a.metadata.type,i.id,R,o),b=ct(t.pmRoot,i.id),w=await _t(f,i,r,async()=>{const S=await Z("item_store_write",{op:t.op,pm_root:t.pmRoot,item_id:i.id,source_item_path:i.itemPath,target_item_path:I,history_path:b,item_format:R,before:m,after:a,contents:x}),{effectiveTargetItemPath:F,effectiveSerializedAfter:q,skipItemWrite:P}=ie(S,I,x),Ft=await st(t.pmRoot,t.author);let B=[];try{P||await A(F,q),!P&&F!==i.itemPath&&await _.rm(i.itemPath);const xt=ot({nowIso:a.metadata.updated_at,author:t.author,op:t.op,before:m,after:a,message:t.message,context:yt({...u,...p.decisions.length===0?{}:{workflow_policies:p.decisions},...K(t.pmRoot,[i.id,n.metadata.id],t.op)})});try{await et(b,xt)}catch(bt){throw await re({skipItemWrite:P,effectiveTargetItemPath:F,originalItemPath:i.itemPath,originalRaw:r}),bt}P||(B=await dt({pmRoot:t.pmRoot,preferredFormat:t.settings.item_format,typeToFolder:o,schema:t.settings.schema,itemPath:F,previousItemPath:i.itemPath,document:a}))}finally{await Ft()}const Rt=P||F!==I||q!==x;return{derivedIndexWarnings:B,effectiveTargetItemPath:F,overrideWarnings:S.warnings,stored:Rt?await It({pmRoot:t.pmRoot,settings:t.settings,id:i.id,typeToFolder:o,extensionFieldNames:t.extensionFieldNames,fallback:a,embeddedId:a.metadata.id}):{document:a}}}),{derivedIndexWarnings:v,effectiveTargetItemPath:L,stored:N}=w;V(t.pmRoot,N.document,i.id,[a.metadata.id],N.revision);const T=[...await D({path:L,scope:"project",op:t.op,item_id:a.metadata.id,item_type:a.metadata.type,before:m,after:a,changed_fields:c.changedFields}),...await D({path:b,scope:"project",op:`${t.op}:history`,item_id:a.metadata.id,item_type:a.metadata.type,before:m,after:a,changed_fields:c.changedFields})];return J({id:a.metadata.id,op:t.op,item_type:a.metadata.type,previous_status:m.metadata.status,status:a.metadata.status,previous:j(m.metadata,c.changedFields),current:j(a.metadata,c.changedFields),changed_fields:c.changedFields}),{item:a.metadata,body:a.body,changedFields:c.changedFields,warnings:[...d,...c.warnings??[],...p.warnings,...C.warnings,...w.overrideWarnings,...v,...T]}}finally{await l()}}async function Ue(t){const{historyContext:e,...o}=t;return U({...o,resolveHistoryContext:()=>e})}async function qe(t){return U(t)}async function Be(t){return U(t)}const Ge={appendWarning:ft,bypassesAssigneeConflict:pt,buildDidYouMeanSuggestions:gt,isErrno:Jt};async function Ve(t){const e=await wt({pmRoot:t.pmRoot,settings:t.settings,id:t.id,op:"delete",author:t.author,force:t.force}),{located:o,originalRaw:i,document:r,warnings:n,releaseLock:d,lease:l}=e;try{Y(t.pmRoot,r,o.id);const f=H(void 0),s=W(r,{schema:t.settings.schema,extensionFieldNames:f}),m=await G({pmRoot:t.pmRoot,settings:t.settings,operation:"delete",author:t.author,before:s,after:null,dryRun:t.dryRun});await Q({pm_root:t.pmRoot,operation:"delete",before:s,after:null,changed_fields:["deleted"],author:t.author,dry_run:t.dryRun===!0,sdk:ht({pmRoot:t.pmRoot,settings:t.settings,typeToFolder:e.typeToFolder})});const g=await it({pmRoot:t.pmRoot,settings:t.settings,itemId:o.id,commandLabel:"delete"}),c=lt(),u=tt,h=ot({nowIso:c,author:t.author,op:"delete",before:s,after:u,message:t.message,context:yt({...m.decisions.length===0?{}:{workflow_policies:m.decisions},...K(t.pmRoot,[o.id,r.metadata.id],"delete")})}),a=ct(t.pmRoot,o.id),p=()=>ne({op:"delete",pm_root:t.pmRoot,item_id:o.id,item_path:o.itemPath,history_path:a,before:s});if(t.dryRun===!0){const w=await p();return{item:s.metadata,changedFields:["deleted"],targetPath:w.effectiveItemPath,warnings:[...n,...m.warnings,...g.warnings,...w.warnings]}}const C=await _t(l,o,i,async()=>{const{effectiveItemPath:w,skipDelete:v,warnings:L}=await p(),N=await st(t.pmRoot,t.author);let T=[];try{v||await _.rm(w);try{await et(a,h)}catch(S){throw v||await A(w,i),S}v||(T=await dt({pmRoot:t.pmRoot,preferredFormat:t.settings.item_format,typeToFolder:e.typeToFolder,schema:t.settings.schema,itemPath:w,document:null}))}finally{await N()}return{derivedIndexWarnings:T,effectiveItemPath:w,overrideWarnings:L,stored:v||w!==o.itemPath?await It({pmRoot:t.pmRoot,settings:t.settings,id:o.id,typeToFolder:e.typeToFolder,fallback:u,embeddedId:r.metadata.id}):{document:u}}}),{derivedIndexWarnings:R,effectiveItemPath:x,stored:I}=C;V(t.pmRoot,I.document,o.id,[r.metadata.id],I.revision);const b=[...await D({path:x,scope:"project",op:"delete",item_id:s.metadata.id,item_type:s.metadata.type,before:s,after:u,changed_fields:["deleted"]}),...await D({path:a,scope:"project",op:"delete:history",item_id:s.metadata.id,item_type:s.metadata.type,before:s,after:u,changed_fields:["deleted"]})];return J({id:s.metadata.id,op:"delete",item_type:s.metadata.type,previous_status:s.metadata.status,previous:j(s.metadata,Object.keys(s.metadata)),changed_fields:["deleted"]}),{item:s.metadata,changedFields:["deleted"],warnings:[...n,...m.warnings,...g.warnings,...C.overrideWarnings,...R,...b]}}finally{await d()}}export{oe as buildItemNotFoundError,ht as createMutationGuardSdk,Ve as deleteItem,Ge as itemStoreTestOnly,te as listAllItemMetadata,He as listAllItemMetadataLight,ze as listAllItemMetadataWithBody,z as locateItem,Be as mutateItem,Ue as mutateItemWithHistoryContext,qe as mutateItemWithHistoryContextResolver,ut as readLocatedItem,Zt as readLocatedItemSnapshot};
2
2
  //# sourceMappingURL=item-store.js.map
@@ -1,4 +1,4 @@
1
- import type{GlobalOptions}from "../core/shared/command-types.js";export{quoteWindowsCommandArg,quoteCommandArg,renderPmCommand}from "../core/shared/command-line.js";export{URL_CREDENTIAL_PLACEHOLDER,invocationCarriesUrlCredentials,redactUrlCredentialsInText,redactUrlCredentialsInToken,runWithUrlCredentialInvocation,}from "../core/shared/url-credentials.js";
1
+ import type{GlobalOptions}from "../core/shared/command-types.js";export{COMMAND_SHELL_ENV,quoteCmdCommandArg,quoteCommandArg,quotePosixCommandArg,quotePowerShellCommandArg,quoteWindowsCommandArg,renderPmCommand,resolveCommandShellDialect,type CommandShellDialect,}from "../core/shared/command-line.js";export{URL_CREDENTIAL_PLACEHOLDER,invocationCarriesUrlCredentials,redactUrlCredentialsInText,redactUrlCredentialsInToken,runWithUrlCredentialInvocation,}from "../core/shared/url-credentials.js";
2
2
  /** Tracker selection a rendered recovery command must preserve: the requested path and extension isolation. */
3
3
  export type CommandScope=Pick<GlobalOptions,"path"|"noExtensions">;
4
4
  /** Retain caller scope before runtime dispatch resolves its working storage path. */
@@ -1,2 +1,2 @@
1
- import{findBootstrapCommandTokenIndex as a}from"./cli-contracts/bootstrap-command-scanner.js";import c from"node:path";import{resolveImplicitPmRoot as d,resolvePmRoot as m,resolveWorkspaceRoot as u}from"../core/store/paths.js";import{isPathWithinDirectory as f}from"../core/fs/path-utils.js";import{quoteWindowsCommandArg as v,quoteCommandArg as _,renderPmCommand as k}from"../core/shared/command-line.js";import{URL_CREDENTIAL_PLACEHOLDER as L,invocationCarriesUrlCredentials as U,redactUrlCredentialsInText as W,redactUrlCredentialsInToken as g,runWithUrlCredentialInvocation as y}from"../core/shared/url-credentials.js";const i=new WeakMap;function P(e){i.set(e,e.path)}function l(e){if(!process.env.PM_PATH?.trim())return;const t=m(e);return f(u(t),e)&&t===d(e)?void 0:c.relative(e,t)||"."}function R(e,t=process.cwd()){const n=i.has(e)?i.get(e):e.path,r=n?.trim()?n:l(t),o=r?["--pm-path",r]:[];return e.noExtensions&&o.push("--no-extensions"),o}const p=new Set(["--literal","--regex","--replacement"]);function h(e){const t=a(e);if(t===void 0)return!1;if(e[t]==="history-redact")return!0;if(e[t]!=="history")return!1;const n=e.slice(t+1),r=a(n);return r!==void 0&&n[r]==="redact"}function S(e){if(!h(e))return[...e];const t=[];let n=!1;for(const r of e){if(n){t.push("[redacted]"),n=!1;continue}n=!1;const o=r.indexOf("="),s=o>=0?r.slice(0,o):r;if(!p.has(s)){t.push(r);continue}if(o>=0){t.push(`${s}=[redacted]`);continue}t.push(s),n=!0}return t}export{L as URL_CREDENTIAL_PLACEHOLDER,P as capturePmCommandScope,U as invocationCarriesUrlCredentials,h as isHistoryRedactInvocation,_ as quoteCommandArg,v as quoteWindowsCommandArg,S as redactSensitiveCommandArgs,W as redactUrlCredentialsInText,g as redactUrlCredentialsInToken,k as renderPmCommand,R as resolvePmCommandScopeArgs,y as runWithUrlCredentialInvocation};
1
+ import{findBootstrapCommandTokenIndex as a}from"./cli-contracts/bootstrap-command-scanner.js";import d from"node:path";import{resolveImplicitPmRoot as c,resolvePmRoot as m,resolveWorkspaceRoot as u}from"../core/store/paths.js";import{isPathWithinDirectory as l}from"../core/fs/path-utils.js";import{COMMAND_SHELL_ENV as v,quoteCmdCommandArg as T,quoteCommandArg as _,quotePosixCommandArg as g,quotePowerShellCommandArg as L,quoteWindowsCommandArg as D,renderPmCommand as k,resolveCommandShellDialect as H}from"../core/shared/command-line.js";import{URL_CREDENTIAL_PLACEHOLDER as U,invocationCarriesUrlCredentials as W,redactUrlCredentialsInText as y,redactUrlCredentialsInToken as M,runWithUrlCredentialInvocation as O}from"../core/shared/url-credentials.js";const i=new WeakMap;function P(e){i.set(e,e.path)}function f(e){if(!process.env.PM_PATH?.trim())return;const t=m(e);return l(u(t),e)&&t===c(e)?void 0:d.relative(e,t)||"."}function S(e,t=process.cwd()){const n=i.has(e)?i.get(e):e.path,o=n?.trim()?n:f(t),r=o?["--pm-path",o]:[];return e.noExtensions&&r.push("--no-extensions"),r}const p=new Set(["--literal","--regex","--replacement"]);function C(e){const t=a(e);if(t===void 0)return!1;if(e[t]==="history-redact")return!0;if(e[t]!=="history")return!1;const n=e.slice(t+1),o=a(n);return o!==void 0&&n[o]==="redact"}function E(e){if(!C(e))return[...e];const t=[];let n=!1;for(const o of e){if(n){t.push("[redacted]"),n=!1;continue}n=!1;const r=o.indexOf("="),s=r>=0?o.slice(0,r):o;if(!p.has(s)){t.push(o);continue}if(r>=0){t.push(`${s}=[redacted]`);continue}t.push(s),n=!0}return t}export{v as COMMAND_SHELL_ENV,U as URL_CREDENTIAL_PLACEHOLDER,P as capturePmCommandScope,W as invocationCarriesUrlCredentials,C as isHistoryRedactInvocation,T as quoteCmdCommandArg,_ as quoteCommandArg,g as quotePosixCommandArg,L as quotePowerShellCommandArg,D as quoteWindowsCommandArg,E as redactSensitiveCommandArgs,y as redactUrlCredentialsInText,M as redactUrlCredentialsInToken,k as renderPmCommand,H as resolveCommandShellDialect,S as resolvePmCommandScopeArgs,O as runWithUrlCredentialInvocation};
2
2
  //# sourceMappingURL=command-line.js.map