@automaton-labs/aib 0.0.1

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 (291) hide show
  1. package/README.md +578 -0
  2. package/dist/bin/aib.js +2 -0
  3. package/dist/bin/cli.js +3 -0
  4. package/dist/client/http-client.js +1 -0
  5. package/dist/client/transport-options.js +1 -0
  6. package/dist/client/websocket-client.js +1 -0
  7. package/dist/commands/add-missing-imports-preview-cache.js +2 -0
  8. package/dist/commands/add-missing-imports.js +2 -0
  9. package/dist/commands/apply-module-plan.js +3 -0
  10. package/dist/commands/captured-input.js +2 -0
  11. package/dist/commands/config-command.js +3 -0
  12. package/dist/commands/diagnostics-command.js +3 -0
  13. package/dist/commands/doctor.js +1 -0
  14. package/dist/commands/entity-resolution.js +1 -0
  15. package/dist/commands/execution-command.js +1 -0
  16. package/dist/commands/feedback-command.js +3 -0
  17. package/dist/commands/find-importers.js +1 -0
  18. package/dist/commands/find-unused-imports.js +1 -0
  19. package/dist/commands/generate-docs-command.js +6 -0
  20. package/dist/commands/help-command.js +3 -0
  21. package/dist/commands/imports-command.js +1 -0
  22. package/dist/commands/init-skill-usage.js +3 -0
  23. package/dist/commands/init-workspace.js +3 -0
  24. package/dist/commands/inspect-cycles.js +5 -0
  25. package/dist/commands/inspect-format.js +18 -0
  26. package/dist/commands/inspect-graph.js +9 -0
  27. package/dist/commands/inspect-imports.js +2 -0
  28. package/dist/commands/inspect-symbol-query.js +1 -0
  29. package/dist/commands/inspect-tree.js +5 -0
  30. package/dist/commands/inspect.js +16 -0
  31. package/dist/commands/json-file-input.js +1 -0
  32. package/dist/commands/list-instances.js +1 -0
  33. package/dist/commands/module-plan-cache.js +2 -0
  34. package/dist/commands/module-plan-command.js +1 -0
  35. package/dist/commands/module-plan-timeout.js +1 -0
  36. package/dist/commands/move-command.js +1 -0
  37. package/dist/commands/move-preview-cache.js +2 -0
  38. package/dist/commands/move-to-file.js +2 -0
  39. package/dist/commands/mutation-execution-cache.js +3 -0
  40. package/dist/commands/normalize-imports.js +4 -0
  41. package/dist/commands/observability-command.js +3 -0
  42. package/dist/commands/ping.js +1 -0
  43. package/dist/commands/print-config.js +1 -0
  44. package/dist/commands/quick-read.js +11 -0
  45. package/dist/commands/refactor-batch-builder.js +1 -0
  46. package/dist/commands/refactor-batch-execution-cache.js +1 -0
  47. package/dist/commands/refactor-batch-preview-cache.js +2 -0
  48. package/dist/commands/refactor-batch.js +4 -0
  49. package/dist/commands/refactor-command.js +1 -0
  50. package/dist/commands/rename-command.js +1 -0
  51. package/dist/commands/rename-entities.js +4 -0
  52. package/dist/commands/rename-execution-cache.js +1 -0
  53. package/dist/commands/rename-input.js +1 -0
  54. package/dist/commands/rename-preview-cache.js +2 -0
  55. package/dist/commands/result-view.js +6 -0
  56. package/dist/commands/runtime-command.js +4 -0
  57. package/dist/commands/runtime-info.js +1 -0
  58. package/dist/commands/session-workspace.js +31 -0
  59. package/dist/commands/shared.js +1 -0
  60. package/dist/commands/sync-command.js +2 -0
  61. package/dist/commands/validate-module-plan.js +2 -0
  62. package/dist/commands/workspace-cache.js +1 -0
  63. package/dist/compatibility/policy.js +1 -0
  64. package/dist/config/auto-start-ide.js +1 -0
  65. package/dist/config/defaults.js +1 -0
  66. package/dist/config/env-vars.js +1 -0
  67. package/dist/config/glob-match.js +1 -0
  68. package/dist/config/import-rules.js +1 -0
  69. package/dist/config/local-config.js +3 -0
  70. package/dist/config/mutation-comments.js +1 -0
  71. package/dist/config/path-aliases.js +1 -0
  72. package/dist/config/path-display.js +1 -0
  73. package/dist/config/product-storage.js +1 -0
  74. package/dist/config/resolve-command-alias.js +1 -0
  75. package/dist/config/resolve.js +1 -0
  76. package/dist/config/workspace-root.js +3 -0
  77. package/dist/config/workspace-state.js +1 -0
  78. package/dist/content/content-bundle.js +1 -0
  79. package/dist/diagnostics/module-plan-timeline.js +2 -0
  80. package/dist/diagnostics/readiness-text.js +8 -0
  81. package/dist/discovery/registry.js +1 -0
  82. package/dist/discovery/select-instance.js +1 -0
  83. package/dist/dsl/aib-dsl.js +1 -0
  84. package/dist/help/bootstrap.md +924 -0
  85. package/dist/help/diagnostics/doctor.json +70 -0
  86. package/dist/help/docs/basics.md +14 -0
  87. package/dist/help/docs/dsl.md +25 -0
  88. package/dist/help/docs/help-format.md +12 -0
  89. package/dist/help/docs/imports.normalize.md +36 -0
  90. package/dist/help/docs/inspect.code.md +29 -0
  91. package/dist/help/docs/inspect.deps.md +32 -0
  92. package/dist/help/docs/inspect.duplicates.md +72 -0
  93. package/dist/help/docs/inspect.exports.md +34 -0
  94. package/dist/help/docs/inspect.file.md +32 -0
  95. package/dist/help/docs/inspect.graph.md +112 -0
  96. package/dist/help/docs/inspect.imports.md +15 -0
  97. package/dist/help/docs/inspect.md +71 -0
  98. package/dist/help/docs/inspect.members.md +24 -0
  99. package/dist/help/docs/inspect.tree.md +30 -0
  100. package/dist/help/docs/inspect.usages.md +48 -0
  101. package/dist/help/docs/modulePlan.md +51 -0
  102. package/dist/help/docs/move.md +37 -0
  103. package/dist/help/docs/mutation.md +47 -0
  104. package/dist/help/docs/patterns.md +178 -0
  105. package/dist/help/docs/prefs.md +40 -0
  106. package/dist/help/docs/qr.md +33 -0
  107. package/dist/help/docs/refactor.batch.md +44 -0
  108. package/dist/help/docs/rename.md +39 -0
  109. package/dist/help/docs/selectors.md +23 -0
  110. package/dist/help/docs/session.md +61 -0
  111. package/dist/help/docs/view.md +30 -0
  112. package/dist/help/dsl/bootstrap.md +924 -0
  113. package/dist/help/dsl/docs/basics.md +14 -0
  114. package/dist/help/dsl/docs/dsl.md +25 -0
  115. package/dist/help/dsl/docs/help-format.md +12 -0
  116. package/dist/help/dsl/docs/imports.normalize.md +36 -0
  117. package/dist/help/dsl/docs/inspect.code.md +29 -0
  118. package/dist/help/dsl/docs/inspect.deps.md +32 -0
  119. package/dist/help/dsl/docs/inspect.duplicates.md +72 -0
  120. package/dist/help/dsl/docs/inspect.exports.md +34 -0
  121. package/dist/help/dsl/docs/inspect.file.md +32 -0
  122. package/dist/help/dsl/docs/inspect.graph.md +112 -0
  123. package/dist/help/dsl/docs/inspect.imports.md +15 -0
  124. package/dist/help/dsl/docs/inspect.md +71 -0
  125. package/dist/help/dsl/docs/inspect.members.md +24 -0
  126. package/dist/help/dsl/docs/inspect.tree.md +30 -0
  127. package/dist/help/dsl/docs/inspect.usages.md +48 -0
  128. package/dist/help/dsl/docs/modulePlan.md +51 -0
  129. package/dist/help/dsl/docs/move.md +37 -0
  130. package/dist/help/dsl/docs/mutation.md +47 -0
  131. package/dist/help/dsl/docs/patterns.md +178 -0
  132. package/dist/help/dsl/docs/prefs.md +40 -0
  133. package/dist/help/dsl/docs/qr.md +33 -0
  134. package/dist/help/dsl/docs/refactor.batch.md +44 -0
  135. package/dist/help/dsl/docs/rename.md +39 -0
  136. package/dist/help/dsl/docs/selectors.md +23 -0
  137. package/dist/help/dsl/docs/session.md +61 -0
  138. package/dist/help/dsl/docs/view.md +30 -0
  139. package/dist/help/dsl/full.md +924 -0
  140. package/dist/help/dsl/snippets/agents.md +14 -0
  141. package/dist/help/dsl/topics/basics.md +12 -0
  142. package/dist/help/dsl/topics/dsl.md +23 -0
  143. package/dist/help/dsl/topics/help-format.md +10 -0
  144. package/dist/help/dsl/topics/imports.normalize.md +34 -0
  145. package/dist/help/dsl/topics/inspect.code.md +27 -0
  146. package/dist/help/dsl/topics/inspect.deps.md +30 -0
  147. package/dist/help/dsl/topics/inspect.duplicates.md +43 -0
  148. package/dist/help/dsl/topics/inspect.exports.md +32 -0
  149. package/dist/help/dsl/topics/inspect.file.md +30 -0
  150. package/dist/help/dsl/topics/inspect.graph.md +110 -0
  151. package/dist/help/dsl/topics/inspect.imports.md +13 -0
  152. package/dist/help/dsl/topics/inspect.md +69 -0
  153. package/dist/help/dsl/topics/inspect.members.md +22 -0
  154. package/dist/help/dsl/topics/inspect.tree.md +20 -0
  155. package/dist/help/dsl/topics/inspect.usages.md +46 -0
  156. package/dist/help/dsl/topics/modulePlan.md +38 -0
  157. package/dist/help/dsl/topics/move.md +27 -0
  158. package/dist/help/dsl/topics/mutation.md +45 -0
  159. package/dist/help/dsl/topics/patterns.md +176 -0
  160. package/dist/help/dsl/topics/prefs.md +38 -0
  161. package/dist/help/dsl/topics/qr.md +31 -0
  162. package/dist/help/dsl/topics/refactor.batch.md +33 -0
  163. package/dist/help/dsl/topics/rename.md +25 -0
  164. package/dist/help/dsl/topics/selectors.md +21 -0
  165. package/dist/help/dsl/topics/session.md +59 -0
  166. package/dist/help/dsl/topics/view.md +28 -0
  167. package/dist/help/full.md +924 -0
  168. package/dist/help/help-meta.json +113 -0
  169. package/dist/help/index.md +167 -0
  170. package/dist/help/json/bootstrap.md +1074 -0
  171. package/dist/help/json/docs/basics.md +15 -0
  172. package/dist/help/json/docs/dsl.md +25 -0
  173. package/dist/help/json/docs/help-format.md +12 -0
  174. package/dist/help/json/docs/imports.normalize.md +47 -0
  175. package/dist/help/json/docs/inspect.code.md +41 -0
  176. package/dist/help/json/docs/inspect.deps.md +46 -0
  177. package/dist/help/json/docs/inspect.duplicates.md +65 -0
  178. package/dist/help/json/docs/inspect.exports.md +40 -0
  179. package/dist/help/json/docs/inspect.file.md +38 -0
  180. package/dist/help/json/docs/inspect.graph.md +139 -0
  181. package/dist/help/json/docs/inspect.imports.md +15 -0
  182. package/dist/help/json/docs/inspect.md +87 -0
  183. package/dist/help/json/docs/inspect.members.md +32 -0
  184. package/dist/help/json/docs/inspect.tree.md +30 -0
  185. package/dist/help/json/docs/inspect.usages.md +61 -0
  186. package/dist/help/json/docs/modulePlan.md +70 -0
  187. package/dist/help/json/docs/move.md +53 -0
  188. package/dist/help/json/docs/mutation.md +62 -0
  189. package/dist/help/json/docs/patterns.md +178 -0
  190. package/dist/help/json/docs/prefs.md +40 -0
  191. package/dist/help/json/docs/qr.md +33 -0
  192. package/dist/help/json/docs/refactor.batch.md +72 -0
  193. package/dist/help/json/docs/rename.md +47 -0
  194. package/dist/help/json/docs/selectors.md +23 -0
  195. package/dist/help/json/docs/session.md +77 -0
  196. package/dist/help/json/docs/view.md +30 -0
  197. package/dist/help/json/full.md +1074 -0
  198. package/dist/help/json/snippets/agents.md +14 -0
  199. package/dist/help/json/topics/basics.md +13 -0
  200. package/dist/help/json/topics/dsl.md +23 -0
  201. package/dist/help/json/topics/help-format.md +10 -0
  202. package/dist/help/json/topics/imports.normalize.md +45 -0
  203. package/dist/help/json/topics/inspect.code.md +39 -0
  204. package/dist/help/json/topics/inspect.deps.md +44 -0
  205. package/dist/help/json/topics/inspect.duplicates.md +37 -0
  206. package/dist/help/json/topics/inspect.exports.md +38 -0
  207. package/dist/help/json/topics/inspect.file.md +36 -0
  208. package/dist/help/json/topics/inspect.graph.md +137 -0
  209. package/dist/help/json/topics/inspect.imports.md +13 -0
  210. package/dist/help/json/topics/inspect.md +85 -0
  211. package/dist/help/json/topics/inspect.members.md +30 -0
  212. package/dist/help/json/topics/inspect.tree.md +20 -0
  213. package/dist/help/json/topics/inspect.usages.md +59 -0
  214. package/dist/help/json/topics/modulePlan.md +57 -0
  215. package/dist/help/json/topics/move.md +43 -0
  216. package/dist/help/json/topics/mutation.md +60 -0
  217. package/dist/help/json/topics/patterns.md +176 -0
  218. package/dist/help/json/topics/prefs.md +38 -0
  219. package/dist/help/json/topics/qr.md +31 -0
  220. package/dist/help/json/topics/refactor.batch.md +61 -0
  221. package/dist/help/json/topics/rename.md +42 -0
  222. package/dist/help/json/topics/selectors.md +21 -0
  223. package/dist/help/json/topics/session.md +59 -0
  224. package/dist/help/json/topics/view.md +28 -0
  225. package/dist/help/snippets/agents.md +14 -0
  226. package/dist/help/topics/basics.md +12 -0
  227. package/dist/help/topics/dsl.md +23 -0
  228. package/dist/help/topics/help-format.md +10 -0
  229. package/dist/help/topics/imports.normalize.md +34 -0
  230. package/dist/help/topics/inspect.code.md +27 -0
  231. package/dist/help/topics/inspect.deps.md +30 -0
  232. package/dist/help/topics/inspect.duplicates.md +43 -0
  233. package/dist/help/topics/inspect.exports.md +32 -0
  234. package/dist/help/topics/inspect.file.md +30 -0
  235. package/dist/help/topics/inspect.graph.md +110 -0
  236. package/dist/help/topics/inspect.imports.md +13 -0
  237. package/dist/help/topics/inspect.md +69 -0
  238. package/dist/help/topics/inspect.members.md +22 -0
  239. package/dist/help/topics/inspect.tree.md +20 -0
  240. package/dist/help/topics/inspect.usages.md +46 -0
  241. package/dist/help/topics/modulePlan.md +38 -0
  242. package/dist/help/topics/move.md +27 -0
  243. package/dist/help/topics/mutation.md +45 -0
  244. package/dist/help/topics/patterns.md +176 -0
  245. package/dist/help/topics/prefs.md +38 -0
  246. package/dist/help/topics/qr.md +31 -0
  247. package/dist/help/topics/refactor.batch.md +33 -0
  248. package/dist/help/topics/rename.md +25 -0
  249. package/dist/help/topics/selectors.md +21 -0
  250. package/dist/help/topics/session.md +59 -0
  251. package/dist/help/topics/view.md +28 -0
  252. package/dist/ide-launch/common.cjs +162 -0
  253. package/dist/managed-host/extension-vsix-resolver.js +1 -0
  254. package/dist/managed-host/manage-serve-web-host.cjs +141 -0
  255. package/dist/managed-host/serve-web-autostart.js +1 -0
  256. package/dist/managed-host/serve-web-host.cjs +1790 -0
  257. package/dist/metrics/central-metrics.js +2 -0
  258. package/dist/observability/config.js +1 -0
  259. package/dist/observability/context.js +1 -0
  260. package/dist/observability/failure-snapshot.js +2 -0
  261. package/dist/observability/recent.js +2 -0
  262. package/dist/payloads/read-stdin-json.js +1 -0
  263. package/dist/runtime/bundled-node.js +1 -0
  264. package/dist/runtime/input-source.js +1 -0
  265. package/dist/runtime/managed-runtime-provisioning.js +1 -0
  266. package/dist/runtime/run-command.js +1 -0
  267. package/dist/selectors/parse-entities.js +1 -0
  268. package/dist/session/client.js +1 -0
  269. package/dist/session/paths.js +1 -0
  270. package/dist/session/server.js +6 -0
  271. package/dist/shared/agent-text.js +1 -0
  272. package/dist/shared/diagnostic-catalog.js +1 -0
  273. package/dist/shared/diagnostics.js +1 -0
  274. package/dist/shared/errors.js +28 -0
  275. package/dist/shared/event-loop.js +1 -0
  276. package/dist/shared/hints.js +1 -0
  277. package/dist/shared/metrics.js +1 -0
  278. package/dist/shared/operations.js +1 -0
  279. package/dist/shared/presentation.js +4 -0
  280. package/dist/shared/protocol.js +1 -0
  281. package/dist/shared/routes.js +1 -0
  282. package/dist/shared/stdout.js +2 -0
  283. package/dist/shared/types.js +1 -0
  284. package/dist/tracing/config.js +2 -0
  285. package/dist/tracing/trace.js +3 -0
  286. package/extension/vscode-refactor-bridge-extension.vsix +0 -0
  287. package/package.json +39 -0
  288. package/runtimes/launcher/win-x64/aib.exe +0 -0
  289. package/scripts/install-windows-launcher.cjs +58 -0
  290. package/scripts/postinstall.cjs +28 -0
  291. package/scripts/provision-runtime.cjs +299 -0
