@unbrained/pm-cli 2026.11.18 → 2026.11.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/AGENTS.md +1 -1
  3. package/dist/cli-bundle/bundle-manifest.json +1 -1
  4. package/dist/cli-bundle/chunks/{chunk-SSZBVRIN.js → chunk-2IZGNOGT.js} +2 -2
  5. package/dist/cli-bundle/chunks/{chunk-T3E3WNHO.js → chunk-3BOR22MC.js} +2 -2
  6. package/dist/cli-bundle/chunks/{chunk-LGWP5D7V.js → chunk-4QQPM3IY.js} +2 -2
  7. package/dist/cli-bundle/chunks/{chunk-TA5VN4ME.js → chunk-4TZW4NLM.js} +2 -2
  8. package/dist/cli-bundle/chunks/{chunk-TS2CZE3O.js → chunk-5LF5QZT3.js} +2 -2
  9. package/dist/cli-bundle/chunks/{chunk-WKHS4QC6.js → chunk-6HRPGEBF.js} +2 -2
  10. package/dist/cli-bundle/chunks/{chunk-FJQCORYR.js → chunk-6X2AGUOT.js} +2 -2
  11. package/dist/cli-bundle/chunks/{chunk-2VH6COJE.js → chunk-7ESF676D.js} +37 -37
  12. package/dist/cli-bundle/chunks/{chunk-CGTVDSAR.js → chunk-7EZZ4W7O.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-QK7RAN7R.js → chunk-DG2EOOFX.js} +2 -2
  14. package/dist/cli-bundle/chunks/{chunk-YJI2Y5N6.js → chunk-FF4TXJDH.js} +2 -2
  15. package/dist/cli-bundle/chunks/{chunk-7UUPLMCU.js → chunk-FOYRE23V.js} +46 -46
  16. package/dist/cli-bundle/chunks/{chunk-L2ZLH3LZ.js → chunk-GXGW6KHB.js} +2 -2
  17. package/dist/cli-bundle/chunks/{chunk-7ETRLLK3.js → chunk-HJQ3XPS3.js} +30 -30
  18. package/dist/cli-bundle/chunks/{chunk-JBPXNG6P.js → chunk-KDDIHGAO.js} +2 -2
  19. package/dist/cli-bundle/chunks/chunk-KEBLUTC3.js +71 -0
  20. package/dist/cli-bundle/chunks/{chunk-7LCJA54R.js → chunk-KQSPKWFH.js} +2 -2
  21. package/dist/cli-bundle/chunks/{chunk-VETSGCF4.js → chunk-M5D3CEMY.js} +2 -2
  22. package/dist/cli-bundle/chunks/{chunk-AGU7632B.js → chunk-MGYAJONE.js} +2 -2
  23. package/dist/cli-bundle/chunks/{chunk-CR5GC3VO.js → chunk-OXG5XPC7.js} +2 -2
  24. package/dist/cli-bundle/chunks/{chunk-H64BNM4A.js → chunk-W4TLA5H3.js} +2 -2
  25. package/dist/cli-bundle/chunks/{chunk-S3RMFLEG.js → chunk-XK25TAJZ.js} +4 -4
  26. package/dist/cli-bundle/chunks/{chunk-XDIJK6VW.js → chunk-ZAO7VGX3.js} +2 -2
  27. package/dist/cli-bundle/chunks/{chunk-MUGGRKK3.js → chunk-ZVEHACE6.js} +2 -2
  28. package/dist/cli-bundle/chunks/{item-revision-BV5BUBCR.js → item-revision-GE2CQECR.js} +2 -2
  29. package/dist/cli-bundle/chunks/item-transaction-YSAWJRA2.js +2 -0
  30. package/dist/cli-bundle/chunks/{mutation-actor-DDYJW5B4.js → mutation-actor-5GYX7LP3.js} +2 -2
  31. package/dist/cli-bundle/chunks/{mutation-admission-5AWMXMCB.js → mutation-admission-72TYKPGU.js} +2 -2
  32. package/dist/cli-bundle/chunks/{register-list-query-RJT7YBRF.js → register-list-query-OQZZEWEB.js} +2 -2
  33. package/dist/cli-bundle/chunks/{register-mutation-6KTMJGYF.js → register-mutation-YZEUZ6XT.js} +2 -2
  34. package/dist/cli-bundle/chunks/{register-operations-W24TA3HZ.js → register-operations-JNVCF7EW.js} +2 -2
  35. package/dist/cli-bundle/chunks/{register-setup-QK67WUX6.js → register-setup-LDKULZSD.js} +2 -2
  36. package/dist/cli-bundle/chunks/{stage-XGWW3T64.js → stage-Q2QZ2IBG.js} +2 -2
  37. package/dist/cli-bundle/focused-chunks/{chunk-IGMFXB5W.js → chunk-3LRSQXCN.js} +2 -2
  38. package/dist/cli-bundle/focused-chunks/{chunk-EZXLY6S4.js → chunk-5VSXKA35.js} +2 -2
  39. package/dist/cli-bundle/focused-chunks/{chunk-LZR3JKYT.js → chunk-7SB6VKEI.js} +2 -2
  40. package/dist/cli-bundle/focused-chunks/{chunk-MTBC32ZR.js → chunk-BZCLW5V7.js} +2 -2
  41. package/dist/cli-bundle/focused-chunks/{chunk-ICEHI4SN.js → chunk-FPKVHC3Q.js} +2 -2
  42. package/dist/cli-bundle/focused-chunks/{chunk-HO2YUD4P.js → chunk-I7XBR2RM.js} +2 -2
  43. package/dist/cli-bundle/focused-chunks/{chunk-XS2YZCT5.js → chunk-JUYJ7NXL.js} +2 -2
  44. package/dist/cli-bundle/focused-chunks/{chunk-ZFUZ4YYN.js → chunk-KQJNJZKP.js} +2 -2
  45. package/dist/cli-bundle/focused-chunks/{chunk-7RF2YPZ5.js → chunk-MJP3TFVW.js} +2 -2
  46. package/dist/cli-bundle/focused-chunks/{chunk-3H3SVHAT.js → chunk-O25KFLLA.js} +2 -2
  47. package/dist/cli-bundle/focused-chunks/{chunk-7Z2NYAK4.js → chunk-PKMDWIP3.js} +2 -2
  48. package/dist/cli-bundle/focused-chunks/{chunk-EO4XM3XJ.js → chunk-PQXTZLK3.js} +2 -2
  49. package/dist/cli-bundle/focused-chunks/{chunk-T3NMYMW4.js → chunk-PRFEOCNZ.js} +24 -24
  50. package/dist/cli-bundle/focused-chunks/{chunk-A2CLYPDA.js → chunk-PZSTRYTA.js} +40 -40
  51. package/dist/cli-bundle/focused-chunks/{chunk-PNCCTZKI.js → chunk-QNJQPJWO.js} +23 -23
  52. package/dist/cli-bundle/focused-chunks/{chunk-5JVB42Z7.js → chunk-SIPDQBJI.js} +2 -2
  53. package/dist/cli-bundle/focused-chunks/{chunk-FPPYE6CY.js → chunk-SJE3PYPI.js} +2 -2
  54. package/dist/cli-bundle/focused-chunks/{chunk-6OZ7BKWJ.js → chunk-TNKI6WKG.js} +55 -54
  55. package/dist/cli-bundle/focused-chunks/{chunk-ONHUG7IL.js → chunk-TRCXANRR.js} +2 -2
  56. package/dist/cli-bundle/focused-chunks/{chunk-DWCFZVT2.js → chunk-UATP3RK3.js} +2 -2
  57. package/dist/cli-bundle/focused-chunks/{chunk-OPY43DNJ.js → chunk-V55XZFOP.js} +2 -2
  58. package/dist/cli-bundle/focused-chunks/{chunk-OAIAZHRG.js → chunk-ZKGGGU2K.js} +2 -2
  59. package/dist/cli-bundle/focused-chunks/{item-revision-NS2V4WON.js → item-revision-OXDZHMJ7.js} +2 -2
  60. package/dist/cli-bundle/focused-chunks/{item-transaction-NENC4HYI.js → item-transaction-54VSTT6L.js} +2 -2
  61. package/dist/cli-bundle/focused-chunks/{mutation-actor-2SVBO324.js → mutation-actor-6DYIF6NH.js} +2 -2
  62. package/dist/cli-bundle/focused-chunks/{mutation-admission-DZIBDJAE.js → mutation-admission-2BYXANVJ.js} +2 -2
  63. package/dist/cli-bundle/focused-chunks/{stage-LVAGKCEE.js → stage-FGHSB3QX.js} +2 -2
  64. package/dist/cli-bundle/main.js +2 -2
  65. package/dist/cli-bundle/sdk-authoring.js +1 -1
  66. package/dist/cli-bundle/sdk-contracts.js +1 -1
  67. package/dist/cli-bundle/sdk-core.js +1 -1
  68. package/dist/cli-bundle/sdk-governance.js +1 -1
  69. package/dist/cli-bundle/sdk-graph.js +1 -1
  70. package/dist/cli-bundle/sdk-merge.js +55 -55
  71. package/dist/cli-bundle/sdk-query.js +1 -1
  72. package/dist/cli-bundle/sdk-runtime.js +1 -1
  73. package/dist/cli-bundle/sdk-testing.js +1 -1
  74. package/dist/cli-bundle/sdk.js +11 -11
  75. package/dist/core/fs/file-glob.js +1 -1
  76. package/dist/core/shared/process-tree.js +3 -0
  77. package/dist/core/shared/secret-rules.d.ts +12 -1
  78. package/dist/core/shared/secret-rules.js +2 -2
  79. package/dist/core/shared/text-normalization.d.ts +9 -0
  80. package/dist/core/shared/text-normalization.js +1 -1
  81. package/dist/sdk/context-intent-contracts.js +1 -1
  82. package/dist/sdk/extension/managed-state.d.ts +3 -1
  83. package/dist/sdk/extension/managed-state.js +1 -1
  84. package/dist/sdk/extension/managed-update-status.js +1 -1
  85. package/dist/sdk/extension/update-check.d.ts +42 -6
  86. package/dist/sdk/extension/update-check.js +1 -1
  87. package/dist/sdk/extension.d.ts +3 -1
  88. package/dist/sdk/extension.js +1 -1
  89. package/dist/sdk/index.d.ts +1 -1
  90. package/dist/sdk/index.js +1 -1
  91. package/dist/sdk/mutation-guard.d.ts +121 -1
  92. package/dist/sdk/mutation-guard.js +1 -1
  93. package/dist/sdk/public-surface.json +1 -1
  94. package/dist/sdk/read-output/continuation.d.ts +9 -3
  95. package/dist/sdk/read-output/continuation.js +1 -1
  96. package/dist/sdk/read-output-budget.d.ts +44 -3
  97. package/dist/sdk/read-output-budget.js +1 -1
  98. package/dist/sdk/read-output-contracts.js +1 -1
  99. package/dist/sdk/test/execution.js +2 -2
  100. package/docs/CONFIGURATION.md +1 -0
  101. package/docs/MUTATION_INTEGRITY.md +72 -0
  102. package/docs/PACKAGE_EVIDENCE.md +66 -0
  103. package/docs/READ_OUTPUT_CONTRACTS.md +16 -1
  104. package/marketplace.json +1 -1
  105. package/package.json +1 -1
  106. package/packages/pm-beads/package.json +1 -1
  107. package/packages/pm-calendar/package.json +1 -1
  108. package/packages/pm-command-kit/package.json +1 -1
  109. package/packages/pm-digital-twin/package.json +1 -1
  110. package/packages/pm-governance-audit/package.json +1 -1
  111. package/packages/pm-guide-shell/package.json +1 -1
  112. package/packages/pm-kanban/package.json +1 -1
  113. package/packages/pm-lifecycle-hooks/package.json +1 -1
  114. package/packages/pm-linked-test-adapters/package.json +1 -1
  115. package/packages/pm-search-advanced/package.json +1 -1
  116. package/packages/pm-templates/package.json +1 -1
  117. package/packages/pm-todos/package.json +1 -1
  118. package/packages/pm-vcs/package.json +1 -1
  119. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  120. package/plugins/pm-claude/package.json +1 -1
  121. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  122. package/plugins/pm-codex/package.json +1 -1
  123. package/plugins/pm-codex/plugin.json +1 -1
  124. package/runtime-dependencies.json +1 -1
  125. package/dist/cli-bundle/chunks/chunk-OD2I3SFQ.js +0 -70
  126. package/dist/cli-bundle/chunks/item-transaction-E2ST3A3X.js +0 -2
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="fa27dff5-0270-505f-bd5f-bc1eb0fe5ad8")}catch{}})();import{readdir,realpath,stat}from"node:fs/promises";import path from"node:path";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";const MAX_PATTERN_LENGTH=4096,MAX_NESTING=32,MAX_RANGE_SIZE=1e3,MAX_STATES=5e4,DFA_LIMITS={nodes:1e4,edges:4e4,stateIds:2e6},SLASH=47;class GlobTooComplex extends Error{}const POSIX_CLASSES=new Map(Object.entries({alnum:[[48,57],[65,90],[97,122]],alpha:[[65,90],[97,122]],ascii:[[0,127]],blank:[[9,9],[32,32]],cntrl:[[0,31],[127,127]],digit:[[48,57]],graph:[[33,126]],lower:[[97,122]],print:[[32,126]],punct:[[33,47],[58,64],[91,96],[123,126]],space:[[9,13],[32,32]],upper:[[65,90]],word:[[48,57],[65,90],[95,95],[97,122]],xdigit:[[48,57],[65,70],[97,102]]}));function negationRefusal(){return new PmCliError("--add-glob does not support negated patterns (a leading ! or !(...)); list the files or patterns to link instead",EXIT_CODE.USAGE)}function bracketEnd(chars,start){let index=start+1;for((chars[index]==="!"||chars[index]==="^")&&(index+=1),chars[index]==="]"&&(index+=1);index<chars.length;){const char=chars[index];if(char==="\\")index+=2;else if(char==="["&&chars[index+1]===":"){const close=chars.indexOf(":",index+2);close===-1||chars[close+1]!=="]"?index+=1:index=close+2}else{if(char==="]")return index+1;index+=1}}return-1}function openerAt(chars,index,open){const char=chars[index];if(char==="{")return{index,kind:"{"};if(char!=="(")return;const operator=chars[index-1];return operator!==void 0&&"@?*+!".includes(operator)&&!isEscaped(chars,index-1)?{index:index-1,kind:"("}:open.some(opener=>opener.kind==="(")?{index,kind:"plain"}:void 0}function closeAt(chars,index,open,closers,groups){const char=chars[index],top=open.at(-1);if(char===")"&&top?.kind==="plain"){open.pop(),groups.set(top.index,index);return}const kind=char==="}"?"{":char===")"?"(":void 0;if(!(kind===void 0||top?.kind!==kind)&&(open.pop(),closers.set(top.index,index),chars[top.index]==="!"))throw negationRefusal()}function pairConstructs(chars){const closers=new Map,brackets=new Map,groups=new Map,open=[];let index=0;for(;index<chars.length;){if(chars[index]==="\\"){index+=2;continue}const end=chars[index]==="["?bracketEnd(chars,index):-1;if(end!==-1){brackets.set(index,end),index=end;continue}const opener=openerAt(chars,index,open);if(opener!==void 0?open.push(opener):closeAt(chars,index,open,closers,groups),open.length>MAX_NESTING)throw new GlobTooComplex;index+=1}return{closers,brackets,groups}}function isEscaped(chars,index){let count=0;for(let cursor=index-1;cursor>=0&&chars[cursor]==="\\";cursor-=1)count+=1;return count%2===1}function literalNodes(text){return Array.from(text,char=>({kind:"char",value:char.codePointAt(0)}))}function braceRange(content){const numeric=/^(-?(?:0|[1-9]\d{0,8}))\.\.(-?(?:0|[1-9]\d{0,8}))$/u.exec(content),alphabetic=/^([A-Za-z])\.\.([A-Za-z])$/u.exec(content);if(numeric===null&&alphabetic===null)return;const[from,to]=numeric!==null?[Number(numeric[1]),Number(numeric[2])]:[alphabetic[1].codePointAt(0),alphabetic[2].codePointAt(0)];if(Math.abs(to-from)+1>MAX_RANGE_SIZE)throw new GlobTooComplex;const step=from<=to?1:-1,values=[];for(let value=from;value!==to+step;value+=step)values.push(numeric!==null?String(value):String.fromCodePoint(value));return values}function posixClassAt(chars,index){if(chars[index]!=="["||chars[index+1]!==":")return;const colon=chars.indexOf(":",index+2);if(!(colon===-1||chars[colon+1]!=="]"))return{ranges:POSIX_CLASSES.get(chars.slice(index+2,colon).join(""))??[],next:colon+2}}function memberAt(chars,index,close){const escaped=chars[index]==="\\"&&index+1<close;return{codePoint:chars[escaped?index+1:index].codePointAt(0),next:index+(escaped?2:1)}}function bracketLiteral(chars,start,end){const literal=[];for(let cursor=start;cursor<end;cursor+=1)chars[cursor]==="\\"&&cursor+1<end&&(cursor+=1),literal.push(chars[cursor].codePointAt(0));return literal}function parseClass(chars,start,end){let index=start+1;const negated=chars[index]==="!"||chars[index]==="^";negated&&(index+=1);const ranges=[],close=end-1;for(;index<close;){const posix=posixClassAt(chars,index);if(posix!==void 0){ranges.push(...posix.ranges),index=posix.next;continue}const low=memberAt(chars,index,close);if(index=low.next,chars[index]!=="-"||index+1>=close){ranges.push([low.codePoint,low.codePoint]);continue}const high=memberAt(chars,index+1,close);index=high.next,low.codePoint<=high.codePoint&&ranges.push([low.codePoint,high.codePoint])}return{kind:"class",negated,ranges,literal:bracketLiteral(chars,start,end)}}class Parser{chars;closers;brackets;groups;constructor(chars,pairs){this.chars=chars,this.closers=pairs.closers,this.brackets=pairs.brackets,this.groups=pairs.groups}alternatives(start,end,separator){const options=[];let cursor=start;for(;;){const{nodes,stop}=this.sequence(cursor,end,separator);if(options.push(nodes),stop>=end)return options;cursor=stop+1}}sequence(start,end,separator){const nodes=[];let index=start;for(;index<end;){if(this.chars[index]===separator)return{nodes,stop:index};const token=this.token(index,end);nodes.push(...token.nodes),index=token.next}return{nodes,stop:end}}token(index,end){const char=this.chars[index];if(char==="\\")return{nodes:literalNodes(index+1<end?this.chars[index+1]:"\\"),next:index+2};const closer=this.closers.get(index);if(closer!==void 0)return{nodes:char==="{"?this.brace(index,closer):this.extglob(char,index,closer),next:closer+1};const group=this.groups.get(index);if(group!==void 0)return{nodes:[...literalNodes("("),...this.sequence(index+1,group,void 0).nodes,...literalNodes(")")],next:group+1};const bracket=this.brackets.get(index);return bracket!==void 0?{nodes:[parseClass(this.chars,index,bracket)],next:bracket}:char==="*"?this.stars(index,end):{nodes:char==="?"?[{kind:"any"}]:literalNodes(char),next:index+1}}extglob(operator,index,closer){const options=this.alternatives(index+2,closer,"|");return[operator==="@"?{kind:"alt",options}:{kind:"repeat",optional:operator!=="+",many:operator!=="?",options}]}brace(index,closer){const options=this.alternatives(index+1,closer,",");if(options.length>1)return[{kind:"alt",options}];const range=braceRange(this.chars.slice(index+1,closer).join(""));return range!==void 0?[{kind:"alt",options:range.map(literalNodes)}]:[...literalNodes("{"),...options[0],...literalNodes("}")]}stars(index,end){let run=1;for(;this.chars[index+run]==="*"&&index+run<end&&!this.closers.has(index+run);)run+=1;if(run!==2)return{nodes:[{kind:"star"}],next:index+run};const slash=index+run<end&&this.chars[index+run]==="/";return{nodes:[{kind:"globstar",slash}],next:index+run+(slash?1:0)}}}const END_KINDS=["segment","inside"],ANY={kind:"any"};function entriesOf(ends){return END_KINDS.flatMap(kind=>ends[kind]===void 0?[]:[ends[kind]])}class Nfa{states=[];add(){if(this.states.length>=MAX_STATES)throw new GlobTooComplex;return this.states.push({epsilon:[],syntactic:[],edges:[]}),this.states.length-1}epsilon(from,to,syntactic=!0){this.states[from].epsilon.push(to),syntactic&&this.states[from].syntactic.push(to)}consume(from,test,kind){const to=this.add();for(const entry of entriesOf(from))this.states[entry].edges.push({test,to});return{[kind]:to}}join(parts){const joined={};for(const kind of END_KINDS){const states=parts.flatMap(part=>part[kind]===void 0?[]:[part[kind]]);if(states.length===1&&(joined[kind]=states[0]),states.length>1){const merged=this.add();for(const state of states)this.epsilon(state,merged);joined[kind]=merged}}return joined}feed(ends,loop){for(const kind of END_KINDS)ends[kind]!==void 0&&this.epsilon(ends[kind],loop[kind])}build(nodes,from){let current=from;for(const node of nodes)current=this.node(node,current);return current}alternation(options,from){return this.join(options.map(option=>this.build(option,from)))}star(from){const loop=this.add();for(const entry of entriesOf(from))this.epsilon(entry,loop,!1);return this.states[loop].edges.push({test:ANY,to:loop}),{inside:loop}}segments(from){const between=this.add();this.epsilon(from,between,!1);const inside=this.add();return this.states[between].edges.push({test:ANY,to:inside}),this.states[inside].edges.push({test:ANY,to:inside},{test:{kind:"char",value:SLASH},to:between}),between}globstar(from,slash){if(slash){const parts=[];return from.segment!==void 0&&parts.push({segment:this.segments(from.segment)}),from.inside!==void 0&&parts.push(this.consume(this.star({inside:from.inside}),{kind:"char",value:SLASH},"segment")),this.join(parts)}const star=this.star(from);return from.segment!==void 0&&this.globstars.push({continuation:star.inside,entry:from.segment}),star}globstars=[];syntacticClosure(seed){const seen=new Set(seed),stack=[...seed];for(;stack.length>0;)for(const next of this.states[stack.pop()].syntactic)seen.has(next)||(seen.add(next),stack.push(next));return seen}resolveGlobstars(accept){for(const{continuation,entry}of this.globstars){const reachable=this.syntacticClosure([continuation]);if(reachable.has(accept)){const rest=this.add();this.epsilon(entry,rest,!1),this.states[rest].edges.push({test:{kind:"all"},to:rest}),this.epsilon(rest,accept,!1)}const targets=new Set;for(const state of reachable)for(const{test,to}of this.states[state].edges)accepts(test,SLASH)&&targets.add(to);if(targets.size===0)continue;const segments=this.segments(entry);for(const target of targets)this.epsilon(segments,target,!1)}}repeat(node,from){if(!node.many)return this.join([from,this.alternation(node.options,from)]);const loop={segment:this.add(),inside:this.add()};return this.feed(node.optional?from:this.alternation(node.options,from),loop),this.feed(this.alternation(node.options,loop),loop),loop}node(node,from){switch(node.kind){case"char":return this.consume(from,{kind:"char",value:node.value},node.value===SLASH?"segment":"inside");case"any":return this.consume(from,ANY,"inside");case"star":return this.star(from);case"globstar":return this.globstar(from,node.slash);case"class":return this.join([this.consume(from,{kind:"class",negated:node.negated,ranges:node.ranges},"inside"),this.build(node.literal.map(value=>({kind:"char",value})),from)]);case"alt":return this.alternation(node.options,from);case"repeat":return this.repeat(node,from)}}}function accepts(test,codePoint){switch(test.kind){case"char":return test.value===codePoint;case"any":return codePoint!==SLASH;case"all":return!0;case"class":return codePoint!==SLASH&&test.ranges.some(([low,high])=>codePoint>=low&&codePoint<=high)!==test.negated}}class PathMatcher{generation=0;nextId=0;nodes=new Map;edges=new Map;stateIds=0;nfa;acceptState;limits;start;constructor(nfa,startState,acceptState,limits){this.nfa=nfa,this.acceptState=acceptState,this.limits=limits,this.start=this.node(this.closure([startState]))}retained(){return{nodes:this.nodes.size,edges:this.edges.size,stateIds:this.stateIds}}reset(){this.generation+=1,this.nodes=new Map,this.edges=new Map,this.stateIds=0}closure(seed){const seen=new Set(seed),stack=[...seed];for(;stack.length>0;)for(const next of this.nfa.states[stack.pop()].epsilon)seen.has(next)||(seen.add(next),stack.push(next));return[...seen].sort((left,right)=>left-right)}node(states){const key=states.join(","),cached=this.nodes.get(key);if(cached!==void 0)return cached;(this.nodes.size>=this.limits.nodes||this.stateIds+states.length>this.limits.stateIds)&&this.reset();const created={id:this.nextId,generation:this.generation,states,accepting:states.includes(this.acceptState)};return this.nextId+=1,this.nodes.set(key,created),this.stateIds+=states.length,created}step(from,codePoint){const key=`${from.id}:${codePoint}`,known=from.generation===this.generation?this.edges.get(key):void 0;if(known!==void 0)return known;const reached=[];for(const state of from.states)for(const{test,to}of this.nfa.states[state].edges)accepts(test,codePoint)&&reached.push(to);const next=this.node(this.closure(reached));return this.edges.size>=this.limits.edges&&this.reset(),from.generation===this.generation&&this.edges.set(key,next),next}advance(from,text){let node=from;for(const char of text){if(node.states.length===0)return node;node=this.step(node,char.codePointAt(0))}return node}}function compile(text,limits=DFA_LIMITS){const chars=Array.from(text),nodes=new Parser(chars,pairConstructs(chars)).sequence(0,chars.length,void 0).nodes,nfa=new Nfa,start=nfa.add(),accept=nfa.add();for(const end of entriesOf(nfa.build(nodes,{segment:start})))nfa.epsilon(end,accept);return nfa.resolveGlobstars(accept),new PathMatcher(nfa,start,accept,limits)}function isStaticSegment(segment){return!/[*?[\]{}()!@+\\]/u.test(segment)}function kindOf(entry){return entry.isFile()?"file":entry.isDirectory()?"directory":"other"}async function resolveEntry(directory,real,entry){if(!entry.isSymbolicLink())return{kind:kindOf(entry),real:path.join(real,entry.name)};try{const target=await realpath(path.join(directory,entry.name));return{kind:kindOf(await stat(target)),real:target}}catch{return}}async function walk(matcher,directory,real,prefix,node,ancestors,out){let entries;try{entries=await readdir(directory,{withFileTypes:!0})}catch{return}for(const entry of entries){const afterName=matcher.advance(node,entry.name);if(afterName.states.length===0)continue;const resolved=await resolveEntry(directory,real,entry);if(resolved===void 0)continue;const relative=path.posix.join(prefix,entry.name);if(resolved.kind==="file"&&afterName.accepting&&out.push(relative),resolved.kind!=="directory")continue;const afterSlash=matcher.step(afterName,SLASH);afterSlash.states.length===0||ancestors.has(resolved.real)||(ancestors.add(resolved.real),await walk(matcher,path.join(directory,entry.name),resolved.real,relative,afterSlash,ancestors,out),ancestors.delete(resolved.real))}}function normalizePattern(pattern){const normalized=path.posix.normalize(pattern);return/^\/\/[^/]/u.test(pattern)?`/${normalized}`:normalized}function trimTrailingSeparators(pattern){let text=pattern;for(;text.length>1&&text.endsWith("/")&&!isEscaped(text,text.length-1);)text=text.slice(0,-1);return text}async function listed(directory,name){return(await readdir(directory).catch(()=>[])).includes(name)}async function exactCase(cwd,segments){let directory=cwd,index=0;for(;segments[index]==="..";)directory=path.dirname(directory),index+=1;for(;index<segments.length;index+=1){if(!await listed(directory,segments[index]))return!1;directory=path.join(directory,segments[index])}return!0}async function literalMatch(text,cwd){const target=path.resolve(cwd,text),found=await stat(target).catch(()=>{});if(found===void 0||!found.isFile())return[];const absolute=path.isAbsolute(text);return(absolute?await listed(path.dirname(target),path.basename(target)):await exactCase(cwd,text.split("/")))?[absolute?target.replaceAll("\\","/"):path.posix.normalize(text)]:[]}function splitStatic(text,cwd){const segments=text.split("/");let count=0;for(;count<segments.length&&isStaticSegment(segments[count]);)count+=1;if(count===segments.length)return;const prefix=count===0?"":`${segments.slice(0,count).join("/")}/`,root=path.resolve(cwd,prefix),rest=segments.slice(count).join("/");if(path.isAbsolute(text))return{root,base:root.replaceAll("\\","/"),rest,prefix:[]};const relative=path.posix.normalize(prefix===""?".":prefix).replace(/\/$/u,"");return{root,base:relative==="."?"":relative,rest,prefix:segments.slice(0,count)}}function compileWithinBounds(text){try{return compile(text)}catch(error){if(error instanceof GlobTooComplex)return;throw error}}async function expandFileGlob(pattern,cwd){if(pattern.startsWith("!"))throw negationRefusal();if(Array.from(pattern).length>MAX_PATTERN_LENGTH)return[];const text=trimTrailingSeparators(normalizePattern(pattern)),parts=splitStatic(text,cwd);if(parts===void 0)return literalMatch(text,cwd);const matcher=compileWithinBounds(parts.rest);if(matcher===void 0||!await exactCase(cwd,parts.prefix))return[];const real=await realpath(parts.root).catch(()=>{});if(real===void 0)return[];const out=[];return await walk(matcher,parts.root,real,"",matcher.start,new Set([real]),out),out.map(relative=>joinOutput(parts.base,relative))}function joinOutput(base,relative){return base.startsWith("//")?`/${path.posix.join(base.slice(1),relative)}`:path.posix.join(base,relative)}const _testOnly={compile,joinOutput,normalizePattern};export{_testOnly,expandFileGlob};
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="30379998-be47-5176-bfd4-a02bca99bd16")}catch{}})();import{readdir,realpath,stat}from"node:fs/promises";import path from"node:path";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";const MAX_PATTERN_LENGTH=4096,MAX_NESTING=32,MAX_RANGE_SIZE=1e3,MAX_STATES=5e4,DFA_LIMITS={nodes:1e4,edges:4e4,stateIds:2e6},SLASH=47;class GlobTooComplex extends Error{}const POSIX_CLASSES=new Map(Object.entries({alnum:[[48,57],[65,90],[97,122]],alpha:[[65,90],[97,122]],ascii:[[0,127]],blank:[[9,9],[32,32]],cntrl:[[0,31],[127,127]],digit:[[48,57]],graph:[[33,126]],lower:[[97,122]],print:[[32,126]],punct:[[33,47],[58,64],[91,96],[123,126]],space:[[9,13],[32,32]],upper:[[65,90]],word:[[48,57],[65,90],[95,95],[97,122]],xdigit:[[48,57],[65,70],[97,102]]}));function negationRefusal(){return new PmCliError("--add-glob does not support negated patterns (a leading ! or !(...)); list the files or patterns to link instead",EXIT_CODE.USAGE)}function bracketEnd(chars,start){let index=start+1;for((chars[index]==="!"||chars[index]==="^")&&(index+=1),chars[index]==="]"&&(index+=1);index<chars.length;){const char=chars[index];if(char==="\\")index+=2;else if(char==="["&&chars[index+1]===":"){const close=chars.indexOf(":",index+2);close===-1||chars[close+1]!=="]"?index+=1:index=close+2}else{if(char==="]")return index+1;index+=1}}return-1}function openerAt(chars,index,open){const char=chars[index];if(char==="{")return{index,kind:"{"};if(char!=="(")return;const operator=chars[index-1];return operator!==void 0&&"@?*+!".includes(operator)&&!isEscaped(chars,index-1)?{index:index-1,kind:"("}:open.some(opener=>opener.kind==="(")?{index,kind:"plain"}:void 0}function closeAt(chars,index,open,closers,groups){const char=chars[index],top=open.at(-1);if(char===")"&&top?.kind==="plain"){open.pop(),groups.set(top.index,index);return}const kind=char==="}"?"{":char===")"?"(":void 0;if(!(kind===void 0||top?.kind!==kind)&&(open.pop(),closers.set(top.index,index),chars[top.index]==="!"))throw negationRefusal()}function pairConstructs(chars){const closers=new Map,brackets=new Map,groups=new Map,open=[];let index=0;for(;index<chars.length;){if(chars[index]==="\\"){index+=2;continue}const end=chars[index]==="["?bracketEnd(chars,index):-1;if(end!==-1){brackets.set(index,end),index=end;continue}const opener=openerAt(chars,index,open);if(opener!==void 0?open.push(opener):closeAt(chars,index,open,closers,groups),open.length>MAX_NESTING)throw new GlobTooComplex;index+=1}return{closers,brackets,groups}}function isEscaped(chars,index){let count=0;for(let cursor=index-1;cursor>=0&&chars[cursor]==="\\";cursor-=1)count+=1;return count%2===1}function literalNodes(text){return Array.from(text,char=>({kind:"char",value:char.codePointAt(0)}))}function braceRange(content){const numeric=/^(-?(?:0|[1-9]\d{0,8}))\.\.(-?(?:0|[1-9]\d{0,8}))$/u.exec(content),alphabetic=/^([A-Za-z])\.\.([A-Za-z])$/u.exec(content);if(numeric===null&&alphabetic===null)return;const[from,to]=numeric!==null?[Number(numeric[1]),Number(numeric[2])]:[alphabetic[1].codePointAt(0),alphabetic[2].codePointAt(0)];if(Math.abs(to-from)+1>MAX_RANGE_SIZE)throw new GlobTooComplex;const step=from<=to?1:-1,values=[];for(let value=from;value!==to+step;value+=step)values.push(numeric!==null?String(value):String.fromCodePoint(value));return values}function posixClassAt(chars,index){if(chars[index]!=="["||chars[index+1]!==":")return;const colon=chars.indexOf(":",index+2);if(!(colon===-1||chars[colon+1]!=="]"))return{ranges:POSIX_CLASSES.get(chars.slice(index+2,colon).join(""))??[],next:colon+2}}function memberAt(chars,index,close){const escaped=chars[index]==="\\"&&index+1<close;return{codePoint:chars[escaped?index+1:index].codePointAt(0),next:index+(escaped?2:1)}}function bracketLiteral(chars,start,end){const literal=[];for(let cursor=start;cursor<end;cursor+=1)chars[cursor]==="\\"&&cursor+1<end&&(cursor+=1),literal.push(chars[cursor].codePointAt(0));return literal}function parseClass(chars,start,end){let index=start+1;const negated=chars[index]==="!"||chars[index]==="^";negated&&(index+=1);const ranges=[],close=end-1;for(;index<close;){const posix=posixClassAt(chars,index);if(posix!==void 0){ranges.push(...posix.ranges),index=posix.next;continue}const low=memberAt(chars,index,close);if(index=low.next,chars[index]!=="-"||index+1>=close){ranges.push([low.codePoint,low.codePoint]);continue}const high=memberAt(chars,index+1,close);index=high.next,low.codePoint<=high.codePoint&&ranges.push([low.codePoint,high.codePoint])}return{kind:"class",negated,ranges,literal:bracketLiteral(chars,start,end)}}class Parser{chars;closers;brackets;groups;constructor(chars,pairs){this.chars=chars,this.closers=pairs.closers,this.brackets=pairs.brackets,this.groups=pairs.groups}alternatives(start,end,separator){const options=[];let cursor=start;for(;;){const{nodes,stop}=this.sequence(cursor,end,separator);if(options.push(nodes),stop>=end)return options;cursor=stop+1}}sequence(start,end,separator){const nodes=[];let index=start;for(;index<end;){if(this.chars[index]===separator)return{nodes,stop:index};const token=this.token(index,end);nodes.push(...token.nodes),index=token.next}return{nodes,stop:end}}token(index,end){const char=this.chars[index];if(char==="\\")return{nodes:literalNodes(index+1<end?this.chars[index+1]:"\\"),next:index+2};const closer=this.closers.get(index);if(closer!==void 0)return{nodes:char==="{"?this.brace(index,closer):this.extglob(char,index,closer),next:closer+1};const group=this.groups.get(index);if(group!==void 0)return{nodes:[...literalNodes("("),...this.sequence(index+1,group,void 0).nodes,...literalNodes(")")],next:group+1};const bracket=this.brackets.get(index);return bracket!==void 0?{nodes:[parseClass(this.chars,index,bracket)],next:bracket}:char==="*"?this.stars(index,end):{nodes:char==="?"?[{kind:"any"}]:literalNodes(char),next:index+1}}extglob(operator,index,closer){const options=this.alternatives(index+2,closer,"|");return[operator==="@"?{kind:"alt",options}:{kind:"repeat",optional:operator!=="+",many:operator!=="?",options}]}brace(index,closer){const options=this.alternatives(index+1,closer,",");if(options.length>1)return[{kind:"alt",options}];const range=braceRange(this.chars.slice(index+1,closer).join(""));return range!==void 0?[{kind:"alt",options:range.map(literalNodes)}]:[...literalNodes("{"),...options[0],...literalNodes("}")]}stars(index,end){let run=1;for(;this.chars[index+run]==="*"&&index+run<end&&!this.closers.has(index+run);)run+=1;if(run!==2)return{nodes:[{kind:"star"}],next:index+run};const slash=index+run<end&&this.chars[index+run]==="/";return{nodes:[{kind:"globstar",slash}],next:index+run+(slash?1:0)}}}const END_KINDS=["segment","inside"],ANY={kind:"any"};function entriesOf(ends){return END_KINDS.flatMap(kind=>ends[kind]===void 0?[]:[ends[kind]])}class Nfa{states=[];add(){if(this.states.length>=MAX_STATES)throw new GlobTooComplex;return this.states.push({epsilon:[],syntactic:[],edges:[]}),this.states.length-1}epsilon(from,to,syntactic=!0){this.states[from].epsilon.push(to),syntactic&&this.states[from].syntactic.push(to)}consume(from,test,kind){const to=this.add();for(const entry of entriesOf(from))this.states[entry].edges.push({test,to});return{[kind]:to}}join(parts){const joined={};for(const kind of END_KINDS){const states=parts.flatMap(part=>part[kind]===void 0?[]:[part[kind]]);if(states.length===1&&(joined[kind]=states[0]),states.length>1){const merged=this.add();for(const state of states)this.epsilon(state,merged);joined[kind]=merged}}return joined}feed(ends,loop){for(const kind of END_KINDS)ends[kind]!==void 0&&this.epsilon(ends[kind],loop[kind])}build(nodes,from){let current=from;for(const node of nodes)current=this.node(node,current);return current}alternation(options,from){return this.join(options.map(option=>this.build(option,from)))}star(from){const loop=this.add();for(const entry of entriesOf(from))this.epsilon(entry,loop,!1);return this.states[loop].edges.push({test:ANY,to:loop}),{inside:loop}}segments(from){const between=this.add();this.epsilon(from,between,!1);const inside=this.add();return this.states[between].edges.push({test:ANY,to:inside}),this.states[inside].edges.push({test:ANY,to:inside},{test:{kind:"char",value:SLASH},to:between}),between}globstar(from,slash){if(slash){const parts=[];return from.segment!==void 0&&parts.push({segment:this.segments(from.segment)}),from.inside!==void 0&&parts.push(this.consume(this.star({inside:from.inside}),{kind:"char",value:SLASH},"segment")),this.join(parts)}const star=this.star(from);return from.segment!==void 0&&this.globstars.push({continuation:star.inside,entry:from.segment}),star}globstars=[];syntacticClosure(seed){const seen=new Set(seed),stack=[...seed];for(;stack.length>0;)for(const next of this.states[stack.pop()].syntactic)seen.has(next)||(seen.add(next),stack.push(next));return seen}resolveGlobstars(accept){for(const{continuation,entry}of this.globstars){const reachable=this.syntacticClosure([continuation]);if(reachable.has(accept)){const rest=this.add();this.epsilon(entry,rest,!1),this.states[rest].edges.push({test:{kind:"all"},to:rest}),this.epsilon(rest,accept,!1)}const targets=new Set;for(const state of reachable)for(const{test,to}of this.states[state].edges)accepts(test,SLASH)&&targets.add(to);if(targets.size===0)continue;const segments=this.segments(entry);for(const target of targets)this.epsilon(segments,target,!1)}}repeat(node,from){if(!node.many)return this.join([from,this.alternation(node.options,from)]);const loop={segment:this.add(),inside:this.add()};return this.feed(node.optional?from:this.alternation(node.options,from),loop),this.feed(this.alternation(node.options,loop),loop),loop}node(node,from){switch(node.kind){case"char":return this.consume(from,{kind:"char",value:node.value},node.value===SLASH?"segment":"inside");case"any":return this.consume(from,ANY,"inside");case"star":return this.star(from);case"globstar":return this.globstar(from,node.slash);case"class":return this.join([this.consume(from,{kind:"class",negated:node.negated,ranges:node.ranges},"inside"),this.build(node.literal.map(value=>({kind:"char",value})),from)]);case"alt":return this.alternation(node.options,from);case"repeat":return this.repeat(node,from)}}}function accepts(test,codePoint){switch(test.kind){case"char":return test.value===codePoint;case"any":return codePoint!==SLASH;case"all":return!0;case"class":return codePoint!==SLASH&&test.ranges.some(([low,high])=>codePoint>=low&&codePoint<=high)!==test.negated}}class PathMatcher{generation=0;nextId=0;nodes=new Map;edges=new Map;stateIds=0;nfa;acceptState;limits;start;constructor(nfa,startState,acceptState,limits){this.nfa=nfa,this.acceptState=acceptState,this.limits=limits,this.start=this.node(this.closure([startState]))}retained(){return{nodes:this.nodes.size,edges:this.edges.size,stateIds:this.stateIds}}reset(){this.generation+=1,this.nodes=new Map,this.edges=new Map,this.stateIds=0}closure(seed){const seen=new Set(seed),stack=[...seed];for(;stack.length>0;)for(const next of this.nfa.states[stack.pop()].epsilon)seen.has(next)||(seen.add(next),stack.push(next));return[...seen].sort((left,right)=>left-right)}node(states){const key=states.join(","),cached=this.nodes.get(key);if(cached!==void 0)return cached;(this.nodes.size>=this.limits.nodes||this.stateIds+states.length>this.limits.stateIds)&&this.reset();const created={id:this.nextId,generation:this.generation,states,accepting:states.includes(this.acceptState)};return this.nextId+=1,this.nodes.set(key,created),this.stateIds+=states.length,created}step(from,codePoint){const key=`${from.id}:${codePoint}`,known=from.generation===this.generation?this.edges.get(key):void 0;if(known!==void 0)return known;const reached=[];for(const state of from.states)for(const{test,to}of this.nfa.states[state].edges)accepts(test,codePoint)&&reached.push(to);const next=this.node(this.closure(reached));return this.edges.size>=this.limits.edges&&this.reset(),from.generation===this.generation&&this.edges.set(key,next),next}advance(from,text){let node=from;for(const char of text){if(node.states.length===0)return node;node=this.step(node,char.codePointAt(0))}return node}}function compile(text,limits=DFA_LIMITS){const chars=Array.from(text),nodes=new Parser(chars,pairConstructs(chars)).sequence(0,chars.length,void 0).nodes,nfa=new Nfa,start=nfa.add(),accept=nfa.add();for(const end of entriesOf(nfa.build(nodes,{segment:start})))nfa.epsilon(end,accept);return nfa.resolveGlobstars(accept),new PathMatcher(nfa,start,accept,limits)}function isStaticSegment(segment){return!/[*?[\]{}()!@+\\]/u.test(segment)}function kindOf(entry){return entry.isFile()?"file":entry.isDirectory()?"directory":"other"}async function resolveEntry(directory,real,entry){if(!entry.isSymbolicLink())return{kind:kindOf(entry),real:path.join(real,entry.name)};try{const target=await realpath(path.join(directory,entry.name));return{kind:kindOf(await stat(target)),real:target}}catch{return}}async function walk(matcher,directory,real,prefix,node,ancestors,out){let entries;try{entries=await readdir(directory,{withFileTypes:!0})}catch{return}for(const entry of entries){const afterName=matcher.advance(node,entry.name);if(afterName.states.length===0)continue;const resolved=await resolveEntry(directory,real,entry);if(resolved===void 0)continue;const relative=path.posix.join(prefix,entry.name);if(resolved.kind==="file"&&afterName.accepting&&out.push(relative),resolved.kind!=="directory")continue;const afterSlash=matcher.step(afterName,SLASH);afterSlash.states.length===0||ancestors.has(resolved.real)||(ancestors.add(resolved.real),await walk(matcher,path.join(directory,entry.name),resolved.real,relative,afterSlash,ancestors,out),ancestors.delete(resolved.real))}}function normalizePattern(pattern){const normalized=path.posix.normalize(pattern);return/^\/\/[^/]/u.test(pattern)?`/${normalized}`:normalized}function trimTrailingSeparators(pattern){let text=pattern;for(;text.length>1&&text.endsWith("/")&&!isEscaped(text,text.length-1);)text=text.slice(0,-1);return text}async function listed(directory,name){return(await readdir(directory).catch(()=>[])).includes(name)}async function exactCase(cwd,segments){let directory=cwd,index=0;for(;segments[index]==="..";)directory=path.dirname(directory),index+=1;for(;index<segments.length;index+=1){if(!await listed(directory,segments[index]))return!1;directory=path.join(directory,segments[index])}return!0}function isAbsolutePattern(text,platform=process.platform){return text.startsWith("/")||platform==="win32"&&/^[A-Za-z]:\//u.test(text)}async function literalMatch(text,cwd){const target=path.resolve(cwd,text),found=await stat(target).catch(()=>{});if(found===void 0||!found.isFile())return[];const absolute=isAbsolutePattern(text);return(absolute?await listed(path.dirname(target),path.basename(target)):await exactCase(cwd,text.split("/")))?[absolute?target.replaceAll("\\","/"):path.posix.normalize(text)]:[]}function splitStatic(text,cwd){const segments=text.split("/");let count=0;for(;count<segments.length&&isStaticSegment(segments[count]);)count+=1;if(count===segments.length)return;const prefix=count===0?"":`${segments.slice(0,count).join("/")}/`,root=path.resolve(cwd,prefix),rest=segments.slice(count).join("/");if(isAbsolutePattern(text))return{root,base:root.replaceAll("\\","/"),rest,prefix:[]};const relative=path.posix.normalize(prefix===""?".":prefix).replace(/\/$/u,"");return{root,base:relative==="."?"":relative,rest,prefix:segments.slice(0,count)}}function compileWithinBounds(text){try{return compile(text)}catch(error){if(error instanceof GlobTooComplex)return;throw error}}async function expandFileGlob(pattern,cwd){if(pattern.startsWith("!"))throw negationRefusal();if(Array.from(pattern).length>MAX_PATTERN_LENGTH)return[];const text=trimTrailingSeparators(normalizePattern(pattern)),parts=splitStatic(text,cwd);if(parts===void 0)return literalMatch(text,cwd);const matcher=compileWithinBounds(parts.rest);if(matcher===void 0||!await exactCase(cwd,parts.prefix))return[];const real=await realpath(parts.root).catch(()=>{});if(real===void 0)return[];const out=[];return await walk(matcher,parts.root,real,"",matcher.start,new Set([real]),out),out.map(relative=>joinOutput(parts.base,relative))}function joinOutput(base,relative){return base.startsWith("//")?`/${path.posix.join(base.slice(1),relative)}`:path.posix.join(base,relative)}const _testOnly={compile,isAbsolutePattern,joinOutput,normalizePattern};export{_testOnly,expandFileGlob};
2
2
  //# sourceMappingURL=file-glob.js.map
@@ -0,0 +1,3 @@
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="4b754f64-1bb8-54ef-a214-f1603b1711b8")}catch{}})();import{spawn}from"node:child_process";import{existsSync,readFileSync}from"node:fs";import path from"node:path";const TEARDOWN_HELPER_TIMEOUT_MS=2e3;function descendantEntriesFromProcessTable(table,root){const children=new Map;for(const line of table.split(`
2
+ `)){const fields=line.trim().split(/\s+/u);if(fields.length!==2)continue;const[child,parent]=fields.map(Number);if(!Number.isSafeInteger(child)||!Number.isSafeInteger(parent)||child<=0)continue;const siblings=children.get(parent);siblings?siblings.push(child):children.set(parent,[child])}const seen=new Set([root]),descendants=[],pending=(children.get(root)??[]).map(pid=>({pid,parent:root}));for(let index=0;index<pending.length;index+=1){const next=pending[index];if(!seen.has(next.pid)){seen.add(next.pid),descendants.push(next);for(const grandchild of children.get(next.pid)??[])pending.push({pid:grandchild,parent:next.pid})}}return descendants.reverse()}function descendantsFromProcessTable(table,root){return descendantEntriesFromProcessTable(table,root).map(entry=>entry.pid)}function parentStillMatches(entry,readStat=readProcStat){const stat=readStat(`/proc/${entry.pid}/stat`);if(stat===void 0)return!existsSync("/proc/self/stat");const fields=stat.slice(stat.lastIndexOf(")")+1).trim().split(/\s+/u);return Number(fields[1])===entry.parent}function processTableSharesNamespace(readStatus=readProcStat,platform=process.platform){const status=readStatus("/proc/self/status");if(status===void 0)return platform!=="linux"&&!existsSync("/proc/self/status");const nspid=/^NSpid:\s*(.*)$/mu.exec(status)?.[1]?.trim().split(/\s+/u);return nspid?.length===1&&Number(nspid[0])===process.pid}function ancestryStillMatches(pid,root,parentOf,matches=parentStillMatches,verified=new Map){const chain=[];let outcome=!0;for(let current=pid;current!==root;){const known=verified.get(current);if(known!==void 0){outcome=known;break}chain.push(current);const parent=parentOf.get(current);if(parent===void 0||!matches({pid:current,parent})){outcome=!1;break}current=parent}for(const link of chain)verified.set(link,outcome);return outcome}function readProcStat(file){try{return readFileSync(file,"utf8")}catch{return}}const TRUSTED_PS_PATHS=["/bin/ps","/usr/bin/ps"],PS_ENV={PATH:"/usr/bin:/bin",LC_ALL:"C"};function resolveTrustedPs(exists=existsSync){return TRUSTED_PS_PATHS.find(file=>exists(file))}const DEFAULT_WINDOWS_ROOT="C:\\Windows";function resolveWindowsSystemRoot(env=process.env,exists=existsSync){const valueOf=name=>Object.entries(env).find(([key])=>key.toLowerCase()===name)?.[1];return[valueOf("systemroot"),valueOf("windir"),DEFAULT_WINDOWS_ROOT].find(candidate=>typeof candidate=="string"&&/^[A-Za-z]:[\\/]/u.test(candidate)&&exists(path.win32.join(candidate,"System32","taskkill.exe")))}function killProcess(pid){try{process.kill(pid,"SIGKILL")}catch{}}function runTeardownHelper(file,args,env,timeoutMs=TEARDOWN_HELPER_TIMEOUT_MS){return new Promise(resolve=>{let settled=!1,stdout="",helper;try{helper=spawn(file,args,{stdio:["ignore","pipe","ignore"],windowsHide:!0,...env===void 0?{}:{env}})}catch{resolve(void 0);return}const deadline=timeoutMs===null?void 0:setTimeout(()=>{settle(void 0),helper.stdout?.destroy(),helper.kill("SIGKILL"),helper.unref()},timeoutMs);function settle(result){settled||(settled=!0,clearTimeout(deadline),resolve(result))}if(helper.on("error",()=>settle(void 0)),!helper.stdout){settle(void 0);return}helper.stdout.setEncoding("utf8"),helper.stdout.on("data",chunk=>{stdout+=chunk}),helper.on("close",code=>settle({code,stdout}))})}async function killProcessTree(pid,root={kill:()=>killProcess(pid),alive:()=>!0},options={}){if(!(!Number.isInteger(pid)||pid<=0)){if(process.platform==="win32"){await killWindowsTree(pid,root,options.taskkillTimeoutMs===void 0?TEARDOWN_HELPER_TIMEOUT_MS:options.taskkillTimeoutMs);return}try{process.kill(-pid,"SIGKILL");return}catch{}await killPosixDescendants(pid,root),root.kill()}}async function killWindowsTree(pid,root,taskkillTimeoutMs){const systemRoot=resolveWindowsSystemRoot();if(systemRoot===void 0){root.alive()&&root.kill();return}const taskkill=path.win32.join(systemRoot,"System32","taskkill.exe");(await runTeardownHelper(taskkill,["/pid",String(pid),"/T","/F"],void 0,taskkillTimeoutMs))?.code!==0&&root.alive()&&root.kill()}async function killPosixDescendants(pid,root){const ps=resolveTrustedPs();if(ps===void 0||!processTableSharesNamespace())return;const table=await runTeardownHelper(ps,["-A","-o","pid=","-o","ppid="],PS_ENV);if(table?.code!==0||!root.alive())return;const descendants=descendantEntriesFromProcessTable(table.stdout,pid),parentOf=new Map(descendants.map(entry=>[entry.pid,entry.parent])),verified=new Map;for(const descendant of descendants)parentStillMatches(descendant)&&ancestryStillMatches(descendant.parent,pid,parentOf,parentStillMatches,verified)&&killProcess(descendant.pid)}export{ancestryStillMatches,descendantEntriesFromProcessTable,descendantsFromProcessTable,killProcessTree,parentStillMatches,processTableSharesNamespace,resolveTrustedPs,resolveWindowsSystemRoot,runTeardownHelper};
3
+ //# sourceMappingURL=process-tree.js.map
@@ -33,12 +33,23 @@ value:string;
33
33
  element?:true;
34
34
  /** Judge element content with the value grammar and entropy predicate instead of length alone. */
35
35
  elementValue?:true;}
36
+ /**
37
+ * What a detector protects: `credential` for secrets that grant access,
38
+ * `network` for private infrastructure addresses and `path` for local
39
+ * filesystem paths that reveal an account. A policy can decide a whole family
40
+ * at once, so a new rule inherits its category's decision (pm-gh1749). The set
41
+ * is part of the public SDK contract: a new rule joins an existing category,
42
+ * and a new category is a declared contract change.
43
+ */
44
+ export type SecretRuleCategory="credential"|"network"|"path";
36
45
  /** One detector and any explicit repository-only scope exception. */
37
46
  export interface SecretRule{
38
47
  /** Repository diagnostic identifier. */
39
48
  name:string;
40
49
  /** Compatible SDK diagnostic identifier. */
41
50
  mutationRule:string;
51
+ /** Stable family of the detector; see {@link SecretRuleCategory}. */
52
+ category:SecretRuleCategory;
42
53
  /** Global pattern; consumers reset lastIndex before each scan. */
43
54
  regex:RegExp;
44
55
  /** Repository paths with deliberate fixture exemptions. */
@@ -86,7 +97,7 @@ regex:RegExp;
86
97
  /** Structured value grammar (regular-expression source), as {@link SecretStructuredSpelling.value}. */
87
98
  value:string;}
88
99
  /** Canonical patterns; repository exemptions never exempt mutation payloads. */
89
- export declare const SECRET_RULES:readonly[{readonly name:"private-key";readonly mutationRule:"private_key";readonly regex:RegExp;},{readonly name:"github-token";readonly mutationRule:"github_token";readonly regex:RegExp;},{readonly name:"npm-token";readonly mutationRule:"npm_token";readonly regex:RegExp;},{readonly name:"aws-access-key";readonly mutationRule:"aws_access_key";readonly regex:RegExp;},{readonly name:"google-api-key";readonly mutationRule:"google_api_key";readonly regex:RegExp;},{readonly name:"slack-token";readonly mutationRule:"slack_token";readonly regex:RegExp;},{readonly name:"anthropic-api-key";readonly mutationRule:"anthropic_api_key";readonly regex:RegExp;},{readonly name:"openai-api-key";readonly mutationRule:"openai_api_key";readonly regex:RegExp;},{readonly name:"gitlab-token";readonly mutationRule:"gitlab_token";readonly regex:RegExp;},{readonly name:"jwt-like-token";readonly mutationRule:"jwt_like_token";readonly regex:RegExp;},{readonly name:"npm-auth-token-assignment";readonly mutationRule:"npm_auth_token_assignment";readonly regex:RegExp;},{readonly name:"sentry-user-token";readonly mutationRule:"sentry_user_token";readonly regex:RegExp;},{readonly name:"sentry-org-token";readonly mutationRule:"sentry_org_token";readonly regex:RegExp;},{readonly name:"private-ip";readonly mutationRule:"private_ip";readonly regex:RegExp;},{readonly name:"private-ssh-target";readonly mutationRule:"private_ssh_target";readonly regex:RegExp;},{readonly name:"sshpass-inline-password";readonly mutationRule:"sshpass_inline_password";readonly regex:RegExp;},{readonly name:"password-assignment";readonly mutationRule:"password_assignment";readonly regex:RegExp;readonly structured:{readonly keys:"password|passphrase";readonly value:string;readonly element:true;};readonly minimumLiteralLength:8;},{readonly name:"absolute-home-path";readonly mutationRule:"absolute_home_path";readonly regex:RegExp;readonly excludeFiles:RegExp;},{readonly name:"user-at-private-host";readonly mutationRule:"user_at_private_host";readonly regex:RegExp;readonly excludeFiles:RegExp;},{readonly name:"high-entropy-assignment";readonly mutationRule:"high_entropy_assignment";readonly regex:RegExp;readonly structured:{readonly keys:"token|secret|password|passwd|api[_-]?key";readonly value:string;};readonly mutationOnlyReason:"Generic assignments in source code are not credentials; preserve the existing mutation heuristic without treating source identifiers as secrets.";readonly minimumEntropy:3.5;},{readonly name:"credential-key-assignment";readonly mutationRule:"credential_key_assignment";readonly regex:RegExp;readonly structured:{readonly keys:"(?<![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))";readonly value:string;readonly element:true;readonly elementValue:true;};readonly 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.";readonly minimumEntropy:3;readonly minimumLiteralLength:8;readonly literalValue:RegExp;readonly baseline:{readonly regex:RegExp;readonly value:string;};readonly rejectValue:RegExp;readonly rejectStatementReference:RegExp;}];
100
+ export declare const SECRET_RULES:readonly[{readonly name:"private-key";readonly mutationRule:"private_key";readonly category:"credential";readonly regex:RegExp;},{readonly name:"github-token";readonly mutationRule:"github_token";readonly category:"credential";readonly regex:RegExp;},{readonly name:"npm-token";readonly mutationRule:"npm_token";readonly category:"credential";readonly regex:RegExp;},{readonly name:"aws-access-key";readonly mutationRule:"aws_access_key";readonly category:"credential";readonly regex:RegExp;},{readonly name:"google-api-key";readonly mutationRule:"google_api_key";readonly category:"credential";readonly regex:RegExp;},{readonly name:"slack-token";readonly mutationRule:"slack_token";readonly category:"credential";readonly regex:RegExp;},{readonly name:"anthropic-api-key";readonly mutationRule:"anthropic_api_key";readonly category:"credential";readonly regex:RegExp;},{readonly name:"openai-api-key";readonly mutationRule:"openai_api_key";readonly category:"credential";readonly regex:RegExp;},{readonly name:"gitlab-token";readonly mutationRule:"gitlab_token";readonly category:"credential";readonly regex:RegExp;},{readonly name:"jwt-like-token";readonly mutationRule:"jwt_like_token";readonly category:"credential";readonly regex:RegExp;},{readonly name:"npm-auth-token-assignment";readonly mutationRule:"npm_auth_token_assignment";readonly category:"credential";readonly regex:RegExp;},{readonly name:"sentry-user-token";readonly mutationRule:"sentry_user_token";readonly category:"credential";readonly regex:RegExp;},{readonly name:"sentry-org-token";readonly mutationRule:"sentry_org_token";readonly category:"credential";readonly regex:RegExp;},{readonly name:"private-ip";readonly mutationRule:"private_ip";readonly category:"network";readonly regex:RegExp;},{readonly name:"private-ssh-target";readonly mutationRule:"private_ssh_target";readonly category:"network";readonly regex:RegExp;},{readonly name:"sshpass-inline-password";readonly mutationRule:"sshpass_inline_password";readonly category:"credential";readonly regex:RegExp;},{readonly name:"password-assignment";readonly mutationRule:"password_assignment";readonly category:"credential";readonly regex:RegExp;readonly structured:{readonly keys:"password|passphrase";readonly value:string;readonly element:true;};readonly minimumLiteralLength:8;},{readonly name:"absolute-home-path";readonly mutationRule:"absolute_home_path";readonly category:"path";readonly regex:RegExp;readonly excludeFiles:RegExp;},{readonly name:"user-at-private-host";readonly mutationRule:"user_at_private_host";readonly category:"network";readonly regex:RegExp;readonly excludeFiles:RegExp;},{readonly name:"high-entropy-assignment";readonly mutationRule:"high_entropy_assignment";readonly category:"credential";readonly regex:RegExp;readonly structured:{readonly keys:"token|secret|password|passwd|api[_-]?key";readonly value:string;};readonly mutationOnlyReason:"Generic assignments in source code are not credentials; preserve the existing mutation heuristic without treating source identifiers as secrets.";readonly minimumEntropy:3.5;},{readonly name:"credential-key-assignment";readonly mutationRule:"credential_key_assignment";readonly category:"credential";readonly regex:RegExp;readonly structured:{readonly keys:"(?<![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))";readonly value:string;readonly element:true;readonly elementValue:true;};readonly 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.";readonly minimumEntropy:3;readonly minimumLiteralLength:8;readonly literalValue:RegExp;readonly baseline:{readonly regex:RegExp;readonly value:string;};readonly rejectValue:RegExp;readonly rejectStatementReference:RegExp;}];
90
101
  /** Share matching and normalization, returning locations rather than matched values. */
91
102
  export declare function findSecretRuleMatches(rule:SecretRule,content:string):Generator<SecretRuleMatch>;
92
103
  /**
@@ -1,5 +1,5 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="b93aa43d-6c3e-5a34-9139-88000581c39f")}catch{}})();const COMPONENT=`[^\\s/\\\\<>"'\\x60()\\[\\]{},;?=:#*]+`,SEPARATOR="[/\\\\]+",ACCOUNT="[\\p{L}\\p{N}._@-]+",ACCOUNT_PATH=ACCOUNT+"(?:"+SEPARATOR+COMPONENT+")*",ROOT_HOME="(?:(?:home|users)"+SEPARATOR+ACCOUNT_PATH+"|root"+SEPARATOR+ACCOUNT_PATH+")",UNIX_HOME="[/\\\\]"+ROOT_HOME,MULTI_ROOT_HOME="[/\\\\]{2,}"+ROOT_HOME,WINDOWS_HOME="/?[a-z]:"+SEPARATOR+"users"+SEPARATOR+ACCOUNT_PATH,SHARE_COMPONENT=COMPONENT+"(?: +"+COMPONENT+")*",SHARED_PROFILE="(?:"+SHARE_COMPONENT+SEPARATOR+")?users"+SEPARATOR+ACCOUNT_PATH,UNC_HOME="[/\\\\]{2,}"+COMPONENT+SEPARATOR+SHARED_PROFILE,DEVICE_VOLUME="(?:[a-z]:|volume\\{[a-f0-9-]+\\}|"+COMPONENT+")",DEVICE_HOME="[/\\\\]{2}[?.]"+SEPARATOR+"(?:unc"+SEPARATOR+COMPONENT+SEPARATOR+SHARED_PROFILE+"|"+DEVICE_VOLUME+SEPARATOR+"users"+SEPARATOR+ACCOUNT_PATH+")",FILE_HOME="file:(?:"+DEVICE_HOME+"|(?:[/\\\\](?![/\\\\])|[/\\\\]{3,}|[/\\\\]{2}localhost"+SEPARATOR+")(?:"+ROOT_HOME+"|[a-z]:"+SEPARATOR+"users"+SEPARATOR+ACCOUNT_PATH+")|[/\\\\]{2}(?:[a-z]:"+SEPARATOR+"users"+SEPARATOR+ACCOUNT_PATH+"|"+COMPONENT+SEPARATOR+"(?:"+ROOT_HOME+"|"+SHARED_PROFILE+")))",PRIVATE_HOME_PATH_PATTERN=new RegExp("(?:^|[^\\p{L}\\p{N}_./\\\\~])(?:"+UNIX_HOME+"|"+WINDOWS_HOME+"|"+FILE_HOME+")|(?:^|[^\\p{L}\\p{N}_:./\\\\~])(?:"+MULTI_ROOT_HOME+"|"+UNC_HOME+"|"+DEVICE_HOME+")","giu"),MAX_NORMALIZATION_PASSES=4,REMAINING_ENCODING=/%[a-f0-9]{2}|\\(?:u[a-f0-9]{4}|x[a-f0-9]{2}|\/)/iu,utf8=new TextDecoder("utf-8");function percentView(value){return value.replace(/(?:%[a-f0-9]{2})+/giu,run=>utf8.decode(Uint8Array.from(run.matchAll(/%([a-f0-9]{2})/giu),match=>Number.parseInt(match[1],16)))).replace(/%(?![a-f0-9]{2})[a-z0-9]{0,2}/giu,"\uFFFD")}function escapedView(value){return value.replace(/\\+(?:u([a-f0-9]{4})|x([a-f0-9]{2})|(\/))?/giu,(match,unicode,byte,slash)=>{const code=unicode??byte;return code===void 0?slash??match:String.fromCharCode(Number.parseInt(code,16))})}function unicodeView(value){return value.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 nextNormalizedView(view,steps){for(const[kind,transform]of[["percent_decode",percentView],["json_unescape",escapedView],["unicode_fold",unicodeView]]){const transformed=transform(view);transformed!==view&&!steps.includes(kind)&&steps.push(kind),view=transformed}return view}function*normalizedHomePathMatches(line,regex,detected){let view=line;const steps=[];for(let pass=0;pass<MAX_NORMALIZATION_PASSES;pass+=1){const previous=view;if(view=nextNormalizedView(view,steps),!detected){regex.lastIndex=0;for(const _match of view.matchAll(regex))detected=!0,yield{index:0,normalizations:[...steps]}}if(view===previous)break;pass===MAX_NORMALIZATION_PASSES-1&&REMAINING_ENCODING.test(view)&&(yield{index:0,normalizations:[...steps],normalization_incomplete:!0})}}function*findPrivateHomePathMatches(content,regex){let offset=0;for(const line of content.split(`
2
- `)){regex.lastIndex=0;let rawFound=!1;for(const match of line.matchAll(regex))rawFound=!0,yield{index:offset+match.index};for(const match of normalizedHomePathMatches(line,regex,rawFound))yield{...match,index:offset};offset+=line.length+1}}const PASSWORD_KEYS="password|passphrase",PASSWORD_QUOTED_PIECES=4,PASSWORD_REPEAT_BOUND=4096,maximalRun=characterClass=>`${characterClass}+(?!${characterClass})`,PASSWORD_QUOTED_SPAN=String.raw`'[^'\r\n]*'|"[^"\\\r\n]*(?:\\.[^"\\\r\n]*){0,${PASSWORD_REPEAT_BOUND}}"`,PASSWORD_REFERENCE=String.raw`\$\{(?:${maximalRun(String.raw`[^{}$'"\\\r\n]`)}|\\[^\r\n]|${PASSWORD_QUOTED_SPAN}|\$(?!\{)|\$\{[^{}\r\n]*\}){0,${PASSWORD_REPEAT_BOUND}}\}`+String.raw`|\$\((?:${maximalRun(String.raw`[^()$'"\\\r\n]`)}|\\[^\r\n]|${PASSWORD_QUOTED_SPAN}|\$(?!\()|\$\([^()\r\n]*\)){0,${PASSWORD_REPEAT_BOUND}}\)`,PASSWORD_PIECE=String.raw`${PASSWORD_REFERENCE}|<[^<>\r\n]*>|${maximalRun(String.raw`[A-Za-z0-9!@#%^&*._+\-=]`)}|\$(?![{(])`,PASSWORD_QUOTED=String.raw`"[^"]*"|'[^']*'`,PASSWORD_QUOTED_PIECE=String.raw`(?:"[^"\s]*"|'[^'\s]*')(?:${PASSWORD_PIECE}){0,${PASSWORD_REPEAT_BOUND}}`,PASSWORD_VALUE=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)?$)))`+`((?:${PASSWORD_PIECE}){1,${PASSWORD_REPEAT_BOUND}}(?:${PASSWORD_QUOTED_PIECE}){0,${PASSWORD_QUOTED_PIECES}}|(?:${PASSWORD_QUOTED_PIECE}){1,${PASSWORD_QUOTED_PIECES}}|${PASSWORD_QUOTED})`),PASSWORD_MINIMUM_LITERAL_LENGTH=8,HIGH_ENTROPY_KEYS="token|secret|password|passwd|api[_-]?key",CREDENTIAL_KEYS="(?<![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))",EXCLUSION_REPEAT_BOUND=4096,CREDENTIAL_OPEN=String.raw`"(?=[^"\s]{8}[^"\s]*")|'(?=[^'\s]{8}[^'\s]*')|(?!["'])`,CREDENTIAL_PLAIN=String.raw`(?![<[$/]|~\/|\.\.?\/|[A-Za-z][\w+.-]*:\/\/|%[A-Za-z_]\w*%|[A-Za-z]:[\\/]|(?<=")(?:(?:[A-Za-z_]\w*\.){1,${EXCLUSION_REPEAT_BOUND}}[A-Za-z_]\w*|[A-Za-z]+(?:-[A-Za-z]+){0,${EXCLUSION_REPEAT_BOUND}}|(?:[\w.-]+\/){1,${EXCLUSION_REPEAT_BOUND}}[\w.-]+\.[A-Za-z][A-Za-z0-9]{0,4})"|(?<=')(?:(?:[A-Za-z_]\w*\.){1,${EXCLUSION_REPEAT_BOUND}}[A-Za-z_]\w*|[A-Za-z]+(?:-[A-Za-z]+){0,${EXCLUSION_REPEAT_BOUND}}|(?:[\w.-]+\/){1,${EXCLUSION_REPEAT_BOUND}}[\w.-]+\.[A-Za-z][A-Za-z0-9]{0,4})'|(?<!["'])[A-Za-z]+(?:-[A-Za-z]+){0,${EXCLUSION_REPEAT_BOUND}}(?![\w!@#$%^&*.+\-=/~])|(?<!["'])(?:[A-Za-z_]\w*\.){1,${EXCLUSION_REPEAT_BOUND}}[A-Za-z_]\w*(?![\w!@#$%^&*.+\-=/~])|(?<!["'])(?:[\w.-]+\/){1,${EXCLUSION_REPEAT_BOUND}}[\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,})`,CREDENTIAL_LITERAL_VALUE=new RegExp(`(?:${CREDENTIAL_OPEN})(${CREDENTIAL_PLAIN})`,"iy"),CREDENTIAL_MINIMUM_LITERAL_LENGTH=8,CREDENTIAL_RUN=String.raw`[A-Za-z0-9!@#%^*._+\-=/~]`,CREDENTIAL_AMPERSAND=String.raw`&(?!&)`,CREDENTIAL_LEADING_LITERAL=64,CREDENTIAL_REFERENCE_SPAN=String.raw`'[^'\s]*'|"[^"\\\s]*(?:\\\S[^"\\\s]*){0,${PASSWORD_REPEAT_BOUND}}"`,CREDENTIAL_REFERENCE=String.raw`\$\{(?:${maximalRun(String.raw`[^{}$'"\\\s]`)}|\\\S|${CREDENTIAL_REFERENCE_SPAN}|\$(?!\{)|\$\{[^{}\s]*\}){0,${PASSWORD_REPEAT_BOUND}}\}`+String.raw`|\$\((?:${maximalRun(String.raw`[^()$'"\\\s]`)}|\\\S|${CREDENTIAL_REFERENCE_SPAN}|\$(?!\()|\$\([^()\s]*\)){0,${PASSWORD_REPEAT_BOUND}}\)`+String.raw`|<[^<>\s]*>|\$[A-Za-z_]\w*(?!\w)`,credentialPiece=run=>String.raw`${CREDENTIAL_REFERENCE}|${maximalRun(run)}|${CREDENTIAL_AMPERSAND}|\$(?![{(A-Za-z_])`,credentialQuotedPiece=run=>String.raw`(?:"[^"\s]*"|'[^'\s]*')(?:${credentialPiece(run)}){0,${PASSWORD_REPEAT_BOUND}}`,credentialReferenced=run=>String.raw`(?:(?:${run}|${CREDENTIAL_AMPERSAND}){1,${CREDENTIAL_LEADING_LITERAL}}(?=[$<]))?(?:${CREDENTIAL_REFERENCE})`+String.raw`(?:${credentialPiece(run)}){0,${PASSWORD_REPEAT_BOUND}}(?:${credentialQuotedPiece(run)}){0,${PASSWORD_QUOTED_PIECES}}`,credentialConcatenated=run=>String.raw`(?:${credentialQuotedPiece(run)}){1,${PASSWORD_QUOTED_PIECES}}`,credentialUnquoted=build=>String.raw`(?<!["'])(?:${build(CREDENTIAL_RUN)})`,CREDENTIAL_CONCATENATION_CONTINUES=String.raw`(?:[\w@#~]|!(?![.+\-*/%=^!(]))`,CREDENTIAL_CONCATENATION_OPEN=String.raw`(?=(?:"[^"\s]*"|'[^'\s]*')[$<"']`+String.raw`|"(?=[^"\s]*[$<])[^"\s]*"${CREDENTIAL_CONCATENATION_CONTINUES}|'(?=[^'\s]*[$<])[^'\s]*'${CREDENTIAL_CONCATENATION_CONTINUES})`,CREDENTIAL_QUOTED_REFERENCED=String.raw`(?<=")(?=[^"\s]*[$<])[^"\s]+|(?<=')(?=[^'\s]*[$<])[^'\s]+`,CREDENTIAL_VALUE=new RegExp(`(?:${CREDENTIAL_CONCATENATION_OPEN}|${CREDENTIAL_OPEN})((?=["'])(?:${credentialUnquoted(credentialConcatenated)})|${CREDENTIAL_QUOTED_REFERENCED}|${credentialUnquoted(credentialReferenced)}|${CREDENTIAL_PLAIN})`),HIGH_ENTROPY_VALUE=/["']?([A-Za-z0-9+/=_-]{24,})/,SECRET_RULES=[{name:"private-key",mutationRule:"private_key",regex:/-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/g},{name:"github-token",mutationRule:"github_token",regex:/\b(?:gh[opsru]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})\b/g},{name:"npm-token",mutationRule:"npm_token",regex:/\bnpm_[A-Za-z0-9]{20,}\b/g},{name:"aws-access-key",mutationRule:"aws_access_key",regex:/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g},{name:"google-api-key",mutationRule:"google_api_key",regex:/\bAIza[0-9A-Za-z_-]{35}\b/g},{name:"slack-token",mutationRule:"slack_token",regex:/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g},{name:"anthropic-api-key",mutationRule:"anthropic_api_key",regex:/\bsk-ant-[A-Za-z0-9_-]{20,}\b/g},{name:"openai-api-key",mutationRule:"openai_api_key",regex:/\bsk-(?!ant-)[A-Za-z0-9_-]{20,}\b/g},{name:"gitlab-token",mutationRule:"gitlab_token",regex:/\bglpat-[A-Za-z0-9_.-]{20,}\b/g},{name:"jwt-like-token",mutationRule:"jwt_like_token",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",regex:/_authToken\s*=\s*\S+/g},{name:"sentry-user-token",mutationRule:"sentry_user_token",regex:/\bsntryu_[A-Za-z0-9]{20,}\b/g},{name:"sentry-org-token",mutationRule:"sentry_org_token",regex:/\bsntrys_[A-Za-z0-9_-]{20,}\b/g},{name:"private-ip",mutationRule:"private_ip",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",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",regex:/\bsshpass\s+-p\s+["'][^"']{6,}["']/g},{name:"password-assignment",mutationRule:"password_assignment",regex:new RegExp(String.raw`\b(?:${PASSWORD_KEYS})\s*[:=]\s*`+PASSWORD_VALUE.source,"gi"),structured:{keys:PASSWORD_KEYS,value:PASSWORD_VALUE.source,element:!0},minimumLiteralLength:PASSWORD_MINIMUM_LITERAL_LENGTH},{name:"absolute-home-path",mutationRule:"absolute_home_path",regex:PRIVATE_HOME_PATH_PATTERN,excludeFiles:/^(?:tests\/|examples\/)/},{name:"user-at-private-host",mutationRule:"user_at_private_host",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",regex:new RegExp(String.raw`\b(?:${HIGH_ENTROPY_KEYS})\s*[:=]\s*`+HIGH_ENTROPY_VALUE.source,"gi"),structured:{keys:HIGH_ENTROPY_KEYS,value:HIGH_ENTROPY_VALUE.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",regex:new RegExp(String.raw`\b(?:${CREDENTIAL_KEYS})\s*[:=]\s*`+CREDENTIAL_VALUE.source,"gi"),structured:{keys:CREDENTIAL_KEYS,value:CREDENTIAL_VALUE.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:CREDENTIAL_MINIMUM_LITERAL_LENGTH,literalValue:CREDENTIAL_LITERAL_VALUE,baseline:{regex:new RegExp(String.raw`\b(?:${CREDENTIAL_KEYS})\s*[:=]\s*`+CREDENTIAL_LITERAL_VALUE.source,"gi"),value:CREDENTIAL_LITERAL_VALUE.source},rejectValue:/^(?:[\w.-]+\/)*id_(?:rsa|dsa|ecdsa|ed25519)(?:_sk)?(?:\.pub)?$/u,rejectStatementReference:/^[A-Z]+(?:_[A-Z]+)+$/u}];function*findSecretRuleMatches(rule,content){if(rule.mutationRule==="absolute_home_path"){yield*findPrivateHomePathMatches(content,rule.regex);return}for(const reading of ruleReadings(rule))yield*flatMatches(reading,content),reading.structured&&(yield*findStructuredSpellingMatches(reading,reading.structured,content))}const baselineRules=new WeakMap;function ruleReadings(rule){const baseline=rule.baseline;if(baseline===void 0)return[rule];let judged=baselineRules.get(rule);return judged===void 0&&(judged={...rule,regex:baseline.regex,minimumLiteralLength:void 0,literalValue:void 0,baseline:void 0},rule.structured&&(judged.structured={...rule.structured,value:baseline.value}),baselineRules.set(rule,judged)),[rule,judged]}function isParameterName(content,index){const name=content[index-1]==="#"||content[index-1]==="!"?index-1:index;return content[name-1]==="{"&&content[name-2]==="$"}const INNER_SHELL_MATCHES=new WeakSet,INNER_CLOSE_AT=new WeakMap,CUT_REFERENCE_BOUND=4096;function referenceSpans(content,offset,text){const spans=[],open=[],end=offset+text.length;return walkReferences(content,offset,end,open,spans),walkReferences(content,end,Math.min(content.length,end+CUT_REFERENCE_BOUND),open),spans}function walkReferences(content,start,end,open,spans){for(let index=start;index<end&&(spans!==void 0||open.length>0);index+=1){const frame=open.at(-1);if(content[index]==="$"&&(content[index+1]==="{"||content[index+1]==="(")&&frame?.quoted!=="'"){const span={open:index,close:end,command:content[index+1]==="(",quoted:[]};spans?.push(span),open.push({span,closer:content[index+1]==="{"?"}":")"}),index+=1}else frame!==void 0&&(index=referenceStep(content,index,open))}}function referenceStep(text,index,open){const frame=open.at(-1),character=text[index];return character==="\\"&&frame.quoted!=="'"?index+1:(frame.quoted!==void 0?character===frame.quoted&&(frame.span.quoted.push([frame.quoteStart,index]),frame.quoted=void 0):character==="'"||character==='"'?(frame.quoted=character,frame.quoteStart=index):character===frame.closer&&(open.pop().span.close=index),index)}function enclosingCloser(spans){const active=[];let next=0;return position=>{for(;next<spans.length&&spans[next].open<position;next+=1){for(;active.length>0&&active.at(-1).close<spans[next].open;)active.pop();active.push(spans[next])}for(;active.length>0&&active.at(-1).close<position;)active.pop();return active.at(-1)}}function insideQuotedRange(span,position){let low=0,high=span.quoted.length-1;for(;low<=high;){const middle=low+high>>1,[start,end]=span.quoted[middle];if(position<start)high=middle-1;else if(position>end)low=middle+1;else return!0}return!1}const VALUE_REFERENCE=/\$[({A-Za-z_]|</u;function*flatMatches(rule,content){const regex=rule.regex;regex.lastIndex=0;const rescan=rescanDepth(rule);let inner;for(const match of content.matchAll(regex))acceptsSecretMatch(rule,match)?yield{index:match.index}:rescan!==void 0&&VALUE_REFERENCE.test(match[1])&&(inner??=new RegExp(regex),yield*keysInsideRejectedValue(rule,inner,content,match,rescan==="deep"))}function rescanDepth(rule){return rule.minimumLiteralLength===void 0?void 0:rule.minimumEntropy===void 0&&rule.literalValue===void 0&&rule.rejectValue===void 0?"deep":"shallow"}function*keysInsideRejectedValue(rule,inner,content,match,deep){const end=match.index+match[0].length;inner.lastIndex=end-match[1].length;let closerAt;for(let found=inner.exec(content);found!==null&&found.index<end;found=inner.exec(content)){if(isParameterName(content,found.index)){inner.lastIndex=found.index+1;continue}closerAt??=enclosingCloser(referenceSpans(content,end-match[1].length,match[1]));const span=closerAt(found.index);span!==void 0&&(INNER_CLOSE_AT.set(found,span.close),span.command&&!insideQuotedRange(span,found.index)&&INNER_SHELL_MATCHES.add(found)),acceptsSecretMatch(rule,found)?yield{index:found.index}:deep&&VALUE_REFERENCE.test(found[1])&&(inner.lastIndex=found.index+found[0].length-found[1].length)}}const compiledSpellings=new Map,LINE_BREAK=/[\r\n\u2028\u2029]/u;function compileSpelling(spelling){const cacheKey=`${spelling.keys}\0${spelling.value}\0${spelling.element===!0}`;let compiled=compiledSpellings.get(cacheKey);return compiled||(compiled={key:new RegExp(String.raw`\b(?:${spelling.keys})(["']?)\s*[:=]\s*`,"gi"),value:new RegExp(spelling.value,"iyd"),...spelling.element?{element:{open:new RegExp(String.raw`<(?:${spelling.keys})(?:\s[^<>]*)?>`,"gi"),close:new RegExp(String.raw`<\/(?:${spelling.keys})\s*>`,"iy"),span:new RegExp(String.raw`<(?!\/?(?:${spelling.keys})\b)[^<>]*>`,"iy")}}:{}},compiledSpellings.set(cacheKey,compiled)),compiled}function scanQuoted(content,start){const quote=content[start];for(let index=start+1;index<content.length;index+=1){const character=content[index];if(character==="\\")index+=1;else if(character===quote)return{end:index+1,terminated:!0}}return{end:content.length,terminated:!1}}function endOfQuoted(content,start){return scanQuoted(content,start).end}function judgeFor(closers,accepts,acceptsMember){return closers.at(-1)==="}"?acceptsMember:accepts}function walkContainer(content,start,accepts,acceptsMember=accepts){const closers=[];let expectKey=!1;for(let index=start;index<content.length;index+=1){const character=content[index];switch(character){case"[":case"{":closers.push(character==="["?"]":"}"),expectKey=character==="{";break;case"]":case"}":if(closers.pop()!==character||closers.length===0)return{found:!1,end:index+1};expectKey=!1;break;case",":expectKey=closers.at(-1)==="}";break;case":":expectKey=!1;break;case'"':case"'":if(!expectKey&&judgeFor(closers,accepts,acceptsMember)(index))return{found:!0,end:index};index=endOfQuoted(content,index)-1;break;default:break}}return{found:!1,end:content.length}}const ESCAPE_SEQUENCE=/\\(?: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,SIMPLE_ESCAPES={n:`
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="a5619fc7-2547-59c9-bfff-4d4cebd14967")}catch{}})();const COMPONENT=`[^\\s/\\\\<>"'\\x60()\\[\\]{},;?=:#*]+`,SEPARATOR="[/\\\\]+",ACCOUNT="[\\p{L}\\p{N}._@-]+",ACCOUNT_PATH=ACCOUNT+"(?:"+SEPARATOR+COMPONENT+")*",ROOT_HOME="(?:(?:home|users)"+SEPARATOR+ACCOUNT_PATH+"|root"+SEPARATOR+ACCOUNT_PATH+")",UNIX_HOME="[/\\\\]"+ROOT_HOME,MULTI_ROOT_HOME="[/\\\\]{2,}"+ROOT_HOME,WINDOWS_HOME="/?[a-z]:"+SEPARATOR+"users"+SEPARATOR+ACCOUNT_PATH,SHARE_COMPONENT=COMPONENT+"(?: +"+COMPONENT+")*",SHARED_PROFILE="(?:"+SHARE_COMPONENT+SEPARATOR+")?users"+SEPARATOR+ACCOUNT_PATH,UNC_HOME="[/\\\\]{2,}"+COMPONENT+SEPARATOR+SHARED_PROFILE,DEVICE_VOLUME="(?:[a-z]:|volume\\{[a-f0-9-]+\\}|"+COMPONENT+")",DEVICE_HOME="[/\\\\]{2}[?.]"+SEPARATOR+"(?:unc"+SEPARATOR+COMPONENT+SEPARATOR+SHARED_PROFILE+"|"+DEVICE_VOLUME+SEPARATOR+"users"+SEPARATOR+ACCOUNT_PATH+")",FILE_HOME="file:(?:"+DEVICE_HOME+"|(?:[/\\\\](?![/\\\\])|[/\\\\]{3,}|[/\\\\]{2}localhost"+SEPARATOR+")(?:"+ROOT_HOME+"|[a-z]:"+SEPARATOR+"users"+SEPARATOR+ACCOUNT_PATH+")|[/\\\\]{2}(?:[a-z]:"+SEPARATOR+"users"+SEPARATOR+ACCOUNT_PATH+"|"+COMPONENT+SEPARATOR+"(?:"+ROOT_HOME+"|"+SHARED_PROFILE+")))",PRIVATE_HOME_PATH_PATTERN=new RegExp("(?:^|[^\\p{L}\\p{N}_./\\\\~])(?:"+UNIX_HOME+"|"+WINDOWS_HOME+"|"+FILE_HOME+")|(?:^|[^\\p{L}\\p{N}_:./\\\\~])(?:"+MULTI_ROOT_HOME+"|"+UNC_HOME+"|"+DEVICE_HOME+")","giu"),MAX_NORMALIZATION_PASSES=4,REMAINING_ENCODING=/%[a-f0-9]{2}|\\(?:u[a-f0-9]{4}|x[a-f0-9]{2}|\/)/iu,utf8=new TextDecoder("utf-8");function percentView(value){return value.replace(/(?:%[a-f0-9]{2})+/giu,run=>utf8.decode(Uint8Array.from(run.matchAll(/%([a-f0-9]{2})/giu),match=>Number.parseInt(match[1],16)))).replace(/%(?![a-f0-9]{2})[a-z0-9]{0,2}/giu,"\uFFFD")}function escapedView(value){return value.replace(/\\+(?:u([a-f0-9]{4})|x([a-f0-9]{2})|(\/))?/giu,(match,unicode,byte,slash)=>{const code=unicode??byte;return code===void 0?slash??match:String.fromCharCode(Number.parseInt(code,16))})}function unicodeView(value){return value.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 nextNormalizedView(view,steps){for(const[kind,transform]of[["percent_decode",percentView],["json_unescape",escapedView],["unicode_fold",unicodeView]]){const transformed=transform(view);transformed!==view&&!steps.includes(kind)&&steps.push(kind),view=transformed}return view}function*normalizedHomePathMatches(line,regex,detected){let view=line;const steps=[];for(let pass=0;pass<MAX_NORMALIZATION_PASSES;pass+=1){const previous=view;if(view=nextNormalizedView(view,steps),!detected){regex.lastIndex=0;for(const _match of view.matchAll(regex))detected=!0,yield{index:0,normalizations:[...steps]}}if(view===previous)break;pass===MAX_NORMALIZATION_PASSES-1&&REMAINING_ENCODING.test(view)&&(yield{index:0,normalizations:[...steps],normalization_incomplete:!0})}}function*findPrivateHomePathMatches(content,regex){let offset=0;for(const line of content.split(`
2
+ `)){regex.lastIndex=0;let rawFound=!1;for(const match of line.matchAll(regex))rawFound=!0,yield{index:offset+match.index};for(const match of normalizedHomePathMatches(line,regex,rawFound))yield{...match,index:offset};offset+=line.length+1}}const PASSWORD_KEYS="password|passphrase",PASSWORD_QUOTED_PIECES=4,PASSWORD_REPEAT_BOUND=4096,maximalRun=characterClass=>`${characterClass}+(?!${characterClass})`,PASSWORD_QUOTED_SPAN=String.raw`'[^'\r\n]*'|"[^"\\\r\n]*(?:\\.[^"\\\r\n]*){0,${PASSWORD_REPEAT_BOUND}}"`,PASSWORD_REFERENCE=String.raw`\$\{(?:${maximalRun(String.raw`[^{}$'"\\\r\n]`)}|\\[^\r\n]|${PASSWORD_QUOTED_SPAN}|\$(?!\{)|\$\{[^{}\r\n]*\}){0,${PASSWORD_REPEAT_BOUND}}\}`+String.raw`|\$\((?:${maximalRun(String.raw`[^()$'"\\\r\n]`)}|\\[^\r\n]|${PASSWORD_QUOTED_SPAN}|\$(?!\()|\$\([^()\r\n]*\)){0,${PASSWORD_REPEAT_BOUND}}\)`,PASSWORD_PIECE=String.raw`${PASSWORD_REFERENCE}|<[^<>\r\n]*>|${maximalRun(String.raw`[A-Za-z0-9!@#%^&*._+\-=]`)}|\$(?![{(])`,PASSWORD_QUOTED=String.raw`"[^"]*"|'[^']*'`,PASSWORD_QUOTED_PIECE=String.raw`(?:"[^"\s]*"|'[^'\s]*')(?:${PASSWORD_PIECE}){0,${PASSWORD_REPEAT_BOUND}}`,PASSWORD_VALUE=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)?$)))`+`((?:${PASSWORD_PIECE}){1,${PASSWORD_REPEAT_BOUND}}(?:${PASSWORD_QUOTED_PIECE}){0,${PASSWORD_QUOTED_PIECES}}|(?:${PASSWORD_QUOTED_PIECE}){1,${PASSWORD_QUOTED_PIECES}}|${PASSWORD_QUOTED})`),PASSWORD_MINIMUM_LITERAL_LENGTH=8,HIGH_ENTROPY_KEYS="token|secret|password|passwd|api[_-]?key",CREDENTIAL_KEYS="(?<![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))",EXCLUSION_REPEAT_BOUND=4096,CREDENTIAL_OPEN=String.raw`"(?=[^"\s]{8}[^"\s]*")|'(?=[^'\s]{8}[^'\s]*')|(?!["'])`,CREDENTIAL_PLAIN=String.raw`(?![<[$/]|~\/|\.\.?\/|[A-Za-z][\w+.-]*:\/\/|%[A-Za-z_]\w*%|[A-Za-z]:[\\/]|(?<=")(?:(?:[A-Za-z_]\w*\.){1,${EXCLUSION_REPEAT_BOUND}}[A-Za-z_]\w*|[A-Za-z]+(?:-[A-Za-z]+){0,${EXCLUSION_REPEAT_BOUND}}|(?:[\w.-]+\/){1,${EXCLUSION_REPEAT_BOUND}}[\w.-]+\.[A-Za-z][A-Za-z0-9]{0,4})"|(?<=')(?:(?:[A-Za-z_]\w*\.){1,${EXCLUSION_REPEAT_BOUND}}[A-Za-z_]\w*|[A-Za-z]+(?:-[A-Za-z]+){0,${EXCLUSION_REPEAT_BOUND}}|(?:[\w.-]+\/){1,${EXCLUSION_REPEAT_BOUND}}[\w.-]+\.[A-Za-z][A-Za-z0-9]{0,4})'|(?<!["'])[A-Za-z]+(?:-[A-Za-z]+){0,${EXCLUSION_REPEAT_BOUND}}(?![\w!@#$%^&*.+\-=/~])|(?<!["'])(?:[A-Za-z_]\w*\.){1,${EXCLUSION_REPEAT_BOUND}}[A-Za-z_]\w*(?![\w!@#$%^&*.+\-=/~])|(?<!["'])(?:[\w.-]+\/){1,${EXCLUSION_REPEAT_BOUND}}[\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,})`,CREDENTIAL_LITERAL_VALUE=new RegExp(`(?:${CREDENTIAL_OPEN})(${CREDENTIAL_PLAIN})`,"iy"),CREDENTIAL_MINIMUM_LITERAL_LENGTH=8,CREDENTIAL_RUN=String.raw`[A-Za-z0-9!@#%^*._+\-=/~]`,CREDENTIAL_AMPERSAND=String.raw`&(?!&)`,CREDENTIAL_LEADING_LITERAL=64,CREDENTIAL_REFERENCE_SPAN=String.raw`'[^'\s]*'|"[^"\\\s]*(?:\\\S[^"\\\s]*){0,${PASSWORD_REPEAT_BOUND}}"`,CREDENTIAL_REFERENCE=String.raw`\$\{(?:${maximalRun(String.raw`[^{}$'"\\\s]`)}|\\\S|${CREDENTIAL_REFERENCE_SPAN}|\$(?!\{)|\$\{[^{}\s]*\}){0,${PASSWORD_REPEAT_BOUND}}\}`+String.raw`|\$\((?:${maximalRun(String.raw`[^()$'"\\\s]`)}|\\\S|${CREDENTIAL_REFERENCE_SPAN}|\$(?!\()|\$\([^()\s]*\)){0,${PASSWORD_REPEAT_BOUND}}\)`+String.raw`|<[^<>\s]*>|\$[A-Za-z_]\w*(?!\w)`,credentialPiece=run=>String.raw`${CREDENTIAL_REFERENCE}|${maximalRun(run)}|${CREDENTIAL_AMPERSAND}|\$(?![{(A-Za-z_])`,credentialQuotedPiece=run=>String.raw`(?:"[^"\s]*"|'[^'\s]*')(?:${credentialPiece(run)}){0,${PASSWORD_REPEAT_BOUND}}`,credentialReferenced=run=>String.raw`(?:(?:${run}|${CREDENTIAL_AMPERSAND}){1,${CREDENTIAL_LEADING_LITERAL}}(?=[$<]))?(?:${CREDENTIAL_REFERENCE})`+String.raw`(?:${credentialPiece(run)}){0,${PASSWORD_REPEAT_BOUND}}(?:${credentialQuotedPiece(run)}){0,${PASSWORD_QUOTED_PIECES}}`,credentialConcatenated=run=>String.raw`(?:${credentialQuotedPiece(run)}){1,${PASSWORD_QUOTED_PIECES}}`,credentialUnquoted=build=>String.raw`(?<!["'])(?:${build(CREDENTIAL_RUN)})`,CREDENTIAL_CONCATENATION_CONTINUES=String.raw`(?:[\w@#~]|!(?![.+\-*/%=^!(]))`,CREDENTIAL_CONCATENATION_OPEN=String.raw`(?=(?:"[^"\s]*"|'[^'\s]*')[$<"']`+String.raw`|"(?=[^"\s]*[$<])[^"\s]*"${CREDENTIAL_CONCATENATION_CONTINUES}|'(?=[^'\s]*[$<])[^'\s]*'${CREDENTIAL_CONCATENATION_CONTINUES})`,CREDENTIAL_QUOTED_REFERENCED=String.raw`(?<=")(?=[^"\s]*[$<])[^"\s]+|(?<=')(?=[^'\s]*[$<])[^'\s]+`,CREDENTIAL_VALUE=new RegExp(`(?:${CREDENTIAL_CONCATENATION_OPEN}|${CREDENTIAL_OPEN})((?=["'])(?:${credentialUnquoted(credentialConcatenated)})|${CREDENTIAL_QUOTED_REFERENCED}|${credentialUnquoted(credentialReferenced)}|${CREDENTIAL_PLAIN})`),HIGH_ENTROPY_VALUE=/["']?([A-Za-z0-9+/=_-]{24,})/,SECRET_RULES=[{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(?:${PASSWORD_KEYS})\s*[:=]\s*`+PASSWORD_VALUE.source,"gi"),structured:{keys:PASSWORD_KEYS,value:PASSWORD_VALUE.source,element:!0},minimumLiteralLength:PASSWORD_MINIMUM_LITERAL_LENGTH},{name:"absolute-home-path",mutationRule:"absolute_home_path",category:"path",regex:PRIVATE_HOME_PATH_PATTERN,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(?:${HIGH_ENTROPY_KEYS})\s*[:=]\s*`+HIGH_ENTROPY_VALUE.source,"gi"),structured:{keys:HIGH_ENTROPY_KEYS,value:HIGH_ENTROPY_VALUE.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(?:${CREDENTIAL_KEYS})\s*[:=]\s*`+CREDENTIAL_VALUE.source,"gi"),structured:{keys:CREDENTIAL_KEYS,value:CREDENTIAL_VALUE.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:CREDENTIAL_MINIMUM_LITERAL_LENGTH,literalValue:CREDENTIAL_LITERAL_VALUE,baseline:{regex:new RegExp(String.raw`\b(?:${CREDENTIAL_KEYS})\s*[:=]\s*`+CREDENTIAL_LITERAL_VALUE.source,"gi"),value:CREDENTIAL_LITERAL_VALUE.source},rejectValue:/^(?:[\w.-]+\/)*id_(?:rsa|dsa|ecdsa|ed25519)(?:_sk)?(?:\.pub)?$/u,rejectStatementReference:/^[A-Z]+(?:_[A-Z]+)+$/u}];function*findSecretRuleMatches(rule,content){if(rule.mutationRule==="absolute_home_path"){yield*findPrivateHomePathMatches(content,rule.regex);return}for(const reading of ruleReadings(rule))yield*flatMatches(reading,content),reading.structured&&(yield*findStructuredSpellingMatches(reading,reading.structured,content))}const baselineRules=new WeakMap;function ruleReadings(rule){const baseline=rule.baseline;if(baseline===void 0)return[rule];let judged=baselineRules.get(rule);return judged===void 0&&(judged={...rule,regex:baseline.regex,minimumLiteralLength:void 0,literalValue:void 0,baseline:void 0},rule.structured&&(judged.structured={...rule.structured,value:baseline.value}),baselineRules.set(rule,judged)),[rule,judged]}function isParameterName(content,index){const name=content[index-1]==="#"||content[index-1]==="!"?index-1:index;return content[name-1]==="{"&&content[name-2]==="$"}const INNER_SHELL_MATCHES=new WeakSet,INNER_CLOSE_AT=new WeakMap,CUT_REFERENCE_BOUND=4096;function referenceSpans(content,offset,text){const spans=[],open=[],end=offset+text.length;return walkReferences(content,offset,end,open,spans),walkReferences(content,end,Math.min(content.length,end+CUT_REFERENCE_BOUND),open),spans}function walkReferences(content,start,end,open,spans){for(let index=start;index<end&&(spans!==void 0||open.length>0);index+=1){const frame=open.at(-1);if(content[index]==="$"&&(content[index+1]==="{"||content[index+1]==="(")&&frame?.quoted!=="'"){const span={open:index,close:end,command:content[index+1]==="(",quoted:[]};spans?.push(span),open.push({span,closer:content[index+1]==="{"?"}":")"}),index+=1}else frame!==void 0&&(index=referenceStep(content,index,open))}}function referenceStep(text,index,open){const frame=open.at(-1),character=text[index];return character==="\\"&&frame.quoted!=="'"?index+1:(frame.quoted!==void 0?character===frame.quoted&&(frame.span.quoted.push([frame.quoteStart,index]),frame.quoted=void 0):character==="'"||character==='"'?(frame.quoted=character,frame.quoteStart=index):character===frame.closer&&(open.pop().span.close=index),index)}function enclosingCloser(spans){const active=[];let next=0;return position=>{for(;next<spans.length&&spans[next].open<position;next+=1){for(;active.length>0&&active.at(-1).close<spans[next].open;)active.pop();active.push(spans[next])}for(;active.length>0&&active.at(-1).close<position;)active.pop();return active.at(-1)}}function insideQuotedRange(span,position){let low=0,high=span.quoted.length-1;for(;low<=high;){const middle=low+high>>1,[start,end]=span.quoted[middle];if(position<start)high=middle-1;else if(position>end)low=middle+1;else return!0}return!1}const VALUE_REFERENCE=/\$[({A-Za-z_]|</u;function*flatMatches(rule,content){const regex=rule.regex;regex.lastIndex=0;const rescan=rescanDepth(rule);let inner;for(const match of content.matchAll(regex))acceptsSecretMatch(rule,match)?yield{index:match.index}:rescan!==void 0&&VALUE_REFERENCE.test(match[1])&&(inner??=new RegExp(regex),yield*keysInsideRejectedValue(rule,inner,content,match,rescan==="deep"))}function rescanDepth(rule){return rule.minimumLiteralLength===void 0?void 0:rule.minimumEntropy===void 0&&rule.literalValue===void 0&&rule.rejectValue===void 0?"deep":"shallow"}function*keysInsideRejectedValue(rule,inner,content,match,deep){const end=match.index+match[0].length;inner.lastIndex=end-match[1].length;let closerAt;for(let found=inner.exec(content);found!==null&&found.index<end;found=inner.exec(content)){if(isParameterName(content,found.index)){inner.lastIndex=found.index+1;continue}closerAt??=enclosingCloser(referenceSpans(content,end-match[1].length,match[1]));const span=closerAt(found.index);span!==void 0&&(INNER_CLOSE_AT.set(found,span.close),span.command&&!insideQuotedRange(span,found.index)&&INNER_SHELL_MATCHES.add(found)),acceptsSecretMatch(rule,found)?yield{index:found.index}:deep&&VALUE_REFERENCE.test(found[1])&&(inner.lastIndex=found.index+found[0].length-found[1].length)}}const compiledSpellings=new Map,LINE_BREAK=/[\r\n\u2028\u2029]/u;function compileSpelling(spelling){const cacheKey=`${spelling.keys}\0${spelling.value}\0${spelling.element===!0}`;let compiled=compiledSpellings.get(cacheKey);return compiled||(compiled={key:new RegExp(String.raw`\b(?:${spelling.keys})(["']?)\s*[:=]\s*`,"gi"),value:new RegExp(spelling.value,"iyd"),...spelling.element?{element:{open:new RegExp(String.raw`<(?:${spelling.keys})(?:\s[^<>]*)?>`,"gi"),close:new RegExp(String.raw`<\/(?:${spelling.keys})\s*>`,"iy"),span:new RegExp(String.raw`<(?!\/?(?:${spelling.keys})\b)[^<>]*>`,"iy")}}:{}},compiledSpellings.set(cacheKey,compiled)),compiled}function scanQuoted(content,start){const quote=content[start];for(let index=start+1;index<content.length;index+=1){const character=content[index];if(character==="\\")index+=1;else if(character===quote)return{end:index+1,terminated:!0}}return{end:content.length,terminated:!1}}function endOfQuoted(content,start){return scanQuoted(content,start).end}function judgeFor(closers,accepts,acceptsMember){return closers.at(-1)==="}"?acceptsMember:accepts}function walkContainer(content,start,accepts,acceptsMember=accepts){const closers=[];let expectKey=!1;for(let index=start;index<content.length;index+=1){const character=content[index];switch(character){case"[":case"{":closers.push(character==="["?"]":"}"),expectKey=character==="{";break;case"]":case"}":if(closers.pop()!==character||closers.length===0)return{found:!1,end:index+1};expectKey=!1;break;case",":expectKey=closers.at(-1)==="}";break;case":":expectKey=!1;break;case'"':case"'":if(!expectKey&&judgeFor(closers,accepts,acceptsMember)(index))return{found:!0,end:index};index=endOfQuoted(content,index)-1;break;default:break}}return{found:!1,end:content.length}}const ESCAPE_SEQUENCE=/\\(?: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,SIMPLE_ESCAPES={n:`
3
3
  `,r:"\r",t:" ",b:"\b",f:"\f",v:"\v"};function decodeQuotedLiteral(literal,terminated){const quote=literal[0],body=literal.slice(1,terminated?-1:void 0).replaceAll(ESCAPE_SEQUENCE,sequence=>{const kind=sequence[1];if((kind==="u"||kind==="x")&&sequence.length>2)return String.fromCharCode(Number.parseInt(sequence.slice(2),16));if(/^[0-7]$/u.test(kind))return String.fromCharCode(Number.parseInt(sequence.slice(1),8));if(kind==="U"&&sequence.length===10){const codePoint=Number.parseInt(sequence.slice(2),16);return codePoint<=1114111?String.fromCodePoint(codePoint):"\uFFFD"}return SIMPLE_ESCAPES[kind]??kind}),neutral=body.replaceAll(quote,quote==='"'?"'":'"').replaceAll(/[\r\n\u2028\u2029]/gu," "),close=terminated?quote:"";return{reading:`${quote}${neutral}${close}`,...literalBody(`${quote}${body}${close}`,terminated)}}function literalBody(original,terminated){return{original,bodyStart:1,bodyEnd:original.length-(terminated?1:0)}}const MAX_KEY_PREFIX=64;function keyShape(content,index,quote){const previous=content[index-1];if(!quote)return previous!==void 0&&/[\p{L}\p{N}_.-]/u.test(previous)?"prefixed":"exact";if(previous===quote)return"exact";const floor=Math.max(0,index-MAX_KEY_PREFIX);for(let cursor=index-1;cursor>=floor;cursor-=1){const character=content[cursor];if(character===quote)return"prefixed";if(character===`
4
4
  `||character==="\r"||character==='"'||character==="'")return"malformed"}return"malformed"}function createValueJudge(rule,value,content,alwaysDecode=!1){const valueMatch=(text,at,decoded)=>{value.lastIndex=at;const match=value.exec(text);if(match===null||LINE_BREAK.test(match[0]))return null;const span=match.indices?.[1];return decoded!==void 0&&span!==void 0&&(match[1]=decoded.original.slice(Math.max(span[0],decoded.bodyStart),Math.min(span[1],decoded.bodyEnd)),DECODED_DATA_MATCHES.add(match)),acceptsSecretMatch(rule,match)?match:null},escapedMatches=at=>{if(content[at]!=='"'&&content[at]!=="'")return;const{end,terminated}=scanQuoted(content,at),literal=content.slice(at,end);if(!alwaysDecode&&!literal.includes("\\"))return;if(LINE_BREAK.test(literal))return[];const decoded=decodeQuotedLiteral(literal,terminated);return(content[at]==="'"?[decoded,{reading:literal,...literalBody(literal,terminated)}]:[decoded]).map(reading=>valueMatch(reading.reading,0,reading)).filter(match=>match!==null)},valuesAt=at=>{const escaped=escapedMatches(at);if(escaped!==void 0)return escaped;const match=valueMatch(content,at);return match===null?[]:[match]};return{direct:at=>valueMatch(content,at)!==null,escaped:at=>(escapedMatches(at)?.length??0)>0,accepts:compact=>at=>valuesAt(at).some(match=>!(compact&&/\s/u.test(compactReading(rule,match))))}}function compactReading(rule,match){return rule.minimumLiteralLength===void 0?match[0]:judgedLiteral(match)}const DECODED_DATA_MATCHES=new WeakSet;function judgedLiteral(match){const word=INNER_SHELL_MATCHES.has(match)&&!isQuote(captureOpener(match))?shellWordPrefix(match[1]):void 0,text=word??match[1],variables=word!==void 0||wordComplete(match);return DECODED_DATA_MATCHES.has(match)||isQuote(captureOpener(match))?expandRuntimeReferences(text,variables):literalAfterReferences(text,variables)}function shellWordPrefix(text){for(let index=0;index<text.length;index+=1){const character=text[index];if(character==="'"||character==='"')index=quotedSpanEnd(text,index);else if(character==="$"&&(text[index+1]==="{"||text[index+1]==="("))index=Math.max(index,referenceEnd(text,index)-1);else if(/[|&;<>]/u.test(character))return text.slice(0,index)}}const STRUCTURE_RUN=/^[;,)}\]]{0,64}/u;function wordComplete(match){const input=match.input,end=match.index+match[0].length,closed=isQuote(captureOpener(match))&&isQuote(input[end])?end+1:isQuote(match[0].at(-1))?end:-1,start=closed===-1?end:closed,structure=STRUCTURE_RUN.exec(input.slice(start,start+WORD_END_BOUND))[0].length,after=start+structure;if(after===input.length||/\s/u.test(input[after])||INNER_CLOSE_AT.get(match)===start||INNER_SHELL_MATCHES.has(match)&&/[|&;<>]/u.test(input[start]))return!0;if(closed===-1||structure===0)return!1;const context=structuredContext(match,closed===end+1),next=input.slice(after,after+40),closedContainer=/[}\]]/u.test(input.slice(start,after));return context!==void 0&&(NEXT_MEMBER.test(next)||(context==="element"||closedContainer)&&BARE_SCALAR_MEMBER.test(next))}function structuredContext(match,openerOutsideCapture){const input=match.input,valueStart=match.index+match[0].length-match[1].length-(openerOutsideCapture?1:0),before=input.slice(Math.max(0,valueStart-STRUCTURED_LOOK_BACK),valueStart);return ARRAY_ELEMENT_BEFORE.test(before)?"element":QUOTED_KEY_BEFORE.test(before)?"key":void 0}const STRUCTURED_LOOK_BACK=512,QUOTED_KEY_BEFORE=/[{,]\s*(["'])[^"'\r\n]{1,256}\1\s*[:=]\s*$/u,ARRAY_ELEMENT_BEFORE=/[[,]\s*$/u,NEXT_MEMBER=/^(?:["'`]|[{[](?:[\s"'`{[\]}]|$|(?:-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null)[\s,\]}]))/u,BARE_SCALAR_MEMBER=/^(?:-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null)[\s,\]}]/u,WORD_END_BOUND=64,CALL_AFTER=/^\s{0,16}\(/u,ASSIGNED_BEFORE=/(?<![=!<>])=[ \t]{0,16}$/u;function captureOpener(match){return match.input[match.index+match[0].length-match[1].length-1]}function isQuote(character){return character==='"'||character==="'"}const SPELLING_SENSITIVE=/[$<"']/u;function isCodeAfterReference(match){if(DECODED_DATA_MATCHES.has(match)||isQuote(captureOpener(match))||!/^[$<]/u.test(match[1]))return!1;const end=match.index+match[0].length,valueStart=end-match[1].length,after=match.input.slice(end,end+18);if(match[1][0]==="<"&&(isTypeAssertion(match[1])||ASSIGNED_BEFORE.test(match.input.slice(Math.max(0,valueStart-18),valueStart))||EXPRESSION_AFTER.test(after)))return!0;const lead=leadingReferencesEnd(match[1]),operator=match[1][lead]==="!"?match[1][lead+1]:match[1][lead];return CODE_OPERATOR.test(operator??"")||CALL_AFTER.test(after)}function leadingReferencesEnd(text){let index=0;for(let next=referenceEnd(text,index);next!==-1;next=referenceEnd(text,index))index=next;return index}function referenceEnd(text,start){const opener=text[start];if(opener==="<")return angleSpanEnd(text,start);if(opener!=="$")return-1;const bracket=text[start+1];if(bracket==="{"||bracket==="(")return bracketedEnd(text,start+1,bracket);VARIABLE_REFERENCE.lastIndex=start;const variable=VARIABLE_REFERENCE.exec(text)?.[0];return variable===void 0?-1:start+variable.length}function angleSpanEnd(text,start){const close=text.indexOf(">",start+1),reopen=text.indexOf("<",start+1);return close!==-1&&(reopen===-1||close<reopen)?close+1:-1}function bracketedEnd(text,start,bracket){const closer=bracket==="{"?"}":")";let depth=0;for(let index=start;index<text.length;index+=1){const character=text[index];if(character==="\\")index+=1;else if(character==="'"||character==='"')index=quotedSpanEnd(text,index);else if(character===bracket)depth+=1;else if(character===closer&&--depth===0)return index+1}return-1}function quotedSpanEnd(text,start){const quote=text[start];for(let index=start+1;index<text.length;index+=1){if(text[index]===quote)return index;quote==='"'&&text[index]==="\\"&&(index+=1)}return text.length}const TYPE_TEXT=/^[\w$.[\]|&,{}:;?]+$/u,LITERAL_TYPE=/^(?:"[^"]*"|'[^']*'|-?\d+(?:\.\d+)?)(?:\|(?:"[^"]*"|'[^']*'|-?\d+(?:\.\d+)?|[A-Za-z_$][\w$.]*))*$/u,PRIMITIVE_TYPE=/\b(?:string|number|boolean|bigint|symbol|any|unknown|object|never|void|undefined|null)\b/u;function isTypeAssertion(value){const type=value.slice(1,value.indexOf(">"));return LITERAL_TYPE.test(type)?!0:TYPE_TEXT.test(type)?PRIMITIVE_TYPE.test(type)||/[.|&[{]/u.test(type)||/^[A-Z][\w$]*$/u.test(type)&&(type.length===1||/[a-z]/u.test(type)):!1}const CODE_OPERATOR=/[.+\-*/%=^&]/u,EXPRESSION_AFTER=/^\s{0,16}(?:\?\.|\?\?|\|\||&&|[([])/u;function literalMatches(grammar,literal,code){if(code)return!1;const body=literal.replaceAll('"',"'");return grammar.lastIndex=0,grammar.exec(`"${body}"`)?.[1]===body}function structuredKeyShape(rule,name){if(!rule.structured)return;const content=`${JSON.stringify(name)}:`,key=compileSpelling(rule.structured).key;key.lastIndex=0;for(let match=key.exec(content);match;match=key.exec(content)){if(match.index+match[0].length!==content.length)continue;const shape=keyShape(content,match.index,match[1]);if(shape!=="malformed")return shape}}function acceptsStructuredValue(rule,value,compact){if(!rule.structured)return!1;const content=JSON.stringify(value).replaceAll("\u2028","\\u2028").replaceAll("\u2029","\\u2029");return ruleReadings(rule).some(reading=>createValueJudge(reading,compileSpelling(reading.structured).value,content,!0).accepts(compact)(0))}function*elementMatches(element,content,judge){const open=new RegExp(element.open);for(let match=open.exec(content);match;match=open.exec(content)){const bodyStart=match.index+match[0].length,body=elementBodyEnd(element,content,bodyStart);if(body===void 0){open.lastIndex=match.index+1;continue}judge(content.slice(bodyStart,body.start).trim())&&(yield{index:match.index}),open.lastIndex=body.end}}function elementBodyEnd(element,content,start){for(let index=content.indexOf("<",start);index!==-1;){element.close.lastIndex=index;const close=element.close.exec(content);if(close!==null)return{start:index,end:index+close[0].length};element.span.lastIndex=index;const span=element.span.exec(content);if(span===null)return;index=content.indexOf("<",index+span[0].length)}}function alreadyWalked(walkedEnd,valueStart,compact){return valueStart<walkedEnd.exact||compact&&valueStart<walkedEnd.compact}function scalarFinds(judge,accepts,quote,valueStart){return(quote||judge.escaped(valueStart)&&!judge.direct(valueStart))&&accepts(valueStart)}function*findStructuredSpellingMatches(rule,spelling,content){const compiled=compileSpelling(spelling),judge=createValueJudge(rule,compiled.value,content),key=new RegExp(compiled.key),walkedEnd={exact:0,compact:0};for(let match=key.exec(content);match;match=key.exec(content)){const quote=match[1],shape=keyShape(content,match.index,quote);if(shape==="malformed")continue;const compact=shape==="prefixed",accepts=judge.accepts(compact),valueStart=match.index+match[0].length,opener=content[valueStart];if(opener==="["||opener==="{"){if(alreadyWalked(walkedEnd,valueStart,compact))continue;const walked=walkContainer(content,valueStart,accepts,judge.accepts(!0));walkedEnd[compact?"compact":"exact"]=walked.end,walked.found&&(yield{index:match.index})}else scalarFinds(judge,accepts,quote,valueStart)&&(yield{index:match.index})}compiled.element&&(yield*elementMatches(compiled.element,content,elementValueJudge(rule,spelling,compiled)))}const DEFAULT_ELEMENT_LITERAL_LENGTH=8;function elementValueJudge(rule,spelling,compiled){if(!spelling.elementValue){const minimum=rule.minimumLiteralLength??DEFAULT_ELEMENT_LITERAL_LENGTH;return value=>expandRuntimeReferences(value).length>=minimum}return value=>{const neutral=value.replaceAll('"',"'");compiled.value.lastIndex=0;const match=compiled.value.exec(`"${neutral}"`);return match===null||match[1]!==neutral?!1:(match[1]=value,acceptsSecretMatch(rule,match))}}function isStatementReference(shape,match,value){const end=match.index+match[0].length;return/^[ \t]*;/u.test(match.input.slice(end,end+64))&&!isQuote(captureOpener(match))&&shape.test(value)}function indexOfAngleClose(text,start){for(let index=start+1;index<text.length;index+=1){if(text[index]===">")return index;if(text[index]==="<")return-1}return-1}function appendText(frame,text){frame.raw+=text,frame.literal+=text}function openReference(text,index,frames){const next=text[index+1];if(text[index]!=="$"||next!=="{"&&next!=="(")return-1;const prefix=next==="{"?text.slice(index+2,index+2+defaultedPrefixLength(text,index+2)):"",root=frames[0],opensPiece=frames.length===1&&root.quote!==void 0&&root.literal.length===root.pieceStart;return frames.push({close:next==="{"?"}":")",keep:prefix!=="",raw:`$${next}${prefix}`,literal:"",opensPiece}),index+2+prefix.length}const NAME_START=/[A-Za-z_]/u,NAME_PART=/\w/u,REFERENCE_AFTER_DOLLAR=/[{(A-Za-z_]/u,VARIABLE_REFERENCE=/\$[A-Za-z_]\w*/y,CONSTANT_NAME=/^_*[A-Z][A-Z0-9_]*$/u,BARE_VARIABLE=/^\$[A-Za-z_]\w*$/u,QUOTED_BARE_VARIABLE=/^(["'])\$[A-Za-z_]\w*\1$/u;function variableStep(text,index,frame){VARIABLE_REFERENCE.lastIndex=index;const variable=VARIABLE_REFERENCE.exec(text)?.[0];return variable===void 0?-1:(frame.literal===""&&CONSTANT_NAME.test(variable.slice(1))?frame.raw+=variable:appendText(frame,variable),index+variable.length)}function defaultedPrefixLength(text,start){if(!NAME_START.test(text[start]??""))return 0;let index=start+1;for(;index<text.length&&NAME_PART.test(text[index]);)index+=1;text[index]===":"&&(index+=1);const operator=text[index];return operator==="-"||operator==="="||operator==="+"?index+1-start:0}function closeReference(frames,character){const frame=frames.pop(),parent=frames.at(-1);parent.raw+=`${frame.raw}${character}`,frame.keep&&(parent.literal+=frame.literal)}const PLAIN_RUN=/[^$<"'\\})]+/y,DOUBLE_QUOTE_ESCAPABLE='$`"\\\n';function escapedContribution(next,quote){return next===`
5
5
  `?"":quote==='"'&&!DOUBLE_QUOTE_ESCAPABLE.includes(next)?`\\${next}`:next}function quotedStep(text,index,frame){const character=text[index],quote=frame.quote;if(quote==='"'&&character==="$"&&REFERENCE_AFTER_DOLLAR.test(text[index+1]??""))return-1;let length=1,contributed=character;if(character==="\\"&&quote!=="'"&&index+1<text.length)length=2,contributed=escapedContribution(text[index+1],quote);else if(quote===void 0){if(character!=='"'&&character!=="'")return-1;frame.quote=character,contributed=""}else character===quote&&(frame.quote=void 0,contributed="");return frame.raw+=text.slice(index,index+length),frame.keep&&(frame.literal+=contributed),index+length}function expandStep(text,index,frames,rootQuotesAreSyntax,variables){const innermost=frames.at(-1);PLAIN_RUN.lastIndex=index;const run=PLAIN_RUN.exec(text)?.[0];if(run!==void 0)return appendText(innermost,run),index+run.length;if(frames.length>1){const quoted=quotedStep(text,index,innermost);if(quoted!==-1)return quoted}else if(rootQuotesAreSyntax&&rootQuoteStep(text[index],innermost))return index+1;const opened=openReference(text,index,frames);if(opened!==-1)return opened;const top=frames.at(-1),character=text[index],variable=variables&&character==="$"?variableStep(text,index,top):-1;if(variable!==-1)return variable;if(frames.length>1&&character===top.close)return closeReference(frames,character),index+1;const angleClose=character==="<"?indexOfAngleClose(text,index):-1;return angleClose!==-1?(top.raw+=text.slice(index,angleClose+1),angleClose+1):(appendText(top,character),index+1)}function rootQuoteStep(character,root){return character!=='"'&&character!=="'"?!1:root.quote===void 0?(root.quote=character,root.pieceStart=root.literal.length,!0):character!==root.quote?!1:(root.quote=void 0,!0)}function expandWords(text,rootQuotesAreSyntax,variables){if(variables&&(BARE_VARIABLE.test(text)||rootQuotesAreSyntax&&QUOTED_BARE_VARIABLE.test(text)))return"";const root={close:"}",keep:!0,raw:"",literal:""},frames=[root];for(let index=0;index<text.length;)index=expandStep(text,index,frames,rootQuotesAreSyntax,variables);for(let depth=frames.length-1;depth>0;depth-=1){const frame=frames[depth],parent=frames[depth-1];parent.raw+=frame.raw,rootQuotesAreSyntax&&depth===1&&frame.opensPiece===!0||(parent.literal+=frame.raw)}return root.literal}function expandRuntimeReferences(text,variables=!0){return expandWords(text,!1,variables)}function literalAfterReferences(value,variables=!0){return expandWords(value,!0,variables)}function acceptsSecretMatch(rule,match){const value=rule.minimumLiteralLength===void 0?match[1]:judgedLiteral(match);if(rule.minimumLiteralLength!==void 0&&value.length<rule.minimumLiteralLength||rule.literalValue&&SPELLING_SENSITIVE.test(match[1])&&!literalMatches(rule.literalValue,value,isCodeAfterReference(match))||rule.rejectValue?.test(value)===!0||rule.rejectStatementReference&&isStatementReference(rule.rejectStatementReference,match,value))return!1;if(rule.minimumEntropy===void 0)return!0;const characters=[...value],counts=new Map;for(const character of characters)counts.set(character,(counts.get(character)??0)+1);let entropy=0;for(const count of counts.values()){const probability=count/characters.length;entropy-=probability*Math.log2(probability)}return entropy>=rule.minimumEntropy}const _testOnly={leadingReferencesEnd};export{PRIVATE_HOME_PATH_PATTERN,SECRET_RULES,_testOnly,acceptsSecretMatch,acceptsStructuredValue,expandRuntimeReferences,findPrivateHomePathMatches,findSecretRuleMatches,literalAfterReferences,structuredKeyShape};
@@ -26,6 +26,15 @@ export declare function readCompactionMarker(text:string):number|undefined;
26
26
  * next call, so compaction never shortens it (GH-1710).
27
27
  */
28
28
  export declare function isContinuationTokenKey(key:string):boolean;
29
+ /**
30
+ * Whether an envelope key of a read surface holds tracker item documents: the
31
+ * item `get` returns, or the rows of a `list` or `search` page. An item's
32
+ * fields are content, not continuation tokens, so a custom field named like
33
+ * one (`next_cursor`, `sync_cursor`) compacts like any other string
34
+ * (GH-1754). Any other surface, an extension's included, keeps the exemption
35
+ * for every key: its rows may carry genuine tokens.
36
+ */
37
+ export declare function isTrackerItemDocumentKey(surface:string|undefined,key:string):boolean;
29
38
  /**
30
39
  * Whether a cursor argument carries an ellipsis, which no encoder emits: the
31
40
  * caller pasted a value a compacted read shortened (GH-1710).
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="21f779fe-fa2c-50d1-893d-8c6d47fbc56a")}catch{}})();function normalizeLowercaseWhitespace(value){return value.trim().toLowerCase().replace(/\s+/g," ")}function unicodeSafePrefix(value,end){const prefix=value.slice(0,end),last=prefix.charCodeAt(prefix.length-1),next=value.charCodeAt(prefix.length);return last>=55296&&last<=56319&&next>=56320&&next<=57343?prefix.slice(0,-1):prefix}const COMPACTED_STRING_LENGTH=240,COMPACTION_MARKER_PATTERN=/\u2026\[\+([1-9]\d*) chars\]$/u;function compactExplanatoryString(value){if(value.length<=COMPACTED_STRING_LENGTH)return value;const marker=COMPACTION_MARKER_PATTERN.exec(value);if(marker!==null&&marker.index<=COMPACTED_STRING_LENGTH)return value;const prefix=unicodeSafePrefix(value,COMPACTED_STRING_LENGTH);return`${prefix}\u2026[+${value.length-prefix.length} chars]`}function readCompactionMarker(text){const match=COMPACTION_MARKER_PATTERN.exec(text.trimEnd());return match?Number(match[1]):void 0}function isContinuationTokenKey(key){return key==="cursor"||key.endsWith("_cursor")}function isCompactedCursorArgument(value){return value.includes("\u2026")}function tokenizeAlphaNumeric(value){return normalizeLowercaseWhitespace(value).split(/[^a-z0-9]+/).filter(token=>token.length>0)}function jaccardSimilarity(leftTokens,rightTokens){if(leftTokens.length===0&&rightTokens.length===0)return 1;if(leftTokens.length===0||rightTokens.length===0)return 0;const leftSet=new Set(leftTokens),rightSet=new Set(rightTokens);let intersection=0;for(const token of leftSet)rightSet.has(token)&&(intersection+=1);const union=new Set([...leftSet,...rightSet]).size;return intersection/union}export{COMPACTED_STRING_LENGTH,compactExplanatoryString,isCompactedCursorArgument,isContinuationTokenKey,jaccardSimilarity,normalizeLowercaseWhitespace,readCompactionMarker,tokenizeAlphaNumeric,unicodeSafePrefix};
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="f74cf2ed-6219-57c6-98a3-4b4c7496a17c")}catch{}})();function normalizeLowercaseWhitespace(value){return value.trim().toLowerCase().replace(/\s+/g," ")}function unicodeSafePrefix(value,end){const prefix=value.slice(0,end),last=prefix.charCodeAt(prefix.length-1),next=value.charCodeAt(prefix.length);return last>=55296&&last<=56319&&next>=56320&&next<=57343?prefix.slice(0,-1):prefix}const COMPACTED_STRING_LENGTH=240,COMPACTION_MARKER_PATTERN=/\u2026\[\+([1-9]\d*) chars\]$/u;function compactExplanatoryString(value){if(value.length<=COMPACTED_STRING_LENGTH)return value;const marker=COMPACTION_MARKER_PATTERN.exec(value);if(marker!==null&&marker.index<=COMPACTED_STRING_LENGTH)return value;const prefix=unicodeSafePrefix(value,COMPACTED_STRING_LENGTH);return`${prefix}\u2026[+${value.length-prefix.length} chars]`}function readCompactionMarker(text){const match=COMPACTION_MARKER_PATTERN.exec(text.trimEnd());return match?Number(match[1]):void 0}function isContinuationTokenKey(key){return key==="cursor"||key.endsWith("_cursor")}const TRACKER_ITEM_READ_SURFACES=new Set(["get","list","search"]);function isTrackerItemDocumentKey(surface,key){return(key==="item"||key==="items")&&surface!==void 0&&TRACKER_ITEM_READ_SURFACES.has(surface)}function isCompactedCursorArgument(value){return value.includes("\u2026")}function tokenizeAlphaNumeric(value){return normalizeLowercaseWhitespace(value).split(/[^a-z0-9]+/).filter(token=>token.length>0)}function jaccardSimilarity(leftTokens,rightTokens){if(leftTokens.length===0&&rightTokens.length===0)return 1;if(leftTokens.length===0||rightTokens.length===0)return 0;const leftSet=new Set(leftTokens),rightSet=new Set(rightTokens);let intersection=0;for(const token of leftSet)rightSet.has(token)&&(intersection+=1);const union=new Set([...leftSet,...rightSet]).size;return intersection/union}export{COMPACTED_STRING_LENGTH,compactExplanatoryString,isCompactedCursorArgument,isContinuationTokenKey,isTrackerItemDocumentKey,jaccardSimilarity,normalizeLowercaseWhitespace,readCompactionMarker,tokenizeAlphaNumeric,unicodeSafePrefix};
2
2
  //# sourceMappingURL=text-normalization.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="100048de-2349-5062-b6c2-7176277ec38d")}catch{}})();import{AsyncLocalStorage}from"node:async_hooks";import{attachExtensionReadOutputRows}from"./read-output/extension.js";import{renderPmCommand}from"./command-line.js";import{attachOutputOmissionReceipt}from"./output-projection.js";import{encodeQueryCursor}from"./pagination.js";import{applyReadOutputDimensions,isReadResultOmittedForBudget,stabilizeReadOutputReceiptEstimates}from"./read-output-contracts.js";import{estimateReadOutputTokens,MAX_ESTIMATE_ITERATIONS,readOutputMeasurementFormat,resolveReadOutputRecoveryBudget}from"./read-output-budget.js";import{propagateContextUsageServingReceipt}from"./context-usage.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{compactExplanatoryString,isContinuationTokenKey}from"../core/shared/text-normalization.js";const CONTEXT_INTENT_LIMIT_OVERRIDE_WARNING="limit_overridden_by_intent",PM_CONTEXT_INTENT_CONTRACTS=Object.freeze([{command:"context",intent:"orient",description:"Bounded active hierarchy, ownership, blockers, and recent progress.",included_field_groups:["summary","focus","hierarchy","blockers","activity"],token_budget:3e3,source:"core"},{command:"context",intent:"handoff",description:"Active ownership, evidence, decisions, and immediate continuation context.",included_field_groups:["summary","focus","in_progress","decisions","activity"],token_budget:2200,source:"core"},{command:"get",intent:"inspect",description:"Standard-depth item metadata, relationships, evidence, and lifecycle state.",included_field_groups:["item","children","claim_state","linked"],token_budget:3200,source:"core"},{command:"list",intent:"triage",description:"A budget-derived page of compact governance, ownership, priority, and blocker rows for triage.",included_field_groups:["identity","governance","ownership","dependencies"],token_budget:3200,source:"core"},{command:"next",intent:"execute",description:"The highest-ranked actionable work with concise ranking evidence.",included_field_groups:["recommended"],token_budget:1200,source:"core"},{command:"search",intent:"discover",description:"A budget-derived page of ranked canonical lineage candidates with compact match evidence.",included_field_groups:["identity","status","lineage","match"],token_budget:1800,source:"core"}]),activeContextIntentContracts=new AsyncLocalStorage;function getActiveContextIntentContracts(){return activeContextIntentContracts.getStore()??PM_CONTEXT_INTENT_CONTRACTS}function runWithContextIntentContracts(layers,run){return activeContextIntentContracts.run(composeContextIntentContracts(layers.workspaceContracts,layers.packageContracts),run)}function normalizeContextIntentDeclaration(declaration,source){const command=declaration.command.trim().toLowerCase(),intent=declaration.intent.trim().toLowerCase(),key=`${command}:${intent}`;if(!/^[a-z0-9][a-z0-9-]*$/.test(command)||!/^[a-z0-9][a-z0-9-]*$/.test(intent))throw new TypeError(`Invalid context intent command or name: ${key}`);if(declaration.description.trim().length===0)throw new TypeError(`Context intent ${key} requires a non-empty description`);if(!Number.isSafeInteger(declaration.token_budget)||declaration.token_budget<=0)throw new TypeError(`Context intent ${key} requires a positive integer token_budget`);const includedFieldGroups=[...new Set(declaration.included_field_groups.map(field=>field.trim()).filter(Boolean))];if(includedFieldGroups.length===0)throw new TypeError(`Context intent ${key} requires included_field_groups`);return{command,intent,description:declaration.description.trim(),included_field_groups:includedFieldGroups,token_budget:declaration.token_budget,source}}function composeContextIntentContracts(workspaceContracts=[],packageContracts=[]){const layers=[{source:"core",contracts:PM_CONTEXT_INTENT_CONTRACTS,allowOverride:!1},{source:"package",contracts:packageContracts,allowOverride:!1},{source:"workspace",contracts:workspaceContracts,allowOverride:!0}],composed=new Map,keysSeenWithinLayer=new Set;for(const layer of layers){keysSeenWithinLayer.clear();for(const declaration of layer.contracts){const normalized=normalizeContextIntentDeclaration(declaration,layer.source),key=`${normalized.command}:${normalized.intent}`;if(keysSeenWithinLayer.has(key))throw new TypeError(`Duplicate context intent declaration: ${key}`);if(keysSeenWithinLayer.add(key),!layer.allowOverride&&composed.has(key))throw new TypeError(`Duplicate context intent declaration: ${key}`);composed.set(key,normalized)}}return[...composed.values()].sort((left,right)=>left.command.localeCompare(right.command)||left.intent.localeCompare(right.intent))}function resolveContextIntentContract(command,intent,contracts=getActiveContextIntentContracts(),positionalArguments=[]){const normalizedCommand=command.trim().toLowerCase(),normalizedIntent=intent.trim().toLowerCase(),exact=contracts.find(entry=>entry.command===normalizedCommand&&entry.intent===normalizedIntent);if(exact)return{...exact,source:exact.source??"core"};const candidates=contracts.filter(entry=>entry.command===normalizedCommand).map(entry=>entry.intent);if(candidates.length===0)return;const suggestion=candidates.map(candidate=>{const rows=Array.from({length:normalizedIntent.length+1},(_,index)=>index);for(let candidateIndex=1;candidateIndex<=candidate.length;candidateIndex+=1){let previous=rows[0];rows[0]=candidateIndex;for(let intentIndex=1;intentIndex<=normalizedIntent.length;intentIndex+=1){const prior=rows[intentIndex];rows[intentIndex]=Math.min(rows[intentIndex]+1,rows[intentIndex-1]+1,previous+(candidate[candidateIndex-1]===normalizedIntent[intentIndex-1]?0:1)),previous=prior}}return{candidate,distance:rows[normalizedIntent.length]}}).sort((left,right)=>left.distance-right.distance||left.candidate.localeCompare(right.candidate))[0].candidate,attemptedArguments=[normalizedCommand,...positionalArguments,"--for",normalizedIntent],suggestedRetryArguments=[normalizedCommand,...positionalArguments,"--for",suggestion],suggestedCommand=renderPmCommand(suggestedRetryArguments);throw new PmCliError(`Unknown context intent "${normalizedIntent}" for ${normalizedCommand}. Did you mean "${suggestion}"?`,EXIT_CODE.USAGE,{code:"unknown_context_intent",reason:"unknown_intent",field:"for",flag:"--for",value:normalizedIntent,required:`Use a declared ${normalizedCommand} intent.`,why:"Intent names are command-local contracts and cannot be inferred from output section names.",nextSteps:[suggestedCommand],recovery:{recovery_mode:"compact",attempted_command:renderPmCommand(attemptedArguments),allowed_values:[...candidates].sort(),suggested_retry:suggestedCommand,suggested_retry_args:suggestedRetryArguments}})}function applyIntentRowLimit(projected,budgetDerivedLimit){const requestedLimit=parsePositiveIntentTokenBudget(projected.limit),effectiveLimit=String(requestedLimit===void 0?budgetDerivedLimit:Math.min(requestedLimit,budgetDerivedLimit));return(projected.limit===void 0||requestedLimit!==void 0)&&(projected.limit=effectiveLimit),effectiveLimit}const CONTEXT_INTENT_DEFAULT_APPLIERS={context:(projected,contract,explicitTokenBudget,canonical)=>{projected.section===void 0&&projected.depth===void 0&&(projected.section=contract.intent==="handoff"?["activity","progress","blockers"]:["hierarchy","blockers","activity"]),projected.depth===void 0&&(projected.depth=contract.intent==="handoff"?"deep":"standard");const tokenBudget=resolveEffectiveIntentTokenBudget(canonical,projected.tokenBudget,contract.token_budget),budgetDerivedLimit=resolveIntentRowBudget("context",contract.intent,tokenBudget,explicitTokenBudget),derivedLimit=applyIntentRowLimit(projected,budgetDerivedLimit);projected.activityLimit===void 0&&(projected.activityLimit=derivedLimit)},get:projected=>{projected.depth===void 0&&projected.fields===void 0&&(projected.depth="standard")},list:(projected,contract,explicitTokenBudget,canonical)=>{projected.brief===void 0&&projected.compact===void 0&&projected.full===void 0&&projected.fields===void 0&&(projected.fields="id,title,status,type,priority,parent,assignee,risk,blocked_by");const tokenBudget=resolveEffectiveIntentTokenBudget(canonical,projected.tokenBudget,contract.token_budget),budgetDerivedLimit=resolveIntentRowBudget("list",contract.intent,tokenBudget,explicitTokenBudget);applyIntentRowLimit(projected,budgetDerivedLimit)},next:projected=>{projected.readyOnly===void 0&&(projected.readyOnly=!0)},search:(projected,contract,explicitTokenBudget,canonical)=>{projected.compact===void 0&&projected.full===void 0&&projected.fields===void 0&&(projected.compact=!0);const tokenBudget=resolveEffectiveIntentTokenBudget(canonical,projected.tokenBudget,contract.token_budget),budgetDerivedLimit=resolveIntentRowBudget("search",contract.intent,tokenBudget,explicitTokenBudget);applyIntentRowLimit(projected,budgetDerivedLimit)}};function applyContextIntentProjection(command,options,positionalArguments=[]){const tokenBudget=options.tokenBudget??options.token_budget;if(typeof options.for!="string"){if(tokenBudget!==void 0&&(command==="get"||command==="list"||command==="search"))throw new PmCliError("--token-budget requires a declared context intent selected with --for",EXIT_CODE.USAGE,{code:"missing_required_option",field:"for",required:"Select a context intent with --for when setting --token-budget.",why:"A token-budget override has no projection contract to constrain without a selected intent.",nextSteps:["Retry with --for <intent> --token-budget <n>, or omit --token-budget."]});if(options.tokenBudget!==void 0||options.token_budget===void 0)return options;const projected2={...options,tokenBudget};return delete projected2.token_budget,projected2}const contract=resolveContextIntentContract(command,options.for,void 0,positionalArguments),canonical=canonicalIntentOutputBudget(options),explicitTokenBudget=parsePositiveIntentTokenBudget(tokenBudget)!==void 0||typeof canonical=="number",projected={...options};return projected.tokenBudget===void 0&&tokenBudget!==void 0&&(projected.tokenBudget=tokenBudget),delete projected.token_budget,typeof canonical=="number"?projected.tokenBudget=String(canonical):projected.tokenBudget===void 0&&(projected.tokenBudget=String(contract.token_budget)),CONTEXT_INTENT_DEFAULT_APPLIERS[command](projected,contract,explicitTokenBudget,canonical),projected}const CONTEXT_INTENT_DEGRADATIONS={context:"bounded_sections",get:"standard_item",list:"bounded_fields_and_rows",next:"bounded_ranked_rows",search:"bounded_ranked_rows"},MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET=256;function compactContextIntentValue(value){return Array.isArray(value)?value.map(compactContextIntentValue):value!==null&&typeof value=="object"?Object.fromEntries(Object.entries(value).map(([key,entry])=>[key,typeof entry=="string"&&isContinuationTokenKey(key)?entry:compactContextIntentValue(entry)])):typeof value=="string"?compactExplanatoryString(value):value}function parsePositiveIntentTokenBudget(value){const parsed=typeof value=="number"?value:typeof value=="string"&&/^\d+$/u.test(value.trim())?Number(value):Number.NaN;return Number.isSafeInteger(parsed)&&parsed>0?parsed:void 0}function canonicalIntentOutputBudget(options){const value=options.outputBudget??options.output_budget;return value==="unbounded"?value:parsePositiveIntentTokenBudget(value)}function intentBudgetFlag(options){return canonicalIntentOutputBudget(options)===void 0?"--token-budget":"--output-budget"}function resolveEffectiveIntentTokenBudget(canonical,legacy,declaredBudget){return typeof canonical=="number"?canonical:resolveIntentTokenBudget(legacy,declaredBudget)}function resolveIntentTokenBudget(value,declaredBudget){const parsed=parsePositiveIntentTokenBudget(value);if(parsed===void 0)return declaredBudget;if(parsed<MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET)throw new PmCliError(`Context intent token budget must be at least ${MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET}`,EXIT_CODE.USAGE,{code:"invalid_argument_value",reason:"below_minimum",field:"tokenBudget",value:String(value),required:`Use an integer token budget of at least ${MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET}.`,why:"Smaller ceilings cannot contain the minimum machine-readable intent receipt.",nextSteps:[`Retry with --token-budget ${MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET} or omit the override.`]});return parsed}function resolveIntentRowCost(command,intent){return command==="context"?command==="context"&&intent==="orient"?{overhead:1200,rowCost:600}:{overhead:800,rowCost:500}:{overhead:command==="list"?520:480,rowCost:16}}function resolveIntentRowBudget(command,intent,tokenBudget,explicitTokenBudget){if(command==="get"||command==="next")return;const{overhead,rowCost}=resolveIntentRowCost(command,intent),calculatedLimit=Math.max(command==="context"?1:2,Math.floor((tokenBudget-overhead)/rowCost));return explicitTokenBudget?calculatedLimit:Math.min(command==="context"?20:100,calculatedLimit)}function updateContextIntentEstimate(projected,receipt,options){const format=readOutputMeasurementFormat(options),rowContractDelivered=options.outputRowContract===!0||options.output_row_contract===!0;let measuredTokens=receipt.estimated_tokens,largestTokens=measuredTokens;for(let iteration=0;iteration<MAX_ESTIMATE_ITERATIONS;iteration+=1){receipt.estimated_tokens=measuredTokens;const nextMeasurement=estimateReadOutputTokens(rowContractDelivered||!Object.hasOwn(projected,"row_contract")?projected:Object.fromEntries(Object.entries(projected).filter(([key])=>key!=="row_contract")),format);if(nextMeasurement===measuredTokens)return;measuredTokens=nextMeasurement,largestTokens=Math.max(largestTokens,measuredTokens)}receipt.estimated_tokens=largestTokens}const CONTEXT_INTENT_ROW_KEYS={context:["high_level","low_level","blocked_fallback","recently_created","unparented","hierarchy","activity","blockers"],get:["children"],list:["items"],next:["ready","decision_needed","gate_needed","containers","blocked","held_by_others"],search:["items"]};function decodeContextIntentCursor(cursor){try{const parsed=JSON.parse(Buffer.from(cursor,"base64url").toString("utf8"));return typeof parsed.fingerprint!="string"||!Number.isSafeInteger(parsed.after_index)?void 0:{fingerprint:parsed.fingerprint,after_index:parsed.after_index,...typeof parsed.snapshot=="string"?{snapshot:parsed.snapshot}:{}}}catch{return}}function contextIntentRowId(row){if(row===null||typeof row!="object")return;if(typeof row.id=="string")return row.id;const nestedId=row.item?.id;return typeof nestedId=="string"?nestedId:void 0}function shrinkContextIntentRowsToBudget(projected,receipt,rows,options){let compacted=!1;for(;;){if(updateContextIntentEstimate(projected,receipt,options),receipt.estimated_tokens<=receipt.token_budget||rows.length<=1)return compacted;const rowBytes=Buffer.byteLength(JSON.stringify(rows),"utf8"),excessBytes=(receipt.estimated_tokens-receipt.token_budget)*4;rows.splice(-Math.min(rows.length-1,Math.max(1,Math.ceil(excessBytes/Math.max(1,Math.ceil(rowBytes/rows.length)))))),compacted=!0}}function compactPaginatedContextIntentRows(projected,receipt,options){const rows=projected.items,cursorContinuesExistingPage=typeof projected.next_cursor=="string",cursorSource=cursorContinuesExistingPage?projected.next_cursor:options.after;if(!Array.isArray(rows)||typeof cursorSource!="string")return!1;const cursorEnvelope=decodeContextIntentCursor(cursorSource);if(cursorEnvelope===void 0)return!1;const originalRowCount=rows.length,originalRows=[...rows];let compacted=!1;for(;;){if(compacted=shrinkContextIntentRowsToBudget(projected,receipt,rows,options)||compacted,!compacted)return!1;const lastId=contextIntentRowId(rows.at(-1));if(lastId===void 0)return rows.splice(0,rows.length,...originalRows),updateContextIntentEstimate(projected,receipt,options),!1;if(projected.next_cursor=encodeQueryCursor(cursorEnvelope.fingerprint,lastId,cursorContinuesExistingPage?cursorEnvelope.after_index-(originalRowCount-rows.length):cursorEnvelope.after_index+rows.length,cursorEnvelope.snapshot),updateContextIntentEstimate(projected,receipt,options),receipt.estimated_tokens<=receipt.token_budget||rows.length<=1)break}return typeof projected.count=="number"&&(projected.count=rows.length),typeof projected.applied_limit=="number"&&(projected.applied_limit=rows.length),!0}function compactContextIntentRows(command,projected,receipt,options){if(command==="list"||command==="search")return compactPaginatedContextIntentRows(projected,receipt,options);if(command!=="next"||typeof projected.next_cursor=="string")return!1;let compacted=!1;for(;;){if(updateContextIntentEstimate(projected,receipt,options),receipt.estimated_tokens<=receipt.token_budget)return compacted;const candidate=CONTEXT_INTENT_ROW_KEYS[command].map(key=>({key,rows:Array.isArray(projected[key])?projected[key]:[]})).filter(({rows})=>rows.length>0).sort((left,right)=>right.rows.length-left.rows.length||left.key.localeCompare(right.key))[0];if(candidate===void 0)return compacted;const retainedTotal=CONTEXT_INTENT_ROW_KEYS[command].reduce((total,key)=>total+(Array.isArray(projected[key])?projected[key].length:0),0);if(retainedTotal<=1)return compacted;const removableRows=Math.min(candidate.rows.length,retainedTotal-1),candidateBytes=Buffer.byteLength(JSON.stringify(candidate.rows),"utf8"),estimatedBytesPerRow=Math.max(1,Math.ceil(candidateBytes/candidate.rows.length)),excessBytes=(receipt.estimated_tokens-receipt.token_budget)*4,removalCount=Math.min(removableRows,Math.max(1,Math.ceil(excessBytes/estimatedBytesPerRow)));candidate.rows.splice(-removalCount,removalCount),compacted=!0}}function attachContextIntentReceipt(command,options,result){if(typeof options.for!="string")return result;const normalizedCommand=command.startsWith("list-")?"list":command;if(!(normalizedCommand in CONTEXT_INTENT_DEFAULT_APPLIERS))return result;const builtInCommand=normalizedCommand,contract=resolveContextIntentContract(builtInCommand,options.for),canonicalBudget=canonicalIntentOutputBudget(options),effectiveTokenBudget=resolveEffectiveIntentTokenBudget(canonicalBudget,options.tokenBudget??options.token_budget,contract.token_budget),receipt={command:builtInCommand,intent:contract.intent,source:contract.source,included_field_groups:[...contract.included_field_groups],token_budget:effectiveTokenBudget,declared_token_budget:contract.token_budget,token_budget_override:effectiveTokenBudget-contract.token_budget,estimated_tokens:0,within_budget:!0,degradation:CONTEXT_INTENT_DEGRADATIONS[builtInCommand],declaration_feasible:!0,result_omitted:!1},resultWithDiagnostics={...result},budgetDerivedLimit=resolveIntentRowBudget(builtInCommand,contract.intent,receipt.token_budget,parsePositiveIntentTokenBudget(options.tokenBudget??options.token_budget)!==void 0||typeof canonicalBudget=="number");if(budgetDerivedLimit!==void 0){const effectiveLimit=parsePositiveIntentTokenBudget(options.limit),explicitLimitBinds=effectiveLimit!==void 0&&effectiveLimit<budgetDerivedLimit;receipt.budget_derived_limit=budgetDerivedLimit,receipt.binding_constraint=explicitLimitBinds?"explicit_limit":"token_budget",receipt.limit_reason=explicitLimitBinds?"The caller supplied a smaller row limit than the budget-derived ceiling.":"The selected intent token budget constrains the effective row ceiling.",resultWithDiagnostics.budget_derived_limit=budgetDerivedLimit,discloseIntentLimitOverride({builtInCommand,intent:contract.intent},receipt,resultWithDiagnostics,options)}const envelopeOverhead=intentEnvelopeOverheads.get(options)??0,reportedBudget=receipt.token_budget;receipt.token_budget=reportedBudget-envelopeOverhead;const projected=canonicalBudget==="unbounded"?estimatedIntentProjection(resultWithDiagnostics,receipt,options):compactIntentProjection(builtInCommand,resultWithDiagnostics,receipt,options);receipt.declaration_feasible=receipt.estimated_tokens<=receipt.declared_token_budget;const outcome=intentBudgetOutcome(canonicalBudget,receipt,projected,()=>buildContextIntentRecoveryCommand(command,builtInCommand,contract.intent,{...receipt,token_budget:reportedBudget,estimated_tokens:receipt.estimated_tokens+envelopeOverhead},resultWithDiagnostics,options));return receipt.result_omitted&&(receipt.estimated_tokens+=envelopeOverhead,receipt.declaration_feasible=receipt.estimated_tokens<=receipt.declared_token_budget),receipt.token_budget=reportedBudget,outcome}function estimatedIntentProjection(result,receipt,options){const projected={...result,context_intent:receipt};return updateContextIntentEstimate(projected,receipt,options),projected}function compactIntentProjection(builtInCommand,result,receipt,options){let projected=estimatedIntentProjection(result,receipt,options);return receipt.estimated_tokens>receipt.token_budget&&(receipt.degradation="recursive_budget_compaction",projected=estimatedIntentProjection(compactContextIntentValue(result),receipt,options)),receipt.estimated_tokens>receipt.token_budget&&compactContextIntentRows(builtInCommand,projected,receipt,options)&&(receipt.degradation="budget_row_compaction",updateContextIntentEstimate(projected,receipt,options)),projected}const intentEnvelopeOverheads=new WeakMap;function intentBudgetOutcome(canonicalBudget,receipt,projected,restoreWith){return receipt.estimated_tokens<=receipt.token_budget||(receipt.within_budget=!1,canonicalBudget==="unbounded")?projected:(receipt.degradation="budget_receipt_only",receipt.result_omitted=!0,typeof canonicalBudget=="number"?{output_budget_exceeded:{omitted_result:!0,reason:"requested_budget_infeasible",restore_with:"Unbounded",recovery:{outputBudget:"unbounded"}},context_intent:receipt}:{budget_exceeded:{omitted_result:!0,reason:receipt.token_budget_override===0?"declared_budget_infeasible":"effective_budget_infeasible",restore_with:restoreWith()},context_intent:receipt})}const CONTINUATION_METADATA_KEYS=["applied_limit","completeness","context_intent","count","filters","has_more","now","omission_receipt","projection","row_contract","sorting","total","truncated"];function collapseContinuationMetadata(options,result){if(typeof options.after!="string"||options.after.length===0||isReadResultOmittedForBudget(result))return result;const fingerprint=decodeContextIntentCursor(options.after)?.fingerprint??"opaque_cursor",projected={...result};for(const key of CONTINUATION_METADATA_KEYS)delete projected[key];return projected.continuation_contract={fingerprint,metadata:"reference",restore_with:"omit --after"},projected}function isOutputRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function contextIntentRecoveryPositional(builtInCommand,result){const recoveryTarget=builtInCommand==="get"&&isOutputRecord(result.item)&&typeof result.item.id=="string"?result.item.id:builtInCommand==="search"&&typeof result.query=="string"?result.query:void 0;return recoveryTarget===void 0?"":` ${shellQuote(recoveryTarget)}`}function shellQuote(value){return`'${value.replaceAll("'",`'"'"'`)}'`}function contextIntentRecoveryProjection(options){return typeof options.fields=="string"&&options.fields.trim()!==""?` --fields ${shellQuote(options.fields)}`:""}function discloseIntentLimitOverride(identity,receipt,result,options){const requested=parsePositiveIntentTokenBudget(options.limit),effective=receipt.budget_derived_limit;if(requested===void 0||requested<=effective)return;const{overhead,rowCost}=resolveIntentRowCost(identity.builtInCommand,identity.intent),sufficientBudget=Math.max(receipt.token_budget,overhead+rowCost*requested);receipt.limit_reason=`The ${receipt.token_budget}-token ${identity.intent} budget carries ${effective} rows, so it reduced the caller's --limit ${requested}.`,receipt.limit_override={flag:"--limit",requested,effective,...Number.isSafeInteger(sufficientBudget)?{token_budget_for_requested:sufficientBudget,restore_with:`${intentBudgetFlag(options)} ${sufficientBudget}`}:{}};const warning=`${CONTEXT_INTENT_LIMIT_OVERRIDE_WARNING}:--limit ${requested}->${effective}`;result.warnings=Array.isArray(result.warnings)?[...result.warnings,warning]:[warning],isOutputRecord(result.filters)&&(result.filters={...result.filters,requested_limit:String(requested)})}function buildContextIntentRecoveryCommand(command,builtInCommand,intent,receipt,result,options){const recoveryPositional=contextIntentRecoveryPositional(builtInCommand,result),boundedRowLimit=builtInCommand==="get"?"":` --limit ${receipt.budget_derived_limit??1}`,{output_budget:retryBudget}=resolveReadOutputRecoveryBudget({effective_budget_tokens:receipt.token_budget,measured_result_tokens:receipt.estimated_tokens});return`pm ${command}${recoveryPositional}${contextIntentRecoveryProjection(options)} --for ${intent} --token-budget ${retryBudget}${boundedRowLimit}`}function receiptEstimate(value,field){if(isOutputRecord(value))return typeof value[field]=="number"?value[field]:void 0}function stabilizeSuppressedRowContractReceipts(result,options){let finalized=result;for(let iteration=0;iteration<8;iteration+=1){reconcileIntentFit(finalized);const previousContextEstimate=receiptEstimate(finalized.context_intent,"estimated_tokens"),previousReadEstimate=receiptEstimate(finalized.read_output,"estimated_tokens"),previousSessionEstimate=receiptEstimate(finalized.read_session,"spent_this_call_tokens");if(isOutputRecord(finalized.context_intent)&&finalized.context_intent.result_omitted!==!0&&updateContextIntentEstimate(finalized,finalized.context_intent,options),finalized=stabilizeReadOutputReceiptEstimates(finalized,options),receiptEstimate(finalized.context_intent,"estimated_tokens")===previousContextEstimate&&receiptEstimate(finalized.read_output,"estimated_tokens")===previousReadEstimate&&receiptEstimate(finalized.read_session,"spent_this_call_tokens")===previousSessionEstimate)break}return finalized}function reconcileIntentFit(result){const intent=result.context_intent;isOutputRecord(intent)&&Number(intent.estimated_tokens)>Number(intent.token_budget)&&(intent.within_budget=!1)}function attachReadOutputContracts(command,options,result){const disclosedResult=attachOutputOmissionReceipt(command,attachExtensionReadOutputRows(command??"",result));if(typeof disclosedResult!="object"||disclosedResult===null||Array.isArray(disclosedResult))return propagateContextUsageServingReceipt(result,disclosedResult),disclosedResult;const surface=command??"",source=disclosedResult,intentProjected=attachContextIntentReceipt(surface,options,source),intentEstimate=receiptEstimate(intentProjected.context_intent,"estimated_tokens"),finalized=finalizeReadOutputEnvelope(surface,options,result,intentProjected),settled=settledIntentOverBudget(options,finalized,intentProjected.context_intent);if(settled===void 0)return finalized;const charged={...options};intentEnvelopeOverheads.set(charged,settled.estimated-Number(intentEstimate));const rechargedIntent=attachContextIntentReceipt(surface,charged,source),recharged=finalizeReadOutputEnvelope(surface,charged,result,rechargedIntent),residual=settledIntentOverBudget(options,recharged,rechargedIntent.context_intent);if(residual===void 0)return recharged;const receipt={...residual.receipt,estimated_tokens:residual.estimated};return finalizeReadOutputEnvelope(surface,options,result,intentBudgetOutcome(canonicalIntentOutputBudget(options),receipt,recharged,()=>buildContextIntentRecoveryCommand(surface,receipt.command,receipt.intent,receipt,source,options)))}function settledIntentOverBudget(options,finalized,intentReceipt){const delivered=isOutputRecord(finalized.context_intent),settled=delivered?finalized.context_intent:intentReceipt;if(!isOutputRecord(settled)||settled.result_omitted===!0||Object.hasOwn(finalized,"output_budget_exceeded"))return;const receipt=settled,estimated=delivered?receipt.estimated_tokens:estimateReadOutputTokens(finalized,readOutputMeasurementFormat(options));return canonicalIntentOutputBudget(options)==="unbounded"||estimated<=receipt.token_budget?void 0:{receipt,estimated}}function finalizeReadOutputEnvelope(command,options,result,intentProjected){const projected=applyReadOutputDimensions(command,{...options,outputRowContract:options.outputRowContract===!0||options.output_row_contract===!0},collapseContinuationMetadata(options,intentProjected));if(propagateContextUsageServingReceipt(result,projected),options.outputRowContract===!0||options.output_row_contract===!0||!Object.hasOwn(projected,"row_contract"))return isOutputRecord(projected.context_intent)?stabilizeSuppressedRowContractReceipts(projected,options):projected;const withoutDiscoveryMetadata=Object.fromEntries(Object.entries(projected).filter(([key])=>key!=="row_contract"));Object.defineProperty(withoutDiscoveryMetadata,"row_contract",{value:projected.row_contract,enumerable:!1,configurable:!0});const suppressed=stabilizeSuppressedRowContractReceipts(withoutDiscoveryMetadata,options);return delete suppressed.row_contract,propagateContextUsageServingReceipt(projected,suppressed),suppressed}export{CONTEXT_INTENT_LIMIT_OVERRIDE_WARNING,PM_CONTEXT_INTENT_CONTRACTS,applyContextIntentProjection,attachContextIntentReceipt,attachReadOutputContracts,composeContextIntentContracts,contextIntentRowId,decodeContextIntentCursor,getActiveContextIntentContracts,resolveContextIntentContract,runWithContextIntentContracts};
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="a64c599a-e4c7-5f37-8ef6-fad2f7a9fd20")}catch{}})();import{AsyncLocalStorage}from"node:async_hooks";import{attachExtensionReadOutputRows}from"./read-output/extension.js";import{renderPmCommand}from"./command-line.js";import{attachOutputOmissionReceipt}from"./output-projection.js";import{encodeQueryCursor}from"./pagination.js";import{applyReadOutputDimensions,decodeReadOutputContinuationCursor,isReadResultOmittedForBudget,resolveReadOutputSurface,stabilizeReadOutputReceiptEstimates}from"./read-output-contracts.js";import{estimateReadOutputTokens,MAX_ESTIMATE_ITERATIONS,readOutputMeasurementFormat,registerReadOutputPassHooks,resolveReadOutputRecoveryBudget}from"./read-output-budget.js";import{propagateContextUsageServingReceipt}from"./context-usage.js";import{readOutputContinuationRowCollections}from"./read-output-rows.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{compactExplanatoryString,isContinuationTokenKey,isTrackerItemDocumentKey}from"../core/shared/text-normalization.js";const CONTEXT_INTENT_LIMIT_OVERRIDE_WARNING="limit_overridden_by_intent",PM_CONTEXT_INTENT_CONTRACTS=Object.freeze([{command:"context",intent:"orient",description:"Bounded active hierarchy, ownership, blockers, and recent progress.",included_field_groups:["summary","focus","hierarchy","blockers","activity"],token_budget:3e3,source:"core"},{command:"context",intent:"handoff",description:"Active ownership, evidence, decisions, and immediate continuation context.",included_field_groups:["summary","focus","in_progress","decisions","activity"],token_budget:2200,source:"core"},{command:"get",intent:"inspect",description:"Standard-depth item metadata, relationships, evidence, and lifecycle state.",included_field_groups:["item","children","claim_state","linked"],token_budget:3200,source:"core"},{command:"list",intent:"triage",description:"A budget-derived page of compact governance, ownership, priority, and blocker rows for triage.",included_field_groups:["identity","governance","ownership","dependencies"],token_budget:3200,source:"core"},{command:"next",intent:"execute",description:"The highest-ranked actionable work with concise ranking evidence.",included_field_groups:["recommended"],token_budget:1200,source:"core"},{command:"search",intent:"discover",description:"A budget-derived page of ranked canonical lineage candidates with compact match evidence.",included_field_groups:["identity","status","lineage","match"],token_budget:1800,source:"core"}]),activeContextIntentContracts=new AsyncLocalStorage;function getActiveContextIntentContracts(){return activeContextIntentContracts.getStore()??PM_CONTEXT_INTENT_CONTRACTS}function runWithContextIntentContracts(layers,run){return activeContextIntentContracts.run(composeContextIntentContracts(layers.workspaceContracts,layers.packageContracts),run)}function normalizeContextIntentDeclaration(declaration,source){const command=declaration.command.trim().toLowerCase(),intent=declaration.intent.trim().toLowerCase(),key=`${command}:${intent}`;if(!/^[a-z0-9][a-z0-9-]*$/.test(command)||!/^[a-z0-9][a-z0-9-]*$/.test(intent))throw new TypeError(`Invalid context intent command or name: ${key}`);if(declaration.description.trim().length===0)throw new TypeError(`Context intent ${key} requires a non-empty description`);if(!Number.isSafeInteger(declaration.token_budget)||declaration.token_budget<=0)throw new TypeError(`Context intent ${key} requires a positive integer token_budget`);const includedFieldGroups=[...new Set(declaration.included_field_groups.map(field=>field.trim()).filter(Boolean))];if(includedFieldGroups.length===0)throw new TypeError(`Context intent ${key} requires included_field_groups`);return{command,intent,description:declaration.description.trim(),included_field_groups:includedFieldGroups,token_budget:declaration.token_budget,source}}function composeContextIntentContracts(workspaceContracts=[],packageContracts=[]){const layers=[{source:"core",contracts:PM_CONTEXT_INTENT_CONTRACTS,allowOverride:!1},{source:"package",contracts:packageContracts,allowOverride:!1},{source:"workspace",contracts:workspaceContracts,allowOverride:!0}],composed=new Map,keysSeenWithinLayer=new Set;for(const layer of layers){keysSeenWithinLayer.clear();for(const declaration of layer.contracts){const normalized=normalizeContextIntentDeclaration(declaration,layer.source),key=`${normalized.command}:${normalized.intent}`;if(keysSeenWithinLayer.has(key))throw new TypeError(`Duplicate context intent declaration: ${key}`);if(keysSeenWithinLayer.add(key),!layer.allowOverride&&composed.has(key))throw new TypeError(`Duplicate context intent declaration: ${key}`);composed.set(key,normalized)}}return[...composed.values()].sort((left,right)=>left.command.localeCompare(right.command)||left.intent.localeCompare(right.intent))}function resolveContextIntentContract(command,intent,contracts=getActiveContextIntentContracts(),positionalArguments=[]){const normalizedCommand=command.trim().toLowerCase(),normalizedIntent=intent.trim().toLowerCase(),exact=contracts.find(entry=>entry.command===normalizedCommand&&entry.intent===normalizedIntent);if(exact)return{...exact,source:exact.source??"core"};const candidates=contracts.filter(entry=>entry.command===normalizedCommand).map(entry=>entry.intent);if(candidates.length===0)return;const suggestion=candidates.map(candidate=>{const rows=Array.from({length:normalizedIntent.length+1},(_,index)=>index);for(let candidateIndex=1;candidateIndex<=candidate.length;candidateIndex+=1){let previous=rows[0];rows[0]=candidateIndex;for(let intentIndex=1;intentIndex<=normalizedIntent.length;intentIndex+=1){const prior=rows[intentIndex];rows[intentIndex]=Math.min(rows[intentIndex]+1,rows[intentIndex-1]+1,previous+(candidate[candidateIndex-1]===normalizedIntent[intentIndex-1]?0:1)),previous=prior}}return{candidate,distance:rows[normalizedIntent.length]}}).sort((left,right)=>left.distance-right.distance||left.candidate.localeCompare(right.candidate))[0].candidate,attemptedArguments=[normalizedCommand,...positionalArguments,"--for",normalizedIntent],suggestedRetryArguments=[normalizedCommand,...positionalArguments,"--for",suggestion],suggestedCommand=renderPmCommand(suggestedRetryArguments);throw new PmCliError(`Unknown context intent "${normalizedIntent}" for ${normalizedCommand}. Did you mean "${suggestion}"?`,EXIT_CODE.USAGE,{code:"unknown_context_intent",reason:"unknown_intent",field:"for",flag:"--for",value:normalizedIntent,required:`Use a declared ${normalizedCommand} intent.`,why:"Intent names are command-local contracts and cannot be inferred from output section names.",nextSteps:[suggestedCommand],recovery:{recovery_mode:"compact",attempted_command:renderPmCommand(attemptedArguments),allowed_values:[...candidates].sort(),suggested_retry:suggestedCommand,suggested_retry_args:suggestedRetryArguments}})}function applyIntentRowLimit(projected,budgetDerivedLimit){const requestedLimit=parsePositiveIntentTokenBudget(projected.limit),effectiveLimit=String(requestedLimit===void 0?budgetDerivedLimit:Math.min(requestedLimit,budgetDerivedLimit));return(projected.limit===void 0||requestedLimit!==void 0)&&(projected.limit=effectiveLimit),effectiveLimit}const CONTEXT_INTENT_DEFAULT_APPLIERS={context:(projected,contract,explicitTokenBudget,canonical)=>{projected.section===void 0&&projected.depth===void 0&&(projected.section=contract.intent==="handoff"?["activity","progress","blockers"]:["hierarchy","blockers","activity"]),projected.depth===void 0&&(projected.depth=contract.intent==="handoff"?"deep":"standard");const tokenBudget=resolveEffectiveIntentTokenBudget(canonical,projected.tokenBudget,contract.token_budget),budgetDerivedLimit=resolveIntentRowBudget("context",contract.intent,tokenBudget,explicitTokenBudget),derivedLimit=applyIntentRowLimit(projected,budgetDerivedLimit);projected.activityLimit===void 0&&(projected.activityLimit=derivedLimit)},get:projected=>{projected.depth===void 0&&projected.fields===void 0&&(projected.depth="standard")},list:(projected,contract,explicitTokenBudget,canonical)=>{projected.brief===void 0&&projected.compact===void 0&&projected.full===void 0&&projected.fields===void 0&&(projected.fields="id,title,status,type,priority,parent,assignee,risk,blocked_by");const tokenBudget=resolveEffectiveIntentTokenBudget(canonical,projected.tokenBudget,contract.token_budget),budgetDerivedLimit=resolveIntentRowBudget("list",contract.intent,tokenBudget,explicitTokenBudget);applyIntentRowLimit(projected,budgetDerivedLimit)},next:projected=>{projected.readyOnly===void 0&&(projected.readyOnly=!0)},search:(projected,contract,explicitTokenBudget,canonical)=>{projected.compact===void 0&&projected.full===void 0&&projected.fields===void 0&&(projected.compact=!0);const tokenBudget=resolveEffectiveIntentTokenBudget(canonical,projected.tokenBudget,contract.token_budget),budgetDerivedLimit=resolveIntentRowBudget("search",contract.intent,tokenBudget,explicitTokenBudget);applyIntentRowLimit(projected,budgetDerivedLimit)}};function applyContextIntentProjection(command,options,positionalArguments=[]){const tokenBudget=options.tokenBudget??options.token_budget;if(typeof options.for!="string"){if(tokenBudget!==void 0&&(command==="get"||command==="list"||command==="search"))throw new PmCliError("--token-budget requires a declared context intent selected with --for",EXIT_CODE.USAGE,{code:"missing_required_option",field:"for",required:"Select a context intent with --for when setting --token-budget.",why:"A token-budget override has no projection contract to constrain without a selected intent.",nextSteps:["Retry with --for <intent> --token-budget <n>, or omit --token-budget."]});if(options.tokenBudget!==void 0||options.token_budget===void 0)return options;const projected2={...options,tokenBudget};return delete projected2.token_budget,projected2}const contract=resolveContextIntentContract(command,options.for,void 0,positionalArguments),canonical=canonicalIntentOutputBudget(options),explicitTokenBudget=parsePositiveIntentTokenBudget(tokenBudget)!==void 0||typeof canonical=="number",projected={...options};return projected.tokenBudget===void 0&&tokenBudget!==void 0&&(projected.tokenBudget=tokenBudget),delete projected.token_budget,typeof canonical=="number"?projected.tokenBudget=String(canonical):projected.tokenBudget===void 0&&(projected.tokenBudget=String(contract.token_budget)),CONTEXT_INTENT_DEFAULT_APPLIERS[command](projected,contract,explicitTokenBudget,canonical),projected}const CONTEXT_INTENT_DEGRADATIONS={context:"bounded_sections",get:"standard_item",list:"bounded_fields_and_rows",next:"bounded_ranked_rows",search:"bounded_ranked_rows"},MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET=256;function compactContextIntentValue(value,surface,exemptTokens=!0,root=!0){return Array.isArray(value)?value.map(entry=>compactContextIntentValue(entry,surface,exemptTokens,!1)):value!==null&&typeof value=="object"?Object.fromEntries(Object.entries(value).map(([key,entry])=>[key,exemptTokens&&typeof entry=="string"&&isContinuationTokenKey(key)?entry:compactContextIntentValue(entry,surface,exemptTokens&&!(root&&isTrackerItemDocumentKey(surface,key)),!1)])):typeof value=="string"?compactExplanatoryString(value):value}function parsePositiveIntentTokenBudget(value){const parsed=typeof value=="number"?value:typeof value=="string"&&/^\d+$/u.test(value.trim())?Number(value):Number.NaN;return Number.isSafeInteger(parsed)&&parsed>0?parsed:void 0}function canonicalIntentOutputBudget(options){const value=options.outputBudget??options.output_budget;return value==="unbounded"?value:parsePositiveIntentTokenBudget(value)}function intentBudgetFlag(options){return canonicalIntentOutputBudget(options)===void 0?"--token-budget":"--output-budget"}function resolveEffectiveIntentTokenBudget(canonical,legacy,declaredBudget){return typeof canonical=="number"?canonical:resolveIntentTokenBudget(legacy,declaredBudget)}function resolveIntentTokenBudget(value,declaredBudget){const parsed=parsePositiveIntentTokenBudget(value);if(parsed===void 0)return declaredBudget;if(parsed<MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET)throw new PmCliError(`Context intent token budget must be at least ${MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET}`,EXIT_CODE.USAGE,{code:"invalid_argument_value",reason:"below_minimum",field:"tokenBudget",value:String(value),required:`Use an integer token budget of at least ${MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET}.`,why:"Smaller ceilings cannot contain the minimum machine-readable intent receipt.",nextSteps:[`Retry with --token-budget ${MINIMUM_CONTEXT_INTENT_TOKEN_BUDGET} or omit the override.`]});return parsed}function resolveIntentRowCost(command,intent){return command==="context"?command==="context"&&intent==="orient"?{overhead:1200,rowCost:600}:{overhead:800,rowCost:500}:{overhead:command==="list"?520:480,rowCost:16}}function resolveIntentRowBudget(command,intent,tokenBudget,explicitTokenBudget){if(command==="get"||command==="next")return;const{overhead,rowCost}=resolveIntentRowCost(command,intent),calculatedLimit=Math.max(command==="context"?1:2,Math.floor((tokenBudget-overhead)/rowCost));return explicitTokenBudget?calculatedLimit:Math.min(command==="context"?20:100,calculatedLimit)}function updateContextIntentEstimate(projected,receipt,options){const format=readOutputMeasurementFormat(options),rowContractDelivered=options.outputRowContract===!0||options.output_row_contract===!0;let measuredTokens=receipt.estimated_tokens,largestTokens=measuredTokens;for(let iteration=0;iteration<MAX_ESTIMATE_ITERATIONS;iteration+=1){receipt.estimated_tokens=measuredTokens;const nextMeasurement=estimateReadOutputTokens(rowContractDelivered||!Object.hasOwn(projected,"row_contract")?projected:Object.fromEntries(Object.entries(projected).filter(([key])=>key!=="row_contract")),format);if(nextMeasurement===measuredTokens)return;measuredTokens=nextMeasurement,largestTokens=Math.max(largestTokens,measuredTokens)}receipt.estimated_tokens=largestTokens}const CONTEXT_INTENT_ROW_KEYS={context:["high_level","low_level","blocked_fallback","recently_created","unparented","hierarchy","activity","blockers"],get:["children"],list:["items"],next:["ready","decision_needed","gate_needed","containers","blocked","held_by_others"],search:["items"]};function decodeContextIntentCursor(cursor){try{const parsed=JSON.parse(Buffer.from(cursor,"base64url").toString("utf8"));return typeof parsed.fingerprint!="string"||!Number.isSafeInteger(parsed.after_index)?void 0:{fingerprint:parsed.fingerprint,after_index:parsed.after_index,...typeof parsed.snapshot=="string"?{snapshot:parsed.snapshot}:{}}}catch{return}}function contextIntentRowId(row){if(row===null||typeof row!="object")return;if(typeof row.id=="string")return row.id;const nestedId=row.item?.id;return typeof nestedId=="string"?nestedId:void 0}function shrinkContextIntentRowsToBudget(projected,receipt,rows,options){let compacted=!1;for(;;){if(updateContextIntentEstimate(projected,receipt,options),receipt.estimated_tokens<=receipt.token_budget||rows.length<=1)return compacted;const rowBytes=Buffer.byteLength(JSON.stringify(rows),"utf8"),excessBytes=(receipt.estimated_tokens-receipt.token_budget)*4;rows.splice(-Math.min(rows.length-1,Math.max(1,Math.ceil(excessBytes/Math.max(1,Math.ceil(rowBytes/rows.length)))))),compacted=!0}}function compactPaginatedContextIntentRows(projected,receipt,options){const rows=projected.items,cursorContinuesExistingPage=typeof projected.next_cursor=="string",cursorSource=cursorContinuesExistingPage?projected.next_cursor:options.after;if(!Array.isArray(rows)||typeof cursorSource!="string")return!1;const cursorEnvelope=decodeContextIntentCursor(cursorSource);if(cursorEnvelope===void 0)return!1;const originalRowCount=rows.length,originalRows=[...rows];let compacted=!1;for(;;){if(compacted=shrinkContextIntentRowsToBudget(projected,receipt,rows,options)||compacted,!compacted)return!1;const lastId=contextIntentRowId(rows.at(-1));if(lastId===void 0)return rows.splice(0,rows.length,...originalRows),updateContextIntentEstimate(projected,receipt,options),!1;if(projected.next_cursor=encodeQueryCursor(cursorEnvelope.fingerprint,lastId,cursorContinuesExistingPage?cursorEnvelope.after_index-(originalRowCount-rows.length):cursorEnvelope.after_index+rows.length,cursorEnvelope.snapshot),updateContextIntentEstimate(projected,receipt,options),receipt.estimated_tokens<=receipt.token_budget||rows.length<=1)break}return typeof projected.count=="number"&&(projected.count=rows.length),typeof projected.applied_limit=="number"&&(projected.applied_limit=rows.length),!0}function compactContextIntentRows(command,projected,receipt,options){if(command==="list"||command==="search")return compactPaginatedContextIntentRows(projected,receipt,options);if(command!=="next"||typeof projected.next_cursor=="string")return!1;let compacted=!1;for(;;){if(updateContextIntentEstimate(projected,receipt,options),receipt.estimated_tokens<=receipt.token_budget)return compacted;const candidate=CONTEXT_INTENT_ROW_KEYS[command].map(key=>({key,rows:Array.isArray(projected[key])?projected[key]:[]})).filter(({rows})=>rows.length>0).sort((left,right)=>right.rows.length-left.rows.length||left.key.localeCompare(right.key))[0];if(candidate===void 0)return compacted;const retainedTotal=CONTEXT_INTENT_ROW_KEYS[command].reduce((total,key)=>total+(Array.isArray(projected[key])?projected[key].length:0),0);if(retainedTotal<=1)return compacted;const removableRows=Math.min(candidate.rows.length,retainedTotal-1),candidateBytes=Buffer.byteLength(JSON.stringify(candidate.rows),"utf8"),estimatedBytesPerRow=Math.max(1,Math.ceil(candidateBytes/candidate.rows.length)),excessBytes=(receipt.estimated_tokens-receipt.token_budget)*4,removalCount=Math.min(removableRows,Math.max(1,Math.ceil(excessBytes/estimatedBytesPerRow)));candidate.rows.splice(-removalCount,removalCount),compacted=!0}}function attachContextIntentReceipt(command,options,result){if(typeof options.for!="string")return result;const normalizedCommand=command.startsWith("list-")?"list":command;if(!(normalizedCommand in CONTEXT_INTENT_DEFAULT_APPLIERS))return result;const builtInCommand=normalizedCommand,contract=resolveContextIntentContract(builtInCommand,options.for),canonicalBudget=canonicalIntentOutputBudget(options),effectiveTokenBudget=resolveEffectiveIntentTokenBudget(canonicalBudget,options.tokenBudget??options.token_budget,contract.token_budget),receipt={command:builtInCommand,intent:contract.intent,source:contract.source,included_field_groups:[...contract.included_field_groups],token_budget:effectiveTokenBudget,declared_token_budget:contract.token_budget,token_budget_override:effectiveTokenBudget-contract.token_budget,estimated_tokens:0,within_budget:!0,degradation:CONTEXT_INTENT_DEGRADATIONS[builtInCommand],declaration_feasible:!0,result_omitted:!1},resultWithDiagnostics={...result},budgetDerivedLimit=resolveIntentRowBudget(builtInCommand,contract.intent,receipt.token_budget,parsePositiveIntentTokenBudget(options.tokenBudget??options.token_budget)!==void 0||typeof canonicalBudget=="number");if(budgetDerivedLimit!==void 0){const effectiveLimit=parsePositiveIntentTokenBudget(options.limit),explicitLimitBinds=effectiveLimit!==void 0&&effectiveLimit<budgetDerivedLimit;receipt.budget_derived_limit=budgetDerivedLimit,receipt.binding_constraint=explicitLimitBinds?"explicit_limit":"token_budget",receipt.limit_reason=explicitLimitBinds?"The caller supplied a smaller row limit than the budget-derived ceiling.":"The selected intent token budget constrains the effective row ceiling.",resultWithDiagnostics.budget_derived_limit=budgetDerivedLimit,discloseIntentLimitOverride({builtInCommand,intent:contract.intent},receipt,resultWithDiagnostics,options)}const envelopeOverhead=intentEnvelopeOverheads.get(options)??0,reportedBudget=receipt.token_budget;receipt.token_budget=reportedBudget-envelopeOverhead;const projected=canonicalBudget==="unbounded"?estimatedIntentProjection(resultWithDiagnostics,receipt,options):compactIntentProjection(builtInCommand,resultWithDiagnostics,receipt,options,resolveReadOutputSurface(command,options));receipt.declaration_feasible=receipt.estimated_tokens<=receipt.declared_token_budget;const outcome=intentBudgetOutcome(canonicalBudget,receipt,projected,()=>buildContextIntentRecoveryCommand(command,builtInCommand,contract.intent,{...receipt,token_budget:reportedBudget,estimated_tokens:receipt.estimated_tokens+envelopeOverhead},resultWithDiagnostics,options));return receipt.result_omitted&&(receipt.estimated_tokens+=envelopeOverhead,receipt.declaration_feasible=receipt.estimated_tokens<=receipt.declared_token_budget),receipt.token_budget=reportedBudget,outcome}function estimatedIntentProjection(result,receipt,options){const projected={...result,context_intent:receipt};return updateContextIntentEstimate(projected,receipt,options),projected}function compactIntentProjection(builtInCommand,result,receipt,options,surface){let projected=estimatedIntentProjection(result,receipt,options);return receipt.estimated_tokens>receipt.token_budget&&(receipt.degradation="recursive_budget_compaction",projected=estimatedIntentProjection(compactContextIntentValue(result,surface),receipt,options)),receipt.estimated_tokens>receipt.token_budget&&compactContextIntentRows(builtInCommand,projected,receipt,options)&&(receipt.degradation="budget_row_compaction",updateContextIntentEstimate(projected,receipt,options)),projected}const intentEnvelopeOverheads=new WeakMap;function intentBudgetOutcome(canonicalBudget,receipt,projected,restoreWith){return receipt.estimated_tokens<=receipt.token_budget||(receipt.within_budget=!1,canonicalBudget==="unbounded")?projected:(receipt.degradation="budget_receipt_only",receipt.result_omitted=!0,typeof canonicalBudget=="number"?{output_budget_exceeded:{omitted_result:!0,reason:"requested_budget_infeasible",restore_with:"Unbounded",recovery:{outputBudget:"unbounded"}},context_intent:receipt}:{budget_exceeded:{omitted_result:!0,reason:receipt.token_budget_override===0?"declared_budget_infeasible":"effective_budget_infeasible",restore_with:restoreWith()},context_intent:receipt})}const CONTINUATION_METADATA_KEYS=["applied_limit","completeness","context_intent","count","filters","has_more","now","omission_receipt","projection","row_contract","sorting","total","truncated"];function collapseContinuationMetadata(options,result){if(typeof options.after!="string"||options.after.length===0||isReadResultOmittedForBudget(result))return result;const fingerprint=decodeContextIntentCursor(options.after)?.fingerprint??"opaque_cursor",projected={...result};for(const key of CONTINUATION_METADATA_KEYS)delete projected[key];return projected.continuation_contract={fingerprint,metadata:"reference",restore_with:"omit --after"},projected}function isOutputRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function contextIntentRecoveryPositional(builtInCommand,result){const recoveryTarget=builtInCommand==="get"&&isOutputRecord(result.item)&&typeof result.item.id=="string"?result.item.id:builtInCommand==="search"&&typeof result.query=="string"?result.query:void 0;return recoveryTarget===void 0?"":` ${shellQuote(recoveryTarget)}`}function shellQuote(value){return`'${value.replaceAll("'",`'"'"'`)}'`}function contextIntentRecoveryProjection(options){return typeof options.fields=="string"&&options.fields.trim()!==""?` --fields ${shellQuote(options.fields)}`:""}function discloseIntentLimitOverride(identity,receipt,result,options){const requested=parsePositiveIntentTokenBudget(options.limit),effective=receipt.budget_derived_limit;if(requested===void 0||requested<=effective)return;const{overhead,rowCost}=resolveIntentRowCost(identity.builtInCommand,identity.intent),sufficientBudget=Math.max(receipt.token_budget,overhead+rowCost*requested);receipt.limit_reason=`The ${receipt.token_budget}-token ${identity.intent} budget carries ${effective} rows, so it reduced the caller's --limit ${requested}.`,receipt.limit_override={flag:"--limit",requested,effective,...Number.isSafeInteger(sufficientBudget)?{token_budget_for_requested:sufficientBudget,restore_with:`${intentBudgetFlag(options)} ${sufficientBudget}`}:{}};const warning=`${CONTEXT_INTENT_LIMIT_OVERRIDE_WARNING}:--limit ${requested}->${effective}`;result.warnings=Array.isArray(result.warnings)?[...result.warnings,warning]:[warning],isOutputRecord(result.filters)&&(result.filters={...result.filters,requested_limit:String(requested)})}function buildContextIntentRecoveryCommand(command,builtInCommand,intent,receipt,result,options){const recoveryPositional=contextIntentRecoveryPositional(builtInCommand,result),boundedRowLimit=builtInCommand==="get"?"":` --limit ${receipt.budget_derived_limit??1}`,{output_budget:retryBudget}=resolveReadOutputRecoveryBudget({effective_budget_tokens:receipt.token_budget,measured_result_tokens:receipt.estimated_tokens});return`pm ${command}${recoveryPositional}${contextIntentRecoveryProjection(options)} --for ${intent} --token-budget ${retryBudget}${boundedRowLimit}`}function receiptEstimate(value,field){if(isOutputRecord(value))return typeof value[field]=="number"?value[field]:void 0}function stabilizeSuppressedRowContractReceipts(result,options){let finalized=result;for(let iteration=0;iteration<8;iteration+=1){reconcileIntentFit(finalized);const previousContextEstimate=receiptEstimate(finalized.context_intent,"estimated_tokens"),previousReadEstimate=receiptEstimate(finalized.read_output,"estimated_tokens"),previousSessionEstimate=receiptEstimate(finalized.read_session,"spent_this_call_tokens");if(isOutputRecord(finalized.context_intent)&&finalized.context_intent.result_omitted!==!0&&updateContextIntentEstimate(finalized,finalized.context_intent,options),finalized=stabilizeReadOutputReceiptEstimates(finalized,options),receiptEstimate(finalized.context_intent,"estimated_tokens")===previousContextEstimate&&receiptEstimate(finalized.read_output,"estimated_tokens")===previousReadEstimate&&receiptEstimate(finalized.read_session,"spent_this_call_tokens")===previousSessionEstimate)break}return finalized}function reconcileIntentFit(result){const intent=result.context_intent;isOutputRecord(intent)&&Number(intent.estimated_tokens)>Number(intent.token_budget)&&(intent.within_budget=!1)}function intentContinuationBinding(source,intentProjected){const intent=intentProjected.context_intent;if(!isOutputRecord(intent)||intent.result_omitted===!0)return;const compacted=intent.degradation==="recursive_budget_compaction"||intent.degradation==="budget_row_compaction",binding={...intentProjected};for(const collection of readOutputContinuationRowCollections(source)){const delivered=intentProjected[collection.path];if(Array.isArray(delivered)&&Array.isArray(collection.value)&&delivered.length<=collection.value.length){const prefix=collection.value.slice(0,delivered.length);binding[collection.path]=compacted?prefix.map(normalizeContextIntentValue):prefix}}return binding}function normalizeContextIntentValue(value){return Array.isArray(value)?value.map(normalizeContextIntentValue):value!==null&&typeof value=="object"?Object.fromEntries(Object.entries(value).map(([key,entry])=>[key,normalizeContextIntentValue(entry)])):value}function attachReadOutputContracts(command,options,result){const disclosedResult=attachOutputOmissionReceipt(command,attachExtensionReadOutputRows(command??"",result));if(typeof disclosedResult!="object"||disclosedResult===null||Array.isArray(disclosedResult))return propagateContextUsageServingReceipt(result,disclosedResult),disclosedResult;const surface=command??"",source=disclosedResult,intentProjected=attachContextIntentReceipt(surface,options,source),intentEstimate=receiptEstimate(intentProjected.context_intent,"estimated_tokens"),binding=intentContinuationBinding(source,intentProjected),finalized=finalizeReadOutputEnvelope(surface,options,result,intentProjected,binding),settled=settledIntentOverBudget(options,finalized,intentProjected.context_intent);if(settled===void 0)return readOutputStageOmittedIntentPage(options,finalized,intentProjected)?chargedIntentPassOrRefusal(surface,options,result,source,intentProjected,Number(intentEstimate),binding,finalized):finalized;const charged={...options};intentEnvelopeOverheads.set(charged,settled.estimated-Number(intentEstimate));const rechargedIntent=attachContextIntentReceipt(surface,charged,source),recharged=finalizeChargedIntentPage(surface,options,charged,result,rechargedIntent,binding),residual=recharged===void 0?settled:settledIntentOverBudget(options,recharged,rechargedIntent.context_intent);if(residual===void 0)return recharged;const omitted={...residual.receipt,estimated_tokens:residual.estimated};return finalizeReadOutputEnvelope(surface,{...options,outputCursor:void 0,output_cursor:void 0},result,intentBudgetOutcome(canonicalIntentOutputBudget(options),omitted,recharged??finalized,()=>buildContextIntentRecoveryCommand(surface,omitted.command,omitted.intent,omitted,source,options)))}function readOutputStageOmittedIntentPage(options,finalized,intentProjected){const intent=intentProjected.context_intent;return Object.hasOwn(finalized,"output_budget_exceeded")&&isOutputRecord(intent)&&intent.result_omitted!==!0&&PRODUCER_PAGED_INTENT_COMMANDS.has(String(intent.command))&&(options.outputInclude??options.output_include)===void 0&&(options.outputSession??options.output_session)===void 0}const PRODUCER_PAGED_INTENT_COMMANDS=new Set(["list","search"]);function chargedIntentPassOrRefusal(surface,options,result,source,intentProjected,intentEstimate,binding,refusal){const measured=finalizeReadOutputEnvelope(surface,{...options,outputBudget:"unbounded"},result,{...intentProjected,context_intent:{...intentProjected.context_intent}},binding),charged={...options};intentEnvelopeOverheads.set(charged,estimateReadOutputTokens(measured,readOutputMeasurementFormat(options))-intentEstimate);const rechargedIntent=attachContextIntentReceipt(surface,charged,source),recharged=finalizeChargedIntentPage(surface,options,charged,result,rechargedIntent,binding);return recharged===void 0||Object.hasOwn(recharged,"output_budget_exceeded")||settledIntentOverBudget(options,recharged,rechargedIntent.context_intent)!==void 0?refusal:recharged}function finalizeChargedIntentPage(surface,options,charged,result,rechargedIntent,binding){return isReadResultOmittedForBudget(rechargedIntent)||chargedPrefixEndsBeforeCursor(options,rechargedIntent)?void 0:finalizeReadOutputEnvelope(surface,charged,result,rechargedIntent,binding)}function chargedPrefixEndsBeforeCursor(options,rechargedIntent){const raw=options.outputCursor??options.output_cursor;if(typeof raw!="string")return!1;const cursor=decodeReadOutputContinuationCursor(raw),rows=rechargedIntent[cursor.path];return Array.isArray(rows)&&rows.length<=cursor.offset}function settledIntentOverBudget(options,finalized,intentReceipt){const delivered=isOutputRecord(finalized.context_intent),settled=delivered?finalized.context_intent:intentReceipt;if(!isOutputRecord(settled)||settled.result_omitted===!0||Object.hasOwn(finalized,"output_budget_exceeded"))return;const receipt=settled,estimated=delivered?receipt.estimated_tokens:estimateReadOutputTokens(finalized,readOutputMeasurementFormat(options));return canonicalIntentOutputBudget(options)==="unbounded"||estimated<=receipt.token_budget?void 0:{receipt,estimated}}function intentEstimateMirror(intentReceipt){return!isOutputRecord(intentReceipt)||intentReceipt.result_omitted===!0?{}:{mirrorEstimate:(result,estimate)=>{isOutputRecord(result.context_intent)&&(result.context_intent.estimated_tokens=estimate)}}}function finalizeReadOutputEnvelope(command,options,result,intentProjected,continuationBinding){const dimensionOptions={...options,outputRowContract:options.outputRowContract===!0||options.output_row_contract===!0};registerReadOutputPassHooks(dimensionOptions,{...continuationBinding===void 0?{}:{continuationBinding:collapseContinuationMetadata(options,continuationBinding)},...intentEstimateMirror(intentProjected.context_intent)});const projected=applyReadOutputDimensions(command,dimensionOptions,collapseContinuationMetadata(options,intentProjected));if(propagateContextUsageServingReceipt(result,projected),options.outputRowContract===!0||options.output_row_contract===!0||!Object.hasOwn(projected,"row_contract"))return isOutputRecord(projected.context_intent)?stabilizeSuppressedRowContractReceipts(projected,options):projected;const withoutDiscoveryMetadata=Object.fromEntries(Object.entries(projected).filter(([key])=>key!=="row_contract"));Object.defineProperty(withoutDiscoveryMetadata,"row_contract",{value:projected.row_contract,enumerable:!1,configurable:!0});const suppressed=stabilizeSuppressedRowContractReceipts(withoutDiscoveryMetadata,options);return delete suppressed.row_contract,propagateContextUsageServingReceipt(projected,suppressed),suppressed}export{CONTEXT_INTENT_LIMIT_OVERRIDE_WARNING,PM_CONTEXT_INTENT_CONTRACTS,applyContextIntentProjection,attachContextIntentReceipt,attachReadOutputContracts,composeContextIntentContracts,contextIntentRowId,decodeContextIntentCursor,getActiveContextIntentContracts,resolveContextIntentContract,runWithContextIntentContracts};
2
2
  //# sourceMappingURL=context-intent-contracts.js.map
@@ -56,7 +56,9 @@ last_update_remote_version?:string;
56
56
  /** Value that configures or reports update available for this contract. */
57
57
  update_available?:boolean|null;
58
58
  /** Value that configures or reports update error for this contract. */
59
- update_error?:string;}
59
+ update_error?:string;
60
+ /** Budget in milliseconds that a diagnostic lookup ran out of; diagnostics never persist this field. */
61
+ update_check_timeout_ms?:number;}
60
62
  /** Documents the managed extension state payload exchanged by command, SDK, and package integrations. */
61
63
  export interface ManagedExtensionState{
62
64
  /** Value that configures or reports version for this contract. */
@@ -1,3 +1,3 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="5181479f-469f-525b-add2-914a9934afbd")}catch{}})();import{isFileMissingError}from"../../core/fs/fs-utils.js";import fs from"node:fs/promises";import path from"node:path";import{EXIT_CODE}from"../../core/shared/constants.js";import{PmCliError}from"../../core/shared/errors.js";import{nowIso}from"../../core/shared/time.js";import{normalizeExtensionContributionInventory}from"../../core/extensions/contribution-inventory.js";import{normalizeExtensionNameForMatch,normalizeStringList}from"./shared.js";const MANAGED_EXTENSION_STATE_FILENAME=".managed-extensions.json",MANAGED_EXTENSION_STATE_VERSION=1;function resolveManagedExtensionStatePath(extensionsRoot){return path.join(extensionsRoot,MANAGED_EXTENSION_STATE_FILENAME)}function createEmptyManagedExtensionState(){return{version:MANAGED_EXTENSION_STATE_VERSION,updated_at:nowIso(),entries:[]}}function sortManagedEntries(entries){return[...entries].sort((left,right)=>{const byScope=left.scope.localeCompare(right.scope);if(byScope!==0)return byScope;const byName=left.name.localeCompare(right.name);return byName!==0?byName:left.directory.localeCompare(right.directory)})}function managedExtensionSourcesEquivalent(left,right){return left.kind!==right.kind||left.input!==right.input||left.location!==right.location?!1:left.kind==="npm"&&right.kind==="npm"?left.package===right.package&&left.version===right.version:left.kind==="github"&&right.kind==="github"?left.repository===right.repository&&left.ref===right.ref&&left.subpath===right.subpath&&left.commit===right.commit:left.kind==="builtin"&&right.kind==="builtin"?left.name===right.name:!0}function optionalString(value){return typeof value=="string"?value:void 0}function hasRequiredManagedRecordFields(entry){return typeof entry.name=="string"&&entry.name.trim().length>0&&typeof entry.directory=="string"&&entry.directory.trim().length>0&&(entry.scope==="project"||entry.scope==="global")&&typeof entry.manifest_version=="string"&&typeof entry.manifest_entry=="string"&&Array.isArray(entry.capabilities)&&entry.capabilities.every(value=>typeof value=="string")&&typeof entry.installed_at=="string"&&typeof entry.updated_at=="string"}function normalizeManagedSource(raw){if(typeof raw!="object"||raw===null)return null;const source=raw;return source.kind!=="local"&&source.kind!=="github"&&source.kind!=="npm"&&source.kind!=="builtin"||typeof source.input!="string"||typeof source.location!="string"?null:{kind:source.kind,input:source.input,location:source.location,name:optionalString(source.name),package:optionalString(source.package),version:optionalString(source.version),repository:optionalString(source.repository),owner:optionalString(source.owner),repo:optionalString(source.repo),ref:optionalString(source.ref),subpath:optionalString(source.subpath),commit:optionalString(source.commit)}}function normalizeManagedRecord(raw){if(typeof raw!="object"||raw===null)return null;const entry=raw;if(!hasRequiredManagedRecordFields(entry))return null;const source=normalizeManagedSource(entry.source);if(!source)return null;const contributions=normalizeExtensionContributionInventory(entry.contributions);return contributions===null?null:{name:entry.name.trim(),directory:entry.directory.trim(),scope:entry.scope,manifest_version:entry.manifest_version,manifest_entry:entry.manifest_entry,capabilities:normalizeStringList(entry.capabilities),contributions,installed_at:entry.installed_at,updated_at:entry.updated_at,source,last_update_check_at:optionalString(entry.last_update_check_at),last_update_remote_commit:optionalString(entry.last_update_remote_commit),last_update_remote_version:optionalString(entry.last_update_remote_version),update_available:typeof entry.update_available=="boolean"||entry.update_available===null?entry.update_available:void 0,update_error:optionalString(entry.update_error)}}function normalizeManagedState(raw){if(typeof raw!="object"||raw===null)return null;const candidate=raw;if(candidate.version!==MANAGED_EXTENSION_STATE_VERSION||!Array.isArray(candidate.entries))return null;const entries=[];for(const rawEntry of candidate.entries){const record=normalizeManagedRecord(rawEntry);record&&entries.push(record)}return{version:MANAGED_EXTENSION_STATE_VERSION,updated_at:optionalString(candidate.updated_at)??nowIso(),entries:sortManagedEntries(entries)}}async function readManagedExtensionState(extensionsRoot){const statePath=resolveManagedExtensionStatePath(extensionsRoot),fallback=createEmptyManagedExtensionState();try{const raw=await fs.readFile(statePath,"utf8"),parsed=JSON.parse(raw),normalized=normalizeManagedState(parsed);if(!normalized)throw new PmCliError(`Managed extension state file "${statePath}" has an invalid schema. Repair or remove it before mutating extension state.`,EXIT_CODE.GENERIC_FAILURE);return{path:statePath,state:normalized,warnings:[]}}catch(error){if(error instanceof PmCliError)throw error;if(typeof error=="object"&&error!==null&&"code"in error&&isFileMissingError(error))return{path:statePath,state:fallback,warnings:[]};throw new PmCliError(`Managed extension state file "${statePath}" could not be read. Repair or remove it before mutating extension state.`,EXIT_CODE.GENERIC_FAILURE)}}async function writeManagedExtensionState(extensionsRoot,state){const statePath=resolveManagedExtensionStatePath(extensionsRoot),normalized={version:MANAGED_EXTENSION_STATE_VERSION,updated_at:nowIso(),entries:sortManagedEntries(state.entries)};await fs.mkdir(extensionsRoot,{recursive:!0}),await fs.writeFile(statePath,`${JSON.stringify(normalized,null,2)}
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="054bae8c-464f-5791-a78a-063588565393")}catch{}})();import{isFileMissingError}from"../../core/fs/fs-utils.js";import fs from"node:fs/promises";import path from"node:path";import{EXIT_CODE}from"../../core/shared/constants.js";import{PmCliError}from"../../core/shared/errors.js";import{nowIso}from"../../core/shared/time.js";import{normalizeExtensionContributionInventory}from"../../core/extensions/contribution-inventory.js";import{normalizeExtensionNameForMatch,normalizeStringList}from"./shared.js";const MANAGED_EXTENSION_STATE_FILENAME=".managed-extensions.json",MANAGED_EXTENSION_STATE_VERSION=1;function resolveManagedExtensionStatePath(extensionsRoot){return path.join(extensionsRoot,MANAGED_EXTENSION_STATE_FILENAME)}function createEmptyManagedExtensionState(){return{version:MANAGED_EXTENSION_STATE_VERSION,updated_at:nowIso(),entries:[]}}function sortManagedEntries(entries){return[...entries].sort((left,right)=>{const byScope=left.scope.localeCompare(right.scope);if(byScope!==0)return byScope;const byName=left.name.localeCompare(right.name);return byName!==0?byName:left.directory.localeCompare(right.directory)})}function managedExtensionSourcesEquivalent(left,right){return left.kind!==right.kind||left.input!==right.input||left.location!==right.location?!1:left.kind==="npm"&&right.kind==="npm"?left.package===right.package&&left.version===right.version:left.kind==="github"&&right.kind==="github"?left.repository===right.repository&&left.ref===right.ref&&left.subpath===right.subpath&&left.commit===right.commit:left.kind==="builtin"&&right.kind==="builtin"?left.name===right.name:!0}function optionalString(value){return typeof value=="string"?value:void 0}const TIMED_OUT_UPDATE_ERROR=/^(?:npm_registry|github_remote)_lookup_timed_out$/u;function stableUpdateError(source,value){const error=optionalString(value);return error===void 0||source.kind!=="github"||error.trim().length===0||/^[a-z0-9_]+$/u.test(error.trim())?error:"github_remote_lookup_failed"}function isTimedOutUpdateError(error){return typeof error=="string"&&TIMED_OUT_UPDATE_ERROR.test(error.trim())}function optionalTimeoutBudget(error,value){return isTimedOutUpdateError(error)&&typeof value=="number"&&Number.isSafeInteger(value)&&value>0?{update_check_timeout_ms:value}:{}}function hasRequiredManagedRecordFields(entry){return typeof entry.name=="string"&&entry.name.trim().length>0&&typeof entry.directory=="string"&&entry.directory.trim().length>0&&(entry.scope==="project"||entry.scope==="global")&&typeof entry.manifest_version=="string"&&typeof entry.manifest_entry=="string"&&Array.isArray(entry.capabilities)&&entry.capabilities.every(value=>typeof value=="string")&&typeof entry.installed_at=="string"&&typeof entry.updated_at=="string"}function normalizeManagedSource(raw){if(typeof raw!="object"||raw===null)return null;const source=raw;return source.kind!=="local"&&source.kind!=="github"&&source.kind!=="npm"&&source.kind!=="builtin"||typeof source.input!="string"||typeof source.location!="string"?null:{kind:source.kind,input:source.input,location:source.location,name:optionalString(source.name),package:optionalString(source.package),version:optionalString(source.version),repository:optionalString(source.repository),owner:optionalString(source.owner),repo:optionalString(source.repo),ref:optionalString(source.ref),subpath:optionalString(source.subpath),commit:optionalString(source.commit)}}function normalizeManagedRecord(raw){if(typeof raw!="object"||raw===null)return null;const entry=raw;if(!hasRequiredManagedRecordFields(entry))return null;const source=normalizeManagedSource(entry.source);if(!source)return null;const contributions=normalizeExtensionContributionInventory(entry.contributions);return contributions===null?null:{name:entry.name.trim(),directory:entry.directory.trim(),scope:entry.scope,manifest_version:entry.manifest_version,manifest_entry:entry.manifest_entry,capabilities:normalizeStringList(entry.capabilities),contributions,installed_at:entry.installed_at,updated_at:entry.updated_at,source,last_update_check_at:optionalString(entry.last_update_check_at),last_update_remote_commit:optionalString(entry.last_update_remote_commit),last_update_remote_version:optionalString(entry.last_update_remote_version),update_available:isTimedOutUpdateError(entry.update_error)?null:typeof entry.update_available=="boolean"||entry.update_available===null?entry.update_available:void 0,update_error:stableUpdateError(source,entry.update_error),...optionalTimeoutBudget(entry.update_error,entry.update_check_timeout_ms)}}function normalizeManagedState(raw){if(typeof raw!="object"||raw===null)return null;const candidate=raw;if(candidate.version!==MANAGED_EXTENSION_STATE_VERSION||!Array.isArray(candidate.entries))return null;const entries=[];for(const rawEntry of candidate.entries){const record=normalizeManagedRecord(rawEntry);record&&entries.push(record)}return{version:MANAGED_EXTENSION_STATE_VERSION,updated_at:optionalString(candidate.updated_at)??nowIso(),entries:sortManagedEntries(entries)}}async function readManagedExtensionState(extensionsRoot){const statePath=resolveManagedExtensionStatePath(extensionsRoot),fallback=createEmptyManagedExtensionState();try{const raw=await fs.readFile(statePath,"utf8"),parsed=JSON.parse(raw),normalized=normalizeManagedState(parsed);if(!normalized)throw new PmCliError(`Managed extension state file "${statePath}" has an invalid schema. Repair or remove it before mutating extension state.`,EXIT_CODE.GENERIC_FAILURE);return{path:statePath,state:normalized,warnings:[]}}catch(error){if(error instanceof PmCliError)throw error;if(typeof error=="object"&&error!==null&&"code"in error&&isFileMissingError(error))return{path:statePath,state:fallback,warnings:[]};throw new PmCliError(`Managed extension state file "${statePath}" could not be read. Repair or remove it before mutating extension state.`,EXIT_CODE.GENERIC_FAILURE)}}async function writeManagedExtensionState(extensionsRoot,state){const statePath=resolveManagedExtensionStatePath(extensionsRoot),normalized={version:MANAGED_EXTENSION_STATE_VERSION,updated_at:nowIso(),entries:sortManagedEntries(state.entries)};await fs.mkdir(extensionsRoot,{recursive:!0}),await fs.writeFile(statePath,`${JSON.stringify(normalized,null,2)}
2
2
  `,"utf8")}function upsertManagedEntry(state,entry){const updatedEntries=state.entries.filter(candidate=>normalizeExtensionNameForMatch(candidate.name)!==normalizeExtensionNameForMatch(entry.name)&&normalizeExtensionNameForMatch(candidate.directory)!==normalizeExtensionNameForMatch(entry.directory));return updatedEntries.push(entry),{...state,updated_at:nowIso(),entries:sortManagedEntries(updatedEntries)}}async function persistManagedContributionInventory(extensionsRoot,state,extensionName,contributions){const entry=state.entries.find(candidate=>normalizeExtensionNameForMatch(candidate.name)===normalizeExtensionNameForMatch(extensionName));if(!entry)return state;const updated=upsertManagedEntry(state,{...entry,contributions});return await writeManagedExtensionState(extensionsRoot,updated),updated}export{createEmptyManagedExtensionState,managedExtensionSourcesEquivalent,normalizeManagedState,persistManagedContributionInventory,readManagedExtensionState,resolveManagedExtensionStatePath,sortManagedEntries,upsertManagedEntry,writeManagedExtensionState};
3
3
  //# sourceMappingURL=managed-state.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="d34e2cc0-5e58-5534-8480-a9ab47ec4a88")}catch{}})();import{mapWithFixedConcurrency}from"./concurrency.js";import{sortManagedEntries}from"./managed-state.js";import{checkGithubUpdate,checkNpmUpdate}from"./update-check.js";const MANAGED_UPDATE_CHECK_CONCURRENCY=4;async function refreshManagedExtensionUpdates(state,offline=!1){const entries=await mapWithFixedConcurrency(state.entries,MANAGED_UPDATE_CHECK_CONCURRENCY,async entry=>{if(!["github","npm"].includes(entry.source.kind))return entry;if(offline)return{...entry,last_update_check_at:void 0,last_update_remote_commit:void 0,last_update_remote_version:void 0,update_available:null,update_error:void 0};const updateStatus=entry.source.kind==="github"?await checkGithubUpdate(entry.source):await checkNpmUpdate(entry.source);return{...entry,last_update_check_at:updateStatus.checked_at,last_update_remote_commit:"remote_commit"in updateStatus?updateStatus.remote_commit:void 0,last_update_remote_version:"remote_version"in updateStatus?updateStatus.remote_version:void 0,update_available:updateStatus.available,update_error:updateStatus.error}});return{...state,entries:sortManagedEntries(entries)}}export{refreshManagedExtensionUpdates};
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="4f307be2-a113-558f-be2e-8b8f209285a5")}catch{}})();import{mapWithFixedConcurrency}from"./concurrency.js";import{sortManagedEntries}from"./managed-state.js";import{checkGithubUpdate,checkNpmUpdate,resolveExtensionUpdateCheckTimeoutMs,updateCheckTeardown}from"./update-check.js";const MANAGED_UPDATE_CHECK_CONCURRENCY=4;function createPermits(limit){let free=limit;const waiters=[];return{acquire:()=>free>0?(free-=1,Promise.resolve()):new Promise(resolve=>waiters.push(resolve)),release:()=>{const next=waiters.shift();next?next():free+=1}}}function withUpdateCheckTimeout(entry,timeoutMs){const{update_check_timeout_ms:_previous,...rest}=entry;return timeoutMs===void 0?rest:{...rest,update_check_timeout_ms:timeoutMs}}async function refreshManagedExtensionUpdates(state,offline=!1,timeoutMs=resolveExtensionUpdateCheckTimeoutMs(),holdPermitsThroughTeardown=!0){const providers=createPermits(MANAGED_UPDATE_CHECK_CONCURRENCY),entries=await mapWithFixedConcurrency(state.entries,MANAGED_UPDATE_CHECK_CONCURRENCY,async entry=>{if(!["github","npm"].includes(entry.source.kind))return entry;if(offline)return withUpdateCheckTimeout({...entry,last_update_check_at:void 0,last_update_remote_commit:void 0,last_update_remote_version:void 0,update_available:null,update_error:void 0},void 0);await providers.acquire();const updateStatus=entry.source.kind==="github"?await checkGithubUpdate(entry.source,void 0,timeoutMs):await checkNpmUpdate(entry.source,void 0,timeoutMs);return holdPermitsThroughTeardown?updateCheckTeardown(updateStatus).then(providers.release):providers.release(),withUpdateCheckTimeout({...entry,last_update_check_at:updateStatus.checked_at,last_update_remote_commit:"remote_commit"in updateStatus?updateStatus.remote_commit:void 0,last_update_remote_version:"remote_version"in updateStatus?updateStatus.remote_version:void 0,update_available:updateStatus.available,update_error:updateStatus.error},updateStatus.timeout_ms)});return{...state,entries:sortManagedEntries(entries)}}export{refreshManagedExtensionUpdates};
2
2
  //# sourceMappingURL=managed-update-status.js.map