@@ -0,0 +1,5 @@
1
+ "use strict";var V=exports&&exports.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var r=Object.getOwnPropertyDescriptor(e,n);(!r||("get"in r?!e.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,r)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),H=exports&&exports.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),C=exports&&exports.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var i=[];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(i[i.length]=r);return i},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var i=t(e),r=0;r<i.length;r++)i[r]!=="default"&&V(n,e,i[r]);return H(n,e),n}})();Object.defineProperty(exports,"__esModule",{value:!0}),exports.isInspectTreeRequest=K,exports.runInspectTree=G,exports.buildInspectTreeResult=J;const I=C(require("node:fs")),d=C(require("node:path")),Q=require("../shared/agent-text"),h=require("../shared/errors"),g=require("../config/path-display"),R=require("../config/local-config"),A=require("./session-workspace"),X=2,w=80,O=["node_modules/**","**/node_modules/**",".git/**","**/.git/**","dist/**","**/dist/**","build/**","**/build/**","out/**","**/out/**",".tmp/**","**/.tmp/**"];function K(t,e){if(t[0]==="tree")return!0;if(!t.includes("--stdin")||!b(e))return!1;const n=v(e);return n.length>0&&n.some(i=>m(i.op)==="tree")}function G(t,e,n){const i=(0,g.buildDisplayPathAliases)(t,(0,A.readEffectiveSessionPathAliases)(t)),r=(0,R.resolveLocalCliConfig)(t),o=Y(t,e,n,i).map(u=>$(t,u,i,r.config.inspect.tree)),l=o.length===1?o[0]:{results:o};return(0,Q.attachAgentText)(l,re(l))}function J(t,e){const n=(0,g.buildDisplayPathAliases)(t,e.aliases??(0,A.readEffectiveSessionPathAliases)(t)),i={scope:e.scope,include:e.include??[],exclude:e.exclude??[],onlyDirs:e.onlyDirs??!1};e.displayScope!==void 0&&(i.displayScope=e.displayScope),e.depth!==void 0&&(i.depth=e.depth),e.minDepth!==void 0&&(i.minDepth=e.minDepth),e.limit!==void 0&&(i.limit=e.limit);const r=x(t,i);return $(t,r,n,(0,R.resolveLocalCliConfig)(t).config.inspect.tree)}function Y(t,e,n,i){if(e[0]==="tree")return[Z(t,e.slice(1),i)];if(!e.includes("--stdin")||!b(n))throw new h.CliError("INSPECT_TREE_SCOPE_REQUIRED","inspect tree expects a file or directory scope.");const r=v(n);if(r.some(s=>m(s.op)!=="tree"))throw new h.CliError("INSPECT_TREE_MIXED_BATCH_UNSUPPORTED","inspect tree --stdin expects only tree requests.");return r.map((s,o)=>k(t,s,o,i))}function Z(t,e,n){const r=e.filter(s=>!s.startsWith("--")&&!ue(e,s))[0];if(!r)throw new h.CliError("INSPECT_TREE_SCOPE_REQUIRED","inspect tree expects a file or directory scope.");return x(t,{scope:r,depth:B(e,"--depth"),minDepth:U(e,"--min-depth")??U(e,"--minDepth"),limit:B(e,"--limit"),include:[..._(e,"--include"),..._(e,"--includes")],exclude:[..._(e,"--exclude"),..._(e,"--excludes")],onlyDirs:e.includes("--only-dirs")||e.includes("--onlyDirs")},n)}function k(t,e,n,i){const r=m(e.scope)??m(e.file)??m(e.dir)??m(e.directory);if(!r)throw new h.CliError("INSPECT_TREE_SCOPE_REQUIRED",`Inspect tree request at index ${n} requires scope.`);return x(t,{scope:r,depth:N(e.depth),minDepth:S(e.minDepth)??S(e.min_depth),limit:N(e.limit),include:E(e.include)??E(e.includes)??[],exclude:E(e.exclude)??E(e.excludes)??[],onlyDirs:W(e.onlyDirs)??W(e.only_dirs)??!1},i)}function x(t,e,n=[]){const i=e.depth??X,r=e.minDepth??0,s=ce(t,e.scope);if(r>i)throw new h.CliError("INSPECT_TREE_DEPTH_INVALID","inspect tree minDepth must be <= depth.");return{scope:s,displayScope:e.displayScope??(0,g.compactDisplayPath)(t,s,n),depth:i,minDepth:r,limit:e.limit??w,include:e.include,exclude:e.exclude,onlyDirs:e.onlyDirs}}function $(t,e,n=[],i={onlyDirs:{exclude:[],include:[]},files:{exclude:[],include:[]}}){const r=le(e.scope);if(!r)throw new h.CliError("INSPECT_TREE_SCOPE_NOT_FOUND","inspect tree scope was not found.",{scope:F(t,e.scope)});const s=r.isDirectory()?e.scope:d.dirname(e.scope),o=e.displayScope??(0,g.compactDisplayPath)(t,e.scope,n),l=e.onlyDirs?i.onlyDirs:i.files,u=q(e,l),c=u.include.map(D),f=[...O,...u.exclude].map(D),a=M(t,s,e.depth,f).filter(p=>e.onlyDirs?p.kind==="dir":p.kind==="file").filter(p=>c.length===0||P(c,p.relative)).filter(p=>p.depth>=e.minDepth),y=a.slice(0,e.limit),z=ee(t,e,s,o,y,u);return{ok:!0,op:"tree",scope:o,depth:e.depth,minDepth:e.minDepth,onlyDirs:e.onlyDirs,[e.onlyDirs?"dirs":"files"]:a.length,shown:y.length,...e.include.length>0?{include:e.include}:{},...e.exclude.length>0?{exclude:e.exclude}:{},...a.length>y.length?{hidden:a.length-y.length}:{},lines:z}}function q(t,e){return{include:t.include.length>0?t.include:e.include,exclude:oe([...e.exclude,...t.exclude])}}function M(t,e,n,i){const r=[],s=(o,l)=>{if(l>n)return;const u=I.readdirSync(o,{withFileTypes:!0}).filter(c=>!c.name.startsWith(".")||c.name===".github").sort((c,f)=>Number(f.isDirectory())-Number(c.isDirectory())||c.name.localeCompare(f.name));for(const c of u){const f=d.join(o,c.name),T=F(t,f),a=c.isDirectory()?"dir":"file";P(i,T)||(r.push({absolute:f,relative:T,depth:l,kind:a}),c.isDirectory()&&s(f,l+1))}};return s(e,1),r}function ee(t,e,n,i,r,s){const o=[`tree ${i.replace(/\\/g,"/")}`];if(e.minDepth>0&&o.push(`depth: ${e.minDepth}..${e.depth}`),e.include.length>0&&o.push(`include: ${e.include.join(", ")}`),e.exclude.length>0&&o.push(`exclude: ${e.exclude.join(", ")}`),e.onlyDirs&&o.push("onlyDirs: true"),o.push(""),r.length===0)return o.push("no matching paths"),o;if(te(o,i,n,r),typeof e.limit=="number"&&e.limit>0&&r.length===e.limit){const l=ie(t,e,n,s);l>r.length&&o.push(`+ ${l-r.length} more paths`)}return o}function te(t,e,n,i){const r=ne(n,i);t.push(`${e.replace(/\\/g,"/").replace(/\/?$/,"/")}`),j(t,r," ")}function ne(t,e){const n=new Map;for(const i of e){const r=d.relative(t,i.absolute).replace(/\\/g,"/").split("/").filter(Boolean);let s=n;for(let o=0;o<r.length;o+=1){const l=r[o];if(o===r.length-1)s.get(l)instanceof Map||s.set(l,i.kind);else{let c=s.get(l);c instanceof Map||(c=new Map,s.set(l,c)),s=c}}}return n}function j(t,e,n){for(const[i,r]of Array.from(e.entries()).sort(([s,o],[l,u])=>+(u instanceof Map)-+(o instanceof Map)||s.localeCompare(l)))r instanceof Map?(t.push(`${n}${i}/`),j(t,r,`${n} `)):r==="dir"?t.push(`${n}${i}/`):t.push(`${n}${i}`)}function ie(t,e,n,i){const r=i.include.map(D),s=[...O,...i.exclude].map(D);return M(t,n,e.depth,s).filter(o=>e.onlyDirs?o.kind==="dir":o.kind==="file").filter(o=>r.length===0||P(r,o.relative)).filter(o=>o.depth>=e.minDepth).length}function re(t){if(Array.isArray(t.results)){const e=t.results.filter(b).map(n=>Array.isArray(n.lines)?n.lines.filter(i=>typeof i=="string").join(`
2
+ `):"").filter(Boolean);return e.length>0?e.join(`
3
+
4
+ `):null}return Array.isArray(t.lines)?t.lines.filter(e=>typeof e=="string").join(`
5
+ `):null}function v(t){return Array.isArray(t.requests)?t.requests.filter(b):[t]}function D(t){const e=t.replace(/\\/g,"/").replace(/^\.?\//,"");let n="";for(let i=0;i<e.length;i+=1){const r=e[i];if(r==="*"){e[i+1]==="*"?(n+=".*",i+=1):n+="[^/]*";continue}n+=se(r)}return new RegExp(`^${n}$`)}function P(t,e){return t.some(n=>n.test(e)||n.test(`${e}/`))}function oe(t){return Array.from(new Set(t))}function se(t){return t.replace(/[|\\{}()[\]^$+?.]/g,"\\$&")}function le(t){try{return I.statSync(t)}catch{return null}}function ce(t,e){return d.normalize(d.isAbsolute(e)?e:d.resolve(t,e))}function F(t,e){const n=d.relative(t,e);return(n&&!n.startsWith("..")&&!d.isAbsolute(n)?n:e).replace(/\\/g,"/")}function L(t,e){const n=t.indexOf(e);if(n<0)return null;const i=t[n+1];return i&&!i.startsWith("--")?i:null}function _(t,e){const n=[];for(let i=0;i<t.length;i+=1){if(t[i]!==e)continue;const r=t[i+1];r&&!r.startsWith("--")&&(n.push(...r.split(",").map(s=>s.trim()).filter(Boolean)),i+=1)}return n}function ue(t,e){const n=t.indexOf(e);return n>0&&t[n-1]?.startsWith("--")===!0}function B(t,e){return N(L(t,e))}function U(t,e){return S(L(t,e))}function N(t){const e=typeof t=="number"?t:typeof t=="string"?Number(t):NaN;return Number.isInteger(e)&&e>0?e:null}function S(t){const e=typeof t=="number"?t:typeof t=="string"?Number(t):NaN;return Number.isInteger(e)&&e>=0?e:null}function m(t){return typeof t=="string"&&t.length>0?t:null}function E(t){return typeof t=="string"&&t.length>0?t.split(",").map(e=>e.trim()).filter(Boolean):Array.isArray(t)?t.filter(e=>typeof e=="string"&&e.length>0):null}function W(t){if(typeof t=="boolean")return t;if(typeof t!="string")return null;const e=t.trim().toLowerCase();return e==="true"?!0:e==="false"?!1:null}function b(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}
@@ -0,0 +1,16 @@
1
+ "use strict";var ht=exports&&exports.__createBinding||(Object.create?(function(e,t,n,s){s===void 0&&(s=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,s,i)}):(function(e,t,n,s){s===void 0&&(s=n),e[s]=t[n]})),gt=exports&&exports.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),ve=exports&&exports.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(n){var s=[];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(s[s.length]=i);return s},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(t!=null)for(var s=e(t),i=0;i<s.length;i++)s[i]!=="default"&&ht(n,t,s[i]);return gt(n,t),n}})();Object.defineProperty(exports,"__esModule",{value:!0}),exports.runInspect=Ce;const L=ve(require("node:path")),ye=ve(require("node:fs")),bt=require("node:crypto"),It=require("../client/http-client"),xt=require("../shared/routes"),At=require("../shared/protocol"),E=require("../shared/errors"),V=require("../shared/agent-text"),ie=require("./shared"),$=require("./inspect-format"),w=require("./module-plan-cache"),he=require("./json-file-input"),ge=require("./inspect-graph"),De=require("./inspect-cycles"),be=require("./inspect-imports"),oe=require("./inspect-tree"),Y=require("../config/path-display"),S=require("./session-workspace"),St=require("./entity-resolution");async function Ce(e,t,n,s={},i={}){if(Et(t))return Nt(e,t);if((0,ge.isInspectGraphRequest)(t,n))return(0,ge.runInspectGraph)(e,t,n);if((0,De.isInspectCyclesRequest)(t,n))return(0,De.runInspectCycles)(e,t,n);if((0,oe.isInspectTreeRequest)(t,n))return(0,oe.runInspectTree)(e,t,n);if(t[0]==="imports")return(0,be.runInspectImports)(e,t,n);const o=Xt(e,t,n);if(o&&Yt(o))return qt(e,t,o,s,i);i.allowModulePlan!==!0&&Un(t,n)&&ct();const l=await(0,ie.resolveCompatibleTargetInstance)(e,At.CLI_COMMAND_IDS.inspect,s),r=await(0,ie.fetchEffectiveConfig)(l.entry,s),c=mn(e,t,n,r,i.allowModulePlan===!0,i.forceResults===!0);an(e,c),await _t(l.entry,c.payload,r,s),sn(e,c);const u=await(0,It.postJson)(l.entry,xt.EXTENSION_ROUTES.inspect,c.payload,(0,ie.extensionRequestOptions)(s));on(e,c,u);const d=(0,$.formatInspectResponse)(u,r,c.formatOptions);return Ct(rn(vt(e,u,d,c),c.revision),c)}async function _t(e,t,n,s){const i=Array.isArray(t.requests)?t.requests.filter(p):[],o=new Map;for(const l of i){const r=a(l.op);if(r!=="code"&&r!=="slice"&&r!=="dependencies"&&r!=="members"&&r!=="usages")continue;const c=a(l.sourceFile),u=a(l.symbolName);if(!c||!u)continue;const d=a(l.symbolKind);if(d==="constructor")continue;const m={raw:u,symbolName:u,symbolKind:d},y=o.get(c)??[];y.push(m),o.set(c,y)}for(const[l,r]of o)await(0,St.ensureSelectorsResolvable)(e,l,r,n,(0,ie.extensionRequestOptions)(s))}function Et(e){return e[0]==="usages"&&F(e,"--from-file")!==null}function Nt(e,t){const n=F(t,"--from-file");if(!n)throw new E.CliError("USAGES_FROM_FILE_REQUIRED","inspect usages --from-file expects a saved usages handle or JSON file.");const s=(0,S.resolveSessionFileArgument)(e,n),i=(0,he.readJsonObjectFile)(e,s,"INVALID_USAGES_ARTIFACT"),o=R(t,"--focus"),l=Ie(e,{detail:F(t,"--detail")??"locations",all:t.includes("--all"),limit:H(t,"--limit"),maxCodeLines:H(t,"--max-code-lines")??H(t,"--maxCodeLines")});if(l.detail==="summary")throw new E.CliError("INVALID_USAGES_DETAIL","inspect usages --from-file --detail expects locations or code.");if(l.detail!=="locations"&&l.detail!=="code")throw new E.CliError("INVALID_USAGES_DETAIL","inspect usages --detail expects locations or code.");const r=Oe(e,i,o,l);return(0,V.attachAgentText)(r,xe(e,r))}function vt(e,t,n,s){const i=s.usagesDetails??[],o=Dt(n,s);if(i.length===0||i.every(m=>m===null||m.detail==="summary"))return o;const l=Array.isArray(t.results)?t.results.filter(p):[];if(l.length===0)return o;const r=Array.isArray(o.results)?o.results.filter(p):[o],c=Array.isArray(s.payload.requests)?s.payload.requests.filter(p):[],u=l.map((m,y)=>{const h=i[y],A=r[y]??{};if(c[y]?.targetLocalUsagesHidden===!0&&(m.targetLocalUsagesHidden=!0),m.op!=="usages"||h===void 0||h===null||h.detail==="summary")return A;const I=Oe(e,m,[],h,!0);return Tt(A,I),I});Mt(e,u),Ut(u);const d=u.length===1?u[0]:{results:u};return(0,V.attachAgentText)(d,Bt(e,d,o))}function Dt(e,t){const n=Array.isArray(t.payload.requests)?t.payload.requests.filter(p):[],s=Array.isArray(e.results)?e.results.filter(p):null;return s?(s.forEach((i,o)=>Pe(i,n[o])),e):(Pe(e,n[0]),e)}function Pe(e,t){t?.targetLocalUsagesHidden===!0&&(e.targetLocalUsagesHidden=!0,e.scope==="excluding target"&&delete e.scope)}function Ct(e,t){return Fe(e,t.dslDiagnostics??[])}function Fe(e,t){if(t.length===0)return e;const n=(0,V.readAgentText)(e),s=Pt(t);return(0,V.attachAgentText)({...e,dslDiagnostics:t.map(i=>({line:i.line,message:i.message}))},n?`${n.trimEnd()}
2
+
3
+ ${s}`:s)}function Pt(e){return["dsl errors:",...e.map(t=>`line ${t.line}: ${t.message}`)].join(`
4
+ `)}function Le(e){const t=e.dslDiagnostics;if(!Array.isArray(t))return{};const n=t.flatMap(s=>{if(!p(s))return[];const i=typeof s.line=="number"&&Number.isFinite(s.line)?s.line:null,o=typeof s.message=="string"&&s.message.length>0?s.message:null;return i!==null&&o!==null?[{line:i,message:o}]:[]});return n.length>0?{dslDiagnostics:n}:{}}function Oe(e,t,n,s,i=!1){const o=s.detail==="code"?Kt(e,t,n,s):jt(e,t,n,s);return $t(e,o,i),o}function Ft(e,t){return Ot(t??(0,S.readSessionStringPref)(e,"inspect.usages.detail","locations"))}function Ie(e,t){const n=t.all===!0,s=n?Number.MAX_SAFE_INTEGER:t.limit??(0,S.readSessionNumberPref)(e,"inspect.usages.maxLocations",12),i=n?Number.MAX_SAFE_INTEGER:t.limit??(0,S.readSessionNumberPref)(e,"inspect.usages.maxCodeBlocks",8);return{detail:Ft(e,t.detail),locationLimit:s,codeBlockLimit:i,maxCodeLines:t.maxCodeLines??(0,S.readSessionNumberPref)(e,"inspect.code.maxNonEmptyLines",120),all:n}}function Lt(e){return typeof e=="string"?e:null}function Ot(e){const t=e.trim().toLowerCase();if(t==="location")return"locations";if(t==="locations"||t==="code"||t==="summary")return t;throw new E.CliError("INVALID_USAGES_DETAIL","usages detail expects summary, locations, or code.",{detail:e})}function Tt(e,t){for(const n of["summary","saved","next","input","targetLocalUsagesHidden"])e[n]!==void 0&&(t[n]=e[n])}function $t(e,t,n){const s=Array.isArray(t.__viewItems)?t.__viewItems.filter(p):[];if(delete t.__viewItems,s.length===0)return;const i=Z({version:1,kind:"usages",source:"inspect",detail:a(t.detail)??"locations",target:a(t.target)??"",items:s}),o=(0,S.saveSessionResultViewJson)(e,Te(i),i);o&&(t.view=o.saved,n&&(t.__viewRecord=i))}function Mt(e,t){const n=t.map(r=>p(r.__viewRecord)?r.__viewRecord:null).filter(r=>r!==null&&a(r.kind)==="usages");if(n.length<=1)return;const s=Array.from(new Set(n.map(r=>a(r.detail)??"").filter(r=>r!==""))),i=n.flatMap(r=>Array.isArray(r.items)?r.items.filter(p):[]);if(i.length===0)return;const o=Z({version:1,kind:"usages",source:"inspect",detail:s.length===1?s[0]:"mixed",items:i}),l=(0,S.saveSessionResultViewJson)(e,Te(o),o);if(l)for(const r of t)p(r.__viewRecord)&&a(r.__viewRecord.kind)==="usages"&&(r.viewAllUsages=l.saved)}function Ut(e){for(const t of e)delete t.__viewRecord,delete t.__viewItems}function Te(e){return`res_${(0,bt.createHash)("sha256").update(JSON.stringify(e)).digest("hex").slice(0,8)}`}function Z(e){const t={};for(const[n,s]of Object.entries(e))s!==void 0&&s!==""&&(t[n]=s);return t}function Bt(e,t,n){if(Array.isArray(t.results)){const i=[],o=t.results.filter(p);let l=[];const r=()=>{if(l.length===0)return;const c=(0,$.formatInspectMixedAgentText)({results:l});c&&i.push(c),l=[]};for(const c of o){const u=a(c.detail);if(u==="locations"||u==="code"){r();const d=xe(e,c);d&&i.push(d);continue}if(a(c.op)==="usages"){r();const d=Rt(c);d&&i.push(d);continue}l.push(c)}return r(),kt(i,o),i.length>0?i.join(`
5
+
6
+ `):null}const s=a(t.detail);return s==="locations"||s==="code"?xe(e,t):(0,V.readAgentText)(n)}function kt(e,t){const n=Array.from(new Set(t.map(i=>a(i.viewAllUsages)??"").filter(i=>i!=="")));if(n.length===0)return;const s=t.every(i=>a(i.op)==="usages");e.push(s?`view all: ${n[0]}`:["view all:",`usages: ${n[0]}`].join(`
7
+ `))}function Rt(e){const t=[],n=a(e.target);t.push(n?`usages ${n}`:"usages");const s=a(e.summary);s&&t.push(s),Ae(t,e);const i=Array.isArray(e.items)?e.items.filter(p):[];for(const o of i){const l=a(o.entity)??"",r=a(o.summary)??"";t.push(`${l}: ${r}`.trim());const c=Array.isArray(o.usedBy)?o.usedBy.filter(u=>typeof u=="string"):[];t.push(...c)}return t.length>1?t.join(`
8
+ `):null}function jt(e,t,n,s){const i=$e(t,n),o=[],r=i.map(c=>{const u=re(c);let d=0,m=0;const y=[],h=Array.isArray(c.usedBy)?c.usedBy.filter(p).flatMap(I=>{const O=Array.isArray(I.locations)?I.locations.filter(p):[],v=Q(e,a(I.file)??""),b=[],_=O.flatMap(D=>{const P=typeof D.line=="number"?D.line:0,f=p(D.container)?le(D.container):"";return d>=s.locationLimit?(m+=1,b.push({line:P,...f!==""?{container:f}:{}}),o.push(Z({name:u,text:f?`${v}:${P} ${f}`:`${v}:${P}`})),[]):(d+=1,[{line:P,...f!==""?{container:f}:{}}])});return b.length>0&&y.push({file:v,locations:b}),_.length>0?[{file:v,locations:_}]:[]}):[],A={entity:u,referenceCount:j(c.referenceCount),usedBy:h,...m>0?{hidden:`+ ${m} more locations`}:{}},C=y.length>0?{entity:u,referenceCount:m,usedBy:y}:null;return{displayItem:A,hiddenItem:C}}).map(c=>c.displayItem);return{op:"usages",detail:"locations",target:Q(e,a(t.targetPath)??""),summary:a(t.summary)??"",referenceCount:j(t.referenceCount),itemCount:j(t.itemCount),fileCount:j(t.fileCount),scopeLabel:Ue(e,t),targetMode:a(t.targetMode)??"",queryMode:a(t.queryMode)??"",targetLocalUsagesHidden:t.targetLocalUsagesHidden===!0,unused:Me(i),items:r,...o.length>0?{__viewItems:o}:{}}}function Kt(e,t,n,s){const i=s.maxCodeLines,o=[],l=new Set,r=new Map,c=new Map,u=[],d=$e(t,n);for(const m of d){const y=re(m),h=Array.isArray(m.usedBy)?m.usedBy.filter(p):[];for(const A of h){const C=a(A.file);if(!C)continue;const I=Array.isArray(A.locations)?A.locations.filter(p):[];for(const O of I){const v=p(O.container)?O.container:null,b=v&&p(v.range)?v.range:null,_=b&&p(b.start)?b.start:null,D=b&&p(b.end)?b.end:null;if(!_||!D||typeof _.line!="number"||typeof _.character!="number"||typeof D.line!="number"||typeof D.character!="number")continue;const P=`${y}:${C}:${_.line}:${_.character}:${D.line}:${D.character}`;if(l.has(P))continue;l.add(P);const f=r.get(y)??0,M=Wt(C,_.line,_.character,D.line,D.character),U=_.line+1,G={entity:y,file:Q(e,C),container:v?le(v):"",line:U,code:M};if(f>=s.codeBlockLimit){c.set(y,(c.get(y)??0)+1),u.push(Z({name:y,text:Ke(G,!1).join(`
9
+ `).trim()}));continue}r.set(y,f+1);const x=Qt(M),ee=`code omitted: ${x} non-empty lines; exceeds inspect.code.maxNonEmptyLines=${i}`;x>i&&u.push(Z({name:y,text:Ke(G,!1).join(`
10
+ `).trim()})),o.push({entity:y,file:Q(e,C),container:v?le(v):"",line:U,...x<=i?{code:M}:{omitted:ee,compactCode:wt(M)}})}}}return{op:"usages",detail:"code",target:Q(e,a(t.targetPath)??""),summary:a(t.summary)??"",referenceCount:j(t.referenceCount),itemCount:j(t.itemCount),fileCount:j(t.fileCount),scopeLabel:Ue(e,t),targetMode:a(t.targetMode)??"",queryMode:a(t.queryMode)??"",targetLocalUsagesHidden:t.targetLocalUsagesHidden===!0,unused:Me(d),blocks:o,hiddenBlocks:Array.from(c.entries()).map(([m,y])=>({entity:m,hidden:`+ ${y} more code blocks`})),...u.length>0?{__viewItems:u}:{}}}function $e(e,t){const n=Array.isArray(e.items)?e.items.filter(p):[];if(t.length===0)return n;const s=new Set(t.map(i=>i.trim()).filter(Boolean));return n.filter(i=>{const o=Vt(i),l=re(i);return s.has(o)||s.has(l)})}function Vt(e){return p(e.entity)?a(e.entity.name)??"":""}function re(e){return p(e.entity)?le(e.entity):""}function Me(e){return e.filter(t=>j(t.referenceCount)===0).map(t=>re(t)).filter(t=>t!=="")}function Ue(e,t){const n=K(t.usageScopes)??[];return n.length===0?"project":n.length===1?Q(e,n[0]):`${n.length} scopes`}function wt(e){const n=e.trim().split(/\r?\n/).map(i=>i.trimEnd()).filter(i=>i.trim()!=="")[0]??"";if(!n)return"";const s=n.indexOf("{");return s>=0?`${n.slice(0,s+1)}...}`:`${n} ...`}function Gt(e,t,n){const s=e.slice(0,t),i=e.length-s.length;return i>0?`${s.join(", ")}, + ${i} ${n}`:s.join(", ")}function j(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function le(e){const t=Array.isArray(e.path)?e.path.filter(n=>typeof n=="string"&&n.trim()!==""):[];return t.length>0?t.join("."):a(e.name)??""}function xe(e,t){const n=a(t.detail);if(j(t.referenceCount)===0){const r=a(t.target),c=a(t.scopeLabel)??"project",u=[r?`usages ${r}`:"usages",`0 refs in ${c}`];Ae(u,t);const d=j(t.itemCount);return(a(t.targetMode)==="directory"||a(t.queryMode)!=="explicit")&&d>0&&u.push(`symbols checked: ${d}`),u.join(`
11
+ `)}const s=[`usages ${n??"detail"}`];if(Ae(s,t),n==="code"){const r=Array.isArray(t.blocks)?t.blocks.filter(p):[],{ownerGroups:c,standalone:u}=ae(r,d=>a(d.entity)??"");for(const[d,m]of c){s.push(""),s.push(`// ${d}:`);for(const[y,h]of Se(m,A=>ce(a(A.entity)??"").name))y&&s.push(`// ${y}`),s.push(...Re(e,t,h))}if(u.length>0){c.length>0&&s.push("");for(const[d,m]of Se(u,y=>a(y.entity)??""))d&&s.push(`// ${d}`),s.push(...Re(e,t,m))}return ke(s,t),Be(s,t),s.join(`
12
+ `).replace(/\n{3,}/g,`
13
+
14
+ `).trimEnd()}const i=Array.isArray(t.items)?t.items.filter(p).filter(r=>j(r.referenceCount)>0):[],{ownerGroups:o,standalone:l}=ae(i,r=>a(r.entity)??"");for(const[r,c]of o){s.push(""),s.push(`// ${r}:`);for(const u of c)s.push(...Ve(u,!1))}l.length>0&&o.length>0&&s.push("");for(const r of l)s.push(...Ve(r,!0));return ke(s,t),Be(s,t),s.join(`
15
+ `).trimEnd()}function Be(e,t){const n=a(t.view);n&&(e.length>0&&e[e.length-1]!==""&&e.push(""),e.push(`view: ${n}`))}function ke(e,t){const n=Array.isArray(t.unused)?t.unused.filter(s=>typeof s=="string"&&s!==""):[];if(n.length!==0){if(a(t.queryMode)==="explicit"){e.push(""),e.push(`unused: ${Gt(n,2,"more")}`);return}a(t.targetMode)==="file"&&(e.push(""),e.push(`unused symbols: ${n.length}`))}}function Ae(e,t){t.targetLocalUsagesHidden===!0&&e.push("target-local usages hidden; use +includeTarget to show")}function Re(e,t,n){const s=[],i=Se(n,r=>a(r.file)??"");for(const[r,c]of i)r&&s.push(`// ${r}`),s.push(...zt(e,c));const o=a(n[0]?.entity)??"",l=Jt(t,"hiddenBlocks",o);return l&&s.push(`// ${l}`),s}function zt(e,t){const n=[],{ownerGroups:s,standalone:i}=ae(t,o=>a(o.container)??"");for(const[o,l]of s)n.push(`// ${o}:`),n.push(...je(e,l));return i.length>0&&n.push(...je(e,i)),n}function je(e,t){const n=[];for(const s of t){if(typeof s.code=="string")n.push(s.code.trimEnd());else if(typeof s.omitted=="string"){const i=(0,S.useSessionGuidance)(e,"inspect.usages.codeOmitted",s.omitted)??"code omitted";n.push(`// ${i}`),typeof s.compactCode=="string"&&s.compactCode!==""&&n.push(s.compactCode)}n.push("")}return n}function Ke(e,t=!0){const n=[],s=a(e.entity);t&&s&&n.push(`// ${s}`);const i=a(e.file)??"",o=typeof e.line=="number"?` l${e.line}`:"";(i||o)&&n.push(`// ${i}${o}`.trim());const l=a(e.code);return l&&n.push(l.trimEnd()),n}function Ve(e,t){const n=a(e.entity)??"",s=ce(n),i=[`${t?n:s.name}:`],o=Array.isArray(e.usedBy)?e.usedBy.filter(p):[];for(const r of o){const c=a(r.file)??"",u=Array.isArray(r.locations)?r.locations.filter(p):[];if(u.length!==0){if(u.length===1){const[d]=u,m=typeof d?.line=="number"?d.line:0,y=a(d?.container);i.push(y?`${c}:${m} ${y}`:`${c}:${m}`);continue}i.push(`${c}:`),i.push(...Ht(u))}}const l=a(e.hidden);return l&&i.push(l),i}function Ht(e){const t=[],{ownerGroups:n,standalone:s}=ae(e,i=>a(i.container)??"");for(const[i,o]of n){t.push(`// ${i}:`);for(const l of o){const r=typeof l.line=="number"?l.line:0,c=ce(a(l.container)??"").name;t.push(c?`${c} l${r}`:`l${r}`)}}for(const i of s){const o=typeof i.line=="number"?i.line:0,l=a(i.container);t.push(l?`${l} l${o}`:`l${o}`)}return t}function Jt(e,t,n){const i=(Array.isArray(e[t])?e[t].filter(p):[]).find(o=>a(o.entity)===n);return i?a(i.hidden):null}function ae(e,t){const n=new Map,s=[];for(const i of e){const o=ce(t(i));if(!o.owner){s.push(i);continue}const l=n.get(o.owner)??[];l.push(i),n.set(o.owner,l)}return{ownerGroups:Array.from(n.entries()),standalone:s}}function ce(e){const t=e.lastIndexOf(".");return t<=0||t>=e.length-1?{owner:null,name:e}:{owner:e.slice(0,t),name:e.slice(t+1)}}function Se(e,t){const n=new Map;for(const s of e){const i=t(s),o=n.get(i)??[];o.push(s),n.set(i,o)}return Array.from(n.entries())}function Wt(e,t,n,s,i){const o=ye.readFileSync(e,"utf8"),l=we(o,t,n),r=we(o,s,i);return o.slice(l,r)}function we(e,t,n){let s=0,i=0;for(;i<e.length&&s<t;){const o=e.charCodeAt(i);o===13?(i+=e.charCodeAt(i+1)===10?2:1,s+=1):o===10?(i+=1,s+=1):i+=1}return Math.max(0,Math.min(i+n,e.length))}function Qt(e){return e.split(/\r?\n/).filter(t=>t.trim()!=="").length}function Q(e,t){const n=L.relative(e,t);return(n&&!n.startsWith("..")&&!L.isAbsolute(n)?n:t).replace(/\\/g,"/")}async function qt(e,t,n,s,i){const o=pe(n),l=[],r=[],c=[],u=(0,Y.buildDisplayPathAliases)(e,(0,S.readEffectiveSessionPathAliases)(e)),d=[];for(const b of o){if(!p(b))throw new E.CliError("INVALID_INSPECT_REQUEST","Inspect request must be an object.");a(b.op)==="graph"?(r.push(Zt(b)),d.push("graph")):a(b.op)==="imports"?(c.push(b),d.push("imports")):(l.push(b),d.push("inspect"))}const m=l.length>0?en((0,V.stripAgentText)(await Ce(e,["--stdin"],{requests:l},s,{...i,forceResults:!0}))):[],y=r.length>0?tn((0,V.stripAgentText)((0,ge.runInspectGraph)(e,["graph","--stdin"],{requests:r}))):[],h=c.map(b=>(0,be.buildInspectImportsResult)(e,{file:a(b.file)??a(b.fromFile)??a(b.sourceFile)??a(n.file)??"",ranges:B(b.ranges)!==!1,dynamic:B(b.dynamic)!==!1},u)),A=[];let C=0,I=0,O=0;for(const b of d)if(b==="graph"){const _=y[I++];_&&A.push(_)}else if(b==="imports"){const _=h[O++];_&&A.push(_)}else{const _=m[C++];_&&A.push(_)}const v={results:(0,be.mergeDirectoryFallbackResults)(A)};return Fe((0,V.attachAgentText)(v,(0,$.formatInspectMixedAgentText)(v)),Le(n).dslDiagnostics??[])}function Xt(e,t,n){if(t[0]==="graph")return null;if(t.includes("--stdin"))return p(n)?n:null;const s=F(t,"--from-json");return s?(0,he.readJsonObjectFile)(e,s,"INVALID_INSPECT_JSON_FILE"):null}function Yt(e){return pe(e).some(t=>p(t)&&(a(t.op)==="graph"||a(t.op)==="imports"))}function Zt(e){const t={...e};return delete t.op,delete t.sourceFile,t}function en(e){return Array.isArray(e.results)?e.results.filter(p).map(Ge):[Ge(e)]}function Ge(e){return e.op==="dependencies"?{...e,op:"deps"}:e}function tn(e){return Array.isArray(e.results)?e.results.filter(p).map(t=>({op:"graph",...t})):[{op:"graph",...nn(e)}]}function nn(e){const t={...e};return delete t.operation,delete t.next,delete t.last,typeof t.saved=="string"&&delete t.graphFile,t}function sn(e,t){(Array.isArray(t.payload.requests)?t.payload.requests:[]).forEach((s,i)=>{if(!p(s)||s.op!=="modulePlan"||s.previewFiles!==!0)return;const o=(0,w.normalizeModulePlanCacheRequest)(s),l=(0,w.buildModulePlanId)(o),r=a(s.previewDir),c=(0,w.resolveModulePlanPreviewDir)(e,l,r??void 0);s.previewDir=c,s.previewPatch=s.previewPatch!==!1,t.cachePlans.push({index:i,planId:l,normalizedRequest:o,previewDir:c})})}function on(e,t,n){if(!(t.cachePlans.length===0||!Array.isArray(n.results)))for(const s of t.cachePlans){const i=n.results[s.index];if(!p(i))continue;const o=a(s.normalizedRequest.sourceFile);if(!o)continue;const l=(0,w.hashFile)(o),r=(0,w.buildModulePlanHash)(s.normalizedRequest,l,i),c={planId:s.planId,planHash:r,createdAt:new Date().toISOString(),cwd:L.resolve(e),sourceFile:o,sourceHash:l,executable:i.ok!==!1,normalizedRequest:s.normalizedRequest,inspectPayload:t.payload,previewDir:s.previewDir,previewResult:i};(0,w.writeModulePlanRecord)(e,c),i.planId=s.planId,i.planHash=r,i.cached=!0,i.executable=i.ok!==!1,i.next=i.ok===!1?`Revise with: aib modulePlan revise --plan ${s.planId} --stdin`:`Run modulePlan apply ${s.planId} if the plan matches intent.`}}function rn(e,t){if(!t||!Array.isArray(e.results)||!p(e.results[0]))return e;const n=e.results[0];n.operation="modulePlan.revise",n.fromPlanId=t.fromPlanId,n.changes=t.changes;const s=En(n),i=t.previousBlocking.filter(o=>!s.includes(o));return i.length>0&&(n.resolved=i),n.remainingBlocking=Array.isArray(n.blocking)?n.blocking:[],delete n.blocking,delete n.boundary,delete n.targets,delete n.moduleCount,delete n.preview,delete n.facade,n.next=n.ok===!1||n.executable===!1?`Revise again from ${typeof n.planId=="string"?n.planId:t.fromPlanId}.`:`aib modulePlan apply ${typeof n.planId=="string"?n.planId:t.fromPlanId}`,(0,V.attachAgentText)(e,ln(n))}function ln(e){const t=[`modulePlan.revise ${typeof e.planId=="string"?e.planId:""}`.trim()];if(typeof e.fromPlanId=="string"&&t.push(`from: ${e.fromPlanId}`),typeof e.integrity=="string"&&t.push(e.integrity),p(e.api)&&typeof e.api.status=="string"){const n=typeof e.api.before=="number"?e.api.before:null,s=typeof e.api.after=="number"?e.api.after:null;t.push(n!==null&&s!==null?`api: ${e.api.status} ${n}->${s}`:`api: ${e.api.status}`)}if(typeof e.cycles=="string"&&t.push(`cycles: ${e.cycles}`),Array.isArray(e.changes)&&e.changes.length>0){t.push("changes:");for(const n of e.changes.filter(s=>typeof s=="string"))t.push(n)}return Array.isArray(e.resolved)&&e.resolved.length>0&&t.push(`resolved: ${e.resolved.length}`),Array.isArray(e.remainingBlocking)&&t.push(`remainingBlocking: ${e.remainingBlocking.length}`),typeof e.next=="string"&&t.push(`next: ${e.next}`),t.join(`
16
+ `)}function an(e,t){if(!Array.isArray(t.payload.requests))return;const n=t.payload.requests.filter(p),s=new Map,i=[],o=new Map;for(let l=0;l<n.length;l+=1){const r=n[l],c=a(r.sourceFile);if(!c||!cn(a(r.op))||!Pn(c)){o.set(l,i.length),i.push(r);continue}let u=s.get(c);u?o.set(l,i.findIndex(m=>a(m.sourceFile)===c&&m.op==="directoryFallback")):(u=un(e,c),s.set(c,u),o.set(l,i.length),i.push(fn(u)));const d=dn(a(r.op));u.ops.includes(d)||u.ops.push(d)}s.size!==0&&(t.payload.requests=i,t.formatOptions.toFiles&&(t.formatOptions.toFiles=ue(t.formatOptions.toFiles,o,i.length)),t.formatOptions.saves&&(t.formatOptions.saves=ue(t.formatOptions.saves,o,i.length)),t.formatOptions.shows&&(t.formatOptions.shows=ze(t.formatOptions.shows,o,i.length)),t.formatOptions.ranges&&(t.formatOptions.ranges=ze(t.formatOptions.ranges,o,i.length)),t.formatOptions.parentNames&&(t.formatOptions.parentNames=ue(t.formatOptions.parentNames,o,i.length)),t.usagesDetails&&(t.usagesDetails=ue(t.usagesDetails,o,i.length)))}function cn(e){return e==="file"||e==="exports"||e==="members"||e==="code"||e==="dependencies"||e==="slice"}function un(e,t){const n=pn(e,t),s=(0,S.readEffectiveSessionPathAliases)(e),i=(0,Y.compactDisplayPath)(e,t,(0,Y.buildDisplayPathAliases)(e,s)),o=(0,oe.buildInspectTreeResult)(e,{scope:t,displayScope:i,depth:n,limit:40,aliases:s}),l=[];return{sourceFile:t,displayPath:i,ops:l,command:`aib inspect tree ${i} --depth ${n}`,result:{op:"directoryFallback",ok:!0,sourceFile:t,directory:i,skippedOps:l,command:`aib inspect tree ${i} --depth ${n}`,tree:o,lines:Array.isArray(o.lines)?o.lines:[]}}}function fn(e){return{op:"directoryFallback",sourceFile:e.sourceFile,fallback:e.result}}function pn(e,t){for(let n=1;n<=4;n+=1){const s=(0,oe.buildInspectTreeResult)(e,{scope:t,depth:n,limit:1});if(typeof s.files=="number"&&s.files>0)return n}return 2}function ue(e,t,n){const s=Array.from({length:n},()=>null);for(const[i,o]of t.entries())s[o]===null&&(s[o]=e[i]??null);return s}function ze(e,t,n){const s=Array.from({length:n},()=>!1);for(const[i,o]of t.entries())s[o]=s[o]||(e[i]??!1);return s}function dn(e){return e==="dependencies"?"deps":e??"inspect"}function mn(e,t,n,s,i,o){const l=Je(t),c=!(t.includes("--no-ranges")||t.includes("--noRanges"))&&(l==="code"||l==="file")||t.includes("--ranges")||l==="exports"&&(0,S.readSessionBooleanPref)(e,"inspect.exports.ranges",!1),u=t.includes("--details"),d=t.includes("--resolve-star")||l==="exports"&&(0,S.readSessionBooleanPref)(e,"inspect.exports.resolveStar",!1),m=t.includes("--local-only"),y=Fn(e,t),h=nt(t,"--offset"),A=H(t,"--limit")??(l==="members"?(0,S.readSessionNumberPref)(e,"inspect.members.maxItems",20):null),C=t.includes("--all")||l==="members"&&(0,S.readSessionBooleanPref)(e,"inspect.members.all",!1),I=F(t,"--to-file")??void 0,O=F(t,"--save")??void 0,v=l==="code"&&(t.includes("--no-show")||t.includes("--noShow")),b=t.includes("--show"),_=v?!1:b||l==="code"&&(0,S.readSessionBooleanPref)(e,"inspect.code.show",!0),D=(0,S.readSessionBooleanPref)(e,"inspect.code.meta",!0),P=l==="usages"?Ie(e,{detail:F(t,"--detail"),all:t.includes("--all"),limit:H(t,"--limit"),maxCodeLines:H(t,"--max-code-lines")??H(t,"--maxCodeLines")}):null,f=F(t,"--bundle-save")??void 0,M=F(t,"--preview-dir")??void 0,U=F(t,"--from-json")??void 0,G=F(t,"--parent")??void 0,x=G?(0,$.parseInspectSelector)(G,s).symbolName:void 0,ee=(0,Y.buildDisplayPathAliases)(e,(0,S.readEffectiveSessionPathAliases)(e)),te=[];if(I!==void 0&&O!==void 0)throw new E.CliError("INSPECT_OUTPUT_TARGET_CONFLICT","Use either --to-file or --save, not both.");const q={cwd:e,includeRanges:c,displayPathAliases:ee,pathAliasHints:te,details:u,localOnly:m,maxCodeLines:y,forceResults:o,show:_,codeMeta:D,...x!==void 0?{parentName:x,parentNames:[x]}:{},...I!==void 0?{toFile:I}:{},...O!==void 0?{save:O}:{},...f!==void 0?{bundleSave:f}:{},...M!==void 0?{previewDir:k(e,M)}:{}};if(U!==void 0){if(t.includes("--stdin")||n!==void 0)throw new E.CliError("INSPECT_INPUT_SOURCE_CONFLICT","Use either inspect --stdin or inspect --from-json, not both.");if(t.includes("--revise"))throw new E.CliError("INSPECT_REVISE_FROM_JSON_UNSUPPORTED","modulePlan revise currently expects --stdin.");const g=He((0,he.readJsonObjectFile)(e,U,"INVALID_INSPECT_JSON_FILE"),Je(t)),z=c||st(g),N=We(e,g,s,z,d,m,{memberOffset:h,memberLimit:A,memberAll:C},i);return{payload:N.payload,cachePlans:[],formatOptions:{...q,includeRanges:z,toFiles:N.toFiles,saves:N.saves,shows:N.shows,ranges:N.ranges,parentNames:N.parentNames,...f===void 0&&N.bundleSave!==void 0?{bundleSave:N.bundleSave}:{}},usagesDetails:N.usagesDetails}}if(n!==void 0){if(!p(n))throw new E.CliError("INVALID_INSPECT_STDIN","inspect input expects a JSON object payload.");if(t.includes("--revise"))return yn(e,t,n,s);const g=He(n,l),z=c||st(g),N=We(e,g,s,z,d,m,{memberOffset:h,memberLimit:A,memberAll:C},i);return{payload:N.payload,cachePlans:[],formatOptions:{...q,includeRanges:z,toFiles:N.toFiles,saves:N.saves,shows:N.shows,ranges:N.ranges,parentNames:N.parentNames,...f===void 0&&N.bundleSave!==void 0?{bundleSave:N.bundleSave}:{}},usagesDetails:N.usagesDetails,...Le(n)}}return{payload:hn(e,t,s,c,d,m,{memberOffset:h,memberLimit:A,memberAll:C},i),formatOptions:q,cachePlans:[],...P!==null?{usagesDetails:[P]}:{}}}function He(e,t){return!t||e.op!==void 0?e:{op:t,...e}}function Je(e){return e.filter(n=>!n.startsWith("--")&&!it(e,n))[0]??null}function yn(e,t,n,s){const i=F(t,"--plan");if(!i)throw new E.CliError("MODULE_PLAN_REVISE_PLAN_REQUIRED","modulePlan revise expects --plan <planId>.");const o=(0,w.readModulePlanRecord)(e,i),l=gn(e,o.previewResult,o.normalizedRequest,n,s),r=(0,w.buildModulePlanId)(l),c=(0,w.resolveModulePlanPreviewDir)(e,r);return{payload:{requests:[{...l,previewFiles:!0,previewPatch:!0,previewDir:c}]},formatOptions:{cwd:e,includeRanges:!1,displayPathAliases:(0,Y.buildDisplayPathAliases)(e,(0,S.readEffectiveSessionPathAliases)(e)),pathAliasHints:[],localOnly:!1,details:!1,maxCodeLines:(0,S.readSessionNumberPref)(e,"inspect.code.maxNonEmptyLines",120),codeMeta:(0,S.readSessionBooleanPref)(e,"inspect.code.meta",!0),previewDir:c},cachePlans:[{index:0,planId:r,normalizedRequest:l,previewDir:c}],revision:{fromPlanId:i,changes:Sn(e,o.normalizedRequest,l),previousBlocking:_n(o.previewResult,s)}}}function hn(e,t,n,s,i,o,l,r){const c=t.filter(I=>!I.startsWith("--")&&!it(t,I)),[u,d,m]=c;if(!u||!d)throw new E.CliError("INVALID_INSPECT_COMMAND","Expected: aib inspect <file|imports|exports|members|code|slice|deps|usages|duplicates> <file-or-dir> [entity].",{examples:["aib inspect file src/example.ts","aib inspect imports src/example.ts","aib inspect exports src/example.ts","aib inspect members src/example.ts c:Example","aib inspect code src/example.ts f:helper","aib inspect deps src/example.ts c:Example","aib inspect usages src/example.ts f:helper --scope src/main","aib inspect duplicates src/scripts --detail code"]});if(!rt(u))throw new E.CliError("INVALID_INSPECT_OP","Expected inspect op to be file, imports, exports, members, code, slice, deps, usages, duplicates, graph, tree, or cycles.");if(at(u,r),F(t,"--save")&&u!=="code"&&u!=="slice"&&u!=="usages"&&u!=="duplicate"&&u!=="duplicates")throw new E.CliError("INVALID_INSPECT_SAVE","inspect --save can be used only with code, slice, usages, or duplicates operations.");const y=lt(u),h={op:y,sourceFile:k(e,d),ranges:s||y==="code"||y==="slice",resolveStar:i,localOnly:y==="file"&&o};if(tt(h,l),y==="members"||y==="code"||y==="dependencies"||y==="slice"){if(!m)throw new E.CliError("INSPECT_ENTITY_REQUIRED",`inspect ${u} expects an entity selector.`);_e(h,m,n)}if(y==="usages"&&m&&_e(h,m,n),y==="duplicates"){h.detail=F(t,"--detail")??"locations",h.mode=F(t,"--mode")??"both";const I=H(t,"--limit"),O=nt(t,"--offset");I!==null&&(h.limit=I),O!==null&&(h.offset=O);const v=Bn(t,n);v.length>0&&(h.kinds=v);const b=de([...m?[m]:[],...R(t,"--entity"),...R(t,"--entities").flatMap(P=>P.split(","))],n);b.length>0&&(h.duplicateEntities=b);const _=de([...R(t,"--exclude"),...R(t,"--excludes").flatMap(P=>P.split(","))],n);_.length>0&&(h.duplicateExclude=_);const D=ft(e,[...R(t,"--path-exclude"),...R(t,"--path-excludes").flatMap(P=>P.split(",")),...R(t,"--exclude-path"),...R(t,"--exclude-paths").flatMap(P=>P.split(","))]);D.length>0&&(h.duplicatePathExclude=D)}const A=R(t,"--scope");if(y==="usages"&&A.length>0&&(h.scope=A.map(I=>k(e,I))),y==="duplicates"&&A.length>0&&(h.scope=A.map(I=>k(e,I))),y==="usages"){h.excludeTarget=t.includes("--exclude-target")||t.includes("--excludeTarget")||!1;const I=t.includes("--include-target")||t.includes("--includeTarget"),O=(0,S.readSessionBooleanPref)(e,"inspect.usages.excludeTarget",!1);I?h.excludeTarget=!1:h.excludeTarget===!0||O?h.excludeTarget=!0:Ze(e,a(h.sourceFile)??"",K(h.scope)??[])&&(h.excludeTarget=!0,h.targetLocalUsagesHidden=!0)}const C=F(t,"--parent");if(C){const I=(0,$.parseInspectSelector)(C,n);h.parentName=I.symbolName,I.symbolKind&&(h.parentKind=I.symbolKind)}return{requests:[h]}}function We(e,t,n,s,i,o,l,r){const c=pe(t),u=[],d=[],m=[],y=[],h=[],A=[],C=Lt(t.detail),I=B(t.all),O=J(t.limit),v=J(t.maxCodeLines),b=B(t.excludeTarget),_=B(t.includeTarget),D=a(t.bundleSave)??a(t.bundle)??a(t.saveBundle)??void 0;return{payload:{requests:c.map((f,M)=>{if(!p(f))throw new E.CliError("INVALID_INSPECT_REQUEST",`Inspect request at index ${M} must be an object.`);const U=a(f.op),G=a(f.sourceFile)??a(f.file)??(U==="usages"?a(f.target)??a(f.usageTarget)??a(f.dir):null)??(U==="duplicate"||U==="duplicates"?a(f.target)??a(f.dir)??ut(f.scope)??ut(f.scopes):null);if(!U||!rt(U))throw new E.CliError("INVALID_INSPECT_OP",`Inspect request at index ${M} has invalid op.`);if(at(U,r),!G)throw new E.CliError("SOURCE_FILE_REQUIRED",`Inspect request at index ${M} requires sourceFile or file.`);const x=lt(U),te=B(f.ranges)??B(f.includeRanges)??(x==="code"||x==="slice"||x==="file"?!0:x==="exports"?(0,S.readSessionBooleanPref)(e,"inspect.exports.ranges",!1):s),q=te||x==="code"||x==="slice",g={op:x,sourceFile:k(e,G),ranges:q,resolveStar:B(f.resolveStar)??(x==="exports"?(0,S.readSessionBooleanPref)(e,"inspect.exports.resolveStar",!1):i),localOnly:x==="file"&&(f.localOnly===!0||o)};if(x==="usages"){A.push(Ie(e,{detail:a(f.detail)??C,all:B(f.all)??I,limit:J(f.limit)??O,maxCodeLines:J(f.maxCodeLines)??v}));const T=K(f.scope)??K(f.scopes);T&&T.length>0&&(g.scope=T.map(se=>k(e,se)));const W=B(f.includeTarget)??_,X=B(f.excludeTarget)??b,ne=(0,S.readSessionBooleanPref)(e,"inspect.usages.excludeTarget",!1);W===!0?g.excludeTarget=!1:X!==null?g.excludeTarget=X:ne?g.excludeTarget=!0:Ze(e,g.sourceFile,K(g.scope)??[])&&(g.excludeTarget=!0,g.targetLocalUsagesHidden=!0),Array.isArray(f.entities)&&(g.usageEntities=$n(f.entities,n))}else A.push(null);if(x==="duplicates"){g.detail=a(f.detail)??a(t.detail)??"locations",g.mode=a(f.mode)??a(t.mode)??"both",g.limit=J(f.limit)??J(t.limit)??10,g.offset=fe(f.offset)??fe(t.offset)??0;const T=K(f.scope)??K(f.scopes)??K(t.scope)??K(t.scopes);T&&T.length>0&&(g.scope=T.map(yt=>k(e,yt)));const W=kn(f.kinds??t.kinds,n);W.length>0&&(g.kinds=W);const X=de(f.entities??f.entity??t.entities??t.entity,n);X.length>0&&(g.duplicateEntities=X);const ne=de(f.exclude??f.excludes??t.exclude??t.excludes,n);ne.length>0&&(g.duplicateExclude=ne);const se=ft(e,f.pathExclude??f.pathExcludes??f.excludePath??f.excludePaths??t.pathExclude??t.pathExcludes??t.excludePath??t.excludePaths);se.length>0&&(g.duplicatePathExclude=se)}if(x==="modulePlan"){g.modules=Tn(e,f.modules,n);const T=a(f.facade)??a(f.facadeFile);if(T&&(g.facadeFile=k(e,T)),f.previewFiles===!0||f.preview==="files"){g.previewFiles=!0;const W=a(f.previewDir)??a(f.outputDir);W&&(g.previewDir=k(e,W)),g.previewPatch=f.previewPatch!==!1}}tt(g,{memberOffset:fe(f.offset)??fe(f.memberOffset)??l.memberOffset,memberLimit:J(f.limit)??J(f.memberLimit)??l.memberLimit??(x==="members"?(0,S.readSessionNumberPref)(e,"inspect.members.maxItems",20):null),memberAll:B(f.all)??B(f.memberAll)??(x==="members"?(0,S.readSessionBooleanPref)(e,"inspect.members.all",!1):l.memberAll)});const z=a(f.id);z&&(g.id=z);const N=x==="modulePlan"?null:a(f.toFile)??a(f.outputFile),me=x==="modulePlan"?null:a(f.save);if(N&&x!=="code"&&x!=="slice")throw new E.CliError("INVALID_INSPECT_TO_FILE",`Inspect request at index ${M} can use toFile only with code or slice operations.`);if(me&&x!=="code"&&x!=="slice"&&x!=="usages"&&x!=="duplicates")throw new E.CliError("INVALID_INSPECT_SAVE",`Inspect request at index ${M} can use save only with code, slice, usages, or duplicates operations.`);if(N&&me)throw new E.CliError("INSPECT_OUTPUT_TARGET_CONFLICT",`Inspect request at index ${M} must use either toFile or save, not both.`);u.push(N),d.push(me);const mt=typeof f.show=="boolean"?f.show:null;m.push(mt??(x==="code"&&(0,S.readSessionBooleanPref)(e,"inspect.code.show",!0))),y.push(te);const Ee=a(f.entity);Ee&&_e(g,Ee,n);const Ne=a(f.parent);if(Ne){const T=(0,$.parseInspectSelector)(Ne,n);g.parentName=T.symbolName,T.symbolKind&&(g.parentKind=T.symbolKind),h.push(T.symbolName)}else h.push(null);return g})},toFiles:u,saves:d,shows:m,ranges:y,parentNames:h,usagesDetails:A,...D!==void 0?{bundleSave:D}:{}}}function _e(e,t,n){const s=(0,$.parseInspectSelector)(t,n);e.symbolName=s.symbolName,s.symbolKind&&(e.symbolKind=s.symbolKind)}function gn(e,t,n,s,i){const o=Nn(n),l=[...bn(e,s),...In(e,t,s,i)];if(l.length===0)throw new E.CliError("MODULE_PLAN_REVISE_MOVES_REQUIRED","modulePlan revise expects moves or applySuggestedFixes.");for(const r of l)An(o,r,i);return o}function bn(e,t){return(Array.isArray(t.moves)?t.moves:[]).filter(p).map(s=>{const i=a(s.entity)??a(s.symbol)??a(s.selector),o=a(s.to)??a(s.target)??a(s.toFile)??a(s.targetFile);return i&&o?{selector:i,toFile:k(e,o)}:null}).filter(s=>s!==null)}function In(e,t,n,s){const i=n.applySuggestedFixes,o=xn(t,s),l=i===!0||i==="all"?o.map((r,c)=>c):Array.isArray(i)?i:[];return l.length===0?[]:l.map(r=>typeof r=="number"?r:typeof r=="string"?Number(r):NaN).filter(r=>Number.isInteger(r)&&r>=0&&r<o.length).map(r=>({selector:o[r].selector,toFile:k(e,o[r].toFile)}))}function xn(e,t){const n=p(e.boundary)?e.boundary:{},s=Array.isArray(n.nonExportedImports)?n.nonExportedImports.filter(p):[],i=[];for(const o of s){const l=Array.isArray(o.suggestedFixes)?o.suggestedFixes.filter(p):[];for(const r of l){if(r.kind!=="moveSymbol")continue;const c=Qe(r.symbol,t),u=a(r.toFile);c&&u&&i.push({selector:c,toFile:u})}}return i}function Qe(e,t){if(!p(e))return null;const n=a(e.name),s=a(e.kind);if(!n||!s)return null;const i=t.entityKindAliases[s];return i?`${i}${t.selectorSeparator}${n}`:`${s}:${n}`}function An(e,t,n){const s=Array.isArray(e.modules)?e.modules.filter(p):[],i=(0,$.parseInspectSelector)(t.selector,n);let o=null;for(const c of s){const u=Array.isArray(c.symbols)?c.symbols:[],d=[];for(const m of u)o===null&&qe(m,i)?o=m:d.push(m);c.symbols=d}if(o===null)throw new E.CliError("MODULE_PLAN_REVISE_SYMBOL_NOT_FOUND",`Symbol not found in cached module plan: ${t.selector}`,{symbol:t.selector});let l=s.find(c=>a(c.targetFile)===t.toFile);l||(l={targetFile:t.toFile,symbols:[]},s.push(l));const r=Array.isArray(l.symbols)?l.symbols:[];r.some(c=>qe(c,i))||r.push(o),l.symbols=r,e.modules=s.filter(c=>Array.isArray(c.symbols)&&c.symbols.length>0)}function qe(e,t){if(!p(e))return!1;const n=a(e.raw),s=a(e.symbolName),i=a(e.symbolKind);return n===t.raw||s===t.symbolName&&(!t.symbolKind||i===t.symbolKind)}function Sn(e,t,n){const s=Ye(t),i=Ye(n),o=[];for(const[l,r]of i.entries()){const c=s.get(l);c&&c!==r&&o.push(`${l}: ${Xe(e,c)} -> ${Xe(e,r)}`)}return o}function _n(e,t){const n=p(e.boundary)?e.boundary:{};return(Array.isArray(n.nonExportedImports)?n.nonExportedImports.filter(p):[]).flatMap(i=>{const o=a(i.code)??"MODULE_PLAN_BOUNDARY_WARNING";return(Array.isArray(i.symbols)?i.symbols.filter(p):[]).map(r=>Qe(r,t)).filter(r=>typeof r=="string").map(r=>`${o}: ${r}`)})}function En(e){return(Array.isArray(e.blocking)?e.blocking.filter(p):[]).flatMap(n=>{const s=a(n.code)??"MODULE_PLAN_BOUNDARY_WARNING";return(Array.isArray(n.symbols)?n.symbols.filter(o=>typeof o=="string"):[]).map(o=>`${s}: ${o}`)})}function Xe(e,t){return L.relative(e,t).replace(/\\/g,"/")}function Ye(e){const t=new Map,n=Array.isArray(e.modules)?e.modules.filter(p):[];for(const s of n){const i=a(s.targetFile);if(!i)continue;const o=Array.isArray(s.symbols)?s.symbols.filter(p):[];for(const l of o){const r=a(l.raw),c=a(l.symbolName),u=a(l.symbolKind),d=r??(c?`${u??"symbol"}:${c}`:null);d&&t.set(d,i)}}return t}function Nn(e){return JSON.parse(JSON.stringify(e))}function k(e,t){return L.normalize(L.isAbsolute(t)?t:L.resolve(e,t))}function Ze(e,t,n){const s=L.normalize(t);return n.length===0?!et(s,e):n.some(i=>vn(i,s))}function vn(e,t){const n=L.normalize(e),s=L.normalize(t);return et(n,s)||Cn(n)?!1:Dn(s,n)}function Dn(e,t){const n=L.relative(L.normalize(t),L.normalize(e));return n!==""&&!n.startsWith("..")&&!L.isAbsolute(n)}function et(e,t){return L.normalize(e).toLowerCase()===L.normalize(t).toLowerCase()}function Cn(e){try{return ye.statSync(e).isFile()}catch{return!1}}function Pn(e){try{return ye.statSync(e).isDirectory()}catch{return!1}}function tt(e,t){if(t.memberAll){e.memberAll=!0;return}typeof t.memberOffset=="number"&&(e.memberOffset=t.memberOffset),typeof t.memberLimit=="number"&&(e.memberLimit=t.memberLimit)}function Fn(e,t){const n=F(t,"--max-lines");if(!n)return(0,S.readSessionNumberPref)(e,"inspect.code.maxNonEmptyLines",120);const s=Number(n);if(!Number.isInteger(s)||s<1)throw new E.CliError("INVALID_MAX_LINES","Expected --max-lines to be a positive integer.");return s}function H(e,t){const n=F(e,t);if(!n)return null;const s=Number(n);if(!Number.isInteger(s)||s<1)throw new E.CliError("INVALID_INSPECT_LIMIT",`Expected ${t} to be a positive integer.`);return s}function nt(e,t){const n=F(e,t);if(!n)return null;const s=Number(n);if(!Number.isInteger(s)||s<0)throw new E.CliError("INVALID_INSPECT_OFFSET",`Expected ${t} to be a non-negative integer.`);return s}function J(e){const t=typeof e=="number"?e:typeof e=="string"?Number(e):NaN;return Number.isInteger(t)&&t>0?t:null}function fe(e){const t=typeof e=="number"?e:typeof e=="string"?Number(e):NaN;return Number.isInteger(t)&&t>=0?t:null}function B(e){return typeof e=="boolean"?e:null}function st(e){return pe(e).some(n=>p(n)&&(n.ranges===!0||n.includeRanges===!0))}function pe(e){const t=On(e),n=Array.isArray(e.requests)?e.requests:[e],s=[];for(const i of n){if(!p(i)){s.push(i);continue}const o={...t,...i};delete o.requests;const l=Array.isArray(o.entities)?o.entities:null;if(!l){delete o.entities,s.push(o);continue}const r=a(o.op);if(r==="usages"||r==="duplicate"||r==="duplicates"){s.push(o);continue}delete o.entities;for(const c of l){if(p(c)){const u=Array.isArray(c.entities)?c.entities:null;if(u){const d={...c};delete d.entities;for(const m of u)s.push(Ln(o,d,m));continue}s.push({...o,...c});continue}if(typeof c!="string"||c.trim()===""){s.push({...o,entity:c});continue}s.push({...o,entity:c.trim()})}}return s}function Ln(e,t,n){return p(n)?{...e,...t,...n}:typeof n=="string"&&n.trim()!==""?{...e,...t,entity:n.trim()}:{...e,...t,entity:n}}function On(e){const t={};for(const n of["op","sourceFile","file","target","usageTarget","dir","scope","scopes","excludeTarget","includeTarget","ranges","includeRanges","resolveStar","localOnly","parent","offset","limit","all","memberOffset","memberLimit","memberAll","detail","mode","kinds","entities","entity","exclude","excludes","pathExclude","pathExcludes","excludePath","excludePaths","toFile","outputFile","save","show","bundleSave","bundle","saveBundle","previewFiles","preview","previewDir","outputDir","previewPatch","modules","facade","facadeFile"])e[n]!==void 0&&(t[n]=e[n]);return t}function F(e,t){const n=e.indexOf(t);if(n<0)return null;const s=e[n+1];return s&&!s.startsWith("--")?s:null}function R(e,t){const n=[];for(let s=0;s<e.length;s+=1){if(e[s]!==t)continue;const i=e[s+1];i&&!i.startsWith("--")&&n.push(i)}return n}function it(e,t){const n=e.indexOf(t);return n>0&&(e[n-1]==="--parent"||e[n-1]==="--max-lines"||e[n-1]==="--to-file"||e[n-1]==="--save"||e[n-1]==="--bundle-save"||e[n-1]==="--preview-dir"||e[n-1]==="--from-json"||e[n-1]==="--from-dsl"||e[n-1]==="--from"||e[n-1]==="--offset"||e[n-1]==="--limit"||e[n-1]==="--max-code-lines"||e[n-1]==="--maxCodeLines"||e[n-1]==="--scope"||e[n-1]==="--detail"||e[n-1]==="--mode"||e[n-1]==="--kind"||e[n-1]==="--kinds"||e[n-1]==="--entity"||e[n-1]==="--entities"||e[n-1]==="--exclude"||e[n-1]==="--excludes"||e[n-1]==="--path-exclude"||e[n-1]==="--path-excludes"||e[n-1]==="--exclude-path"||e[n-1]==="--exclude-paths")}function Tn(e,t,n){return Array.isArray(t)?t.filter(p).map(s=>{const i=a(s.target)??a(s.targetFile)??a(s.file),o=Array.isArray(s.entities)?s.entities:Array.isArray(s.symbols)?s.symbols:[];return{...i?{targetFile:k(e,i)}:{},symbols:o.map(l=>Mn(l,n)).filter(p)}}):[]}function $n(e,t){return e.flatMap(n=>ot(n,t,{})).filter(p)}function ot(e,t,n){if(typeof e=="string"&&e.trim()!==""){const c=(0,$.parseInspectSelector)(e,t);return[{...n,raw:e.trim(),symbolName:c.symbolName,...c.symbolKind?{symbolKind:c.symbolKind}:{}}]}if(!p(e))return[];const s=a(e.parent),i={...n};if(s){const c=(0,$.parseInspectSelector)(s,t);i.parentName=c.symbolName,c.symbolKind&&(i.parentKind=c.symbolKind)}const o=Array.isArray(e.entities)?e.entities:null;if(o)return o.flatMap(c=>ot(c,t,i));const l=a(e.entity)??a(e.selector)??a(e.raw);if(!l)return[];const r=(0,$.parseInspectSelector)(l,t);return[{...i,raw:l,symbolName:r.symbolName,...r.symbolKind?{symbolKind:r.symbolKind}:{}}]}function Mn(e,t){if(typeof e=="string"&&e.trim()!==""){const s=(0,$.parseInspectSelector)(e,t);return{raw:e.trim(),symbolName:s.symbolName,...s.symbolKind?{symbolKind:s.symbolKind}:{}}}if(!p(e))return null;const n=a(e.entity)??a(e.selector)??a(e.raw);if(n){const s=(0,$.parseInspectSelector)(n,t);return{raw:n,symbolName:s.symbolName,...s.symbolKind?{symbolKind:s.symbolKind}:{}}}return e}function rt(e){return e==="file"||e==="exports"||e==="imports"||e==="members"||e==="code"||e==="deps"||e==="slice"||e==="modulePlan"||e==="usages"||e==="duplicate"||e==="duplicates"||e==="tree"||e==="cycles"}function lt(e){return e==="deps"?"dependencies":e==="duplicate"?"duplicates":e==="cycles"?"cycles":e==="imports"?"imports":e}function at(e,t){e!=="modulePlan"||t||ct()}function ct(){throw new E.CliError("INSPECT_MODULE_PLAN_UNSUPPORTED","inspect is limited to file, exports, members, code, slice, deps, usages, duplicates, graph, tree, cycles, and imports. Use modulePlan preview/revise/apply/validate for module extraction plans.")}function Un(e,t){return e[0]==="modulePlan"?!0:!e.includes("--stdin")||!p(t)?!1:a(t.op)==="modulePlan"?!0:(Array.isArray(t.requests)?t.requests:[]).some(i=>p(i)&&a(i.op)==="modulePlan")}function a(e){return typeof e=="string"&&e.trim()!==""?e.trim():null}function K(e){return typeof e=="string"&&e.trim()!==""?[e.trim()]:Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim()!=="").map(t=>t.trim()):null}function ut(e){if(typeof e=="string"&&e.trim()!=="")return e.trim();if(!Array.isArray(e))return null;const t=e.find(n=>typeof n=="string"&&n.trim()!=="");return typeof t=="string"?t.trim():null}function Bn(e,t){const n=[...R(e,"--kind"),...R(e,"--kinds").flatMap(s=>s.split(","))];return dt(n,t)}function kn(e,t){const n=K(e)??[];return dt(n.flatMap(s=>s.split(",")),t)}function de(e,t){return(Array.isArray(e)?e:typeof e=="string"?e.split(","):e&&typeof e=="object"&&!Array.isArray(e)?[e]:[]).flatMap(s=>{if(typeof s=="string"){const l=s.trim();if(!l)return[];const r=(0,$.parseInspectSelector)(l,t);return[pt(r.symbolName,r.symbolKind??null)]}if(!p(s))return[];const i=a(s.entity)??a(s.selector)??a(s.name);if(!i)return[];const o=(0,$.parseInspectSelector)(i,t);return[pt(o.symbolName,o.symbolKind??null)]})}function ft(e,t){return(Array.isArray(t)?t:typeof t=="string"?t.split(","):[]).filter(s=>typeof s=="string").map(s=>s.trim()).filter(s=>s.length>0).map(s=>L.isAbsolute(s)?s:L.resolve(e,s)).map(s=>s.replace(/\\/g,"/"))}function pt(e,t){return t?{symbolName:e,symbolKind:t}:{symbolName:e}}function dt(e,t){const n=new Map;for(const[i,o]of Object.entries(t.entityKindAliases))n.set(i.toLowerCase(),i),n.set(String(o).toLowerCase(),i);const s=e.map(i=>n.get(i.trim().toLowerCase())??"").filter(i=>i!=="");return Array.from(new Set(s))}function p(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}
@@ -0,0 +1 @@
1
+ "use strict";var l=exports&&exports.__createBinding||(Object.create?(function(i,e,t,r){r===void 0&&(r=t);var n=Object.getOwnPropertyDescriptor(e,t);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(i,r,n)}):(function(i,e,t,r){r===void 0&&(r=t),i[r]=e[t]})),f=exports&&exports.__setModuleDefault||(Object.create?(function(i,e){Object.defineProperty(i,"default",{enumerable:!0,value:e})}):function(i,e){i.default=e}),o=exports&&exports.__importStar||(function(){var i=function(e){return i=Object.getOwnPropertyNames||function(t){var r=[];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[r.length]=n);return r},i(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r=i(e),n=0;n<r.length;n++)r[n]!=="default"&&l(t,e,r[n]);return f(t,e),t}})();Object.defineProperty(exports,"__esModule",{value:!0}),exports.readJsonObjectFile=d;const _=o(require("node:fs")),c=o(require("node:path")),s=require("../shared/errors"),b=require("./session-workspace");function d(i,e,t){const r=(0,b.resolveSessionFileArgument)(i,e),n=c.isAbsolute(r)?r:c.resolve(i,r);let u;try{u=JSON.parse(_.readFileSync(n,"utf8"))}catch(a){throw new s.CliError(t,`Failed to read JSON file: ${e}`,{file:e,error:a instanceof Error?a.message:String(a)})}if(!u||typeof u!="object"||Array.isArray(u))throw new s.CliError(t,`JSON file must contain an object: ${e}`,{file:e});return u}
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.runListInstances=n;const a=require("../discovery/registry"),i=require("../client/http-client"),r=require("../shared/routes");async function n(){const o=(0,a.readRegistryEntries)(),t=await Promise.all(o.map(async s=>{try{const e=await(0,i.postJson)(s,r.EXTENSION_ROUTES.runtimeInfo,{});return{instanceId:s.instanceId,pid:s.pid,appName:s.appName,appHost:s.appHost,host:s.host,port:s.port,workspaceFolders:s.workspaceFolders,startedAt:s.startedAt,lastSeenAt:s.lastSeenAt,protocolVersion:s.protocolVersion??null,extensionVersion:s.extensionVersion,capabilities:s.capabilities,healthy:!0,runtimeInfo:e}}catch(e){return{instanceId:s.instanceId,pid:s.pid,appName:s.appName,appHost:s.appHost,host:s.host,port:s.port,workspaceFolders:s.workspaceFolders,startedAt:s.startedAt,lastSeenAt:s.lastSeenAt,protocolVersion:s.protocolVersion??null,extensionVersion:s.extensionVersion,capabilities:s.capabilities,healthy:!1,error:e instanceof Error?e.message:String(e)}}}));return{ok:!0,instanceCount:t.length,instances:t}}
@@ -0,0 +1,2 @@
1
+ "use strict";var y=exports&&exports.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),_=exports&&exports.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),s=exports&&exports.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(n){var r=[];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(r[r.length]=i);return r},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(t!=null)for(var r=e(t),i=0;i<r.length;i++)r[i]!=="default"&&y(n,t,r[i]);return _(n,t),n}})();Object.defineProperty(exports,"__esModule",{value:!0}),exports.buildModulePlanId=M,exports.buildModulePlanHash=b,exports.normalizeModulePlanCacheRequest=E,exports.resolveModulePlanPreviewDir=O,exports.readModulePlanRecord=g,exports.writeModulePlanRecord=F,exports.modulePlanRecordPath=d,exports.buildModulePlanExecutionId=S,exports.readModulePlanExecutionStatus=x,exports.writeModulePlanExecutionStatus=j,exports.modulePlanExecutionPath=w,exports.modulePlanExecutionLastPath=C,exports.hashFile=v,exports.formatRelativePath=A,exports.resolveCliFilePath=h;const p=s(require("node:crypto")),o=s(require("node:fs")),a=s(require("node:path")),m=require("../shared/errors"),P=require("./workspace-cache"),u=require("./mutation-execution-cache");function M(e){return`plan_${f(l(e)).slice(0,10)}`}function b(e,t,n){return`sha256:${f(l({normalizedRequest:e,sourceHash:t,moduleCount:n.moduleCount,cycles:n.cycles??[]}))}`}function E(e){return{op:"modulePlan",...typeof e.sourceFile=="string"?{sourceFile:a.normalize(e.sourceFile)}:{},...typeof e.facadeFile=="string"?{facadeFile:a.normalize(e.facadeFile)}:{},...e.expectEmpty===!0?{expectEmpty:!0}:{},modules:Array.isArray(e.modules)?e.modules.filter(L).map(t=>({...typeof t.targetFile=="string"?{targetFile:a.normalize(t.targetFile)}:{},symbols:Array.isArray(t.symbols)?t.symbols:[]})):[]}}function O(e,t,n){return n?h(e,n):(0,P.workspaceCachePath)(e,"previews",t)}function g(e,t){const n=d(e,t);if(!o.existsSync(n))throw new m.CliError("APPLY_MODULE_PLAN_NOT_FOUND",`Module plan not found: ${t}`,{planId:t,expectedPath:n});return JSON.parse(o.readFileSync(n,"utf8"))}function F(e,t){const n=d(e,t.planId);o.mkdirSync(a.dirname(n),{recursive:!0}),o.writeFileSync(n,`${JSON.stringify(t,null,2)}
2
+ `)}function d(e,t){return(0,P.workspaceCachePath)(e,"plans",`${N(t)}.json`)}function S(e){return(0,u.buildMutationExecutionId)()}function x(e,t){return(0,u.readMutationExecutionStatus)(e,t,c)}function j(e,t){(0,u.writeMutationExecutionStatus)(e,t,c)}function w(e,t,n){return(0,u.mutationExecutionPath)(e,c.namespace,t,n)}function C(e,t){return(0,u.mutationExecutionLastPath)(e,c.namespace,t)}function v(e){return f(o.readFileSync(e))}function A(e,t){return a.relative(e,t).replace(/\\/g,"/")}function h(e,t){return a.normalize(a.isAbsolute(t)?t:a.resolve(e,t))}function f(e){return p.createHash("sha256").update(e).digest("hex")}function l(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(t=>l(t)).join(",")}]`:`{${Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${l(n)}`).join(",")}}`}function N(e){return e.replace(/[^a-z0-9_-]+/gi,"-")}const c={namespace:"executions",notFoundCode:"MODULE_PLAN_EXECUTION_NOT_FOUND",notFoundLabel:"Module plan"};function L(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.runModulePlanCommand=p;const i=require("./apply-module-plan"),s=require("./validate-module-plan"),d=require("../shared/errors");async function p(e,t,r,n={},o={}){const[u="preview",...l]=t;if(u==="preview")return(0,i.runApplyModulePlan)(e,l,r,n);if(u==="revise"){const a=c(l,"--plan")??m(l);if(!a)throw new d.CliError("MODULE_PLAN_REVISE_PLAN_REQUIRED","modulePlan revise expects --plan <planId>.");return(0,i.reviseCachedModulePlan)(e,a)}if(u==="apply"){const a=l[0];return(0,i.runApplyModulePlan)(e,a&&!a.startsWith("--")?["--plan",a]:l,r,n,o)}if(u==="execute")return(0,i.runApplyModulePlan)(e,["--execute",...l],r,n,o);if(u==="validate")return(0,s.runValidateModulePlan)(e,l);throw new d.CliError("UNKNOWN_MODULE_PLAN_COMMAND",`Unknown modulePlan command: ${u}`,{availableCommands:["modulePlan preview","modulePlan revise","modulePlan apply","modulePlan execute","modulePlan validate"]})}function c(e,t){const r=e.indexOf(t);if(r<0)return null;const n=e[r+1];return n&&!n.startsWith("--")?n:null}function m(e){return e.find(t=>!t.startsWith("--"))??null}
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.estimateModulePlanDurationMs=r,exports.estimateModulePlanSuggestedFirstCheckMs=o,exports.estimateModulePlanTimeoutMs=i,exports.estimateModulePlanTimeoutFromRequest=a,exports.buildModulePlanTimeoutHintFromRequest=M,exports.formatModulePlanTimeoutEstimate=c;function r(t,e){return e<=16?s(5e3+e*900+t*800+12e3,8e3,6e4):s(14e3+e*1200+12e3,2e4,18e4)}function o(t){return t<=2e4?1e4:s(t*.35,15e3,3e4)}function i(t,e){const n=r(t,e);return s(n+3e4,3e4,24e4)}function a(t){if(!l(t))return null;const e=Array.isArray(t.modules)?t.modules.filter(l):[];if(e.length===0)return null;const n=e.reduce((m,d)=>m+f(d),0),u=r(e.length,n);return{recommendedTimeoutMs:i(e.length,n),estimatedDurationMs:u,suggestedFirstCheckMs:o(u),rowCount:e.length,symbolCount:n}}function M(t){const e=a(t);return e?{recommendedTimeoutMs:e.recommendedTimeoutMs,estimatedDurationMs:e.estimatedDurationMs,suggestedFirstCheckMs:e.suggestedFirstCheckMs,rowCount:e.rowCount,symbolCount:e.symbolCount,message:"If the calling agent times out, inspect progress with: aib execution status last"}:null}function c(t){const e=Math.max(1,Math.round(t/1e3));return e<90?`~${e} sec`:`~${Math.max(1,Math.round(e/60))} min`}function s(t,e,n){return Math.min(n,Math.max(e,Math.round(t)))}function f(t){return(Array.isArray(t.symbols)?t.symbols:Array.isArray(t.entities)?t.entities:[]).length}function l(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.runMoveCommand=h;const a=require("../shared/errors"),u=require("./move-to-file"),l=require("./refactor-batch");async function h(e,i,r,t={}){const[n="toFile",s="preview",...o]=i;if(n==="--help"||n==="help")return m();if(n!=="toFile")throw new a.CliError("UNKNOWN_MOVE_TARGET",`Unknown move target: ${n}`,{availableTargets:["toFile"]});switch(s){case"--help":case"help":return m();case"preview":return f(r)?(0,l.runRefactorBatch)(e,v(r,!1),t,"preview",{routedFrom:"move.toFile"}):(0,u.runMoveToFile)(e,p(r,!1),t);case"validate":return f(r)?(0,l.runRefactorBatch)(e,v(r,!1),t,"validate",{routedFrom:"move.toFile"}):(0,u.runMoveToFile)(e,p(r,!1),t);case"execute":return f(r)?(0,l.runRefactorBatch)(e,v(r,!0),t,"execute",{routedFrom:"move.toFile"}):(0,u.runMoveToFile)(e,p(r,!0),t);case"apply":{const c=o[0];if(!c||c.startsWith("--"))throw new a.CliError("MOVE_PREVIEW_ID_REQUIRED","move toFile apply expects a preview id.",{usage:"aib move toFile apply <previewId>"});return(0,u.runMoveToFile)(e,void 0,t,["--preview",c])}default:throw new a.CliError("UNKNOWN_MOVE_COMMAND",`Unknown move toFile command: ${s}`,{availableCommands:["preview","apply","execute","validate","help"]})}}function m(){return{ok:!0,command:"move",usage:"aib move toFile preview --stdin | aib move toFile execute --stdin | aib move toFile apply <previewId>",preview:{sourceFile:"src/path/to/source-file.ts",targetFile:"src/path/to/target-file.ts",entities:["c-MyClass","i-MyShape"]},apply:"aib move toFile apply move_abc123",notes:["preview and validate force execute:false.","execute runs the payload immediately.","apply uses the cached preview id and refuses to run if source/target changed.","For large module extraction, prefer modulePlan preview/apply."]}}function p(e,i){return!e||typeof e!="object"||Array.isArray(e)?e:{...e,execute:i}}function v(e,i){if(!e||typeof e!="object"||Array.isArray(e))return e;const r=e,t=Array.isArray(r.operations)?r.operations:Array.isArray(r.requests)?r.requests:null;if(!t)return{...r,execute:i};const{operations:n,...s}=r;return{...s,requests:t.map(o=>o&&typeof o=="object"&&!Array.isArray(o)?{...o,execute:i}:o),execute:i}}function f(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&(Array.isArray(e.requests)||Array.isArray(e.operations))}
@@ -0,0 +1,2 @@
1
+ "use strict";var l=exports&&exports.__createBinding||(Object.create?(function(e,r,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(r,t);(!i||("get"in i?!r.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return r[t]}}),Object.defineProperty(e,n,i)}):(function(e,r,t,n){n===void 0&&(n=t),e[n]=r[t]})),d=exports&&exports.__setModuleDefault||(Object.create?(function(e,r){Object.defineProperty(e,"default",{enumerable:!0,value:r})}):function(e,r){e.default=r}),c=exports&&exports.__importStar||(function(){var e=function(r){return e=Object.getOwnPropertyNames||function(t){var n=[];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(n[n.length]=i);return n},e(r)};return function(r){if(r&&r.__esModule)return r;var t={};if(r!=null)for(var n=e(r),i=0;i<n.length;i++)n[i]!=="default"&&l(t,r,n[i]);return d(t,r),t}})();Object.defineProperty(exports,"__esModule",{value:!0}),exports.buildMovePreviewId=w,exports.buildMovePreviewHash=P,exports.readMovePreviewRecord=b,exports.writeMovePreviewRecord=O,exports.movePreviewRecordPath=a,exports.hashFile=f,exports.hashFileIfExists=p;const h=c(require("node:crypto")),u=c(require("node:fs")),v=c(require("node:path")),y=require("../shared/errors"),_=require("./workspace-cache");function w(e){return`move_${s(o(e)).slice(0,10)}`}function P(e,r,t,n){return`sha256:${s(o({normalizedPayload:e,sourceHash:r,targetHash:t,entityCount:n.entityCount,summary:n.summary}))}`}function b(e,r){const t=a(e,r);if(!u.existsSync(t))throw new y.CliError("MOVE_PREVIEW_NOT_FOUND",`Move preview not found: ${r}`,{previewId:r,expectedPath:t});return JSON.parse(u.readFileSync(t,"utf8"))}function O(e,r){const t=a(e,r.previewId);u.mkdirSync(v.dirname(t),{recursive:!0}),u.writeFileSync(t,`${JSON.stringify(r,null,2)}
2
+ `)}function a(e,r){return(0,_.workspaceCachePath)(e,"move-previews",`${g(r)}.json`)}function f(e){return s(u.readFileSync(e))}function p(e){return u.existsSync(e)?f(e):null}function s(e){return h.createHash("sha256").update(e).digest("hex")}function o(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(r=>o(r)).join(",")}]`:`{${Object.entries(e).sort(([r],[t])=>r.localeCompare(t)).map(([r,t])=>`${JSON.stringify(r)}:${o(t)}`).join(",")}}`}function g(e){return e.replace(/[^a-z0-9_-]+/gi,"-")}
@@ -0,0 +1,2 @@
1
+ "use strict";var Y=exports&&exports.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),Q=exports&&exports.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),w=exports&&exports.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(r){var n=[];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(n[n.length]=i);return n},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(t!=null)for(var n=e(t),i=0;i<n.length;i++)n[i]!=="default"&&Y(r,t,n[i]);return Q(r,t),r}})();Object.defineProperty(exports,"__esModule",{value:!0}),exports.runMoveToFile=oe;const F=w(require("node:path")),j=w(require("node:fs")),p=require("zod"),Z=require("../client/http-client"),W=require("../shared/agent-text"),E=require("../shared/errors"),ee=require("../shared/routes"),te=require("../shared/protocol"),z=require("../config/import-rules"),D=require("../config/mutation-comments"),x=require("./shared"),re=require("../selectors/parse-entities"),ne=require("./entity-resolution"),h=require("./move-preview-cache"),T=require("../metrics/central-metrics"),k=require("../shared/event-loop"),C=require("../diagnostics/module-plan-timeline"),ie=require("../config/env-vars"),N=p.z.object({sourceFile:p.z.string().min(1),targetFile:p.z.string().min(1),entities:p.z.union([p.z.array(p.z.string().min(1)).min(1),p.z.string().min(1)]),execute:p.z.boolean().optional()});async function oe(e,t,r={},n=[],i={}){const l=Me(n,"--preview");if(l)return le(e,l,r);const f=N.parse(t);return V(e,f,r,void 0,i)}async function le(e,t,r){const n=(0,h.readMovePreviewRecord)(e,t);if((0,h.hashFile)(n.sourceFile)!==n.sourceHash)throw new E.CliError("MOVE_PREVIEW_SOURCE_CHANGED","Source file changed after move preview. Rerun move preview.",{previewId:t,sourceFile:u(e,n.sourceFile)});const l=j.existsSync(n.targetFile),f=(0,h.hashFileIfExists)(n.targetFile);if(l!==n.targetExisted||f!==n.targetHash)throw new E.CliError("MOVE_PREVIEW_TARGET_CHANGED","Target file changed after move preview. Rerun move preview.",{previewId:t,targetFile:u(e,n.targetFile)});const o=N.parse({...n.normalizedPayload,execute:!0}),c=await V(e,o,r,{previewId:t}),a={...c,operation:"move.toFile.apply",...c.ok===!1?{next:"Fix the move request and rerun preview."}:{}};return(0,W.attachAgentText)(a,B(a))}async function V(e,t,r,n,i={}){const l=await(0,x.resolveCompatibleTargetInstance)(e,te.CLI_COMMAND_IDS.moveToFile,r),f=await(0,x.fetchEffectiveConfig)(l.entry,r),o=(0,re.parseEntitySelectors)(t.entities,f),c=K(e,t.sourceFile),a=K(e,t.targetFile),_=r.importRules??(0,z.readConfigImportRules)(e),I=r.mutationComments??(0,D.normalizeMutationCommentsPolicy)(void 0),y=t.execute===!0,g=[],b=typeof i.metricsContext?.executionId=="string"?i.metricsContext.executionId:void 0;(0,C.recordModulePlanTimeline)(e,b,"moveToFile.resolveSelectors.start",{sourceFile:u(e,c),targetFile:u(e,a),entityCount:o.length,execute:y}),await(0,ne.ensureSelectorsResolvable)(l.entry,c,o,f,(0,x.extensionRequestOptions)(r)),(0,C.recordModulePlanTimeline)(e,b,"moveToFile.resolveSelectors.end",{sourceFile:u(e,c),targetFile:u(e,a),entityCount:o.length,execute:y});for(const s of o){await(0,k.yieldToEventLoop)(),(0,C.recordModulePlanTimeline)(e,b,"moveToFile.entity.start",{sourceFile:u(e,c),targetFile:u(e,a),entity:s.raw,execute:y});const M=(0,T.startCentralMetricSpan)({kind:"mutation.entity",operation:y?"move.toFile.execute":"move.toFile.preview",cwd:F.resolve(e),sourceFile:u(e,c),targetFile:u(e,a),entity:s.raw,...i.metricsContext??{}});try{const m=process.env[ie.CLI_ENV.testMoveToFileFailEntity];if(y&&m&&s.raw===m)throw new E.CliError("TS_MOVE_TO_FILE_UNSUPPORTED_BY_ENGINE","TypeScript refactor failed: Debug Failure. False expression: Expected symbol to be a module",{diagnostic:"typescript-refactor-limitation",hint:"TypeScript move-to-file can fail on symbols that depend on default imports from CommonJS `export =` packages, e.g. `fast-json-stable-stringify`. If smaller moves still fail, use manual extraction.",next:"Retry with a smaller move or use manual extraction if TypeScript rejects the refactor."});const S=await(0,Z.postJson)(l.entry,ee.EXTENSION_ROUTES.moveRefactor,{sourceFile:c,targetFile:a,symbolName:s.symbolName,symbolKind:s.symbolKind,execute:y,importRules:(0,z.importRulesToJson)(_),mutationComments:(0,D.mutationCommentsPolicyToJson)(I),impactMetrics:(0,T.mutationImpactMetricsEnabled)()},(0,x.extensionRequestOptions)(r));g.push({entity:s.raw,...ue(e,s.raw,S)}),(0,C.recordModulePlanTimeline)(e,b,"moveToFile.entity.end",{sourceFile:u(e,c),targetFile:u(e,a),entity:s.raw,execute:y,ok:!0}),M.end(se(e,S,g[g.length-1]??{},o.length)),H(i,s.raw,g,o.length),await(0,k.yieldToEventLoop)()}catch(m){g.push(fe(s.raw,m)),(0,C.recordModulePlanTimeline)(e,b,"moveToFile.entity.end",{sourceFile:u(e,c),targetFile:u(e,a),entity:s.raw,execute:y,ok:!1,error:m instanceof Error?m.message:String(m)}),M.end({ok:!1,code:m instanceof E.CliError?m.code:"MOVE_TO_FILE_FAILED",error:m instanceof Error?m.message:String(m),totalEntities:o.length}),H(i,s.raw,g,o.length),await(0,k.yieldToEventLoop)();break}}const A=g.every(s=>s.ok!==!1),X=g.filter(s=>s.ok===!1).length,$=ye(c,a,o.map(s=>s.raw),y),O=L(g,"changedFiles"),q=L(g,"savedFiles"),v={...A?{}:{ok:!1},operation:y?"move.toFile.execute":"move.toFile.preview",source:u(e,c),target:u(e,a),...o.length===1?{move:o[0].raw}:{moves:o.map(s=>s.raw)},summary:A?ge(y,o.length,O,q,a):de(o.length,X),...!y&&O.length>0?{files:P(O,5)}:{},...y&&q.length>0?{filesWritten:P(q,5)}:{},...A?{}:{results:g}};if(!y&&A){const s=(0,h.buildMovePreviewId)($),M=(0,h.hashFile)(c),m=(0,h.hashFileIfExists)(a),S=(0,h.buildMovePreviewHash)($,M,m,v);(0,h.writeMovePreviewRecord)(e,{previewId:s,previewHash:S,createdAt:new Date().toISOString(),cwd:F.resolve(e),sourceFile:c,sourceHash:M,targetFile:a,targetExisted:j.existsSync(a),targetHash:m,normalizedPayload:$,previewResult:v}),v.previewId=s,v.next=`aib move toFile apply ${s}`}return ae(e,v,i.metricsContext),(0,W.attachAgentText)(v,B(v))}function ae(e,t,r){(0,T.recordCentralMetric)({kind:"mutation.summary",operation:typeof t.operation=="string"?t.operation:"move.toFile",cwd:F.resolve(e),ok:t.ok!==!1,sourceFile:typeof t.source=="string"?t.source:null,targetFile:typeof t.target=="string"?t.target:null,summary:typeof t.summary=="string"?t.summary:null,filesWrittenCount:Array.isArray(t.filesWritten)?t.filesWritten.filter(n=>typeof n=="string"&&!n.startsWith("+")).length:0,...r??{}})}function se(e,t,r,n){const i=d(t.referenceImpact)?t.referenceImpact:{},l=d(t.operationSummary)?t.operationSummary:{};return{ok:t.ok!==!1,totalEntities:n,editCount:typeof l.editCount=="number"?l.editCount:null,changedFileCount:Array.isArray(r.allChangedFiles)?r.allChangedFiles.length:0,savedFileCount:Array.isArray(r.allSavedFiles)?r.allSavedFiles.length:0,...(0,T.mutationImpactMetricsEnabled)()?{impactCollectionMs:typeof i.impactCollectionMs=="number"?i.impactCollectionMs:null,impact:ce(i),changedFiles:Array.isArray(r.allChangedFiles)?r.allChangedFiles:[],savedFiles:Array.isArray(r.allSavedFiles)?r.allSavedFiles:[]}:{},configFilePath:typeof t.configFilePath=="string"?u(e,t.configFilePath):null}}function ce(e){return{referenceCount:typeof e.referenceCount=="number"?e.referenceCount:null,definitionCount:typeof e.definitionCount=="number"?e.definitionCount:null,realReferenceCount:typeof e.realReferenceCount=="number"?e.realReferenceCount:null,importExportReferenceCount:typeof e.importExportReferenceCount=="number"?e.importExportReferenceCount:null,fileCount:typeof e.fileCount=="number"?e.fileCount:null,realReferenceFileCount:typeof e.realReferenceFileCount=="number"?e.realReferenceFileCount:null,impactCollectionMs:typeof e.impactCollectionMs=="number"?e.impactCollectionMs:null}}function H(e,t,r,n){e.onProgress&&e.onProgress({entity:t,completedEntities:r.length,totalEntities:n,filesWritten:L(r,"savedFiles"),ok:r.every(i=>i.ok!==!1)})}function ue(e,t,r){const n=d(r.operationSummary)?r.operationSummary:{},i=Array.isArray(n.changedFiles)?n.changedFiles.filter(o=>typeof o=="string").map(o=>u(e,o)):[],l=Array.isArray(r.savedFiles)?r.savedFiles.filter(o=>typeof o=="string").map(o=>u(e,o)):[],f=Array.isArray(n.warnings)?n.warnings.filter(d).map(o=>typeof o.code=="string"?o.code:"MOVE_WARNING"):[];return R({entity:t,ok:r.ok!==!1,applied:typeof r.applied=="boolean"?r.applied:null,editCount:typeof n.editCount=="number"?n.editCount:null,allChangedFiles:i,changedFiles:P(i,5),allSavedFiles:l,savedFiles:P(l,5),warnings:f,code:typeof r.code=="string"?r.code:typeof r.errorCode=="string"?r.errorCode:null,error:typeof r.error=="string"?r.error:null,hint:typeof r.hint=="string"?r.hint:null})}function fe(e,t){const r=t instanceof E.CliError&&d(t.details)?t.details:{},n=d(r.details)?r.details:{},i=d(n.diagnostic)?n.diagnostic:{},l=Array.isArray(i.hints)?i.hints.filter(d).map(o=>typeof o.description=="string"?o.description:"").filter(o=>o.length>0):[],f=typeof r.hint=="string"?r.hint:typeof n.hint=="string"?n.hint:l[0]??null;return R({entity:e,ok:!1,code:t instanceof E.CliError?t.code:"MOVE_TO_FILE_FAILED",error:me(t instanceof Error?t.message:String(t)),diagnostic:typeof i.kind=="string"?i.kind:null,hint:f,next:"Retry with a smaller move or use manual extraction if TypeScript rejects the refactor."})}function me(e){return e.replace(/^TypeScript refactor failed: Debug Failure\. False expression: /,"")}function ye(e,t,r,n){return{sourceFile:e,targetFile:t,entities:r,execute:n}}function ge(e,t,r,n,i){const l=j.existsSync(i)?"target exists":"target will be created";return e?`${t} ${t===1?"symbol":"symbols"}, ${n.length} ${n.length===1?"file":"files"} written`:`${t} ${t===1?"symbol":"symbols"}, ${r.length} ${r.length===1?"file":"files"}; ${l}`}function de(e,t){return`${e} ${e===1?"symbol":"symbols"}, ${t} failed`}function L(e,t){const r=t==="changedFiles"?"allChangedFiles":"allSavedFiles";return Array.from(new Set(e.flatMap(n=>Array.isArray(n[r])?n[r].filter(i=>typeof i=="string"&&!i.startsWith("+")):Array.isArray(n[t])?n[t].filter(i=>typeof i=="string"&&!i.startsWith("+")):[]))).sort((n,i)=>n.localeCompare(i))}function P(e,t){const r=e.slice(0,t),n=e.length-r.length;return n>0?[...r,`+ ${n} more`]:r}function B(e){const t=typeof e.operation=="string"?e.operation:"";if(t!=="move.toFile.preview"&&t!=="move.toFile.execute"&&t!=="move.toFile.apply")return null;const r=[],n=typeof e.previewId=="string"?e.previewId:"";r.push(e.ok===!1?`${t} failed`:n&&t==="move.toFile.preview"?`${t} ${n}`:t);const i=ve(e),l=_e(e.results),f=Fe(e.results),o=l?U(l.entity):null,c=o?i.indexOf(o):-1,a=c>=0?i.slice(c+1):[],_=Array.isArray(e.filesWritten)?e.filesWritten:e.files,I=Ee(_);return r.push(pe(t,e,i.length,f.length,l?1:0,a.length,I)),e.ok!==!1?G(r,"moves:",e.target,i):f.length>0&&G(r,"moves:",e.target,f),he(r,l),a.length>0&&(r.push("not run:"),r.push(J(a,15))),Array.isArray(_)&&_.length>0&&(r.push(t==="move.toFile.preview"?"files:":"filesWritten:"),be(r,_)),typeof e.next=="string"&&r.push(`next: ${e.next}`),r.join(`
2
+ `)}function pe(e,t,r,n,i,l,f){const o=`${r} ${r===1?"symbol":"symbols"}`;if(t.ok===!1){const a=[o];return n>0&&a.push(`${n} applied`),i>0&&a.push(`${i} failed`),l>0&&a.push(`${l} not run`),a.join(", ")}if(e==="move.toFile.preview")return`${o}, 1 target ready`;const c=`${f} ${f===1?"file":"files"} written`;return`${o}, 1 target moved; ${c}`}function G(e,t,r,n){typeof r!="string"||n.length===0||(e.push(t),e.push(`${r}: ${J(n,15)}`))}function he(e,t){if(!t)return;const r=typeof t.entity=="string"?t.entity:"symbol",n=typeof t.code=="string"?t.code:"MOVE_TO_FILE_FAILED",i=typeof t.error=="string"?t.error:"Move failed.";e.push("failed:"),e.push(r),e.push(`code: ${n}`),e.push(i),typeof t.hint=="string"&&e.push(`hint: ${t.hint}`)}function ve(e){return typeof e.move=="string"?[e.move]:Array.isArray(e.moves)?e.moves.filter(t=>typeof t=="string"):[]}function Fe(e){return Array.isArray(e)?e.filter(d).filter(t=>t.ok!==!1).map(t=>U(t.entity)).filter(t=>!!t):[]}function _e(e){return Array.isArray(e)?e.filter(d).find(t=>t.ok===!1)??null:null}function Ee(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&!t.startsWith("+")).length:0}function J(e,t){const r=e.slice(0,t),n=e.length-r.length;return n>0?`${r.join(", ")}, + ${n} more`:r.join(", ")}function be(e,t){if(Array.isArray(t))for(const r of t)typeof r=="string"&&e.push(r)}function U(e){return typeof e=="string"&&e.length>0?e:null}function K(e,t){const r=t.trim();return F.normalize(F.isAbsolute(r)?r:F.resolve(e,r))}function u(e,t){return F.relative(e,t).replace(/\\/g,"/")}function Me(e,t){const r=e.indexOf(t);if(r<0)return null;const n=e[r+1];return n&&!n.startsWith("--")?n:null}function R(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t==null?!1:!(Array.isArray(t)&&t.length===0)))}function d(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}
@@ -0,0 +1,3 @@
1
+ "use strict";var d=exports&&exports.__createBinding||(Object.create?(function(n,t,e,r){r===void 0&&(r=e);var i=Object.getOwnPropertyDescriptor(t,e);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[e]}}),Object.defineProperty(n,r,i)}):(function(n,t,e,r){r===void 0&&(r=e),n[r]=t[e]})),h=exports&&exports.__setModuleDefault||(Object.create?(function(n,t){Object.defineProperty(n,"default",{enumerable:!0,value:t})}):function(n,t){n.default=t}),o=exports&&exports.__importStar||(function(){var n=function(t){return n=Object.getOwnPropertyNames||function(e){var r=[];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[r.length]=i);return r},n(t)};return function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r=n(t),i=0;i<r.length;i++)r[i]!=="default"&&d(e,t,r[i]);return h(e,t),e}})();Object.defineProperty(exports,"__esModule",{value:!0}),exports.buildMutationExecutionId=P,exports.readMutationExecutionStatus=f,exports.tryReadMutationExecutionStatus=M,exports.writeMutationExecutionStatus=p,exports.mutationExecutionPath=c,exports.mutationExecutionLastPath=l,exports.waitForMutationDeadline=b,exports.readMutationSyncWaitMs=m;const _=o(require("node:crypto")),a=o(require("node:fs")),y=o(require("node:path")),S=require("../shared/errors"),u=require("./workspace-cache");function P(){return`exec_${_.randomBytes(3).toString("hex")}`}function f(n,t,e){const r=t==="last"?l(n,e.namespace):c(n,e.namespace,t);if(!a.existsSync(r))throw new S.CliError(e.notFoundCode,`${e.notFoundLabel} execution not found: ${t}`,{executionId:t,expectedPath:r});return JSON.parse(a.readFileSync(r,"utf8"))}function M(n,t,e){try{return f(n,t,e)}catch{return null}}function p(n,t,e){const r=new Date().toISOString();t.updatedAt=r,(t.status==="completed"||t.status==="failed")&&(t.completedAt=t.completedAt??r);const i=c(n,e.namespace,t.executionId,t.productStorageDir);a.mkdirSync(y.dirname(i),{recursive:!0}),a.writeFileSync(i,`${JSON.stringify(t,null,2)}
2
+ `),a.writeFileSync(l(n,e.namespace,t.productStorageDir),`${JSON.stringify(t,null,2)}
3
+ `)}function c(n,t,e,r){return r?(0,u.workspaceCachePathInProductStorageRoot)(r,n,t,`${s(e)}.json`):(0,u.workspaceCachePath)(n,t,`${s(e)}.json`)}function l(n,t,e){return e?(0,u.workspaceCachePathInProductStorageRoot)(e,n,t,"_last.json"):(0,u.workspaceCachePath)(n,t,"_last.json")}async function b(n,t,e){let r=null;try{return await Promise.race([n.then(i=>({status:"result",result:i})),new Promise(i=>{r=setTimeout(()=>{e?.(),i({status:"deadline"})},t)})])}finally{r&&clearTimeout(r)}}function m(n,t){if(n!==void 0){const e=Number.parseInt(n,10);return!Number.isFinite(e)||e<=0?0:Math.min(e,12e4)}return t}function s(n){return n.replace(/[^a-z0-9_-]+/gi,"-")}
@@ -0,0 +1,4 @@
1
+ "use strict";var G=exports&&exports.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),H=exports&&exports.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),R=exports&&exports.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(r){var n=[];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(n[n.length]=i);return n},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(t!=null)for(var n=e(t),i=0;i<n.length;i++)n[i]!=="default"&&G(r,t,n[i]);return H(r,t),r}})();Object.defineProperty(exports,"__esModule",{value:!0}),exports.runNormalizeImports=te,exports.readWorkspaceNormalizeImportRules=B;const K=R(require("node:crypto")),u=R(require("node:fs")),c=R(require("node:path")),m=require("../shared/errors"),Y=require("./json-file-input"),q=require("./workspace-cache"),E=[".ts",".tsx",".mts",".cts"],N=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],ee=new Set(["node_modules",".git","dist","out","build",".tmp"]);function te(e,t,r){const n=xe(e,t);if(n.action==="apply"){const l=n.applyPlanId;if(!l)throw new m.CliError("NORMALIZE_IMPORTS_PLAN_REQUIRED","imports normalize apply expects a preview id.");return re(e,l,n.showAll)}if(n.action==="show"){const l=n.showPlanId;if(!l)throw new m.CliError("NORMALIZE_IMPORTS_PLAN_REQUIRED","imports normalize show expects a preview id.");return ne(e,l,n.showAll)}const i=x(t,"--from-json"),o=r!==void 0?oe(r):i?(0,Y.readJsonObjectFile)(e,i,"INVALID_NORMALIZE_IMPORTS_JSON_FILE"):null;if(o){const a=ie(e,o,n).map(f=>C(e,f));return a.length===1?a[0]:{ok:a.every(f=>f.ok!==!1),operation:"imports.normalizeBatch",results:a}}const s=n.positionals[0];if(!s)throw new m.CliError("NORMALIZE_IMPORTS_SCOPE_REQUIRED","normalizeImports expects a file or directory scope.");return C(e,L(e,{scope:s,action:n.action,...n.mode!==void 0?{mode:n.mode}:{},...n.preferAlias!==void 0?{preferAlias:n.preferAlias}:{},exclude:n.exclude,ruleSources:n.ruleSources,showAll:n.showAll},n.rules))}function C(e,t){if(!t.scope)throw new m.CliError("NORMALIZE_IMPORTS_SCOPE_REQUIRED","normalizeImports JSON requests expect scope, file, dir, or directory.");const r=U(c.resolve(e,t.scope),e,t.exclude),n=new Map,i=r.flatMap(l=>se(e,l,t.mode,t.preferAlias,n)),o=new Set(i.map(l=>l.file)).size;t.action==="execute"&&D(e,i);const s={ok:!0,operation:"imports.normalize",mode:t.action,target:t.mode,filesScanned:r.length,filesChanged:o,edits:i.length,...t.exclude.length>0?{exclude:t.exclude}:{},...t.ruleSources.length>0?{ruleSources:t.ruleSources.map(l=>I(e,l))}:{},...z(i,t.showAll),next:t.action==="execute"?"Run typecheck or targeted validation for the affected project.":"Rerun with execute or apply the preview id if the preview matches intent."};if(t.action==="preview"){const l=ze(e,t,i);Pe(e,{planId:l,createdAt:new Date().toISOString(),cwd:e,request:t,files:Me(e,i),edits:i}),s.planId=l,s.next=`aib imports normalize apply ${l}`}return s}function re(e,t,r=!1){const n=k(e,t),i=Object.entries(n.files).filter(([o,s])=>{const l=c.resolve(e,o);return!u.existsSync(l)||b(u.readFileSync(l))!==s}).map(([o])=>o);if(i.length>0)throw new m.CliError("NORMALIZE_IMPORTS_PLAN_STALE",`imports normalize plan is stale: ${t}`,{planId:t,staleFiles:i.slice(0,20),...i.length>20?{hidden:`+ ${i.length-20} more stale files`}:{}});return D(e,n.edits),{ok:!0,operation:"imports.normalize",mode:"apply",planId:t,target:n.request.mode,filesChanged:new Set(n.edits.map(o=>o.file)).size,edits:n.edits.length,...z(n.edits,r),next:"Run typecheck or targeted validation for the affected project."}}function ne(e,t,r){const n=k(e,t);return{ok:!0,operation:"imports.normalize",mode:"show",planId:t,target:n.request.mode,filesChanged:new Set(n.edits.map(i=>i.file)).size,edits:n.edits.length,...z(n.edits,r),next:`aib imports normalize apply ${t}`}}function ie(e,t,r){const n=P(t),i=[...r.rules,...n],o=v(t,r);return(Array.isArray(t.requests)?t.requests:[t]).map((l,a)=>{if(!S(l))throw new m.CliError("INVALID_NORMALIZE_IMPORTS_REQUEST",`normalizeImports request at index ${a} must be an object.`);return L(e,v({...o,...l},r),i)})}function v(e,t){const r=p(e.scope)??p(e.file)??p(e.dir)??p(e.directory),n=t.action==="show"?"preview":t.action;return{scope:r??"",...T(e,t)!==void 0?{mode:T(e,t)}:{},action:e.execute===!0?"execute":n,...p(e.preferAlias)?{preferAlias:p(e.preferAlias)}:{},exclude:A([...t.exclude,...g(e.exclude),...g(e.excludes)]),ruleSources:t.ruleSources,showAll:t.showAll||e.all===!0||e.details==="all"}}function L(e,t,r=[]){const n=B(e),s=[...n.rules,...r].filter(f=>Re(e,t.scope,f)).sort((f,d)=>Q(d)-Q(f))[0],l=t.mode??s?.mode??"relative",a=t.preferAlias??s?.preferAlias;return{scope:t.scope,mode:l,action:t.action,...a?{preferAlias:a}:{},exclude:A([...s?.exclude??[],...t.exclude]),ruleSources:A([...n.sources,...t.ruleSources]),showAll:t.showAll}}function T(e,t){const r=p(e.to)??p(e.mode)??t.mode;if(r!==void 0){if(V(r))return r;throw new m.CliError("INVALID_NORMALIZE_IMPORTS_MODE","normalizeImports to/mode expects relative, alias, or shortestAlias.")}}function oe(e){if(!je(e))throw new m.CliError("INVALID_NORMALIZE_IMPORTS_STDIN","normalizeImports --stdin expects a JSON object payload.");return e}function se(e,t,r,n,i){const o=u.readFileSync(t,"utf8"),s=pe(t,e,i),l=[],a=/\b(from\s+["']|import\s*\(\s*["'])([^"']+)(["'])/g;for(const f of o.matchAll(a)){const d=f[2];if(!d)continue;const h=le(t,d,s);if(!h)continue;const y=r==="relative"?ce(t,h):ue(h,s,n,r);!y||y===d||l.push({file:I(e,t),from:d,to:y})}return l}function D(e,t){const r=new Map;for(const n of t){const i=r.get(n.file)??[];i.push(n),r.set(n.file,i)}for(const[n,i]of r.entries()){const o=c.resolve(e,n);let s=u.readFileSync(o,"utf8");for(const l of i)s=s.replace(new RegExp(F(`"${l.from}"`),"g"),`"${l.to}"`),s=s.replace(new RegExp(F(`'${l.from}'`),"g"),`'${l.to}'`);u.writeFileSync(o,s)}}function U(e,t,r){if(!u.existsSync(e))throw new m.CliError("NORMALIZE_IMPORTS_SCOPE_NOT_FOUND",`Scope does not exist: ${e}`);if(M(t,e,r))return[];const n=u.statSync(e);if(n.isFile())return $(e)?[e]:[];if(!n.isDirectory())return[];const i=[];for(const o of u.readdirSync(e,{withFileTypes:!0})){const s=c.join(e,o.name);if(o.isDirectory()){!ee.has(o.name)&&!M(t,s,r)&&i.push(...U(s,t,r));continue}o.isFile()&&$(s)&&!M(t,s,r)&&i.push(s)}return i.sort()}function le(e,t,r){if(t.startsWith("."))return J(c.resolve(c.dirname(e),t));if(!r)return null;for(const n of r.mappings){const i=Se(t,n);if(i!==null)for(const o of n.targets){const s=o.includes("*")?o.replace(/\*/g,i):o,l=J(c.resolve(n.baseUrl,s));if(l)return l}}return null}function ce(e,t){const r=c.dirname(e),n=O(t);let i=c.relative(r,n).replace(/\\/g,"/");return i.startsWith(".")||(i=`./${i}`),`${i}.js`}function ue(e,t,r,n){if(!t||t.mappings.length===0)return null;const i=ae(e,t,r);return(n==="shortestAlias"?i.sort((s,l)=>s.specifier.length-l.specifier.length||s.specifier.localeCompare(l.specifier)):i.sort((s,l)=>l.specificity-s.specificity||s.specifier.length-l.specifier.length||s.specifier.localeCompare(l.specifier)))[0]?.specifier??null}function ae(e,t,r){const n=O(e);return t.mappings.filter(i=>!r||i.pattern===r).flatMap(i=>i.targets.map(o=>{const s=fe(n,i,o);return s?{specifier:s,pattern:i.pattern,specificity:i.specificity}:null}).filter(o=>o!==null))}function fe(e,t,r){const n=r.indexOf("*");if(n<0)return O(c.resolve(t.baseUrl,r))===e&&!t.pattern.includes("*")?t.pattern:null;const i=O(c.resolve(t.baseUrl,r.slice(0,n))),o=O(r.slice(n+1));if(!e.startsWith(i)||o&&!e.endsWith(o))return null;const s=e.slice(i.length,o?-o.length:void 0).replace(/^[/\\]/,"");return t.pattern.replace("*",s.replace(/\\/g,"/"))}function pe(e,t,r){let n=c.dirname(e);const i=c.parse(c.resolve(t)).root;for(;;){const o=c.join(n,"tsconfig.json");if(u.existsSync(o))return W(o,r);const s=c.dirname(n);if(s===n||n===i)return null;n=s}}function W(e,t){const r=c.resolve(e);if(t.has(r))return t.get(r)??null;t.set(r,null);try{const n=w(u.readFileSync(r,"utf8")),i=de(r,n,t),o=S(n.compilerOptions)?n.compilerOptions:{},s=typeof o.baseUrl=="string"?c.resolve(c.dirname(r),o.baseUrl):i?.baseUrl??c.dirname(r),l=S(o.paths)?o.paths:null,a=(l?Object.entries(l).flatMap(([d,h])=>Array.isArray(h)?he(d,h.filter(y=>typeof y=="string"),s):[]):i?.mappings??[]).sort((d,h)=>h.specificity-d.specificity||d.pattern.localeCompare(h.pattern)),f={configPath:r,baseUrl:s,mappings:a};return t.set(r,f),f}catch{return t.set(r,null),null}}function de(e,t,r){const n=p(t.extends);if(!n)return null;const i=me(e,n);return i?W(i,r):null}function me(e,t){const r=[];return t.startsWith(".")||c.isAbsolute(t)?r.push(c.resolve(c.dirname(e),t)):r.push(c.resolve(c.dirname(e),"node_modules",t)),r.flatMap(i=>c.extname(i)?[i]:[`${i}.json`,c.join(i,"tsconfig.json")]).find(i=>u.existsSync(i)&&u.statSync(i).isFile())??null}function he(e,t,r){const n=e.indexOf("*");return[{pattern:e,prefix:n>=0?e.slice(0,n):e,suffix:n>=0?e.slice(n+1):"",targets:t,specificity:e.replace("*","").length,baseUrl:r}]}function Se(e,t){return t.pattern.includes("*")?!e.startsWith(t.prefix)||!e.endsWith(t.suffix)?null:e.slice(t.prefix.length,e.length-t.suffix.length):e===t.pattern?"":null}function J(e){const t=new Set;t.add(e);const r=c.extname(e);if(r&&[".js",".jsx",".mjs",".cjs"].includes(r)){const n=e.slice(0,-r.length);for(const i of E)t.add(`${n}${i}`)}if(!r)for(const n of N)t.add(`${e}${n}`);for(const n of N)t.add(c.join(e,`index${n}`));for(const n of t)if(u.existsSync(n)&&u.statSync(n).isFile()&&$(n))return n;return null}function w(e){const t=ye(e),r=JSON.parse(t.replace(/,\s*([}\]])/g,"$1"));return S(r)?r:{}}function ye(e){let t="",r=!1,n=!1;for(let i=0;i<e.length;i+=1){const o=e[i]??"",s=e[i+1]??"";if(r){t+=o,n?n=!1:o==="\\"?n=!0:o==='"'&&(r=!1);continue}if(o==='"'){r=!0,t+=o;continue}if(o==="/"&&s==="/"){for(;i<e.length&&e[i]!==`
2
+ `;)i+=1;t+=`
3
+ `;continue}if(o==="/"&&s==="*"){for(i+=2;i<e.length&&!(e[i]==="*"&&e[i+1]==="/");)i+=1;i+=1;continue}t+=o}return t}function x(e,t){const r=e.indexOf(t);return r>=0?e[r+1]:void 0}function xe(e,t){const r=t.filter((h,y)=>!h.startsWith("--")&&!Oe(t,y)),n=r[0],i=n==="preview"||n==="apply"||n==="execute"||n==="show"?n:t.includes("--execute")?"execute":"preview",o=n===i?r.slice(1):r,s=x(t,"--to"),l=s===void 0?void 0:Z(s),a=x(t,"--rules")??x(t,"--rules-file"),f=[],d=a?ge(c.resolve(e,a),f):[];return{action:i,...i==="apply"&&o[0]?{applyPlanId:o[0]}:{},...i==="show"&&o[0]?{showPlanId:o[0]}:{},positionals:i==="apply"||i==="show"?o.slice(1):o,...l!==void 0?{mode:l}:{},...x(t,"--prefer-alias")!==void 0?{preferAlias:x(t,"--prefer-alias")}:{},exclude:Ie(t,"--exclude"),rules:d,ruleSources:f,showAll:t.includes("--all")||t.includes("--details")||t.includes("--full")}}function Z(e){if(V(e))return e;throw new m.CliError("INVALID_NORMALIZE_IMPORTS_MODE","normalizeImports --to expects relative, alias, or shortestAlias.")}function V(e){return e==="relative"||e==="alias"||e==="shortestAlias"}function Ie(e,t){const r=[];for(let n=0;n<e.length;n+=1)e[n]===t&&typeof e[n+1]=="string"&&(r.push(e[n+1]),n+=1);return r}function Oe(e,t){const r=e[t-1];return t>0&&r!==void 0&&_e.has(r)}const _e=new Set(["--to","--prefer-alias","--exclude","--from-json","--from-dsl","--from","--rules","--rules-file"]);function z(e,t){const r=t?e:e.slice(0,12);return{samples:r.map(n=>`${n.file}: ${n.from} -> ${n.to}`),...!t&&e.length>r.length?{hidden:`+ ${e.length-r.length} more edits`}:{}}}function ge(e,t){if(!u.existsSync(e)||!u.statSync(e).isFile())throw new m.CliError("NORMALIZE_IMPORTS_RULES_NOT_FOUND",`imports normalize rules file not found: ${e}`);return t.push(e),P(w(u.readFileSync(e,"utf8")))}function B(e){const t=be(e),r=[],n=[];for(const i of t){const o=c.join(i,"aib.json");if(!(!u.existsSync(o)||!u.statSync(o).isFile()))try{const s=P(w(u.readFileSync(o,"utf8")));s.length>0&&(r.push(...s),n.push(o))}catch{}}return{rules:r,sources:n}}function P(e){const t=S(e.aib)?e.aib:{};return[e.importNormalize,e.importsNormalize,e["imports.normalize"],t.importNormalize,t.importsNormalize,t["imports.normalize"]].flatMap(n=>Ae(n))}function Ae(e){return Array.isArray(e)?e.flatMap(t=>S(t)?[_(t)]:[]):S(e)?Array.isArray(e.rules)?e.rules.flatMap(t=>S(t)?[_(t)]:[]):Array.isArray(e.requests)?e.requests.flatMap(t=>S(t)?[_(t)]:[]):[_(e)]:[]}function _(e){const t=p(e.to)??p(e.mode);return{...p(e.scope)?{scope:p(e.scope)}:{},...t!==null?{mode:Z(t)}:{},...p(e.preferAlias)?{preferAlias:p(e.preferAlias)}:{},exclude:A([...g(e.exclude),...g(e.excludes)])}}function Re(e,t,r){if(!r.scope)return!0;const n=I(e,c.resolve(e,t)),i=I(e,c.resolve(e,r.scope));return n===i||n.startsWith(`${i}/`)||i.startsWith(`${n}/`)}function Q(e){return e.scope?e.scope.length:0}function M(e,t,r){if(r.length===0)return!1;const n=I(e,c.resolve(t));return r.some(i=>Ee(e,n,i))}function Ee(e,t,r){const n=I(e,c.isAbsolute(r)?r:c.resolve(e,r));return Ne(r)?we(r.replace(/\\/g,"/")).test(t):t===n||t.startsWith(`${n}/`)}function Ne(e){return/[*?]/.test(e)}function we(e){let t="";for(let r=0;r<e.length;r+=1){const n=e[r];n==="*"?e[r+1]==="*"?(t+=".*",r+=1):t+="[^/]*":n==="?"?t+="[^/]":t+=F(n??"")}return new RegExp(`^${t}$`)}function ze(e,t,r){return`imports_${b(j({cwd:e,request:t,edits:r})).slice(0,8)}`}function Pe(e,t){const r=X(e,t.planId);u.mkdirSync(c.dirname(r),{recursive:!0}),u.writeFileSync(r,`${JSON.stringify(t,null,2)}
4
+ `)}function k(e,t){const r=X(e,t);if(!u.existsSync(r))throw new m.CliError("NORMALIZE_IMPORTS_PLAN_NOT_FOUND",`imports normalize plan not found: ${t}`,{planId:t,expectedPath:r});return JSON.parse(u.readFileSync(r,"utf8"))}function X(e,t){return(0,q.workspaceCachePath)(e,"imports-normalize",`${t.replace(/[^a-z0-9_-]+/gi,"-")}.json`)}function Me(e,t){const r={};for(const n of new Set(t.map(i=>i.file)))r[n]=b(u.readFileSync(c.resolve(e,n)));return r}function be(e){const t=[];let r=c.resolve(e);const n=c.parse(r).root;for(;t.push(r),r!==n;){const i=c.dirname(r);if(i===r)break;r=i}return t.reverse()}function b(e){return K.createHash("sha256").update(e).digest("hex")}function j(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(t=>j(t)).join(",")}]`:`{${Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>`${JSON.stringify(t)}:${j(r)}`).join(",")}}`}function p(e){return typeof e=="string"&&e.trim()!==""?e.trim():null}function g(e){return typeof e=="string"&&e.trim()!==""?[e.trim()]:Array.isArray(e)?e.filter(t=>typeof t=="string").map(t=>t.trim()).filter(t=>t.length>0):[]}function A(e){return Array.from(new Set(e))}function $(e){return E.includes(c.extname(e))&&!e.endsWith(".d.ts")}function O(e){const t=c.extname(e);return E.includes(t)||N.includes(t)?e.slice(0,-t.length):e}function S(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function je(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function I(e,t){return c.relative(e,t).replace(/\\/g,"/")}function F(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}
@@ -0,0 +1,3 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.runObservabilityCommand=a;const s=require("../shared/agent-text"),o=require("../shared/errors"),c=require("../observability/config");function a(t,n){const e=n[0]??"status";if(e==="status"){const r=(0,c.observabilityStatus)(t);return(0,s.attachAgentText)(r,u(r))}if(e==="cleanup")return(0,s.attachAgentText)({ok:!0,command:"observability",action:"cleanup",dryRun:!0,enforced:!1,note:"Cleanup policy is visible but not enforced yet."},`observability cleanup dry-run
2
+ no files deleted`);throw new o.CliError("UNKNOWN_OBSERVABILITY_COMMAND",`Unknown aib observability command: ${e}`,{availableCommands:["status","cleanup"]})}function u(t){const n=i(t.effective)?t.effective:{},e=i(t.storage)?t.storage:{},r=i(t.counters)?t.counters:{};return["observability",`metrics: ${String(n.metrics??"unknown")}`,`mutationImpactMetrics: ${String(n.mutationImpactMetrics??"unknown")}`,`trace: ${String(n.trace??"unknown")}`,`failureSnapshots: ${String(n.failureSnapshots??"unknown")}`,`metricsRows: ${String(r.metricsRows??0)}`,`traceBytes: ${String(r.traceBytes??0)}`,`feedbackRows: ${String(r.feedbackRows??0)}`,`metricsFile: ${String(e.metricsFile??"")}`,`traceDir: ${String(e.traceDir??"")}`,`feedbackFile: ${String(e.feedbackFile??"")}`].join(`
3
+ `)}function i(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.runPing=o;const a=require("../client/http-client"),n=require("./shared"),c=require("../shared/routes");async function o(r,t={}){const e=await(0,n.resolveTargetInstance)(r,t),s=await(0,a.postJson)(e.entry,c.EXTENSION_ROUTES.health,{},(0,n.extensionRequestOptions)(t));return{ok:!0,selectedInstance:{instanceId:e.entry.instanceId,reason:e.reason,matchedWorkspace:e.matchedWorkspace,port:e.entry.port},response:s}}
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.runPrintConfig=a;const n=require("./shared"),o=require("../shared/protocol");async function a(r,t={}){const e=await(0,n.resolveCompatibleTargetInstance)(r,o.CLI_COMMAND_IDS.printConfig,t),c=await(0,n.fetchEffectiveConfig)(e.entry,t);return{ok:!0,selectedInstance:{instanceId:e.entry.instanceId,reason:e.reason,matchedWorkspace:e.matchedWorkspace,port:e.entry.port},config:c}}
@@ -0,0 +1,11 @@
1
+ "use strict";var E=exports&&exports.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),R=exports&&exports.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),p=exports&&exports.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(n){var r=[];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(r[r.length]=i);return r},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(t!=null)for(var r=e(t),i=0;i<r.length;i++)r[i]!=="default"&&E(n,t,r[i]);return R(n,t),n}})();Object.defineProperty(exports,"__esModule",{value:!0}),exports.runQuickReadCommand=A;const _=p(require("node:fs/promises")),m=p(require("node:path")),w=require("../config/path-display"),q=require("../config/path-aliases"),F=require("../shared/agent-text"),f=require("../shared/errors"),N=require("./session-workspace"),v=80;async function A(e,t){const n=(0,N.readEffectiveSessionPathAliases)(e),r=(0,w.buildDisplayPathAliases)(e,n),i=t.includes("--stdin")?M(e,n,r,await L()):[h(e,n,r,t)],s=await $(O(i)),c={ok:s.some(o=>o.error===void 0),blocks:s.map(o=>({file:o.file,...o.window!==void 0?{window:o.window}:{},...o.content!==void 0?{content:o.content}:{},...o.error!==void 0?{error:o.error}:{}}))};return(0,F.attachAgentText)(c,b(s))}function O(e){const t=new Set(e.filter(i=>i.windows.some(s=>s.kind==="all")).map(i=>i.resolvedFile));if(t.size===0)return e;const n=new Set,r=[];for(const i of e){if(!t.has(i.resolvedFile)){r.push(i);continue}n.has(i.resolvedFile)||(n.add(i.resolvedFile),r.push({...i,windows:[{kind:"all"}]}))}return r}async function $(e){const t=new Map;for(const r of e)t.has(r.resolvedFile)||t.set(r.resolvedFile,y(r.resolvedFile));const n=[];for(const r of e){const i=await t.get(r.resolvedFile);if(i.error!==void 0||i.lines===void 0){n.push({file:r.displayFile,error:i.error??"read failed"});continue}for(const s of r.windows)n.push({file:r.displayFile,window:x(s),content:I(i.lines,s).join(`
2
+ `)})}return n}async function y(e){let t;try{t=await _.stat(e)}catch(r){return{error:(typeof r=="object"&&r!==null&&"code"in r?String(r.code):"")==="ENOENT"?"file not found":"cannot stat file"}}if(t.isDirectory())return{error:"is a directory"};if(!t.isFile())return{error:"not a regular file"};let n;try{n=await _.readFile(e)}catch{return{error:"cannot read file"}}return Q(n)?{error:"binary file"}:{lines:C(n.toString("utf8"))}}function Q(e){const t=Math.min(e.length,8192);for(let n=0;n<t;n+=1)if(e[n]===0)return!0;return!1}function C(e){const t=e.replace(/\r\n/g,`
3
+ `).replace(/\r/g,`
4
+ `);return t.endsWith(`
5
+ `)?t.slice(0,-1).split(`
6
+ `):t.split(`
7
+ `)}function I(e,t){return t.kind==="all"?e:t.kind==="head"?e.slice(0,t.count):t.kind==="tail"?e.slice(Math.max(0,e.length-t.count)):e.slice(t.offset-1,t.offset-1+t.limit)}function M(e,t,n,r){const i=r.replace(/^\uFEFF/,"").split(/\r?\n/),s=[];for(let u=0;u<i.length;u+=1){const c=i[u]?.trim()??"";if(!c||c.startsWith("#"))continue;const o=B(c);if(o.length===0)continue;const l=o[0]==="qr"?o.slice(1):o;try{s.push(h(e,t,n,l))}catch(a){throw a instanceof f.CliError?new f.CliError(a.code,`qr stdin line ${u+1}: ${a.message}`,a.details):a}}if(s.length===0)throw new f.CliError("QR_STDIN_EMPTY","qr --stdin expects at least one qr line.");return s}function h(e,t,n,r){const i=r.filter(o=>o!=="--stdin");if(i.length===0)throw new f.CliError("QR_FILE_REQUIRED","qr expects a file path.");if(i[0]==="qr")return h(e,t,n,i.slice(1));const s=i[0]??"";if(s.startsWith("-")||T(s))throw new f.CliError("QR_FILE_REQUIRED","qr expects a file path before window flags.");const u=m.resolve(e,(0,q.expandPathAliasValue)(e,s,t)),c=S(i.slice(1));return{file:s,resolvedFile:u,displayFile:(0,w.compactDisplayPath)(e,u,n),windows:c}}function S(e){let t=!1,n=null,r=null,i=null,s=null;for(let o=0;o<e.length;o+=1){const l=e[o]??"",a=P(l);if(a){c(a.key,a.value);continue}if(l==="-a"||l==="--all"||l==="a"||l==="all"||l==="+all"){t=!0;continue}if(l==="-h"||l==="--head"){n=d(e,++o,l);continue}if(l==="-t"||l==="--tail"){r=d(e,++o,l);continue}if(l==="-o"||l==="--offset"){i=d(e,++o,l);continue}if(l==="-l"||l==="--limit"){s=d(e,++o,l);continue}throw new f.CliError("QR_UNKNOWN_ARGUMENT",`Unknown qr argument: ${l}`)}if(i===null!=(s===null))throw new f.CliError("QR_RANGE_INCOMPLETE","qr range reads require both o=<line> and l=<count>.");if(t)return[{kind:"all"}];const u=[];return n!==null&&u.push({kind:"head",count:n}),i!==null&&s!==null&&u.push({kind:"range",offset:i,limit:s}),r!==null&&u.push({kind:"tail",count:r}),u.length>0?u:[{kind:"head",count:v}];function c(o,l){if(o==="a"||o==="all"){t=D(l,o);return}const a=g(l,o);if(o==="h"||o==="head"){n=a;return}if(o==="t"||o==="tail"){r=a;return}if(o==="o"||o==="offset"){i=a;return}if(o==="l"||o==="limit"){s=a;return}throw new f.CliError("QR_UNKNOWN_ARGUMENT",`Unknown qr window field: ${o}`)}}function D(e,t){if(e==="true"||e==="1"||e==="yes")return!0;if(e==="false"||e==="0"||e==="no")return!1;throw new f.CliError("QR_INVALID_BOOLEAN",`${t} expects true or false.`)}function P(e){const t=e.indexOf("=");return t<=0?null:{key:e.slice(0,t),value:e.slice(t+1)}}function d(e,t,n){const r=e[t];if(!r||r.startsWith("-"))throw new f.CliError("QR_MISSING_FLAG_VALUE",`Expected a positive integer after ${n}.`);return g(r,n)}function g(e,t){const n=Number(e);if(!Number.isInteger(n)||n<1)throw new f.CliError("QR_INVALID_NUMBER",`${t} expects a positive integer.`);return n}function T(e){return/^(?:h|head|t|tail|o|offset|l|limit|a|all)=/.test(e)||e==="+all"}function b(e){return e.map(t=>{if(t.error!==void 0)return`// ${t.file} - ${t.error}`;const n=`// ${t.file}${t.window?` ${t.window}`:""}`;return t.content?`${n}
8
+ ${t.content}`:`${n}
9
+ `}).join(`
10
+
11
+ `)}function x(e){return e.kind==="all"?"all":e.kind==="head"?`h=${e.count}`:e.kind==="tail"?`t=${e.count}`:`o=${e.offset} l=${e.limit}`}function B(e){const t=[];let n="",r=null;for(let i=0;i<e.length;i+=1){const s=e[i]??"";if(r){s===r?r=null:n+=s;continue}if(s==='"'||s==="'"){r=s;continue}if(/\s/.test(s)){n.length>0&&(t.push(n),n="");continue}n+=s}if(r)throw new f.CliError("QR_UNTERMINATED_QUOTE","qr input has an unterminated quote.");return n.length>0&&t.push(n),t}async function L(){const e=[];for await(const t of process.stdin)e.push(Buffer.isBuffer(t)?t:Buffer.from(String(t)));return Buffer.concat(e).toString("utf8")}
@@ -0,0 +1 @@
1
+ "use strict";var z=exports&&exports.__createBinding||(Object.create?(function(e,t,r,i){i===void 0&&(i=r);var o=Object.getOwnPropertyDescriptor(t,r);(!o||("get"in o?!t.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,i,o)}):(function(e,t,r,i){i===void 0&&(i=r),e[i]=t[r]})),O=exports&&exports.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),R=exports&&exports.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(r){var i=[];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(i[i.length]=o);return i},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(t!=null)for(var i=e(t),o=0;o<i.length;o++)i[o]!=="default"&&z(r,t,i[o]);return O(r,t),r}})();Object.defineProperty(exports,"__esModule",{value:!0}),exports.buildExtensionRefactorBatchPayload=E;const f=R(require("node:path")),s=require("zod"),b=require("../selectors/parse-entities"),p=require("../shared/errors"),y=require("./rename-input"),w=s.z.object({id:s.z.string().min(1).optional(),kind:s.z.enum(["moveRefactor","renameSymbol"]),body:s.z.object({}).passthrough()}),F=s.z.object({id:s.z.string().min(1).optional(),op:s.z.union([s.z.literal("moveToFile"),s.z.literal("move")]),sourceFile:s.z.string().min(1).optional(),targetFile:s.z.string().min(1),entities:s.z.union([s.z.array(s.z.string().min(1)).min(1),s.z.string().min(1)]),execute:s.z.boolean().optional()}),v=s.z.object({id:s.z.string().min(1).optional(),op:s.z.union([s.z.literal("renameEntities"),s.z.literal("rename")]),sourceFile:s.z.string().min(1).optional(),renames:y.RenamesInputSchema,execute:s.z.boolean().optional()}).transform(e=>({...e,renames:(0,y.normalizeRenamesInput)(e.renames)}));function E(e,t){const r=Array.isArray(e.requests)?e.requests:Array.isArray(e.operations)?e.operations:[],i=[],o=[],a=j(e);for(let n=0;n<r.length;n+=1){const l=r[n],m=S(C(l,a),n,t);i.push(...m.operations),o.push(m.summary)}const{requests:u,...c}=e;return{payload:{...c,operations:i.map(n=>({id:n.id,kind:n.kind,body:n.body}))},summary:{source:o.some(n=>n.source==="agent-facing")?"agent-facing":"low-level",sourceOperationCount:r.length,builtOperationCount:i.length,rows:o}}}function j(e){return{...typeof e.sourceFile=="string"?{sourceFile:e.sourceFile}:{},...typeof e.execute=="boolean"?{execute:e.execute}:{}}}function C(e,t){return e&&typeof e=="object"&&!Array.isArray(e)?{...t,...e}:e}function S(e,t,r){const i=w.safeParse(e);if(i.success){const u=q(i.data,t);return{operations:[u],summary:{source:"low-level",index:t+1,id:u.id,kind:u.kind,builtOperationCount:1}}}const o=F.safeParse(e);if(o.success)return A(o.data,t,r);const a=v.safeParse(e);return a.success?I(a.data,t,r):N(t,e)}function q(e,t){return{id:e.id??`op-${t+1}`,kind:e.kind,body:_(e.body)}}function A(e,t,r){const i=f.normalize(g(e.sourceFile,e.op)),o=f.normalize(e.targetFile),a=e.execute===!0,u=(0,b.parseEntitySelectors)(e.entities,r),c=u.map((n,l)=>({id:h(e.id??`move-${t+1}`,n.raw,l),kind:"moveRefactor",body:{sourceFile:i,targetFile:o,symbolName:n.symbolName,symbolKind:n.symbolKind,execute:a}}));return{operations:c,summary:{source:"agent-facing",index:t+1,op:"move",sourceFile:i,targetFile:o,entities:u.map(n=>n.raw),builtRows:c.map((n,l)=>({id:n.id,entity:u[l].raw,targetFile:o})),entityCount:u.length,builtOperationCount:c.length}}}function I(e,t,r){const i=f.normalize(g(e.sourceFile,e.op)),o=e.execute===!0,a=(0,b.parseEntitySelectors)(e.renames.map(n=>n.entity),r),u=new Map(e.renames.map(n=>[n.entity.trim(),n.newName])),c=a.map((n,l)=>({id:h(e.id??`rename-${t+1}`,n.raw,l),kind:"renameSymbol",body:{sourceFile:i,symbolName:n.symbolName,symbolKind:n.symbolKind,newName:u.get(n.raw)??"",execute:o}}));return{operations:c,summary:{source:"agent-facing",index:t+1,op:"rename",builtRows:c.map((n,l)=>{const m=a[l].raw;return{id:n.id,entity:m,newName:u.get(m)??""}}),renameCount:a.length,builtOperationCount:c.length}}}function g(e,t){if(!e)throw new p.CliError("SOURCE_FILE_REQUIRED",`refactor batch ${t} request requires sourceFile or top-level sourceFile.`);return e}function h(e,t,r){return`${e}#${r+1}:${t}`}function _(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>[t,d(r)]))}function d(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?e:Array.isArray(e)?e.map(t=>d(t)):e&&typeof e=="object"?_(e):String(e)}function N(e,t){throw new p.CliError("INVALID_REFACTOR_BATCH_OPERATION",`Invalid refactorBatch operation at index ${e+1}.`,{index:e+1,operation:d(t)})}
@@ -0,0 +1 @@
1
+ "use strict";var o=exports&&exports.__createBinding||(Object.create?(function(e,t,a,n){n===void 0&&(n=a);var r=Object.getOwnPropertyDescriptor(t,a);(!r||("get"in r?!t.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return t[a]}}),Object.defineProperty(e,n,r)}):(function(e,t,a,n){n===void 0&&(n=a),e[n]=t[a]})),i=exports&&exports.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),f=exports&&exports.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(a){var n=[];for(var r in a)Object.prototype.hasOwnProperty.call(a,r)&&(n[n.length]=r);return n},e(t)};return function(t){if(t&&t.__esModule)return t;var a={};if(t!=null)for(var n=e(t),r=0;r<n.length;r++)n[r]!=="default"&&o(a,t,n[r]);return i(a,t),a}})();Object.defineProperty(exports,"__esModule",{value:!0}),exports.buildRefactorBatchExecutionId=h,exports.createRefactorBatchExecutionStatus=l,exports.readRefactorBatchExecutionStatus=_,exports.tryReadRefactorBatchExecutionStatus=E,exports.writeRefactorBatchExecutionStatus=R,exports.refactorBatchExecutionPath=b,exports.refactorBatchExecutionLastPath=B;const s=f(require("node:path")),d=require("../config/product-storage"),u=require("./mutation-execution-cache");function h(){return(0,u.buildMutationExecutionId)()}function l(e,t,a,n){const r=new Date().toISOString();return{executionId:t,operation:a,cwd:s.resolve(e),status:"running",phase:"mutation",startedAt:r,updatedAt:r,rowCount:n,completedRows:0,failedRows:0,filesWritten:[],productStorageDir:(0,d.productStorageRoot)()}}function _(e,t){return(0,u.readMutationExecutionStatus)(e,t,c)}function E(e,t){return(0,u.tryReadMutationExecutionStatus)(e,t,c)}function R(e,t){(0,u.writeMutationExecutionStatus)(e,t,c)}function b(e,t,a){return(0,u.mutationExecutionPath)(e,c.namespace,t,a)}function B(e,t){return(0,u.mutationExecutionLastPath)(e,c.namespace,t)}const c={namespace:"refactor-batch-executions",notFoundCode:"REFACTOR_BATCH_EXECUTION_NOT_FOUND",notFoundLabel:"Refactor batch"};
@@ -0,0 +1,2 @@
1
+ "use strict";var s=exports&&exports.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),h=exports&&exports.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),u=exports&&exports.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var n=[];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(n[n.length]=i);return n},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=r(e),i=0;i<n.length;i++)n[i]!=="default"&&s(t,e,n[i]);return h(t,e),t}})();Object.defineProperty(exports,"__esModule",{value:!0}),exports.buildRefactorBatchPreviewId=b,exports.buildRefactorBatchPreviewHash=w,exports.readRefactorBatchPreviewRecord=P,exports.writeRefactorBatchPreviewRecord=p,exports.refactorBatchPreviewRecordPath=o,exports.hashFileIfExists=O;const l=u(require("node:crypto")),c=u(require("node:fs")),d=u(require("node:path")),_=require("../shared/errors"),y=require("./workspace-cache");function b(r){return`batch_${f(a(r)).slice(0,10)}`}function w(r,e,t){return`sha256:${f(a({normalizedPayload:r,files:e,summary:t.summary,response:t.response}))}`}function P(r,e){const t=o(r,e);if(!c.existsSync(t))throw new _.CliError("REFACTOR_BATCH_PREVIEW_NOT_FOUND",`Refactor batch preview not found: ${e}`,{previewId:e,expectedPath:t});return JSON.parse(c.readFileSync(t,"utf8"))}function p(r,e){const t=o(r,e.previewId);c.mkdirSync(d.dirname(t),{recursive:!0}),c.writeFileSync(t,`${JSON.stringify(e,null,2)}
2
+ `)}function o(r,e){return(0,y.workspaceCachePath)(r,"refactor-batch-previews",`${v(e)}.json`)}function O(r){return c.existsSync(r)?f(c.readFileSync(r)):null}function f(r){return l.createHash("sha256").update(r).digest("hex")}function a(r){return r===null||typeof r!="object"?JSON.stringify(r):Array.isArray(r)?`[${r.map(e=>a(e)).join(",")}]`:`{${Object.entries(r).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${JSON.stringify(e)}:${a(t)}`).join(",")}}`}function v(r){return r.replace(/[^a-z0-9_-]+/gi,"-")}
@@ -0,0 +1,4 @@
1
+ "use strict";var oe=exports&&exports.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);(!o||("get"in o?!t.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),ae=exports&&exports.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),J=exports&&exports.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(r){var n=[];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[n.length]=o);return n},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(t!=null)for(var n=e(t),o=0;o<n.length;o++)n[o]!=="default"&&oe(r,t,n[o]);return ae(r,t),r}})();Object.defineProperty(exports,"__esModule",{value:!0}),exports.runRefactorBatch=de,exports.readCachedRefactorBatchExecution=he;const G=J(require("node:fs")),M=J(require("node:path")),A=require("zod"),ie=require("../client/http-client"),w=require("../config/env-vars"),se=require("../config/product-storage"),ce=require("../shared/routes"),ue=require("../shared/protocol"),P=require("../shared/agent-text"),le=require("../shared/errors"),fe=require("./refactor-batch-builder"),I=require("./refactor-batch-preview-cache"),x=require("./refactor-batch-execution-cache"),K=require("./mutation-execution-cache"),j=require("./shared"),q=A.z.object({operations:A.z.array(A.z.unknown()).min(1).optional(),requests:A.z.array(A.z.unknown()).min(1).optional(),continueOnError:A.z.boolean().optional(),execution:A.z.literal("sequential").optional()}).passthrough().refine(e=>Array.isArray(e.operations)||Array.isArray(e.requests),{message:"refactor batch expects operations[] or requests[]."});async function de(e,t,r={},n="preview",o={}){if(n==="apply"&&o.previewId){const u=L();if(u>0){const s=U(e,o.previewId),h=q.parse(z(s.normalizedPayload,!0));return X(e,h,r,"apply",{...o,previewId:o.previewId},u)}return pe(e,o.previewId,r,o)}const a=q.parse(t);return(n==="execute"||n==="apply")&&L()>0?X(e,a,r,n,o,L()):N(e,a,r,n,o)}async function pe(e,t,r,n){const o=U(e,t),a=q.parse(z(o.normalizedPayload,!0));return N(e,a,r,"apply",{...n,previewId:t})}function U(e,t){const r=(0,I.readRefactorBatchPreviewRecord)(e,t),n=r.files.find(o=>G.existsSync(o.file)!==o.existed||(0,I.hashFileIfExists)(o.file)!==o.hash);if(n)throw new le.CliError("REFACTOR_BATCH_PREVIEW_FILES_CHANGED","Touched files changed after refactor batch preview. Rerun preview.",{previewId:t,file:k(e,n.file)});return r}async function X(e,t,r,n,o,a){const u=(0,x.buildRefactorBatchExecutionId)(),s=`refactor.batch.${n}`,h=Ae(t),p=(0,x.createRefactorBatchExecutionStatus)(e,u,s,Q(t));(0,x.writeRefactorBatchExecutionStatus)(e,p);const f=Date.now(),y=Be(),R=ve(()=>(0,se.runWithProductStorageOverride)(y[w.CLI_ENV.productStorageDir],()=>Ie(y,async()=>{try{const l=await N(e,t,r,n,o),g=Y(l);return p.status=l.ok===!1?"failed":"completed",p.phase="completed",p.completedRows=g.filter(i=>i.ok!==!1).length,p.failedRows=g.filter(i=>i.ok===!1).length,p.filesWritten=xe(l),p.result=l,l.ok===!1&&(p.error=c(l.code)??"REFACTOR_BATCH_FAILED"),(0,x.writeRefactorBatchExecutionStatus)(e,p),l}catch(l){throw p.status="failed",p.phase="completed",p.error=l instanceof Error?l.message:String(l),(0,x.writeRefactorBatchExecutionStatus)(e,p),l}}))),m=await _e(R,a);return m.status==="result"?m.result:(R.catch(()=>{}),we(e,u,s,h,Date.now()-f))}async function N(e,t,r,n,o){await $e();const a=await(0,j.resolveCompatibleTargetInstance)(e,ue.CLI_COMMAND_IDS.refactorBatch,r),u=await(0,j.fetchEffectiveConfig)(a.entry,r),s=(0,fe.buildExtensionRefactorBatchPayload)(t,u),h=await(0,ie.postJson)(a.entry,ce.EXTENSION_ROUTES.refactorBatch,s.payload,(0,j.extensionRequestOptions)(r)),p=me(e,h),f={ok:p.batchOk===!0,...p.batchOk===!0?{}:{code:"REFACTOR_BATCH_FAILED"},operation:`refactor.batch.${n}`,builder:s.summary,response:p};if(n==="preview"&&f.ok!==!1){const R=z(t,!1),m=(0,I.buildRefactorBatchPreviewId)(R),l=Ce(e,s.payload),g=(0,I.buildRefactorBatchPreviewHash)(R,l,f);(0,I.writeRefactorBatchPreviewRecord)(e,{previewId:m,previewHash:g,createdAt:new Date().toISOString(),cwd:M.resolve(e),normalizedPayload:R,files:l,builder:s.summary,previewResult:f}),f.previewId=m,f.next=`aib refactor batch apply ${m}`}const y={...o,...typeof f.previewId=="string"?{previewId:f.previewId}:{},...typeof f.next=="string"?{next:f.next}:{}};return(0,P.attachAgentText)(f,Re(e,s.summary,p,n,y))}function he(e,t){const r=(0,x.readRefactorBatchExecutionStatus)(e,t);if((r.status==="completed"||r.status==="failed")&&r.result)return r.result;const n={operation:"execution.status",executionId:r.executionId,status:r.status,phase:r.phase,summary:F(r),progress:`${r.completedRows}/${r.rowCount}`,filesWritten:r.filesWritten,updatedAt:r.updatedAt,...r.error?{error:r.error}:{}};return(0,P.attachAgentText)(n,be(r))}function me(e,t){const r=Array.isArray(t.rows)?t.rows.map(n=>ye(e,n)):[];return{ok:t.ok===!0,operation:c(t.operation),contract:t.contract??null,execution:c(t.execution),continueOnError:t.continueOnError===!0,batchOk:t.batchOk===!0,batchStatus:c(t.batchStatus),requestedOperationCount:b(t.requestedOperationCount),plannedOperationCount:b(t.plannedOperationCount),attemptedRowCount:b(t.attemptedRowCount),rowCount:b(t.rowCount),passedRowCount:b(t.passedRowCount),failedRowCount:b(t.failedRowCount),skippedRowCount:b(t.skippedRowCount),guidance:t.guidance??null,rows:r,...t._metrics?{_metrics:t._metrics}:{}}}function ye(e,t){if(!t||typeof t!="object"||Array.isArray(t))return{ok:!1,error:"Invalid batch row shape."};const r=t;return r.skipped===!0?T({index:b(r.index),id:c(r.id),kind:c(r.kind),planned:r.planned===!0,attempted:!1,outcome:c(r.outcome),skipped:!0,skipReason:c(r.skipReason),error:c(r.error)}):T({index:b(r.index),id:c(r.id),kind:c(r.kind),planned:r.planned===!0,attempted:r.attempted===!0,outcome:c(r.outcome),ok:r.ok===!0,statusCode:b(r.statusCode),durationMs:b(r.durationMs),applied:r.applied===!0,touchedFiles:E(r.touchedFiles).map(n=>k(e,n)),savedFiles:E(r.savedFiles).map(n=>k(e,n)),error:c(r.error),response:Le(r.response)})}function Re(e,t,r,n,o={}){const a=Array.isArray(r.rows)?r.rows.filter(l=>!!l&&typeof l=="object"&&!Array.isArray(l)):[],u=a.filter(l=>l.outcome==="applied").length,s=a.filter(l=>l.outcome==="validated").length,h=typeof r.failedRowCount=="number"?r.failedRowCount:a.filter(l=>l.ok===!1).length,p=n==="execute"||n==="apply"||n==="validate"?n:u>0?"apply":"preview",f=[];o.routedFrom==="move.toFile"&&(f.push("move.toFile routed to refactor.batch"),f.push(""));const y=Me(t,e),R=Fe(t);if(f.push(Ee(p,o)),f.push(Se(p,{movePlan:y,renamePlan:R},a,u,s,h)),(y||R)&&a.length>0)ke(f,{movePlan:y,renamePlan:R},a);else for(const l of a){const g=c(l.id)??`row ${b(l.index)??"?"}`,i=c(l.kind)??"operation",v=c(l.outcome)??(l.ok===!0?"ok":"failed");f.push(`${Pe(i)} ${je(g)} ${v}`)}const m=D(a.flatMap(l=>E(l.savedFiles)));return m.length>0&&(f.push("filesWritten:"),f.push(...m)),o.next&&f.push(`next: ${o.next}`),f.join(`
2
+ `)}function we(e,t,r,n,o){const a=(0,x.readRefactorBatchExecutionStatus)(e,t),u=Math.max(0,n-o),s={operation:"execution.status",executionId:a.executionId,status:a.status,phase:a.phase,summary:F(a),progress:`${a.completedRows}/${a.rowCount}`,filesWritten:a.filesWritten,updatedAt:a.updatedAt,estimatedRemainingMs:u};return(0,P.attachAgentText)(s,ge(r,a,u))}function ge(e,t,r){return[`${e} ${t.executionId}`,F(t),"applying mutation",`status: aib execution status ${t.executionId}`,r>0?`estimated remaining: ${Ne(Math.max(r,5e3))}`:"estimated remaining: check status again soon"].join(`
3
+ `)}function be(e){const t=[`${e.operation} ${e.executionId}`,F(e)];return e.status==="running"&&(t.push("applying mutation"),t.push(`status: aib execution status ${e.executionId}`)),e.error&&t.push(e.error),t.join(`
4
+ `)}function F(e){return e.status==="completed"?`completed, ${e.completedRows}/${e.rowCount} rows, ${e.filesWritten.length} files written`:e.status==="failed"?`failed, ${e.completedRows}/${e.rowCount} rows, ${e.failedRows} failed`:`in progress, ${e.completedRows}/${e.rowCount} rows`}function ve(e){return new Promise((t,r)=>{setImmediate(()=>{e().then(t,r)})})}async function _e(e,t){return(0,K.waitForMutationDeadline)(e,t)}function L(){return(0,K.readMutationSyncWaitMs)(process.env[w.CLI_ENV.refactorBatchSyncWaitMs],12e4)}function Ae(e){return 12e3+Q(e)*2e3}function Q(e){const t=Array.isArray(e.operations)?e.operations:Array.isArray(e.requests)?e.requests:[];let r=0;for(const n of t){if(!_(n)){r+=1;continue}const o=Array.isArray(n.entities)?n.entities:Array.isArray(n.symbols)?n.symbols:[],a=Array.isArray(n.renames)?n.renames:[];r+=Math.max(1,o.length,a.length)}return Math.max(1,r)}function xe(e){const t=Y(e);return D(t.flatMap(r=>E(r.savedFiles)))}function Y(e){const t=_(e.response)?e.response:null;return Array.isArray(t?.rows)?t.rows.filter(_):[]}async function $e(){const e=process.env[w.CLI_ENV.testRefactorBatchDelayMs];if(!e)return;const t=Number.parseInt(e,10);!Number.isFinite(t)||t<=0||await new Promise(r=>setTimeout(r,Math.min(t,12e4)))}function Be(){const e=[w.CLI_ENV.productStorageDir,w.CLI_ENV.trace,w.CLI_ENV.traceDir,w.CLI_ENV.metrics,w.CLI_ENV.metricsDir,w.CLI_ENV.metricsTag,w.CLI_ENV.mutationImpactMetrics,w.CLI_ENV.mutationImpactStream,w.CLI_ENV.testMoveToFileFailEntity,w.CLI_ENV.testRefactorBatchDelayMs],t={};for(const r of e)t[r]=process.env[r];return t}async function Ie(e,t){const r={};for(const[n,o]of Object.entries(e))r[n]=process.env[n],o===void 0?delete process.env[n]:process.env[n]=o;try{return await t()}finally{for(const[n,o]of Object.entries(r))o===void 0?delete process.env[n]:process.env[n]=o}}function Ce(e,t){const r=Array.isArray(t.operations)?t.operations.filter(_):[],n=new Set;for(const o of r){const a=_(o.body)?o.body:{},u=c(a.sourceFile),s=c(a.targetFile);u&&n.add(Z(e,u)),s&&n.add(Z(e,s))}return Array.from(n).sort((o,a)=>o.localeCompare(a)).map(o=>({file:o,existed:G.existsSync(o),hash:(0,I.hashFileIfExists)(o)}))}function Z(e,t){return M.normalize(M.isAbsolute(t)?t:M.resolve(e,t))}function Ee(e,t){return e==="preview"&&t.previewId?`refactor.batch.preview ${t.previewId}`:`refactor.batch.${e}`}function Se(e,t,r,n,o,a){const u=t.movePlan?.rows??[],s=t.renamePlan?.rows??[];if(u.length===0&&s.length===0)return`${r.length} rows, ${n>0?`${n} applied`:`${o} validated`}${a>0?`, ${a} failed`:""}`;const h=new Map(r.map(d=>[c(d.id),d]).filter(d=>!!d[0])),p=r.find(d=>d.ok===!1||d.outcome==="failed")??null,f=p?c(p.id):null,y=f?u.some(d=>d.id===f):!1,R=f?s.some(d=>d.id===f):!1,m=new Set(r.filter(d=>d.outcome==="applied").map(d=>c(d.id)).filter(d=>!!d)),l=new Set(r.filter(d=>d.outcome==="validated").map(d=>c(d.id)).filter(d=>!!d)),g=new Set(u.map(d=>d.targetFile)).size,i=D(r.flatMap(d=>E(d.savedFiles))).length,v=u.filter(d=>m.has(d.id)||l.has(d.id)).length,$=s.filter(d=>m.has(d.id)||l.has(d.id)).length;if(p){const d=[...s,...u],V=f?d.findIndex(B=>B.id===f):-1,H=d.filter((B,ne)=>!m.has(B.id)&&!l.has(B.id)&&B.id!==f&&(V<0||ne>V||!h.has(B.id))).length,C=[];return $>0&&C.push(`${$} ${$===1?"rename":"renames"} applied`),v>0&&C.push(`${v} ${v===1?"symbol":"symbols"} moved`),C.push(y?"1 symbol failed":R?"1 rename failed":"1 failed"),H>0&&C.push(`${H} not run`),C.join(", ")}const S=[];s.length>0&&S.push(`${s.length} ${s.length===1?"rename":"renames"}`),u.length>0&&(S.push(`${u.length} ${u.length===1?"symbol":"symbols"}`),S.push(`${g} ${g===1?"target":"targets"}`));const O=S.join(", ");if(e==="preview"||e==="validate")return`${O} ready`;const W=s.length>0?"applied":"moved";return i>0?`${O} ${W}; ${i} ${i===1?"file":"files"} written`:`${O} ${W}`}function Me(e,t){const n=(Array.isArray(e.rows)?e.rows.filter(_):[]).filter(a=>c(a.op)==="move");if(n.length===0)return null;const o=[];for(const a of n){const u=Array.isArray(a.builtRows)?a.builtRows.filter(_):[];for(const s of u){const h=c(s.id),p=c(s.entity),f=c(s.targetFile);h&&p&&f&&o.push({id:h,entity:p,targetFile:k(t,f)})}}return o.length>0?{rows:o}:null}function Fe(e){const r=(Array.isArray(e.rows)?e.rows.filter(_):[]).filter(o=>c(o.op)==="rename");if(r.length===0)return null;const n=[];for(const o of r){const a=Array.isArray(o.builtRows)?o.builtRows.filter(_):[];for(const u of a){const s=c(u.id),h=c(u.entity),p=c(u.newName);s&&h&&p&&n.push({id:s,entity:h,newName:p})}}return n.length>0?{rows:n}:null}function ke(e,t,r){const n=t.movePlan?.rows??[],o=t.renamePlan?.rows??[],a=new Map(r.map(i=>[c(i.id),i]).filter(i=>!!i[0])),u=new Set(r.filter(i=>i.outcome==="applied").map(i=>c(i.id)).filter(i=>!!i)),s=r.find(i=>i.ok===!1||i.outcome==="failed")??null,h=s?c(s.id):null,p=h?n.find(i=>i.id===h)??null:null,f=h?o.find(i=>i.id===h)??null:null,y=[...o,...n];if(s===null&&y.every(i=>u.has(i.id)||a.get(i.id)?.outcome==="validated")){ee(e,o,a,u),te(e,n,a,u);return}if(ee(e,o.filter(i=>u.has(i.id)),a,u),te(e,n.filter(i=>u.has(i.id)),a,u),s){e.push("failed:"),p?e.push(`${p.entity} -> ${p.targetFile}`):f&&e.push(`${f.entity} -> ${f.newName}`);const i=_(s.response)?s.response:null,v=c(i?.code)??c(i?.errorCode)??c(s.statusCode),$=qe(c(s.error)??(i?c(i.error):null));v&&e.push(`code: ${v}`),$&&e.push($)}const m=h??null,l=m?y.findIndex(i=>i.id===m):-1,g=y.filter((i,v)=>!u.has(i.id)&&i.id!==h&&(l<0||v>l||!a.has(i.id)));g.length>0&&(e.push("not run:"),e.push(re(g.map(i=>i.entity),15)))}function ee(e,t,r,n){const o=t.filter(a=>n.has(a.id)||r.get(a.id)?.outcome==="validated");if(o.length!==0){e.push("renames:");for(const a of o)e.push(`${a.entity} -> ${a.newName}`)}}function te(e,t,r,n){const o=t.filter(a=>n.has(a.id)||r.get(a.id)?.outcome==="validated");o.length!==0&&(e.push("moves:"),Oe(e,o))}function Oe(e,t){const r=new Map;for(const n of t){const o=r.get(n.targetFile)??[];o.push(n.entity),r.set(n.targetFile,o)}for(const[n,o]of r)e.push(`${n}: ${re(o,15)}`)}function Pe(e){return e==="moveRefactor"?"move":e==="renameSymbol"?"rename":e}function je(e){const t=e.indexOf(":");return t>=0?e.slice(t+1):e}function D(e){return Array.from(new Set(e))}function re(e,t){const r=e.slice(0,t),n=e.length-r.length;return n>0?`${r.join(", ")}, + ${n} more`:r.join(", ")}function qe(e){return e?.replace(/^TypeScript refactor failed: Debug Failure\. False expression: /,"")??null}function Ne(e){const t=Math.max(1,Math.round(e/1e3));return t<60?`~${t} sec`:`~${Math.max(1,Math.round(t/60))} min`}function _(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function k(e,t){const r=t.replace(/\\/g,"/"),n=e.replace(/\\/g,"/").replace(/\/$/,""),o=r.toLowerCase(),a=n.toLowerCase();return o.startsWith(`${a}/`)?r.slice(n.length+1):r}function Le(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;return T({ok:t.ok===!0,code:c(t.code),errorCode:c(t.errorCode),error:c(t.error),hint:c(t.hint),execute:typeof t.execute=="boolean"?t.execute:null,applied:typeof t.applied=="boolean"?t.applied:null})}function c(e){return typeof e=="string"?e:null}function b(e){return typeof e=="number"?e:null}function E(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function T(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t==null?!1:!(Array.isArray(t)&&t.length===0)))}function z(e,t){const r=Array.isArray(e.operations)?e.operations:Array.isArray(e.requests)?e.requests:null;if(!r)return{...e,execute:t};const{operations:n,...o}=e;return{...o,requests:r.map(a=>a&&typeof a=="object"&&!Array.isArray(a)?{...a,execute:t}:a),execute:t}}
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.runRefactorCommand=l;const f=require("../shared/errors"),o=require("./refactor-batch");async function l(e,n,r,a={}){const[i="batch",t="preview",...c]=n;if(i==="--help"||i==="help")return p();if(i!=="batch")throw new f.CliError("UNKNOWN_REFACTOR_TARGET",`Unknown refactor target: ${i}`,{availableTargets:["batch"]});switch(t){case"--help":case"help":return p();case"preview":case"validate":return(0,o.runRefactorBatch)(e,u(r,!1),a,t);case"apply":{const s=c[0];return s&&!s.startsWith("--")?(0,o.runRefactorBatch)(e,void 0,a,t,{previewId:s}):(0,o.runRefactorBatch)(e,u(r,!0),a,t)}case"execute":return(0,o.runRefactorBatch)(e,u(r,!0),a,t);default:throw new f.CliError("UNKNOWN_REFACTOR_COMMAND",`Unknown refactor batch command: ${t}`,{availableCommands:["preview","apply","execute","validate","help"]})}}function p(){return{ok:!0,command:"refactor",usage:"aib refactor batch preview --stdin | aib refactor batch apply <previewId> | aib refactor batch execute --stdin",notes:["preview and validate force every operation to execute:false.","execute writes immediately.","apply uses the cached preview id and refuses to run if touched files changed.","For large module extraction, prefer modulePlan preview/apply."]}}function u(e,n){if(!e||typeof e!="object"||Array.isArray(e))return e;const r=e,a=Array.isArray(r.operations)?r.operations:Array.isArray(r.requests)?r.requests:null;if(!a)return{...r,execute:n};const{operations:i,...t}=r;return{...t,requests:a.map(c=>c&&typeof c=="object"&&!Array.isArray(c)?{...c,execute:n}:c),execute:n}}
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.runRenameCommand=E;const m=require("../shared/errors"),t=require("./rename-entities");async function E(e,i,u,n={}){const[c="preview",...r]=i;switch(c){case"help":return(0,t.runRenameEntities)(e,void 0,n,["--help"]);case"--help":return(0,t.runRenameEntities)(e,void 0,n,["--help"]);case"preview":return(0,t.runRenameEntities)(e,u??s(r),n,r);case"validate":return(0,t.runRenameEntities)(e,p(u??s(r),!1),n,r);case"execute":return(0,t.runRenameEntities)(e,p(u??s(r),!0),n,r);case"apply":{const a=r[0];if(!a||a.startsWith("--"))throw new m.CliError("RENAME_PREVIEW_ID_REQUIRED","rename apply expects a preview id.",{usage:"aib rename apply <previewId>"});return(0,t.runRenameEntities)(e,void 0,n,["--preview",a])}default:throw new m.CliError("UNKNOWN_RENAME_COMMAND",`Unknown rename command: ${c}`,{availableCommands:["preview","apply","execute","validate","help"]})}}function s(e){if(e.length<3||e[0]?.startsWith("--"))return;const[i,u,n]=e;return{sourceFile:i,renames:{[u??""]:n}}}function p(e,i){return!e||typeof e!="object"||Array.isArray(e)?e:{...e,execute:i}}
@@ -0,0 +1,4 @@
1
+ "use strict";var ie=exports&&exports.__createBinding||(Object.create?(function(e,n,t,i){i===void 0&&(i=t);var r=Object.getOwnPropertyDescriptor(n,t);(!r||("get"in r?!n.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return n[t]}}),Object.defineProperty(e,i,r)}):(function(e,n,t,i){i===void 0&&(i=t),e[i]=n[t]})),re=exports&&exports.__setModuleDefault||(Object.create?(function(e,n){Object.defineProperty(e,"default",{enumerable:!0,value:n})}):function(e,n){e.default=n}),T=exports&&exports.__importStar||(function(){var e=function(n){return e=Object.getOwnPropertyNames||function(t){var i=[];for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(i[i.length]=r);return i},e(n)};return function(n){if(n&&n.__esModule)return n;var t={};if(n!=null)for(var i=e(n),r=0;r<i.length;r++)i[r]!=="default"&&ie(t,n,i[r]);return re(t,n),t}})();Object.defineProperty(exports,"__esModule",{value:!0}),exports.runRenameEntities=de,exports.readCachedRenameExecution=he;const $=T(require("node:fs")),g=T(require("node:path")),E=require("zod"),oe=require("../client/http-client"),v=require("../config/env-vars"),se=require("../config/product-storage"),ae=require("../shared/routes"),ce=require("../shared/protocol"),R=require("../shared/agent-text"),I=require("../shared/errors"),C=require("./shared"),le=require("../selectors/parse-entities"),ue=require("./entity-resolution"),fe=require("../shared/types"),_=require("./rename-preview-cache"),F=require("./rename-execution-cache"),j=require("./mutation-execution-cache"),me=require("./inspect-symbol-query"),V=require("./rename-input"),M=require("../metrics/central-metrics"),K=E.z.object({sourceFile:E.z.string().min(1).optional(),file:E.z.string().min(1).optional(),renames:V.RenamesInputSchema,execute:E.z.boolean().optional()}).superRefine((e,n)=>{!e.sourceFile&&!e.file&&n.addIssue({code:"custom",path:["sourceFile"],message:"rename expects sourceFile or file."})}).transform(e=>({sourceFile:e.sourceFile??e.file??"",renames:(0,V.normalizeRenamesInput)(e.renames),...e.execute!==void 0?{execute:e.execute}:{}}));async function de(e,n,t={},i=[]){if(i.includes("--help"))return rt();const r=te(i,"--preview")??te(i,"--preview-id");if(r){const s=W();return s>0?ye(e,r,t,s):pe(e,r,t)}const o=K.parse(n);return o.execute===!0&&W()>0?U(e,o,t,"execute",W()):P(e,o,t)}async function pe(e,n,t){const i=z(e,n),r=B(i),o=await P(e,r,t,{previewId:n});return H(o,i)}async function ye(e,n,t,i){const r=z(e,n),o=B(r);return U(e,o,t,"apply",i,{previewId:n,record:r})}function z(e,n){const t=(0,_.readRenamePreviewRecord)(e,n);if((0,_.hashFile)(t.sourceFile)!==t.sourceHash)throw new I.CliError("RENAME_PREVIEW_SOURCE_CHANGED","Source file changed after rename preview. Rerun rename preview.",{previewId:n,sourceFile:S(e,t.sourceFile)});return t}function B(e){return K.parse({...e.normalizedPayload,execute:!0})}function H(e,n){const t=b(e.api)&&e.api.status==="preserved-via-alias",i=e.ok===!1?"Fix the rename request and rerun preview.":t||e.api!==void 0?"If public API rename is intended, update consumers explicitly.":null,r=b(n.previewResult)?n.previewResult.api:void 0,o={...e,operation:"rename.apply",...r!==void 0?{api:r}:{},...i?{next:i}:{}};return(0,R.attachAgentText)(o,G(o))}async function U(e,n,t,i,r,o){const s=(0,F.buildRenameExecutionId)(),c=`rename.${i}`,l=xe(n),a=(0,F.createRenameExecutionStatus)(e,s,c,J(n));(0,F.writeRenameExecutionStatus)(e,a);const d=Date.now(),y=$e(),f=Ae(()=>(0,se.runWithProductStorageOverride)(y[v.CLI_ENV.productStorageDir],()=>_e(y,async()=>{try{const u=o?H(await P(e,n,t,{previewId:o.previewId}),o.record):await P(e,n,t),m=Fe(u);return a.status=u.ok===!1?"failed":"completed",a.phase="completed",a.completedRows=m.filter(h=>h.ok!==!1).length,a.failedRows=m.filter(h=>h.ok===!1).length,a.filesWritten=we(u),a.result=u,u.ok===!1&&(a.error=nt(u.code)??"RENAME_FAILED"),(0,F.writeRenameExecutionStatus)(e,a),u}catch(u){throw a.status="failed",a.phase="completed",a.error=u instanceof Error?u.message:String(u),(0,F.writeRenameExecutionStatus)(e,a),u}}))),p=await(0,j.waitForMutationDeadline)(f,r);return p.status==="result"?p.result:(f.catch(()=>{}),ge(e,s,c,l,Date.now()-d))}async function P(e,n,t,i){await Se();const r=await(0,C.resolveCompatibleTargetInstance)(e,ce.CLI_COMMAND_IDS.renameEntities,t),o=await(0,C.fetchEffectiveConfig)(r.entry,t),s=Re(e,n.sourceFile),c=n.execute===!0,l=(0,le.parseEntitySelectors)(n.renames.map(m=>m.entity),o),a=new Map;for(const m of n.renames)a.set(m.entity.trim(),m);await(0,ue.ensureSelectorsResolvable)(r.entry,s,l,o,(0,C.extensionRequestOptions)(t));const d=[];for(const m of l){const h=a.get(m.raw);if(!h)throw new Error(`Rename operation not found for selector: ${m.raw}`);const w=(0,M.startCentralMetricSpan)({kind:"mutation.entity",operation:c?"rename.execute":"rename.preview",cwd:g.resolve(e),sourceFile:S(e,s),entity:m.raw,newName:h.newName,totalEntities:l.length});try{const A=await(0,oe.postJson)(r.entry,ae.EXTENSION_ROUTES.renameSymbol,{sourceFile:s,symbolName:m.symbolName,symbolKind:m.symbolKind,newName:h.newName,execute:c,impactMetrics:(0,M.mutationImpactMetricsEnabled)()},(0,C.extensionRequestOptions)(t)),O=Me(e,o,m,h.newName,A);d.push(O),w.end(Ne(A,O,l.length))}catch(A){d.push(Ie(o,m,h.newName,A)),w.end({ok:!1,code:A instanceof I.CliError?A.code:"RENAME_FAILED",error:A instanceof Error?A.message:String(A),totalEntities:l.length})}}const y=d.every(m=>m.ok!==!1),f=tt(s,n.renames,l,c),p=await Qe(r.entry,s,l,n.renames,d,o,e,t),u=Ee(e,s,c,l,d,y,p,r.entry.workspaceFolders);if(!c&&y){const m=(0,_.buildRenamePreviewId)(f),h=(0,_.hashFile)(s),w=(0,_.buildRenamePreviewHash)(f,h,u);(0,_.writeRenamePreviewRecord)(e,{previewId:m,previewHash:w,createdAt:new Date().toISOString(),cwd:g.resolve(e),sourceFile:s,sourceHash:h,normalizedPayload:f,previewResult:u}),u.previewId=m,u.next=`aib rename apply ${m}`}return Ce(e,u),(0,R.attachAgentText)(u,G(u))}function he(e,n){const t=(0,F.readRenameExecutionStatus)(e,n);if((t.status==="completed"||t.status==="failed")&&t.result)return t.result;const i={operation:"execution.status",executionId:t.executionId,status:t.status,phase:t.phase,summary:k(t),progress:`${t.completedRows}/${t.rowCount}`,filesWritten:t.filesWritten,updatedAt:t.updatedAt,...t.error?{error:t.error}:{}};return(0,R.attachAgentText)(i,be(t))}function ge(e,n,t,i,r){const o=(0,F.readRenameExecutionStatus)(e,n),s=Math.max(0,i-r),c={operation:"execution.status",executionId:o.executionId,status:o.status,phase:o.phase,summary:k(o),progress:`${o.completedRows}/${o.rowCount}`,filesWritten:o.filesWritten,updatedAt:o.updatedAt,estimatedRemainingMs:s};return(0,R.attachAgentText)(c,ve(t,o,s))}function ve(e,n,t){return[`${e} ${n.executionId}`,k(n),"applying mutation",`status: aib execution status ${n.executionId}`,t>0?`estimated remaining: ${it(Math.max(t,5e3))}`:"estimated remaining: check status again soon"].join(`
2
+ `)}function be(e){const n=[`${e.operation} ${e.executionId}`,k(e)];return e.status==="running"&&(n.push("applying mutation"),n.push(`status: aib execution status ${e.executionId}`)),e.error&&n.push(e.error),n.join(`
3
+ `)}function k(e){return e.status==="completed"?`completed, ${e.completedRows}/${e.rowCount} renames, ${e.filesWritten.length} files written`:e.status==="failed"?`failed, ${e.completedRows}/${e.rowCount} renames, ${e.failedRows} failed`:`in progress, ${e.completedRows}/${e.rowCount} renames`}function Ae(e){return new Promise((n,t)=>{setImmediate(()=>{e().then(n,t)})})}function W(){return(0,j.readMutationSyncWaitMs)(process.env[v.CLI_ENV.renameSyncWaitMs],12e4)}function xe(e){return 12e3+J(e)*2e3}function J(e){return Math.max(1,e.renames.length)}function we(e){return(Array.isArray(e.filesWritten)?e.filesWritten:Array.isArray(e.files)?e.files:[]).filter(t=>typeof t=="string"&&!t.startsWith("+"))}function Fe(e){const n=Array.isArray(e.renames)?e.renames.map(i=>({ok:typeof i=="string"&&!i.includes("failed")})):e.rename?[{ok:e.ok!==!1}]:[];if(n.length>0)return n;const t=Array.isArray(e.failed)?e.failed.filter(b):[];return t.length>0?t.map(i=>({...i,ok:!1})):[{ok:e.ok!==!1}]}async function Se(){const e=process.env[v.CLI_ENV.testRenameDelayMs];if(!e)return;const n=Number.parseInt(e,10);!Number.isFinite(n)||n<=0||await new Promise(t=>setTimeout(t,Math.min(n,12e4)))}function $e(){const e=[v.CLI_ENV.productStorageDir,v.CLI_ENV.trace,v.CLI_ENV.traceDir,v.CLI_ENV.metrics,v.CLI_ENV.metricsDir,v.CLI_ENV.metricsTag,v.CLI_ENV.mutationImpactMetrics,v.CLI_ENV.mutationImpactStream,v.CLI_ENV.testRenameDelayMs],n={};for(const t of e)n[t]=process.env[t];return n}async function _e(e,n){const t={};for(const[i,r]of Object.entries(e))t[i]=process.env[i],r===void 0?delete process.env[i]:process.env[i]=r;try{return await n()}finally{for(const[i,r]of Object.entries(t))r===void 0?delete process.env[i]:process.env[i]=r}}function Ce(e,n){(0,M.recordCentralMetric)({kind:"mutation.summary",operation:typeof n.operation=="string"?n.operation:"rename",cwd:g.resolve(e),ok:n.ok!==!1,sourceFile:typeof n.file=="string"?n.file:null,summary:typeof n.summary=="string"?n.summary:null,filesWrittenCount:Array.isArray(n.filesWritten)?n.filesWritten.filter(t=>typeof t=="string"&&!t.startsWith("+")).length:0})}function Ne(e,n,t){const i=b(e.renameImpact)?e.renameImpact:{};return{ok:e.ok!==!1,totalEntities:t,editCount:typeof n.editCount=="number"?n.editCount:0,changedFileCount:Array.isArray(n.allFiles)?n.allFiles.length:0,savedFileCount:Array.isArray(n.allSavedFiles)?n.allSavedFiles.length:0,...(0,M.mutationImpactMetricsEnabled)()?{impactCollectionMs:typeof i.impactCollectionMs=="number"?i.impactCollectionMs:null,impact:{locationCount:typeof i.locationCount=="number"?i.locationCount:null,fileCount:typeof i.fileCount=="number"?i.fileCount:null,impactCollectionMs:typeof i.impactCollectionMs=="number"?i.impactCollectionMs:null},changedFiles:Array.isArray(n.allFiles)?n.allFiles:[],savedFiles:Array.isArray(n.allSavedFiles)?n.allSavedFiles:[]}:{},configFilePath:typeof e.configFilePath=="string"?e.configFilePath:null}}function Ee(e,n,t,i,r,o,s,c){const l=r.reduce((u,m)=>u+ee(m.editCount),0),a=Ye(r),d=ke(r),y=r.map((u,m)=>({oldName:i[m]?.symbolName??(typeof u.oldName=="string"?u.oldName:u.entity),newName:u.newName})),f=Le(e,c,r,y,a,n)??Oe(e,c,a,y);return{...o?{}:{ok:!1},operation:t?"rename.execute":"rename.preview",file:S(e,n),...i.length===1?{rename:q(r[0],!1)}:{renames:r.map(u=>q(u,!0))},summary:t?`${d.length} ${d.length===1?"file":"files"} written, ${l} edits`:i.length===1?`${a.length} ${a.length===1?"file":"files"}, ${l} edits`:`${i.length} symbols, ${a.length} ${a.length===1?"file":"files"}, ${l} edits`,...t?{}:{files:D(a,5)},...t?{filesWritten:D(d,5)}:{},...o?{}:{failed:r.filter(u=>u.ok===!1).map(u=>Pe(u))},...f?{api:De(f)}:{},...o?{}:{next:"Fix failed rename rows and rerun preview."}}}function Re(e,n){const t=n.trim();return g.normalize(g.isAbsolute(t)?t:g.resolve(e,t))}function Ie(e,n,t,i){const r=i instanceof I.CliError&&b(i.details)?i.details:{},o=b(r.details)?r.details:{},s=Z(e,o.candidates),c=b(o.sourceConsistency)?Q(o.sourceConsistency):null;return{entity:n.raw,oldName:n.symbolName,acceptedSelector:N(n,e),newName:t,ok:!1,code:i instanceof I.CliError?i.code:"RENAME_FAILED",error:i instanceof Error?i.message:String(i),...c?{source:c}:{},...s.length>0?{candidates:s}:{},next:s.length>0?"Retry with one of the candidate selectors.":"Run inspect file for this source file, then retry with a canonical selector."}}function Me(e,n,t,i,r){const o=b(r.locationPreview)?r.locationPreview:{},s=Array.isArray(o.locations)?o.locations.filter(b):[],c=et(e,s),l=ze(s,t.symbolName,i),a=l.length>0?[]:Be(e,c,t.symbolName,i,typeof r.sourceFile=="string"?r.sourceFile:null),d=b(r.sourceConsistency)?Q(r.sourceConsistency):null;return r.ok!==!1?{entity:t.raw,oldName:t.symbolName,...typeof r.sourceFile=="string"?{sourceFilePath:r.sourceFile}:{},acceptedSelector:N(t,n),newName:i,ok:!0,editCount:s.length,...typeof r.configFilePath=="string"?{projectConfig:S(e,r.configFilePath)}:{},allFiles:c.map(({file:f,count:p})=>`${f} x${p}`),files:D(c.map(({file:f,count:p})=>`${f} x${p}`),5),...l.length+a.length>0?{apiAliases:[...l,...a]}:{},...d?{source:d}:{},...r.applied!==void 0?{applied:r.applied===!0}:{},...Array.isArray(r.savedFiles)?{allSavedFiles:r.savedFiles.filter(f=>typeof f=="string").map(f=>S(e,f)),savedFiles:D(r.savedFiles.filter(f=>typeof f=="string").map(f=>S(e,f)),5)}:{}}:{entity:t.raw,acceptedSelector:N(t,n),newName:i,ok:!1,code:typeof r.code=="string"?r.code:"RENAME_FAILED",error:typeof r.error=="string"?r.error:"Rename failed.",...d?{source:d}:{},candidates:Z(n,r.candidates),next:"Use one of the candidates or rerun inspect file if the file changed."}}function q(e,n){const t=typeof e.acceptedSelector=="string"?e.acceptedSelector:e.entity,i=e.ok===!1?"failed":`${ee(e.editCount)} edits`,r=n?`, ${i}`:"";return`${t} -> ${e.newName}${r}`}function Pe(e){const n={rename:q(e,!1),code:typeof e.code=="string"?e.code:"RENAME_FAILED",error:typeof e.error=="string"?e.error:"Rename failed."};for(const t of["source","candidates","next"])e[t]!==void 0&&(n[t]=e[t]);return n}function ke(e){const n=new Set;for(const t of e){const i=Array.isArray(t.allSavedFiles)?t.allSavedFiles:t.savedFiles;if(Array.isArray(i))for(const r of i)typeof r=="string"&&!r.startsWith("+")&&n.add(r)}return Array.from(n)}function De(e){const n=typeof e.aliases=="string"?e.aliases:"aliases",t=typeof e.consumers=="string"?e.consumers:"",i=/^(\d+)\s+/.exec(t),r=i?Number(i[1]):0,o=n.startsWith("1 ")?"name":"names";return r>0?`old ${o} preserved by ${n}; ${t} still use old names`:`old ${o} preserved by ${n}`}function G(e){if(e.ok===!1)return null;const n=typeof e.operation=="string"?e.operation:"";if(n!=="rename.preview"&&n!=="rename.execute"&&n!=="rename.apply")return null;const t=[],i=typeof e.previewId=="string"?e.previewId:"";if(t.push(i&&n==="rename.preview"?`${n} ${i}`:n),typeof e.file=="string"&&t.push(e.file),typeof e.rename=="string")t.push(e.rename);else if(Array.isArray(e.renames))for(const r of e.renames)typeof r=="string"&&t.push(We(r));return typeof e.summary=="string"&&t.push(e.summary),qe(t,Array.isArray(e.filesWritten)?e.filesWritten:e.files),typeof e.api=="string"&&t.push(`api: ${e.api}`),typeof e.next=="string"&&t.push(`next: ${e.next}`),t.join(`
4
+ `)}function We(e){return e.replace(/,\s+\d+\s+edits$/,"")}function qe(e,n){if(Array.isArray(n))for(const t of n)typeof t=="string"&&e.push(t)}function Le(e,n,t,i,r,o){const s=Ve(t),c=Ke(e,t,i),l=je(e,r,o,i),a=L([...s,...c,...l]);if(a.length===0)return null;const d=Ue(e,t),y=n.length>0?n:[e],f=X(y,a.map(p=>p.oldName),d);return{status:"preserved-via-alias",aliases:`${a.length} ${a.length===1?"alias":"aliases"}`,consumers:`${f.length} ${f.length===1?"file":"files"} not rewritten`,hint:"Public API names were preserved through re-export aliases. Consumers still use old names."}}function Oe(e,n,t,i){if(!t.some(l=>/(^|[/\\])index\.(ts|tsx|mts|cts) x\d+$/i.test(l))||i.length===0)return null;const o=Te(e,t),s=n.length>0?n:[e],c=X(s,i.map(l=>l.oldName),o);return{status:"preserved-via-alias",aliases:`${i.length} ${i.length===1?"alias":"aliases"}`,consumers:`${c.length} ${c.length===1?"file":"files"} not rewritten`,hint:"Public API names were preserved through re-export aliases. Consumers still use old names."}}function Te(e,n){const t=new Set;for(const i of n){if(typeof i!="string"||i.startsWith("+"))continue;const r=/^(.*) x(\d+)$/.exec(i);r&&t.add(x(g.resolve(e,r[1])))}return t}function je(e,n,t,i){const r=x(t),o=[];for(const s of n){if(typeof s!="string"||s.startsWith("+"))continue;const c=/^(.*) x(\d+)$/.exec(s);if(!c)continue;const l=g.resolve(e,c[1]);if(x(l)===r)continue;if(/^index\.(ts|tsx|mts|cts)$/i.test(g.basename(l))){o.push(...i);continue}let a="";try{a=$.readFileSync(l,"utf8")}catch{continue}if(!(!a.includes("export")||!a.includes("from")))for(const d of i)a.includes(d.oldName)&&o.push(d)}return L(o)}function Ve(e){const n=[];for(const t of e)if(Array.isArray(t.apiAliases))for(const i of t.apiAliases)b(i)&&typeof i.oldName=="string"&&typeof i.newName=="string"&&n.push({oldName:i.oldName,newName:i.newName});return L(n)}function L(e){const n=new Set;return e.filter(t=>{const i=`${t.newName} as ${t.oldName}`;return n.has(i)?!1:(n.add(i),!0)})}function Ke(e,n,t){const i=[];for(const o of n){const s=typeof o.sourceFilePath=="string"?x(o.sourceFilePath):null,c=Array.isArray(o.allFiles)?o.allFiles:[];for(const l of c){if(typeof l!="string"||l.startsWith("+"))continue;const a=/^(.*) x(\d+)$/.exec(l);if(!a)continue;const d=g.resolve(e,a[1]);if(s&&x(d)===s)continue;let y="";try{y=$.readFileSync(d,"utf8")}catch{continue}if(!(!y.includes("export")||!y.includes("from")))for(const f of t)y.includes(f.oldName)&&i.push(f)}}const r=new Set;return i.filter(o=>{const s=`${o.newName} as ${o.oldName}`;return r.has(s)?!1:(r.add(s),!0)})}function ze(e,n,t){const i=new RegExp(`\\b${Y(t)}\\s+as\\s+${Y(n)}\\b`);return e.filter(o=>typeof o.replacementPreview=="string"&&(i.test(o.replacementPreview)||He(o,n,t))).map(o=>({oldName:n,newName:t,...typeof o.fileName=="string"?{fileName:o.fileName}:{}})).slice(0,20)}function Be(e,n,t,i,r){const o=r?x(r):null,s=[];for(const{file:c}of n){const l=g.resolve(e,c);if(o&&x(l)===o)continue;let a="";try{a=$.readFileSync(l,"utf8")}catch{continue}!a.includes(t)||!a.includes("export")||!a.includes("from")||s.push({oldName:t,newName:i,fileName:l})}return s.slice(0,20)}function He(e,n,t){if(typeof e.fileName!="string"||typeof e.replacementPreview!="string"||!e.replacementPreview.includes(t))return!1;let i="";try{i=$.readFileSync(e.fileName,"utf8")}catch{return!1}return i.includes(n)&&i.includes("export")&&i.includes("from")}function Ue(e,n){const t=new Set;for(const i of n){const r=Array.isArray(i.allFiles)?i.allFiles:[];for(const o of r){if(typeof o!="string"||o.startsWith("+"))continue;const s=/^(.*) x(\d+)$/.exec(o);s&&t.add(x(g.resolve(e,s[1])))}}return t}function X(e,n,t){const i=Array.from(new Set(n.filter(s=>s.length>0)));if(i.length===0)return[];const r=[],o=new Set;for(const s of e)for(const c of Je(s,5e3)){const l=x(c);if(t.has(l)||o.has(l))continue;o.add(l);let a="";try{a=$.readFileSync(c,"utf8")}catch{continue}i.some(d=>a.includes(d))&&r.push(c)}return r}function Je(e,n){const t=[],i=[g.resolve(e)];for(;i.length>0&&t.length<n;){const r=i.pop();if(!r)continue;let o=[];try{o=$.readdirSync(r,{withFileTypes:!0})}catch{continue}for(const s of o){if(t.length>=n)break;if(s.isDirectory()){if(Ge(s.name))continue;i.push(g.join(r,s.name));continue}s.isFile()&&Xe(s.name)&&t.push(g.join(r,s.name))}}return t}function Ge(e){return[".git",".aib-plan-cache",".aib-preview",".aib-trace",".tmp","dist","node_modules","out"].includes(e)}function Xe(e){return/\.(ts|tsx|mts|cts)$/i.test(e)&&!/\.d\.(ts|mts|cts)$/i.test(e)}function x(e){return g.normalize(e).toLowerCase()}function Y(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ye(e){const n=new Map;for(const t of e){const i=Array.isArray(t.allFiles)?t.allFiles:t.files;if(Array.isArray(i))for(const r of i){if(typeof r!="string"||r.startsWith("+"))continue;const o=/^(.*) x(\d+)$/.exec(r);if(!o)continue;const s=o[1],c=Number(o[2]);n.set(s,(n.get(s)??0)+c)}}return Array.from(n.entries()).sort((t,i)=>t[0].localeCompare(i[0])).map(([t,i])=>`${t} x${i}`)}function ot(e,n){return Array.from(new Set(n.map(t=>t.projectConfig).filter(t=>typeof t=="string"&&t.length>0))).sort((t,i)=>t.localeCompare(i))}async function Qe(e,n,t,i,r,o,s,c){const l=new Set(t.map(p=>p.symbolName)),a=new Set(i.map(p=>p.newName.trim())),d=Array.from(l).filter(p=>p.length>0);if(d.length===0)return[];const y=Ze(n,r,s).slice(0,40),f=[];for(const p of y){let u;try{u=await(0,me.queryTopLevelInspectSymbols)(e,p,(0,C.extensionRequestOptions)(c))}catch{continue}for(const m of u){if(typeof m.name!="string")continue;const h=m.name;if(!d.some(A=>h.includes(A))||l.has(h)||a.has(h))continue;const w=typeof m.kind=="string"?m.kind.toLowerCase():"";f.push(N({raw:h,symbolName:h,symbolKind:ne(w)?w:null},o))}}return Array.from(new Set(f)).sort((p,u)=>p.localeCompare(u))}function Ze(e,n,t){const i=new Set([e]);for(const r of n){const o=Array.isArray(r.allFiles)?r.allFiles:[];for(const s of o){if(typeof s!="string"||s.startsWith("+"))continue;const c=/^(.*) x(\d+)$/.exec(s);c&&i.add(g.resolve(t,c[1]))}}return Array.from(i)}function et(e,n){const t=new Map;for(const i of n){if(typeof i.fileName!="string")continue;const r=S(e,i.fileName);t.set(r,(t.get(r)??0)+1)}return Array.from(t.entries()).sort((i,r)=>i[0].localeCompare(r[0])).map(([i,r])=>({file:i,count:r}))}function Q(e){return e.documentMatchesDisk===!0&&e.documentIsDirty!==!0?null:{documentMatchesDisk:e.documentMatchesDisk===!0,documentIsDirty:e.documentIsDirty===!0}}function tt(e,n,t,i){return{sourceFile:e,renames:n.map((r,o)=>({entity:t[o]?.raw??r.entity.trim(),symbolName:t[o]?.symbolName??r.entity.trim(),...t[o]?.symbolKind?{symbolKind:t[o]?.symbolKind}:{},newName:r.newName})),execute:i}}function Z(e,n){return Array.isArray(n)?n.filter(b).slice(0,8).map(t=>{const i=typeof t.name=="string"?t.name:"",r=typeof t.kind=="string"?t.kind.toLowerCase():"";return{name:i,kind:r,selector:N({raw:i,symbolName:i,symbolKind:ne(r)?r:null},e)}}):[]}function N(e,n){return e.symbolKind?`${n.entityKindAliases[e.symbolKind]}${n.selectorSeparator}${e.symbolName}`:e.raw}function D(e,n){const t=e.slice(0,n),i=e.length-t.length;return i>0?[...t,`+ ${i} more`]:t}function ee(e){return typeof e=="number"?e:0}function nt(e){return typeof e=="string"?e:null}function it(e){const n=Math.max(1,Math.ceil(e/1e3));return n<60?`~${n} sec`:`~${Math.ceil(n/60)} min`}function S(e,n){return g.relative(e,n).replace(/\\/g,"/")}function te(e,n){const t=e.indexOf(n);if(t<0)return null;const i=e[t+1];return i&&!i.startsWith("--")?i:null}function rt(){return{ok:!0,command:"rename",usage:"aib rename preview <sourceFile> <entity> <newName> | aib rename preview --stdin | aib rename execute --stdin | aib rename apply <previewId>",preview:{sourceFile:"src/path/to/source-file.ts",renames:[{entity:"OldSymbolName",newName:"NewSymbolName"}],execute:!1},apply:"aib rename apply rename_abc123",notes:["Use execute:false first when selector resolution is uncertain.","Preview returns previewId, file/edit summary, and candidate selectors on failure.","Apply by previewId refuses to run if the source file changed after preview."]}}function b(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function ne(e){return fe.ENTITY_KIND_IDS.includes(e)}
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.buildRenameExecutionId=c,exports.createRenameExecutionStatus=r,exports.readRenameExecutionStatus=s,exports.tryReadRenameExecutionStatus=E,exports.writeRenameExecutionStatus=m,exports.renameExecutionPath=d,exports.renameExecutionLastPath=x;const n=require("./mutation-execution-cache");function c(){return(0,n.buildMutationExecutionId)()}function r(t,e,u,i){const o=new Date().toISOString();return{executionId:e,operation:u,cwd:t,status:"running",phase:"mutation",startedAt:o,updatedAt:o,rowCount:i,completedRows:0,failedRows:0,filesWritten:[]}}function s(t,e){return(0,n.readMutationExecutionStatus)(t,e,a)}function E(t,e){return(0,n.tryReadMutationExecutionStatus)(t,e,a)}function m(t,e){(0,n.writeMutationExecutionStatus)(t,e,a)}function d(t,e,u){return(0,n.mutationExecutionPath)(t,a.namespace,e,u)}function x(t,e){return(0,n.mutationExecutionLastPath)(t,a.namespace,e)}const a={namespace:"rename-executions",notFoundCode:"RENAME_EXECUTION_NOT_FOUND",notFoundLabel:"Rename"};
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.RenamesInputSchema=void 0,exports.normalizeRenamesInput=a;const e=require("zod"),i=e.z.object({entity:e.z.string().min(1),newName:e.z.string().min(1)});exports.RenamesInputSchema=e.z.union([e.z.array(i).min(1),e.z.record(e.z.string().min(1),e.z.string().min(1))]);function a(n){return Array.isArray(n)?n:Object.entries(n).map(([r,t])=>({entity:r,newName:t}))}
@@ -0,0 +1,2 @@
1
+ "use strict";var s=exports&&exports.__createBinding||(Object.create?(function(r,e,n,t){t===void 0&&(t=n);var i=Object.getOwnPropertyDescriptor(e,n);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(r,t,i)}):(function(r,e,n,t){t===void 0&&(t=n),r[t]=e[n]})),l=exports&&exports.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),c=exports&&exports.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(n){var t=[];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(t[t.length]=i);return t},r(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var t=r(e),i=0;i<t.length;i++)t[i]!=="default"&&s(n,e,t[i]);return l(n,e),n}})();Object.defineProperty(exports,"__esModule",{value:!0}),exports.buildRenamePreviewId=P,exports.buildRenamePreviewHash=w,exports.readRenamePreviewRecord=m,exports.writeRenamePreviewRecord=b,exports.renamePreviewRecordPath=o,exports.hashFile=O;const d=c(require("node:crypto")),a=c(require("node:fs")),h=c(require("node:path")),_=require("../shared/errors"),y=require("./workspace-cache");function P(r){return`rename_${f(u(r)).slice(0,10)}`}function w(r,e,n){return`sha256:${f(u({normalizedPayload:r,sourceHash:e,renameCount:n.renameCount,summary:n.summary}))}`}function m(r,e){const n=o(r,e);if(!a.existsSync(n))throw new _.CliError("RENAME_PREVIEW_NOT_FOUND",`Rename preview not found: ${e}`,{previewId:e,expectedPath:n});return JSON.parse(a.readFileSync(n,"utf8"))}function b(r,e){const n=o(r,e.previewId);a.mkdirSync(h.dirname(n),{recursive:!0}),a.writeFileSync(n,`${JSON.stringify(e,null,2)}
2
+ `)}function o(r,e){return(0,y.workspaceCachePath)(r,"rename-previews",`${p(e)}.json`)}function O(r){return f(a.readFileSync(r))}function f(r){return d.createHash("sha256").update(r).digest("hex")}function u(r){return r===null||typeof r!="object"?JSON.stringify(r):Array.isArray(r)?`[${r.map(e=>u(e)).join(",")}]`:`{${Object.entries(r).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>`${JSON.stringify(e)}:${u(n)}`).join(",")}}`}function p(r){return r.replace(/[^a-z0-9_-]+/gi,"-")}
@@ -0,0 +1,6 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.runResultViewCommand=S;const x=require("../shared/agent-text"),p=require("../shared/errors"),w=require("./inspect-cycles"),g=require("./session-workspace");function S(e,t,s){if(s!==void 0)return M(e,s);const i=t.find(u=>!u.startsWith("--"));if(!i)throw new p.CliError("VIEW_HANDLE_REQUIRED","Usage: aib view aib:res_<id>");const n=V(i),r=N(t.slice(1));if(n.short)return L((0,g.readSessionResultViewJson)(e,n.id),r,i);if(n.kind==="cycles")return(0,w.buildCyclesViewResponse)((0,g.readSessionResultJson)(e,n.kind,n.id),{...r.detail!==void 0?{detail:_(r.detail)}:{},...r.offset!==void 0?{offset:r.offset}:{},...r.limit!==void 0?{limit:r.limit}:{},...r.index!==void 0?{index:r.index}:{},...r.kind!==void 0?{kind:b(r.kind)}:{},resultHandle:i});const d={ok:!1,code:"UNSUPPORTED_RESULT_VIEW",error:`aib view does not support result kind: ${n.kind}`};return(0,x.attachAgentText)(d,`unsupported result view: ${n.kind}`)}function M(e,t){const s=Array.isArray(t.views)?t.views.filter(m):m(t.view)?[t.view]:m(t)?[t]:[];if(s.length===0)throw new p.CliError("VIEW_HANDLE_REQUIRED","view expects a handle.");const i=s.map(n=>{const r=o(n.handle)??o(n.from)??"";if(!r)throw new p.CliError("VIEW_HANDLE_REQUIRED","view expects a handle.");const d=V(r),u={...o(n.detail)!==void 0?{detail:o(n.detail)}:{},...h(n.offset)!==void 0?{offset:h(n.offset)}:{},...h(n.limit)!==void 0?{limit:h(n.limit)}:{},...h(n.index)!==void 0?{index:h(n.index)}:{},...o(n.kind)!==void 0?{kind:o(n.kind)}:{},...k(n.only).length>0?{only:k(n.only)}:{},...k(n.except).length>0?{except:k(n.except)}:{}};return d.short?L((0,g.readSessionResultViewJson)(e,d.id),u,r):d.kind==="cycles"?(0,w.buildCyclesViewResponse)((0,g.readSessionResultJson)(e,d.kind,d.id),{...u.detail!==void 0?{detail:_(u.detail)}:{},...u.offset!==void 0?{offset:u.offset}:{},...u.limit!==void 0?{limit:u.limit}:{},...u.index!==void 0?{index:u.index}:{},...u.kind!==void 0?{kind:b(u.kind)}:{},resultHandle:r}):(0,x.attachAgentText)({ok:!1,code:"UNSUPPORTED_RESULT_VIEW",error:`aib view does not support result kind: ${d.kind}`},`unsupported result view: ${d.kind}`)});return i.length===1?i[0]:(0,x.attachAgentText)({results:i},i.map(n=>{if(!m(n))return"";const r=n.__aib_text;return typeof r=="string"?r.trimEnd():""}).filter(n=>n!=="").join(`
2
+
3
+ `))}function V(e){if(/^aib:res_[A-Za-z0-9_-]+$/.test(e))return{kind:"view",id:e.slice(4),short:!0};const t=e.split(":");if(t.length!==4||t[0]!=="aib"||t[1]!=="result"||!t[2]||!t[3])throw new p.CliError("INVALID_RESULT_HANDLE",`Invalid result handle: ${e}`,{expected:"aib:res_<id>"});return{kind:t[2],id:t[3],short:!1}}function N(e){const t={},s=I(e,"--detail"),i=A(e,"--offset"),n=A(e,"--limit"),r=A(e,"--index"),d=I(e,"--kind"),u=$(e,"--only").flatMap(E),f=$(e,"--except").flatMap(E);return s!==void 0&&(t.detail=s),i!==void 0&&(t.offset=i),n!==void 0&&(t.limit=n),r!==void 0&&(t.index=r),d!==void 0&&(t.kind=d),u.length>0&&(t.only=u),f.length>0&&(t.except=f),t}function L(e,t,s){const i=o(e.kind);return e.op==="cycles"?(0,w.buildCyclesViewResponse)(e,{...t.detail!==void 0?{detail:_(t.detail)}:{},...t.offset!==void 0?{offset:t.offset}:{},...t.limit!==void 0?{limit:t.limit}:{},...t.index!==void 0?{index:t.index}:{},...t.kind!==void 0?{kind:b(t.kind)}:{},resultHandle:s}):i==="code"?U(e,t,s):i==="members"||i==="duplicates"||i==="usages"?T(e,t,s,i):(0,x.attachAgentText)({ok:!1,code:"UNSUPPORTED_RESULT_VIEW",error:`aib view does not support result kind: ${i??"unknown"}`},`unsupported result view: ${i??"unknown"}`)}function T(e,t,s,i){const n=Array.isArray(e.items)?e.items.filter(m):[],r=C(n,t,y=>[o(y.name),o(y.text)?.split(/\s+/)[0]]),d=Math.max(0,t.offset??0),u=r.length||1,f=Math.max(1,t.limit??u),c=r.slice(d,d+f),l=Math.max(0,r.length-d-c.length),a={ok:!0,op:"view",handle:s,kind:i,source:o(e.source)??"inspect",...o(e.file)!==void 0?{file:o(e.file)}:{},...o(e.entity)!==void 0?{entity:o(e.entity)}:{},...o(e.target)!==void 0?{target:o(e.target)}:{},...o(e.detail)!==void 0?{detail:o(e.detail)}:{},items:c,offset:d,limit:f,...l>0?{hidden:l}:{}};return(0,x.attachAgentText)(a,O(a))}function U(e,t,s){const i=Array.isArray(e.items)?e.items.filter(m):[],n=C(i,t,a=>[o(a.entity),o(a.name)]),r=Math.max(0,t.offset??0),d=n.length||1,u=Math.max(1,t.limit??d),f=n.slice(r,r+u),c=Math.max(0,n.length-r-f.length),l={ok:!0,op:"view",handle:s,kind:"code",source:o(e.source)??"inspect",items:f,offset:r,limit:u,...c>0?{hidden:c}:{},...f.length===0&&i.length>0&&H(t)?{noMatches:!0}:{}};return(0,x.attachAgentText)(l,W(l))}function W(e){const t=[],s=Array.isArray(e.items)?e.items.filter(m):[];if(s.length===0&&e.noMatches===!0)return t.push("no hidden code matched view filters"),t.join(`
4
+ `);let i="";for(const r of s){const d=o(r.file)??"";d&&d!==i&&(t.length>0&&t.push(""),t.push(`// ${d}`),i=d);const u=o(r.entity)??"",f=o(r.meta)??o(r.rangeMeta)??"",c=[u,f].filter(a=>a!=="").join(" ");c&&t.push(`// ${c}`);const l=o(r.code);l&&t.push(l.trimEnd())}const n=h(e.hidden)??0;return n>0&&t.push(`+ ${n} more hidden code blocks`),t.join(`
5
+ `)}function O(e){const t=[],s=o(e.file),i=o(e.target),n=o(e.kind)??"",r=o(e.detail);s?t.push(`// ${s}`):n==="usages"?t.push(r?`usages ${r}`:"usages"):i&&t.push(`duplicates ${i}`);const d=o(e.entity);d&&t.push(`// ${d}:`);const u=Array.isArray(e.items)?e.items.filter(m):[];if(n==="usages")for(const[c,l]of j(u,a=>o(a.name)??"")){c&&t.push(`${c}:`);for(const a of l){const y=o(a.text);y&&t.push(y.trimEnd())}}else for(const c of u){const l=o(c.text);l&&t.push(l.trimEnd())}const f=h(e.hidden)??0;return f>0&&t.push(`+ ${f} more hidden ${n==="members"?"members":n==="usages"?"usages":"items"}`),t.join(`
6
+ `)}function j(e,t){const s=new Map;for(const i of e){const n=t(i),r=s.get(n)??[];r.push(i),s.set(n,r)}return Array.from(s.entries())}function _(e){if(e==="summary"||e==="sum")return"summary";if(e==="imports"||e==="files")return e;throw new p.CliError("INVALID_CYCLES_DETAIL","aib view cycles --detail expects summary, imports, or files.")}function b(e){if(e==="runtime"||e==="type-only"||e==="mixed")return e;throw new p.CliError("INVALID_CYCLES_KIND","aib view cycles --kind expects runtime, type-only, or mixed.")}function I(e,t){const s=e.indexOf(t),i=s>=0?e[s+1]:void 0;return i&&!i.startsWith("--")?i:void 0}function $(e,t){const s=[];for(let i=0;i<e.length;i+=1){if(e[i]!==t)continue;const n=e[i+1];n&&!n.startsWith("--")&&s.push(n)}return s}function A(e,t){const s=I(e,t);if(s===void 0)return;const i=Number(s),n=t==="--offset"?0:1;if(!Number.isInteger(i)||i<n)throw new p.CliError("INVALID_VIEW_OPTION",`${t} expects ${n===0?"a non-negative":"a positive"} integer.`);return i}function m(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function o(e){return typeof e=="string"&&e!==""?e:void 0}function h(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function k(e){return typeof e=="string"&&e!==""?E(e):Array.isArray(e)?e.filter(t=>typeof t=="string"&&t!=="").flatMap(E):[]}function C(e,t,s){const i=t.only??[],n=t.except??[],r=i.length>0?e.filter(d=>D(s(d),i)):e;return n.length===0?r:r.filter(d=>!D(s(d),n))}function H(e){return(e.only?.length??0)>0||(e.except?.length??0)>0}function D(e,t){return e.some(s=>s!==void 0&&t.some(i=>P(s,i)))}function P(e,t){if(e===t)return!0;const s=e.split(".").pop()??e,i=t.split(".").pop()??t;return s===i&&!t.includes(".")}function E(e){const t=e.trim();return(q(t)??R(t)).flatMap(F)}function F(e){const t=e.trim(),s=t.match(/^(.+)\.\{(.+)\}$/);if(s){const i=s[1],n=s[2];if(i&&n)return R(n).map(r=>`${i}.${r}`)}return t?[t]:[]}function q(e){if(!e.startsWith("[")||!e.endsWith("]"))return null;const t=e.slice(1,-1).trim();return t?R(t):[]}function R(e){const t=[];let s="",i=0;for(const n of e){if(n==="{"?i+=1:n==="}"&&i>0&&(i-=1),n===","&&i===0){s.trim()&&t.push(s.trim()),s="";continue}s+=n}return s.trim()&&t.push(s.trim()),t}
@@ -0,0 +1,4 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.runRuntimeCommand=d;const l=require("../shared/errors"),f=require("../shared/agent-text"),o=require("../managed-host/serve-web-autostart"),a=require("../diagnostics/readiness-text");async function d(t,n){const e=n[0]??"status",r=n.includes("--verbose"),u=n.includes("--json"),s=n.includes("--all"),c=g(n.slice(1))??t;if(e==="status"){const i=await m(()=>s?(0,o.statusAllManagedServeWeb)():(0,o.statusManagedServeWebForCwd)(c),"MANAGED_IDE_STATUS_FAILED");return u?i:(0,f.attachAgentText)(i,s?h(i,{verbose:r}):(0,a.formatRuntimeStatusText)(i,{verbose:r}))}if(e==="stop"){const i=await m(()=>s?(0,o.stopAllManagedServeWeb)():(0,o.stopManagedServeWebForCwd)(c),"MANAGED_IDE_STOP_FAILED");return u?i:(0,f.attachAgentText)(i,s?S(i,{verbose:r}):(0,a.formatRuntimeStopText)(i,{verbose:r}))}if(e==="kill"){if(!s)throw new l.CliError("RUNTIME_KILL_REQUIRES_ALL","runtime kill currently requires --all.",{command:"aib runtime kill --all"});const i=await m(()=>(0,o.killAllManagedServeWeb)(),"MANAGED_IDE_KILL_FAILED");return u?i:(0,f.attachAgentText)(i,A(i,{verbose:r}))}if(e==="cleanup")return(0,o.cleanupExpiredManagedServeWebForCwd)(c);throw new l.CliError("UNKNOWN_RUNTIME_COMMAND",`Unknown runtime command: ${e}`,{availableCommands:["status","stop","kill","cleanup"]})}function g(t){return t.find(n=>!n.startsWith("--"))??null}function h(t,n={}){if(t.ok===!1)return(0,a.formatRuntimeStatusText)(t,n);const e=Array.isArray(t.runtimes)?t.runtimes:[],r=["runtime status --all","",`${String(t.running??0)} running, ${String(t.healthy??0)} healthy, ${String(t.count??e.length)} known`];return e.length>0&&(r.push("",...e.slice(0,20).map(_)),e.length>20&&r.push(`+ ${e.length-20} more`)),n.verbose===!0&&r.push("","details:",JSON.stringify(t,null,2)),r.join(`
2
+ `)}function S(t,n={}){if(t.ok===!1)return(0,a.formatRuntimeStopText)(t,n);const e=["runtime stop --all","",`${String(t.stopped??0)} stopped, ${String(t.count??0)} known`];return n.verbose===!0&&e.push("","details:",JSON.stringify(t,null,2)),e.join(`
3
+ `)}function A(t,n={}){if(t.ok===!1)return(0,a.formatRuntimeStopText)(t,n);const e=t.stop&&typeof t.stop=="object"&&!Array.isArray(t.stop)?t.stop:{},r=["runtime kill --all","",`${String(e.stopped??0)} metadata-backed runtimes stopped`,`${String(t.killed??0)} orphan processes killed`];return n.verbose===!0&&r.push("","details:",JSON.stringify(t,null,2)),r.join(`
4
+ `)}function _(t){if(!t||typeof t!="object"||Array.isArray(t))return"- unknown";const n=t,e=n.running===!0?n.healthy===!0?"healthy":"running":"stopped",r=typeof n.hostKind=="string"?n.hostKind:"managed",u=typeof n.hostId=="string"?n.hostId:"unknown",s=typeof n.fixture=="string"?` ${n.fixture}`:"";return`- ${e} ${r} ${u}${s}`}async function m(t,n){try{return await t()}catch(e){return{ok:!1,code:e instanceof l.CliError?e.code:n,error:e instanceof Error?e.message:String(e),...e instanceof l.CliError&&e.details&&typeof e.details=="object"&&!Array.isArray(e.details)?{details:e.details}:{}}}}