@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,3 @@
1
+ "use strict";var Oe=exports&&exports.__createBinding||(Object.create?(function(e,t,n,o){o===void 0&&(o=n);var r=Object.getOwnPropertyDescriptor(t,n);(!r||("get"in r?!t.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,o,r)}):(function(e,t,n,o){o===void 0&&(o=n),e[o]=t[n]})),$e=exports&&exports.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),re=exports&&exports.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(n){var o=[];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(o[o.length]=r);return o},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(t!=null)for(var o=e(t),r=0;r<o.length;r++)o[r]!=="default"&&Oe(n,t,o[r]);return $e(n,t),n}})();Object.defineProperty(exports,"__esModule",{value:!0}),exports.runApplyModulePlan=qe,exports.reviseCachedModulePlan=Be,exports.readCachedModulePlanExecution=ze;const F=re(require("node:path")),O=re(require("node:fs")),E=require("zod"),ie=require("../client/http-client"),$=require("../shared/agent-text"),k=require("../shared/errors"),se=require("../shared/routes"),le=require("./session-workspace"),ae=require("./session-workspace"),D=require("./shared"),ue=require("../shared/protocol"),ce=require("./inspect-format"),De=require("./json-file-input"),Ue=require("./move-to-file"),d=require("./module-plan-cache"),fe=require("../metrics/central-metrics"),de=require("./module-plan-timeout"),me=require("./inspect-cycles"),_=require("../config/env-vars"),H=require("../config/product-storage"),R=require("../shared/event-loop"),h=require("../diagnostics/module-plan-timeline"),je=E.z.object({targetFile:E.z.string().min(1).optional(),target:E.z.string().min(1).optional(),file:E.z.string().min(1).optional(),symbols:E.z.array(E.z.union([E.z.string().min(1),E.z.object({}).passthrough()])).optional(),entities:E.z.array(E.z.union([E.z.string().min(1),E.z.object({}).passthrough()])).optional()}).passthrough(),We=E.z.object({sourceFile:E.z.string().min(1).optional(),file:E.z.string().min(1).optional(),facadeFile:E.z.string().min(1).optional(),facade:E.z.string().min(1).optional(),modules:E.z.array(je).optional(),execute:E.z.boolean().optional(),planId:E.z.string().min(1).optional()}).passthrough();async function qe(e,t,n,o={},r={}){const s=Te(t,"--plan"),i=Te(t,"--from-json");if(i&&n!==void 0)throw new k.CliError("APPLY_MODULE_PLAN_INPUT_SOURCE_CONFLICT","Use either modulePlan --stdin or modulePlan --from-json, not both.");const u=i?(0,De.readJsonObjectFile)(e,i,"INVALID_MODULE_PLAN_JSON_FILE"):n,f=t.includes("--execute")||Ct(u),c=u===void 0?{}:We.parse(u),m=typeof c.planId=="string"?c.planId:void 0,p=s??m;if(p&&u===void 0||f&&p)return J(e,p,o,"modulePlan.apply",r.executionId);if(f&&!p){(0,h.recordModulePlanTimeline)(e,r.executionId,"modulePlan.execute.enter",{hasExecutionId:!!r.executionId});const P=Ye();if(r.executionId&&P>0){const g=Me(e,r.executionId,"modulePlan.execute",c);g.phase="preview",I(e,g),(0,h.recordModulePlanTimeline)(e,r.executionId,"modulePlan.execute.pending.persisted",{rowCount:g.rowCount,entityCount:g.entityCount,syncWaitMs:P});const l=Date.now(),C=Ke();(0,h.recordModulePlanTimeline)(e,r.executionId,"modulePlan.execute.background.schedule");const w=Ve(()=>(0,H.runWithProductStorageOverride)(C[_.CLI_ENV.productStorageDir],()=>He(C,()=>((0,h.recordModulePlanTimeline)(e,r.executionId,"modulePlan.execute.background.start"),pe(e,c,o,r,g)))));(0,h.recordModulePlanTimeline)(e,r.executionId,"modulePlan.execute.wait.start",{syncWaitMs:P});const A=await Je(w,P);return A.status==="result"?((0,h.recordModulePlanTimeline)(e,r.executionId,"modulePlan.execute.wait.result"),A.result):(w.catch(()=>{}),(0,h.recordModulePlanTimeline)(e,r.executionId,"modulePlan.execute.wait.deadline",{elapsedMs:Date.now()-l}),Ge(e,r.executionId,"modulePlan.execute",Date.now()-l))}return pe(e,c,o,r)}return ye(e,c,o)}async function pe(e,t,n,o,r){const s=r??(o.executionId?Me(e,o.executionId,"modulePlan.execute",t):void 0);s&&((0,h.recordModulePlanTimeline)(e,s.executionId,"modulePlan.executePayload.start"),s.phase="preview",I(e,s),await(0,R.yieldToEventLoop)());let i;try{(0,h.recordModulePlanTimeline)(e,s?.executionId,"modulePlan.preview.start"),i=await ye(e,t,n,"modulePlan.execute-preview"),(0,h.recordModulePlanTimeline)(e,s?.executionId,"modulePlan.preview.end",{ok:i.ok!==!1,moduleCount:typeof i.moduleCount=="number"?i.moduleCount:null})}catch(u){throw s&&(s.status="failed",s.error=u instanceof Error?u.message:String(u),I(e,s)),u}return i.ok===!1||typeof i.planId!="string"?(s&&(s.status="failed",s.planId=typeof i.planId=="string"?i.planId:s.planId,s.error="modulePlan preview failed before execute.",I(e,s)),i):(s&&(s.planId=i.planId,s.phase="mutation",I(e,s),(0,h.recordModulePlanTimeline)(e,s.executionId,"modulePlan.mutation.phase.persisted",{planId:i.planId}),await(0,R.yieldToEventLoop)()),J(e,i.planId,n,"modulePlan.execute",o.executionId))}function Be(e,t){const n=(0,d.readModulePlanRecord)(e,t),o={operation:"modulePlan.revise",fromPlanId:t,planId:t,executable:n.executable!==!1,summary:n.executable===!1?"semantic module plan still has blocking move diagnostics":"semantic module plan already executable",changes:[],resolved:[],remainingBlocking:Et(n.previewResult),next:n.executable===!1?"Fix the plan manually, then rerun modulePlan preview.":`aib modulePlan apply ${t}`};return n.executable===!1&&(o.ok=!1,o.code="MODULE_PLAN_REVISE_NOT_APPLICABLE"),(0,$.attachAgentText)(o,z(o))}function ze(e,t){const n=(0,d.readModulePlanExecutionStatus)(e,t),o=n.rows,r=n.status==="failed"?Xe(e,n.planId,o.length):[],s=[...ge(o),...r],i={operation:"execution.status",executionId:n.executionId,planId:n.planId,status:n.status,summary:Y(n),progress:`${n.completedRows}/${n.rowCount}`,entityProgress:`${n.completedEntities??0}/${n.entityCount??0}`,filesWritten:X(n.filesWritten.map(u=>(0,d.formatRelativePath)(e,u)).sort((u,f)=>u.localeCompare(f))),rows:o,...s.length>0?{notRun:s}:{},...n.remainingSource?{remainingSource:n.remainingSource}:{},...n.phase?{phase:n.phase}:{},...n.postMutation?{postMutation:n.postMutation}:{},updatedAt:n.updatedAt,...n.error?{error:n.error}:{}};return(0,$.attachAgentText)(i,z(i))}function Ve(e){return new Promise((t,n)=>{setImmediate(()=>{e().then(t,n)})})}function Ke(){const e=[_.CLI_ENV.productStorageDir,_.CLI_ENV.trace,_.CLI_ENV.traceDir,_.CLI_ENV.metrics,_.CLI_ENV.metricsDir,_.CLI_ENV.metricsTag,_.CLI_ENV.mutationImpactMetrics,_.CLI_ENV.mutationImpactStream,_.CLI_ENV.testMoveToFileFailEntity,_.CLI_ENV.testPostMutationCyclesDelayMs,_.CLI_ENV.modulePlanDebugTimeline],t={};for(const n of e)t[n]=process.env[n];return t}async function He(e,t){const n={};for(const[o,r]of Object.entries(e))n[o]=process.env[o],r===void 0?delete process.env[o]:process.env[o]=r;try{return await t()}finally{for(const[o,r]of Object.entries(n))r===void 0?delete process.env[o]:process.env[o]=r}}async function Je(e,t){let n=null;try{return await Promise.race([e.then(o=>({status:"result",result:o})),new Promise(o=>{n=setTimeout(()=>o({status:"deadline"}),t)})])}finally{n&&clearTimeout(n)}}function Ye(){const e=process.env[_.CLI_ENV.modulePlanSyncWaitMs];if(e!==void 0){const t=Number.parseInt(e,10);return!Number.isFinite(t)||t<=0?0:Math.min(t,12e4)}return 12e4}function Ge(e,t,n,o){const r=(0,d.readModulePlanExecutionStatus)(e,t),s=y(r.timeoutHint)&&typeof r.timeoutHint.estimatedDurationMs=="number"?r.timeoutHint.estimatedDurationMs:null,i=s===null?null:Math.max(0,s-o),u={operation:"execution.status",executionId:r.executionId,planId:r.planId,status:r.status,...r.phase?{phase:r.phase}:{},summary:Y(r),progress:`${r.completedRows}/${r.rowCount}`,entityProgress:`${r.completedEntities??0}/${r.entityCount??0}`,expectEmpty:r.expectEmpty===!0,filesWritten:X(r.filesWritten.map(f=>(0,d.formatRelativePath)(e,f)).sort((f,c)=>f.localeCompare(c))),rows:r.rows,updatedAt:r.updatedAt,...i!==null?{estimatedRemainingMs:i}:{}};return(0,$.attachAgentText)(u,Qe(n,r,i))}function Qe(e,t,n){const o=[`${e} ${t.executionId}`,Y(t)];return t.phase==="preview"?o.push("previewing plan"):t.phase==="mutation"?o.push("applying mutation"):t.phase==="postMutation.cycles"&&(o.push("mutation completed"),o.push("checking cycles")),o.push(`status: aib execution status ${t.executionId}`),n!==null&&o.push(n>0?`estimated remaining: ${(0,de.formatModulePlanTimeoutEstimate)(Math.max(n,5e3))}`:"estimated remaining: check status again soon"),o.join(`
2
+ `)}async function ye(e,t,n,o="modulePlan.preview"){(0,h.recordModulePlanTimeline)(e,void 0,"modulePlan.preview.resolveInstance.start",{operation:o});const r=await(0,D.resolveCompatibleTargetInstance)(e,ue.CLI_COMMAND_IDS.modulePlan,n);(0,h.recordModulePlanTimeline)(e,void 0,"modulePlan.preview.resolveInstance.end",{operation:o});const s=await(0,D.fetchEffectiveConfig)(r.entry,n),i=Se(e,t),u=ct(e,t,i,s),f=(0,d.buildModulePlanId)(u),c=await Ze(e,u,n,r),m=(0,d.hashFile)(i),p=(0,d.buildModulePlanHash)(u,m,c),P={planId:f,planHash:p,createdAt:new Date().toISOString(),cwd:F.resolve(e),sourceFile:i,sourceHash:m,executable:c.ok!==!1,normalizedRequest:u,inspectPayload:{requests:[u]},previewDir:"",previewResult:c};(0,d.writeModulePlanRecord)(e,P);const g={...c.ok===!1?{ok:!1,code:"MODULE_PLAN_BLOCKED"}:{},operation:o,planId:f,executable:c.ok!==!1,summary:Ie(c,!1),...typeof c.moduleCount=="number"?{moduleCount:c.moduleCount}:{},...Array.isArray(c.targets)?{targets:c.targets}:{},...Array.isArray(c.blocking)&&c.blocking.length>0?{blocking:c.blocking}:{},next:c.ok===!1?"Fix the plan, then rerun modulePlan preview.":`aib modulePlan apply ${f}`};return(0,$.attachAgentText)(g,z(g))}function Xe(e,t,n){if(t==="pending")return[];try{const o=(0,d.readModulePlanRecord)(e,t);return he(e,Q(o.normalizedRequest),n)}catch{return[]}}async function Ze(e,t,n,o){const r=Q(t),s=a(t.sourceFile)??"",i=await et(e,o,s,r,n);if(i)return i;const u=[],f=[],c=[];for(const m of r){await(0,R.yieldToEventLoop)();const p=a(m.targetFile)??"",P=U(m);(0,h.recordModulePlanTimeline)(e,void 0,"modulePlan.preview.row.start",{target:(0,d.formatRelativePath)(e,p),entityCount:P.length});const g=await Pe(e,s,p,P,m,!1,n);(0,h.recordModulePlanTimeline)(e,void 0,"modulePlan.preview.row.end",{target:(0,d.formatRelativePath)(e,p),ok:g.ok!==!1});const l=Ce("preview",e,s,p,P,g);if(f.push(l),u.push({file:(0,d.formatRelativePath)(e,p),entities:P,...typeof l.summary=="string"?{summary:l.summary}:{}}),l.ok===!1){c.push(l);break}await(0,R.yieldToEventLoop)()}return{op:"modulePlan",ok:c.length===0,sourceFile:s,moduleCount:r.length,targets:u,rows:f,...c.length>0?{blocking:c}:{},cycles:"notChecked"}}async function et(e,t,n,o,r){const s=await(0,ie.postJson)(t.entry,se.EXTENSION_ROUTES.inspect,{requests:[{op:"file",sourceFile:n,includeRanges:!1}]},(0,D.extensionRequestOptions)(r)),i=Array.isArray(s.results)?s.results.find(y):null,u=Array.isArray(i?.symbols)?i.symbols.filter(y):[];if(u.length===0)return null;const f=[],c=[],m=[];for(const p of o){const P=a(p.targetFile)??"",g=U(p),l={target:(0,d.formatRelativePath)(e,P),entities:g,ok:!0,summary:P&&!O.existsSync(P)?"target will be created":"target ready"};for(const C of tt(p)){const w=u.filter(A=>nt(A,C));if(w.length===0){l.ok=!1,l.entity=C.raw,l.code="MODULE_PLAN_SYMBOL_NOT_FOUND",l.error=`Symbol not found: ${C.raw}`,l.source=(0,d.formatRelativePath)(e,n);break}if(!C.symbolKind&&w.length>1){l.ok=!1,l.entity=C.raw,l.code="MODULE_PLAN_SYMBOL_AMBIGUOUS",l.error=`Ambiguous symbol: ${C.raw}`,l.available=w.map(A=>`${a(A.kind)??"symbol"}:${a(A.name)??C.symbolName}`),l.source=(0,d.formatRelativePath)(e,n);break}}if(f.push(W(l)),c.push({file:(0,d.formatRelativePath)(e,P),entities:g,...typeof l.summary=="string"?{summary:l.summary}:{}}),l.ok===!1){m.push(W(l));break}}return m.length===0?null:{op:"modulePlan",ok:!1,sourceFile:n,moduleCount:o.length,targets:c,rows:f,blocking:m,cycles:"notChecked"}}function tt(e){return(Array.isArray(e.symbols)?e.symbols.filter(y):[]).map(n=>{const o=a(n.raw)??a(n.symbolName)??"",r=a(n.symbolName)??o,s=a(n.symbolKind)??void 0;return{raw:o,symbolName:r,...s?{symbolKind:s}:{}}})}function nt(e,t){return a(e.name)!==t.symbolName?!1:!t.symbolKind||a(e.kind)===t.symbolKind}async function J(e,t,n,o="modulePlan.apply",r,s){const i=(0,d.readModulePlanRecord)(e,t);if(i.executable===!1||i.previewResult.ok===!1)throw new k.CliError("APPLY_MODULE_PLAN_NOT_EXECUTABLE","Module plan has blocking move diagnostics. Fix the plan before applying.",{planId:t,next:"Fix the plan, then rerun modulePlan preview."});if((0,d.hashFile)(i.sourceFile)!==i.sourceHash)throw new k.CliError("APPLY_MODULE_PLAN_SOURCE_CHANGED","Source file changed after modulePlan preview. Rerun modulePlan preview.",{planId:t,sourceFile:(0,d.formatRelativePath)(e,i.sourceFile)});const f=Q(i.normalizedRequest),c=[],m=new Set,p=i.sourceFile,P=f.map(M=>a(M.targetFile)).filter(M=>!!M),g=Z([p,...P]),l=s??ot(e,i,o,f,r);(0,h.recordModulePlanTimeline)(e,l.executionId,"modulePlan.apply.start",{operation:o,rowCount:f.length,entityCount:l.entityCount});const C={executionId:l.executionId,planId:i.planId,parentOperation:o,sourceFile:(0,d.formatRelativePath)(e,p),rowCount:f.length,entityCount:l.entityCount},w=(0,fe.startCentralMetricSpan)({kind:"mutation.execution",operation:o,cwd:F.resolve(e),...C});I(e,l),(0,h.recordModulePlanTimeline)(e,l.executionId,"modulePlan.apply.execution.persisted"),await(0,R.yieldToEventLoop)(),(0,h.recordModulePlanTimeline)(e,l.executionId,"modulePlan.cycles.pre.start",{fileCount:g.length});const A=xe(e,g);(0,h.recordModulePlanTimeline)(e,l.executionId,"modulePlan.cycles.pre.end",{componentCount:j(A.componentCount)??null});try{for(let x=0;x<f.length;x+=1){await(0,R.yieldToEventLoop)();const S=f[x],N=a(S.targetFile)??"",K=U(S),Fe=Mt(c.filter(L=>L.ok!==!1));(0,h.recordModulePlanTimeline)(e,l.executionId,"modulePlan.apply.row.start",{rowIndex:x,target:(0,d.formatRelativePath)(e,N),entityCount:K.length});const oe=await Pe(e,p,N,K,S,!0,n,{onProgress:L=>it(e,l,Fe,L,Array.from(m)),metricsContext:{...C,rowIndex:x,rowTargetFile:(0,d.formatRelativePath)(e,N)}}),q=Ce("execute",e,p,N,K,oe);c.push(q),(0,h.recordModulePlanTimeline)(e,l.executionId,"modulePlan.apply.row.end",{rowIndex:x,target:(0,d.formatRelativePath)(e,N),ok:q.ok!==!1});for(const L of b(oe.filesWritten))m.add((0,d.resolveCliFilePath)(e,L));if(rt(e,l,q,Array.from(m)),await(0,R.yieldToEventLoop)(),q.ok===!1)break}const M=c.every(x=>x.ok!==!1);if(M){l.phase="postMutation.cycles",I(e,l),(0,h.recordModulePlanTimeline)(e,l.executionId,"modulePlan.cycles.phase.persisted"),await(0,R.yieldToEventLoop)(),await at();const x=Z([...g,...Array.from(m)]);(0,h.recordModulePlanTimeline)(e,l.executionId,"modulePlan.cycles.post.start",{fileCount:x.length});const S=xe(e,x);(0,h.recordModulePlanTimeline)(e,l.executionId,"modulePlan.cycles.post.end",{componentCount:j(S.componentCount)??null}),l.postMutation={cycles:st(A,S,new Set(_e(e,x)))}}l.status=M?"completed":"failed",M&&(l.phase="completed"),l.failedRows=c.filter(x=>x.ok===!1).length,l.filesWritten=Array.from(m).sort((x,S)=>x.localeCompare(S));const T=await Re(e,p,n);T&&(l.remainingSource=T),I(e,l),(0,h.recordModulePlanTimeline)(e,l.executionId,"modulePlan.apply.execution.final.persisted",{status:l.status,completedRows:l.completedRows,completedEntities:l.completedEntities})}catch(M){throw l.status="failed",l.error=M instanceof Error?M.message:String(M),l.filesWritten=Array.from(m).sort((T,x)=>T.localeCompare(x)),I(e,l),w.end({ok:!1,status:l.status,error:M instanceof Error?M.message:String(M),completedRows:l.completedRows,failedRows:l.failedRows,completedEntities:l.completedEntities,filesWrittenCount:l.filesWritten.length}),M}const v=c.every(M=>M.ok!==!1),ee=v?[]:he(e,f,c.length),te=v?[]:[...ge(c),...ee];Ee(e,l);const ne={...v?{}:{ok:!1,code:"MODULE_PLAN_APPLY_FAILED"},operation:o,applied:v,planId:i.planId,executionId:l.executionId,expectEmpty:i.normalizedRequest.expectEmpty===!0,summary:Ie({rows:[...c,...ee]},!0),rows:c,...te.length>0?{notRun:te}:{},remainingSource:await Re(e,p,n),...l.postMutation?{postMutation:l.postMutation}:{},...G(i.previewResult).length>0?{createdFiles:ke(G(i.previewResult),8)}:{},filesWritten:X(Array.from(m).sort((M,T)=>M.localeCompare(T)).map(M=>(0,d.formatRelativePath)(e,M))),...v?{}:{next:"Fix failed move row and rerun modulePlan preview."}};return w.end({ok:v,status:l.status,completedRows:l.completedRows,failedRows:l.failedRows,completedEntities:l.completedEntities,filesWrittenCount:l.filesWritten.length}),(0,fe.recordCentralMetric)({kind:"mutation.summary",operation:o,cwd:F.resolve(e),ok:v,status:l.status,executionId:l.executionId,planId:i.planId,rowCount:l.rowCount,completedRows:l.completedRows,failedRows:l.failedRows,entityCount:l.entityCount,completedEntities:l.completedEntities,filesWrittenCount:l.filesWritten.length}),(0,$.attachAgentText)(ne,z(ne))}function he(e,t,n){return t.slice(n).map(o=>W({target:(0,d.formatRelativePath)(e,a(o.targetFile)??""),entities:U(o)}))}function ge(e){return e.map(t=>W({target:a(t.target)??"",entities:b(t.notRunEntities)})).filter(t=>b(t.entities).length>0)}async function Pe(e,t,n,o,r,s,i,u={}){const f=await(0,Ue.runMoveToFile)(e,{sourceFile:t,targetFile:n,entities:o,execute:s},i,[],u);return f.ok!==!1,f}function ot(e,t,n,o,r){const s=new Date().toISOString(),i=r??(0,d.buildModulePlanExecutionId)(t.planId),u=we(o);return{executionId:i,planId:t.planId,operation:n,cwd:F.resolve(e),sourceFile:t.sourceFile,status:"running",phase:"mutation",startedAt:s,updatedAt:s,rowCount:o.length,completedRows:0,failedRows:0,entityCount:u,completedEntities:0,expectEmpty:t.normalizedRequest.expectEmpty===!0,filesWritten:[],rows:[],timeoutHint:ut(t.normalizedRequest),productStorageDir:(0,H.productStorageRoot)()}}function Me(e,t,n,o){const r=new Date().toISOString(),s=Array.isArray(o.modules)?o.modules.filter(y):[];return{executionId:t,planId:"pending",operation:n,cwd:F.resolve(e),sourceFile:o.sourceFile||o.file?Se(e,o):"",status:"running",phase:"mutation",startedAt:r,updatedAt:r,rowCount:s.length,completedRows:0,failedRows:0,entityCount:we(s),completedEntities:0,expectEmpty:o.expectEmpty===!0,filesWritten:[],rows:[],productStorageDir:(0,H.productStorageRoot)()}}function rt(e,t,n,o){t.rows.push(n),t.completedRows=t.rows.filter(r=>r.ok!==!1).length,t.failedRows=t.rows.filter(r=>r.ok===!1).length,t.completedEntities=dt(t.rows),t.filesWritten=o.sort((r,s)=>r.localeCompare(s)),n.ok===!1&&(t.status="failed"),I(e,t)}function it(e,t,n,o,r){t.completedEntities=n+o.completedEntities,t.filesWritten=Array.from(new Set([...r,...o.filesWritten.map(s=>(0,d.resolveCliFilePath)(e,s))])).sort((s,i)=>s.localeCompare(i)),o.ok||(t.status="failed"),I(e,t)}function I(e,t){(0,d.writeModulePlanExecutionStatus)(e,t),Ee(e,t)}function Ee(e,t){if(!(0,ae.sessionWorkspaceExists)(e))return null;try{return(0,ae.saveSessionOutputJson)(e,"execution",`modulePlan-${t.executionId}`,t)}catch{return null}}function xe(e,t){const n=_e(e,t).filter(r=>O.existsSync((0,d.resolveCliFilePath)(e,r)));if(n.length===0)return{op:"cycles",componentCount:0,components:[]};const o=["cycles"];for(const r of n)o.push("--files",r);return o.push("--detail","imports","--limit","50"),(0,me.runInspectCycles)(e,o,void 0)}function st(e,t,n){const o=new Set(B(e).map(be)),r=B(t).filter(s=>b(s.files).some(i=>n.has(i))&&!o.has(be(s)));return{status:r.length>0?"new-or-changed":"none",detail:"imports",newOrChangedCount:r.length,preComponentCount:j(e.componentCount)??B(e).length,postComponentCount:j(t.componentCount)??B(t).length,components:r}}function B(e){return(Array.isArray(e.components)?e.components:[]).filter(y).map(t=>({kind:a(t.kind)??"mixed",files:b(t.files).sort(),chain:a(t.chain)??"",...y(t.cycle)?{cycle:t.cycle}:{},imports:lt(t)}))}function lt(e){const t=y(e.cycle)?e.cycle:{};return b(t.imports)}function be(e){return`${a(e.kind)??"mixed"}:${b(e.files).sort().join("|")}`}function _e(e,t){return Z(t.map(n=>(0,d.formatRelativePath)(e,(0,d.resolveCliFilePath)(e,n))))}async function at(){const e=process.env[_.CLI_ENV.testPostMutationCyclesDelayMs],t=e?Number.parseInt(e,10):0;!Number.isFinite(t)||t<=0||await new Promise(n=>setTimeout(n,Math.min(t,6e4)))}function Y(e){const t=e.filesWritten.length,n=`${e.completedRows}/${e.rowCount}`,o=e.entityCount??0,r=e.completedEntities??0,s=o>0?`, ${Math.floor(r/o*100)}% entities`:"",i=e.status==="running"&&e.phase==="postMutation.cycles"?`${n} rows${s}`:`${e.status==="running"?"in progress":e.status}, ${n} rows${s}`;return t>0?`${i}, ${t} ${t===1?"file":"files"} written`:i}function ut(e){return(0,de.buildModulePlanTimeoutHintFromRequest)(e)??{recommendedTimeoutMs:9e4,rowCount:0,symbolCount:0,message:"If the calling agent times out, inspect progress with: aib execution status last"}}function ct(e,t,n,o){const r=t.modules??[];if(r.length===0)throw new k.CliError("MODULE_PLAN_MODULES_REQUIRED","modulePlan expects a non-empty modules array.");const s=r.map(i=>{const u=i.target??i.targetFile??i.file;if(!u)throw new k.CliError("MODULE_PLAN_TARGET_REQUIRED","Each module expects target.");const f=i.entities??i.symbols??[];if(f.length===0)throw new k.CliError("MODULE_PLAN_ENTITIES_REQUIRED","Each module expects a non-empty entities array.");return{targetFile:(0,d.resolveCliFilePath)(e,u),symbols:f.map(c=>ft(c,o))}});return{op:"modulePlan",sourceFile:n,...t.expectEmpty===!0?{expectEmpty:!0}:{},modules:s}}function ft(e,t){if(typeof e=="string"){const o=(0,ce.parseInspectSelector)(e,t);return{raw:e,symbolName:o.symbolName,...o.symbolKind?{symbolKind:o.symbolKind}:{}}}const n=a(e.entity)??a(e.selector)??a(e.raw);if(n){const o=(0,ce.parseInspectSelector)(n,t);return{raw:n,symbolName:o.symbolName,...o.symbolKind?{symbolKind:o.symbolKind}:{}}}return Ne(e)}function Ce(e,t,n,o,r,s){const i={target:(0,d.formatRelativePath)(t,o),entities:r,ok:s.ok!==!1,summary:typeof s.summary=="string"?s.summary:null};if(e==="preview"&&typeof s.previewId=="string"&&(i.movePreviewId=s.previewId),Array.isArray(s.files)&&(i.files=s.files),Array.isArray(s.filesWritten)&&(i.filesWritten=s.filesWritten),s.ok===!1){const u=pt(s),f=a(u?.entity)??r[0]??null,m=(Array.isArray(s.results)?s.results.filter(y):[]).filter(g=>g.ok!==!1).map(g=>a(g.entity)).filter(g=>!!g),p=f?r.indexOf(f):-1,P=p>=0?r.slice(p+1):[];i.appliedEntities=m,i.notRunEntities=P,i.entity=f,i.code=a(u?.code)??a(s.code)??"MOVE_TO_FILE_FAILED",i.error=yt(a(u?.error)??a(s.error)??"Move failed."),i.hint=mt(t,a(u?.code),a(u?.hint)),i.next=a(u?.next),i.source=(0,d.formatRelativePath)(t,n)}return W(i)}function dt(e){return e.reduce((t,n)=>n.ok===!1?t+b(n.appliedEntities).length:t+b(n.entities).length,0)}function mt(e,t,n){return n?t==="TS_MOVE_TO_FILE_UNSUPPORTED_BY_ENGINE"?(0,le.useSessionGuidance)(e,"modulePlan.tsMoveUnsupportedHint",n,(0,le.readSessionNumberPref)(e,"diagnostics.hintLimit",2))??null:n:null}function pt(e){return(Array.isArray(e.results)?e.results.filter(y):[]).find(n=>n.ok===!1)??null}function yt(e){return e.replace(/^TypeScript refactor failed: Debug Failure\. False expression: /,"")}function Ie(e,t){const n=Array.isArray(e.rows)?e.rows.filter(y):[],o=n.reduce((m,p)=>m+b(p.entities).length,0),r=n.filter(m=>m.ok===!1).length,s=n.length,i=t?G(e).length:n.filter(m=>Ae(m)).length,u=t?Array.from(new Set(n.flatMap(m=>b(m.filesWritten).filter(p=>!p.startsWith("+"))))).length:0;if(r>0)return`${o} ${o===1?"symbol":"symbols"}, ${r} blocked`;const f=`${o} ${o===1?"symbol":"symbols"}, ${s} ${s===1?"target":"targets"} ${t?"moved":"ready"}`,c=[];return t&&u>0&&c.push(`${u} ${u===1?"file":"files"} written`),i>0&&c.push(`${i} ${i===1?"file":"files"} ${t?"created":"will be created"}`),c.length>0?`${f}; ${c.join(", ")}`:f}function Ae(e){return typeof e.summary=="string"&&e.summary.includes("target will be created")}function G(e){return(Array.isArray(e.rows)?e.rows.filter(y):[]).filter(n=>Ae(n)).map(n=>a(n.target)).filter(n=>!!n)}function z(e){const t=[],n=a(e.operation)??"modulePlan",o=a(e.planId),r=a(e.executionId);if(n!=="execution.status"){const i=n==="modulePlan.apply"||n==="modulePlan.execute"?r??o:o;t.push(i?`${n} ${i}`:n)}e.executable===!1&&t.push("blocked"),typeof e.summary=="string"&&t.push(e.summary),n==="execution.status"&&e.status==="running"&&e.phase==="postMutation.cycles"&&(t.push("mutation completed"),t.push("checking cycles"));const s=n==="execution.status"&&e.status==="running"&&e.phase==="postMutation.cycles";if(Array.isArray(e.targets)&&e.targets.length>0){t.push("targets:");for(const i of e.targets.filter(y)){const u=a(i.file),f=b(i.entities);u&&t.push(`${u}: ${V(f,5)}`)}}if(!s&&Array.isArray(e.rows)&&e.rows.length>0){t.push("moves:");for(const i of e.rows.filter(y)){const u=a(i.target),f=i.ok===!1&&b(i.appliedEntities).length>0?b(i.appliedEntities):b(i.entities);if(u&&f.length>0&&t.push(`${u}: ${V(f,5)}`),i.ok===!1){const c=a(i.code),m=a(i.error);c&&t.push(`code: ${c}`),m&&t.push(m)}}}if(Array.isArray(e.notRun)&&e.notRun.length>0){t.push("not run:");for(const i of e.notRun.filter(y)){const u=a(i.target),f=b(i.entities);u&&t.push(`${u}: ${V(f,5)}`)}}if(y(e.remainingSource)){const i=b(e.remainingSource.symbols);i.length===0?e.remainingSource.hasNonDeclarationText===!0?(t.push("source has no declarations"),t.push("source file still has non-declaration text")):t.push("source is empty"):e.expectEmpty===!0&&(t.push("source still contains:"),t.push(V(i,15)))}if(Array.isArray(e.blocking)&&e.blocking.length>0&&ht(t,e.blocking.filter(y)),e.status!=="running"&&Array.isArray(e.filesWritten)&&e.filesWritten.length>0){t.push("filesWritten:");for(const i of e.filesWritten.filter(u=>typeof u=="string"))t.push(i)}return y(e.postMutation)&&y(e.postMutation.cycles)&&gt(t,e.postMutation.cycles),typeof e.next=="string"&&!(Array.isArray(e.blocking)&&e.blocking.length>0)&&t.push(`next: ${e.next}`),t.join(`
3
+ `)}function ht(e,t){const n=t.filter(i=>a(i.code)==="MODULE_PLAN_SYMBOL_NOT_FOUND").map(i=>a(i.entity)).filter(i=>!!i),o=t.filter(i=>a(i.code)==="MODULE_PLAN_SYMBOL_AMBIGUOUS").map(i=>a(i.entity)).filter(i=>!!i),r=n.length+o.length;n.length>0&&e.push(`not found symbols: ${n.join(", ")}`),o.length>0&&e.push(`ambiguous symbols: ${o.join(", ")}`);const s=t.filter(i=>a(i.code)!=="MODULE_PLAN_SYMBOL_NOT_FOUND"&&a(i.code)!=="MODULE_PLAN_SYMBOL_AMBIGUOUS");if(!(r>0&&s.length===0)){e.push("blocking:");for(const i of s.length>0?s:t){const u=a(i.target),f=a(i.entity),c=a(i.code),m=a(i.error),p=a(i.hint),P=a(i.next);u&&e.push(u),(f||c)&&e.push([f,c].filter(Boolean).join(": ")),m&&e.push(m),p&&e.push(`hint: ${p}`),P&&e.push(`next: ${P}`)}}}function gt(e,t){e.push("cycles:");const n=j(t.newOrChangedCount)??0;if(n===0){e.push("no new/changed cycles involving touched files");return}const o=Array.isArray(t.components)?t.components.filter(y):[];e.push(Pt(n,o)),o.forEach((r,s)=>{(0,me.appendCycleComponentText)(e,r,{detail:"imports",prefix:o.length===1?"":`${s+1}. `,indent:o.length===1?"":" "})})}function Pt(e,t){const n=t.map(s=>a(s.kind)??"mixed"),o=Array.from(new Set(n)),r=o.length===1?`${o[0]} `:"";return`${e} new/changed ${r}${e===1?"cycle":"cycles"} involving touched files`}function Q(e){return Array.isArray(e.modules)?e.modules.filter(y):[]}function we(e){return e.reduce((t,n)=>{const o=U(n);if(o.length>0)return t+o.length;const r=Array.isArray(n.entities)?n.entities:[],s=Array.isArray(n.symbols)?n.symbols:[];return t+Math.max(r.length,s.length)},0)}function Mt(e){return e.reduce((t,n)=>t+b(n.entities).length,0)}function U(e){return(Array.isArray(e.symbols)?e.symbols.filter(y):[]).map(n=>a(n.raw)??a(n.selector)??a(n.entity)).filter(n=>!!n)}function Se(e,t){const n=t.sourceFile??t.file;if(!n)throw new k.CliError("MODULE_PLAN_SOURCE_REQUIRED","modulePlan expects sourceFile or file.");return(0,d.resolveCliFilePath)(e,n)}function Et(e){return Array.isArray(e.blocking)?e.blocking.filter(y):[]}function X(e){return ke(e,15)}async function Re(e,t,n){try{const o=await(0,D.resolveCompatibleTargetInstance)(e,ue.CLI_COMMAND_IDS.inspect,n),r=await(0,ie.postJson)(o.entry,se.EXTENSION_ROUTES.inspect,{requests:[{op:"file",file:t}]},(0,D.extensionRequestOptions)(n));return{file:(0,d.formatRelativePath)(e,t),symbols:bt(r),hasNonDeclarationText:xt(r,t)}}catch{return null}}function xt(e,t){const o=(Array.isArray(e.results)?e.results.filter(y):[])[0]??e;if(o.hasNonDeclarationText===!0)return!0;const r=a(o.sourceFile)??t;if(!r)return!1;try{return O.existsSync(r)&&O.statSync(r).isFile()&&O.readFileSync(r,"utf8").trim()!==""}catch{return!1}}function bt(e){const n=(Array.isArray(e.results)?e.results.filter(y):[])[0]??e;return(Array.isArray(n.symbols)?n.symbols:Array.isArray(n.items)?n.items:Array.isArray(n.declarations)?n.declarations:[]).map(_t).filter(r=>!!r)}function _t(e){if(typeof e=="string")return ve(e);if(!y(e))return null;const t=a(e.raw)??a(e.selector)??a(e.entity)??a(e.name)??a(e.label)??a(e.text);return t?ve(t):null}function ve(e){return(e.replace(/^export\s+/,"").trim().split(/\s+/)[0]??"").replace(/\(.*/,"").replace(/^[a-z]-/,"")||null}function ke(e,t){const n=e.slice(0,t),o=e.length-n.length;return o>0?[...n,`+ ${o} more`]:n}function V(e,t){const n=e.slice(0,t),o=e.length-n.length;return o>0?`${n.join(", ")}, +${o} more`:n.join(", ")}function Ct(e){return!!(e&&typeof e=="object"&&!Array.isArray(e)&&e.execute===!0)}function Te(e,t){const n=e.indexOf(t);if(n<0)return null;const o=e[n+1];return o&&!o.startsWith("--")?o:null}function a(e){return typeof e=="string"&&e.trim()!==""?e.trim():null}function j(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function b(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function Z(e){return Array.from(new Set(e)).sort((t,n)=>t.localeCompare(n))}function W(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t==null?!1:!(Array.isArray(t)&&t.length===0)))}function y(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Ne(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Le(n)]))}function Le(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?e:Array.isArray(e)?e.map(t=>Le(t)):e&&typeof e=="object"?Ne(e):String(e)}
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.attachCapturedInput=$;const h=require("node:crypto"),m=require("../shared/agent-text"),b=require("./session-workspace");function $(e,r,n,t,u){if(!p(n)||y(t))return t;const f=I(r,n),o=A(n,t),c=(0,b.captureSessionInput)(e,f,o,n,u);if(!c)return t;const a=l(n)?"capturedInput":"input",s=t[a]!==void 0?t:{...t,[a]:c.handle};return t.ok!==!1||d(r)?s:g(e,r,f,c,s)}function y(e){if(e.ok===!1)return!1;const r=i(e.operation);return r!==null&&r.endsWith(".execute")}function I(e,r){return e!=="inspect"?e:F(r,"modulePlan")?"modulePlan":"inspect"}function d(e){return e==="inspect"||e==="graph"||e==="modulePlan"||e==="move"||e==="refactor"}function g(e,r,n,t,u){const f=v(r,n,u.operation,t.handle),o=f?(0,b.useSessionGuidance)(e,`failureInputRecovery.${r}.${i(u.operation)??"unknown"}`,`Edit inputFile, then rerun: ${f}`):void 0,c={...u,input:t.handle,inputFile:t.file,...o?{inputNext:o}:{}},a=(0,m.readAgentText)(u);if(!a)return c;const s=[a.trimEnd(),`input: ${t.handle}`,`inputFile: ${t.file}`,...o?[`next: ${o}`]:[]];return(0,m.attachAgentText)(c,s.join(`
2
+ `))}function v(e,r,n,t){const u=i(n)??"";return e==="modulePlan"?`aib modulePlan preview --from ${t}`:e==="move"?u==="move.toFile.execute"?`aib move toFile execute --from ${t}`:`aib move toFile preview --from ${t}`:e==="rename"?u==="rename.execute"?`aib rename execute --from ${t}`:`aib rename preview --from ${t}`:e==="refactor"?u==="refactor.batch.execute"?`aib refactor batch execute --from ${t}`:u==="refactor.batch.apply"?`aib refactor batch apply --from ${t}`:`aib refactor batch preview --from ${t}`:r==="modulePlan"?`aib modulePlan preview --from ${t}`:null}function A(e,r){const n=i(e.save);return n||(i(r.planId)??i(r.previewId)??x(r.results,"planId")??x(r.results,"previewId")??`req_${_(e).slice(0,12)}`)}function F(e,r){return e.op===r?!0:(Array.isArray(e.requests)?e.requests:[]).some(t=>p(t)&&t.op===r)}function l(e){return Array.isArray(e)?e.some(r=>l(r)):p(e)?e.execute===!0?!0:Object.values(e).some(r=>l(r)):!1}function _(e){return(0,h.createHash)("sha256").update(JSON.stringify(e)).digest("hex")}function i(e){return typeof e=="string"&&e.trim()!==""?e.trim():null}function x(e,r){if(!Array.isArray(e))return null;const n=e.find(p);return n?i(n[r]):null}function p(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}
@@ -0,0 +1,3 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.runConfigCommand=A;const p=require("../shared/agent-text"),f=require("../shared/errors"),g=require("../config/import-rules"),d=require("../config/path-aliases"),$=require("../config/local-config"),m=require("../config/workspace-root"),C=require("./session-workspace"),x=require("./normalize-imports");function A(e,n=[]){const o=b(n,"--session-dir");if(o)return _(e,o);if(n.length>0)throw new f.CliError("CONFIG_USAGE","Usage: aib config [--session-dir .tmp/aib]");const s=(0,m.resolveRequiredWorkspaceRoot)(e),i=(0,d.readConfigPathAliases)(e),t=(0,C.readSessionPathAliasOverrides)(e),r=(0,d.effectivePathAliases)(e,t),l=(0,g.readConfigImportRules)(e),u=(0,x.readWorkspaceNormalizeImportRules)(e),a=(0,$.resolveLocalCliConfig)(e),h={ok:!0,root:s.root,configPath:s.configPath,pathAliases:r,configPathAliases:i,sessionPathAliases:t,importRules:(0,g.importRulesToJson)(l),importNormalize:u.rules.map(S),importNormalizeSources:u.sources,graphExclude:a.config.inspect.graph.exclude,tree:a.config.inspect.tree,graphConfigSources:a.sources};return(0,p.attachAgentText)(h,I({root:s.root,configPath:s.configPath,aliases:r,configAliases:i,sessionAliases:t,importRules:l,importNormalize:u.rules,graphExclude:a.config.inspect.graph.exclude,tree:a.config.inspect.tree}))}function _(e,n){const o=(0,m.updateWorkspaceConfig)(e,{sessionDir:n}),i={ok:!0,config:"aib.json",...(0,m.workspaceConfigSummary)(o),next:"Create sessions without --dir: aib session init --name <name>"};return(0,p.attachAgentText)(i,y(i))}function b(e,n){let o=null;for(let s=0;s<e.length;s+=1){if(e[s]!==n)throw new f.CliError("CONFIG_USAGE","Usage: aib config [--session-dir .tmp/aib]");if(o!==null)throw new f.CliError("CONFIG_USAGE",`${n} can be provided only once.`);const t=e[s+1];if(!t||t.startsWith("--"))throw new f.CliError("MISSING_FLAG_VALUE",`Expected a value after ${n}.`);o=t,s+=1}return o}function y(e){const n=String(e.sessionDir??".tmp/aib"),o=typeof e["session.ttlCleanMinutes"]=="number"?e["session.ttlCleanMinutes"]:60,s=typeof e["runtime.managedIdeTtlMinutes"]=="number"?e["runtime.managedIdeTtlMinutes"]:15;return["aib session defaults configured","","config: aib.json",`workspace.root: ${String(e["workspace.root"]??".")}`,`sessionDir: ${n}`,`new sessions: ${n.replace(/[\\/]+$/,"")}/<name>/**`,`session cleanup: after ${o} minutes of inactivity`,`runtime cleanup: after ${s} minutes of inactivity`,"","Create sessions without --dir:","aib session init --name <name>"].join(`
2
+ `)}function S(e){return{...e.scope?{scope:e.scope}:{},...e.mode?{to:e.mode}:{},...e.preferAlias?{preferAlias:e.preferAlias}:{},...e.exclude.length>0?{exclude:e.exclude}:{}}}function I(e){const n=[{name:"pathAliases",lines:P(e.aliases,e.configAliases,e.sessionAliases)},{name:"importRules",lines:N(e.importRules)},{name:"importNormalize",lines:w(e.importNormalize)},{name:"inspect.graph.exclude",lines:c(e.graphExclude)},{name:"inspect.tree.onlyDirs.include",lines:c(e.tree.onlyDirs.include)},{name:"inspect.tree.onlyDirs.exclude",lines:c(e.tree.onlyDirs.exclude)},{name:"inspect.tree.files.include",lines:c(e.tree.files.include)},{name:"inspect.tree.files.exclude",lines:c(e.tree.files.exclude)}],o=[`config: ${e.configPath}`,`root: ${e.root}`],s=[];for(const i of n){if(i.lines.length===0){s.push(i.name);continue}o.push("",`${i.name}:`,...i.lines)}return s.length>0&&o.push("","not set:",...s.map(i=>` ${i}`)),o.join(`
3
+ `)}function P(e,n,o){const s=Object.entries(e).sort(([i],[t])=>i.localeCompare(t));return s.length===0?[]:s.map(([i,t])=>{const r=Object.prototype.hasOwnProperty.call(o,i),l=Object.prototype.hasOwnProperty.call(n,i);return` @${i} -> ${t}${r&&l?" (session overrides config)":r?" (session)":""}`})}function N(e){return e.length===0?[]:e.map(n=>{const o=[n.specifier?`specifier=${n.specifier}`:null,n.ending?`ending=${n.ending}`:null,n.builtin?`builtin=${n.builtin}`:null,n.unusedImports?`unusedImports=${n.unusedImports}`:null].filter(s=>s!==null);return` ${n.scope}: ${o.length>0?o.join(" "):"defaults"}`})}function w(e){return e.length===0?[]:e.map(n=>{const o=[n.mode?`to=${n.mode}`:null,n.preferAlias?`preferAlias=${n.preferAlias}`:null,n.exclude.length>0?`exclude=${n.exclude.join(" ")}`:null].filter(s=>s!==null);return` ${n.scope??"*"}: ${o.length>0?o.join(" "):"defaults"}`})}function c(e){return e.map(n=>` ${n}`)}
@@ -0,0 +1,3 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.runDiagnosticsCommand=m;const a=require("../shared/errors");async function m(t){const o=t[0]??"status";if(o!=="timeout-stream")throw new a.CliError("UNKNOWN_DIAGNOSTICS_COMMAND",`Unknown diagnostics command: ${o}`,{availableCommands:["timeout-stream"]});await l(t.slice(1))}async function l(t){const o=w(t),e=u(t,"--delay-ms",6e4),s=u(t,"--interval-ms",1e3),n=Math.max(1,Math.min(10,Math.floor(e/Math.max(1,s))));f(),r(o,`diagnostics.timeout-stream started mode=${o} delayMs=${e}`);for(let i=1;i<=n;i+=1)await d(s),r(o,`diagnostics.timeout-stream tick ${i}/${n}`);const c=e-n*s;c>0&&await d(c),r(o,"diagnostics.timeout-stream completed")}function f(){const t=o=>{if(o.code!=="EPIPE")throw o};process.stdout.on("error",t),process.stderr.on("error",t)}function r(t,o){(t==="stdout"||t==="both")&&process.stdout.write(`${o}
2
+ `),(t==="stderr"||t==="both")&&process.stderr.write(`${o}
3
+ `),t==="console"&&(console.log(o),console.error(o))}function w(t){const o=t.indexOf("--mode"),e=o>=0?t[o+1]:"stderr";if(e==="stdout"||e==="stderr"||e==="both"||e==="console")return e;throw new a.CliError("INVALID_DIAGNOSTICS_MODE","diagnostics timeout-stream --mode expects stdout, stderr, both, or console.")}function u(t,o,e){const s=t.indexOf(o);if(s<0)return e;const n=Number(t[s+1]);return Number.isFinite(n)&&n>=0?n:e}function d(t){return new Promise(o=>setTimeout(o,t))}
@@ -0,0 +1 @@
1
+ "use strict";var k=exports&&exports.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),N=exports&&exports.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),b=exports&&exports.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&k(n,e,r[s]);return N(n,e),n}})();Object.defineProperty(exports,"__esModule",{value:!0}),exports.runDoctor=q;const i=b(require("node:fs")),a=b(require("node:path")),E=require("node:child_process"),c=require("../config/env-vars"),f=require("../shared/diagnostic-catalog"),d=require("../shared/hints"),w=require("../managed-host/extension-vsix-resolver"),x=require("../managed-host/serve-web-autostart"),D=require("./ping"),O=require("../shared/agent-text"),j=require("../shared/errors"),A=require("../diagnostics/readiness-text"),v=require("../runtime/bundled-node"),V=require("../runtime/managed-runtime-provisioning"),M=["code.cmd","code.exe","code"],L=["code"];function l(t,e){return t.ok||!e?t:{...t,code:e.code,...e.hints&&e.hints.length>0?{hints:e.hints}:{}}}async function q(t){const e=[],n=a.resolve(__dirname,"..",".."),r=Z(),s=t.runtime===!0;s&&(0,V.ensureManagedRuntimeProvisioned)(n),e.push(B()),e.push(F(n)),e.push(W(n,r)),e.push(K(n,r)),e.push(X(n)),e.push(G(n)),e.push($(n)),e.push(z(s)),s&&e.every(u=>u.severity!=="required"||u.ok)&&e.push(...await R(t.cwd));const o=e.filter(u=>u.severity==="required"&&!u.ok),g=e.filter(u=>u.severity==="optional"&&!u.ok),p={ok:o.length===0,command:"doctor",mode:s?"runtime-install-gate":"static",cwd:a.resolve(t.cwd),generatedAt:new Date().toISOString(),platform:{node:process.version,platform:process.platform,arch:process.arch},packageRoot:n,repoRoot:r,summary:{checkCount:e.length,passedCount:e.filter(u=>u.ok).length,failedRequiredCount:o.length,failedOptionalCount:g.length},checks:e};return t.json===!0?p:(0,O.attachAgentText)(p,(0,A.formatDoctorText)(p,{verbose:t.verbose===!0}))}async function R(t){const e=[];let n=!1;try{const r=await(0,x.startManagedServeWebForCwd)(t);n=!0,e.push({id:"managed-runtime-start",ok:!0,severity:"required",message:"Managed IDE runtime starts and activates the bridge.",details:H(r)})}catch(r){return e.push(S("managed-runtime-start","Managed IDE runtime failed to start or activate the bridge.",r)),e}try{const r=await(0,D.runPing)(t);e.push({id:"bridge-ping",ok:!0,severity:"required",message:"Bridge ping succeeds through the managed runtime.",details:T(r)})}catch(r){e.push(S("bridge-ping","Bridge ping failed through the managed runtime.",r))}if(n)try{const r=await(0,x.stopManagedServeWebForCwd)(t);e.push({id:"managed-runtime-stop",ok:r.stopped===!0,severity:"required",message:r.stopped===!0?"Managed IDE runtime stops cleanly.":"Managed IDE runtime stop did not report a stopped runtime.",details:r})}catch(r){e.push(S("managed-runtime-stop","Managed IDE runtime stop failed.",r))}return e}function S(t,e,n){const r=n instanceof j.CliError?n:null;return{id:t,ok:!1,severity:"required",message:e,code:r?.code??"DOCTOR_RUNTIME_CHECK_FAILED",details:{error:n instanceof Error?n.message:String(n),...r?.details&&typeof r.details=="object"&&!Array.isArray(r.details)?{details:r.details}:{}},hints:r?.details&&typeof r.details=="object"&&!Array.isArray(r.details)&&Array.isArray(r.details.hints)?r.details.hints:(0,f.buildAutoStartHints)()}}function H(t){const e=t.metadata&&typeof t.metadata=="object"&&!Array.isArray(t.metadata)?t.metadata:{},n=t.artifacts&&typeof t.artifacts=="object"&&!Array.isArray(t.artifacts)?t.artifacts:{};return{hostId:typeof t.hostId=="string"?t.hostId:null,hostKind:typeof t.hostKind=="string"?t.hostKind:e.hostKind??null,reused:t.reused===!0,codeCommand:typeof t.codeCommand=="string"?t.codeCommand:e.codeCommand??null,codeCommandSource:typeof t.codeCommandSource=="string"?t.codeCommandSource:e.codeCommandSource??null,runDir:typeof t.runDir=="string"?t.runDir:e.runDir??null,logsDir:typeof n.logsDir=="string"?n.logsDir:e.logsDir??null,instanceId:typeof e.instanceId=="string"?e.instanceId:null,serveWebPid:typeof e.serveWebPid=="number"?e.serveWebPid:null,browserPid:typeof e.browserPid=="number"?e.browserPid:null}}function T(t){const e=t.selectedInstance&&typeof t.selectedInstance=="object"&&!Array.isArray(t.selectedInstance)?t.selectedInstance:{},n=t.response&&typeof t.response=="object"&&!Array.isArray(t.response)?t.response:{};return{instanceId:typeof e.instanceId=="string"?e.instanceId:n.instanceId??null,reason:typeof e.reason=="string"?e.reason:null,matchedWorkspace:typeof e.matchedWorkspace=="string"?e.matchedWorkspace:null,pid:typeof n.pid=="number"?n.pid:null,protocolVersion:typeof n.protocolVersion=="number"?n.protocolVersion:null,extensionVersion:typeof n.extensionVersion=="string"?n.extensionVersion:null}}function B(){const t=Number(process.versions.node.split(".")[0]??"0"),e=Number.isInteger(t)&&t>=20;return l({id:"node-version",ok:e,severity:"required",message:e?"Node.js version is supported.":"Node.js 20 or newer is required.",details:{node:process.version,required:">=20"}},{code:"DOCTOR_NODE_VERSION_UNSUPPORTED",hints:[(0,d.actionHint)("Install Node.js 20 or newer, then retry the CLI command.")]})}function F(t){const e=a.join(t,"package.json"),n=a.join(t,"dist","bin","aib.js"),r=i.existsSync(e)&&i.existsSync(n);return l({id:"cli-package-root",ok:r,severity:"required",message:r?"CLI package root looks complete.":"CLI package root is missing package metadata or the built bin.",details:{packageRoot:t,packageJsonPath:e,packageJsonExists:i.existsSync(e),binPath:n,binExists:i.existsSync(n)}},{code:"DOCTOR_CLI_PACKAGE_INCOMPLETE",hints:[(0,d.commandHint)("npm run cli:build","Build the local CLI package."),(0,d.actionHint)("For an installed package, reinstall the CLI package.")]})}function W(t,e){const n=a.join(t,"dist","managed-host","manage-serve-web-host.cjs"),r=e?a.join(e,"scripts","managed-host","manage-serve-web-host.cjs"):null,s=_(c.CLI_ENV.managedHostScript),o=!!(s&&i.existsSync(s)||i.existsSync(n)||r&&i.existsSync(r));return l({id:"managed-host-assets",ok:o,severity:"required",message:o?"Managed host assets are available.":"Managed host assets were not found.",details:{env:c.CLI_ENV.managedHostScript,envScriptPath:s,envScriptExists:s?i.existsSync(s):!1,packagedScriptPath:n,packagedScriptExists:i.existsSync(n),repoScriptPath:r,repoScriptExists:r?i.existsSync(r):!1}},{code:"DOCTOR_MANAGED_HOST_ASSETS_MISSING",hints:(0,f.buildAutoStartHints)()})}function K(t,e){try{const n=(0,w.resolveExtensionVsixPath)({packageRoot:t,repoRoot:e}),r=i.existsSync(n.path);return l({id:"extension-vsix",ok:r,severity:"required",message:r?"Extension VSIX is available.":"Extension VSIX path resolved but the file does not exist.",details:{...n,exists:r}},{code:"DOCTOR_EXTENSION_VSIX_MISSING",hints:[(0,d.configHint)(c.CLI_ENV.extensionVsix,"Point to an existing packaged VSIX artifact."),(0,d.commandHint)("npm --prefix packages/extension run package:vsix","Build a local VSIX artifact.")]})}catch(n){return{id:"extension-vsix",ok:!1,severity:"required",message:"Extension VSIX resolution failed.",code:"DOCTOR_EXTENSION_VSIX_RESOLUTION_FAILED",details:{error:n instanceof Error?n.message:String(n),code:typeof n=="object"&&n!==null&&"code"in n?String(n.code):null},hints:(0,f.buildAutoStartHints)()}}}function G(t){const e=process.env[c.CLI_ENV.ideCommand]?.trim(),n=process.env[c.CLI_ENV.managedHostKind]?.trim()||U(t),r=_(c.CLI_ENV.codeServerPath),s=a.join(t,"runtimes","code-server","node_modules","code-server","out","node","entry.js"),o=(0,v.resolveNodeRuntime)(t),g=i.existsSync(s)?`${o.command} ${s}`:null,p=a.join(t,"runtimes","code-server","bin",process.platform==="win32"?"code-server.cmd":"code-server"),u=[r,g,p,"code-server"].filter(m=>!!m),y=e?[e]:n==="code-server"?u:process.platform==="win32"?M:L,h=y.map(m=>({candidate:m,result:m===g?{ok:!0,path:s}:C(m)})).find(m=>m.result.ok),I=!!h;return l({id:"ide-command",ok:I,severity:"required",message:I?"VS Code CLI command is available.":"VS Code CLI command was not found.",details:{env:c.CLI_ENV.ideCommand,codeServerEnv:c.CLI_ENV.codeServerPath,hostKindEnv:c.CLI_ENV.managedHostKind,hostKind:n,explicitIdeCommand:e||null,nodeRuntimeCommand:o.command,nodeRuntimeSource:o.source,candidates:y,resolvedCommand:h?.candidate??null,resolvedPath:h?.result.path??null}},{code:"DOCTOR_IDE_COMMAND_MISSING",hints:[(0,d.configHint)(c.CLI_ENV.ideCommand,"Set an explicit VS Code-compatible CLI command path."),(0,d.configHint)(c.CLI_ENV.codeServerPath,"Set an explicit Coder code-server executable path when using the code-server managed host."),(0,d.actionHint)("Install VS Code, install Coder code-server, or include a packaged code-server runtime.")]})}function X(t){const e=(0,v.findPackagedNodeRuntime)(t),n=(0,v.resolveNodeRuntime)(t),r=i.existsSync(a.join(t,"runtimes","code-server","node_modules","code-server","out","node","entry.js"));return l({id:"managed-runtime-node",ok:!!e||!r,severity:r?"required":"optional",message:e?"Bundled Node runtime is available for managed runtime.":r?"Bundled Node runtime is missing for package-local code-server.":"Bundled Node runtime is not needed because package-local code-server is not present.",details:{env:c.CLI_ENV.nodePath,packagedNodePath:e,resolvedCommand:n.command,resolvedSource:n.source,packagedCodeServerPresent:r}},{code:"DOCTOR_MANAGED_RUNTIME_NODE_MISSING",hints:[(0,d.commandHint)("node scripts/runtime/provision-managed-runtimes.cjs --node","Provision the bundled Node runtime."),(0,d.actionHint)("For installed packages, reprovision or reinstall the managed runtime bundle.")]})}function U(t){const e=a.join(t,"runtimes","code-server","node_modules","code-server","out","node","entry.js");return i.existsSync(e)?"code-server":null}function $(t){const e=_(c.CLI_ENV.chromePath),r=[e,J(t),"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe","C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe","C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe","C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe","google-chrome","chromium","chromium-browser","microsoft-edge"].filter(o=>!!o).map(o=>({candidate:o,result:C(o)})).find(o=>o.result.ok),s=!!r;return l({id:"headless-browser",ok:s,severity:"required",message:s?"Headless browser command is available.":"Chrome or Edge was not found for managed serve-web activation.",details:{env:c.CLI_ENV.chromePath,explicitChromePath:e,resolvedCommand:r?.candidate??null}},{code:"DOCTOR_HEADLESS_BROWSER_MISSING",hints:[(0,d.configHint)(c.CLI_ENV.chromePath,"Set an explicit Chrome or Edge executable path."),(0,d.actionHint)("Install Chrome, Edge, Chromium, or another compatible headless browser.")]})}function J(t){const e=[a.join(t,"runtimes","browser"),a.join(t,"runtimes","chrome"),a.join(t,"runtimes","chromium")],n=process.platform==="win32"?new Set(["chrome.exe","chromium.exe","msedge.exe"]):new Set(["chrome","chromium"]);for(const r of e){const s=P(r,n,5);if(s)return s}return null}function P(t,e,n){if(!i.existsSync(t)||n<0)return null;let r;try{r=i.readdirSync(t,{withFileTypes:!0})}catch{return null}for(const s of r){const o=a.join(t,s.name);if(s.isFile()&&e.has(s.name)&&C(o).ok)return o}for(const s of r){if(!s.isDirectory())continue;const o=P(a.join(t,s.name),e,n-1);if(o)return o}return null}function z(t){const e=process.platform==="win32"||process.platform==="linux";return l({id:"managed-runtime-platform",ok:e||t!==!0,severity:t?"required":"optional",message:e?"Managed serve-web auto-start is supported on this platform.":"Managed serve-web auto-start is currently supported on Windows and Linux.",details:{platform:process.platform,runtimeRequested:t}},{code:"DOCTOR_MANAGED_RUNTIME_PLATFORM_UNSUPPORTED",hints:[(0,d.actionHint)("Run static doctor checks only, or use a Windows/Linux environment for managed runtime.")]})}function Z(){const t=[a.resolve(__dirname),process.cwd()];for(const e of t){let n=e;for(;;){const r=a.join(n,"scripts","managed-host","manage-serve-web-host.cjs"),s=a.join(n,"package.json");if(i.existsSync(r)&&i.existsSync(s))return n;const o=a.dirname(n);if(o===n)break;n=o}}return null}function _(t){const e=process.env[t];return e&&e.trim()?a.resolve(e.trim()):null}function C(t){if(Q(t))return{ok:i.existsSync(t),status:i.existsSync(t)?0:1,error:null};const e=process.platform==="win32"?(0,E.spawnSync)("where.exe",[t],{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","pipe"]}):(0,E.spawnSync)("sh",["-lc",`command -v "${t.replace(/"/g,'\\"')}"`],{encoding:"utf8",stdio:["ignore","pipe","pipe"]});return{ok:e.status===0,status:e.status,error:e.error?e.error.message:null}}function Q(t){return t.includes("\\")||t.includes("/")||/^[A-Za-z]:/.test(t)}
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ensureSelectorResolvable=g,exports.ensureSelectorsResolvable=S;const m=require("../shared/types"),b=require("../shared/errors"),u=require("./inspect-symbol-query");function c(t,e,s,i){return t.filter(o=>o.name===e).map(o=>{const n=f(typeof o.kind=="string"?o.kind:"");return n?`${s[n]}${i}${e}`:`unknown${i}${e}`})}function f(t){const e=t.toLowerCase();return e==="typeparameter"||e==="typealias"?"type":m.ENTITY_KIND_IDS.includes(e)?e:null}async function g(t,e,s,i,o={}){if(s.symbolKind)return;const n=await(0,u.queryTopLevelInspectSymbols)(t,e,o);n.filter(r=>r.name===s.symbolName).length<=1||y([{entity:s.symbolName,suggestions:c(n,s.symbolName,i.entityKindAliases,i.selectorSeparator)}])}async function S(t,e,s,i,o={}){const n=[],l=await(0,u.queryTopLevelInspectSymbols)(t,e,o);for(const r of s){if(r.symbolKind)continue;l.filter(a=>a.name===r.symbolName).length>1&&n.push({entity:r.symbolName,suggestions:c(l,r.symbolName,i.entityKindAliases,i.selectorSeparator)})}n.length!==0&&y(n)}function y(t){const e=t[0];throw new b.CliError("AMBIGUOUS_ENTITY_SELECTOR",t.length===1?`Ambiguity detected for entity "${e.entity}".`:`Ambiguity detected for ${t.length} entities.`,{ambiguities:t,suggestions:e.suggestions})}
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.runExecutionCommand=R;const d=require("./apply-module-plan"),p=require("./module-plan-cache"),f=require("./refactor-batch"),h=require("./refactor-batch-execution-cache"),m=require("./rename-entities"),_=require("./rename-execution-cache"),E=require("../shared/errors");function R(t,e){const[n="status",...a]=e;if(n==="status"){const c=N(a,"--execution")??y(a)??"last";return P(t,c)}throw new E.CliError("UNKNOWN_EXECUTION_COMMAND",`Unknown execution command: ${n}`,{availableCommands:["execution status"]})}function P(t,e){if(e==="last"){const r=x(t,"last"),o=(0,h.tryReadRefactorBatchExecutionStatus)(t,"last"),u=(0,_.tryReadRenameExecutionStatus)(t,"last");if(r||o||u){const s=r?Date.parse(r.updatedAt):0,i=o?Date.parse(o.updatedAt):0,l=u?Date.parse(u.updatedAt):0;return l>s&&l>i?(0,m.readCachedRenameExecution)(t,"last"):i>s?(0,f.readCachedRefactorBatchExecution)(t,"last"):(0,d.readCachedModulePlanExecution)(t,"last")}C(e)}if((0,_.tryReadRenameExecutionStatus)(t,e))return(0,m.readCachedRenameExecution)(t,e);if((0,h.tryReadRefactorBatchExecutionStatus)(t,e))return(0,f.readCachedRefactorBatchExecution)(t,e);if(x(t,e))return(0,d.readCachedModulePlanExecution)(t,e);C(e)}function x(t,e){try{return(0,p.readModulePlanExecutionStatus)(t,e)}catch{return null}}function C(t){throw new E.CliError("EXECUTION_NOT_FOUND",`Execution status not found: ${t}`,{executionId:t})}function N(t,e){const n=t.indexOf(e);if(n<0)return null;const a=t[n+1];return a&&!a.startsWith("--")?a:null}function y(t){return t.find(e=>!e.startsWith("--"))??null}
@@ -0,0 +1,3 @@
1
+ "use strict";var k=exports&&exports.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.runFeedbackCommand=w;const c=k(require("node:fs")),l=k(require("node:path")),b=require("node:crypto"),m=require("../config/workspace-root"),a=require("../observability/config"),y=require("../observability/context"),_=require("../observability/recent"),d=require("../shared/agent-text"),p=require("../shared/errors"),g=["Thanks for the feedback.","Thanks, we will use this feedback.","Feedback received.","Noted, thank you.","Thanks, this helps improve aib."];function w(e,t,n="feedback"){const r=t[0]??"";if(r==="list"){const i=I(t.slice(1));return(0,d.attachAgentText)(i,F(i))}if(r==="where"){const i=(0,a.feedbackFilePath)();return(0,d.attachAgentText)({file:i},`feedback file: ${i}`)}return r==="add"||r==="write"?h(e,t.slice(1),n):r==="help"||r==="--help"?{command:n,usage:[`aib ${n} "kind | message"`,`aib ${n} add "kind | message"`,`aib ${n} list`,`aib ${n} where`]}:h(e,t,n)}function h(e,t,n){const r=A(t),i=(0,y.buildCorrelationContext)(e),f=(0,_.readRecentTraceCalls)(e).slice(0,5).map(s=>({traceCallId:s.traceCallId,...s.traceRunId?{traceRunId:s.traceRunId}:{},command:s.command,ok:s.ok,finishedAt:s.finishedAt,...s.executionId?{executionId:s.executionId}:{}})),o={id:`fb_${(0,b.randomUUID)().replace(/-/g,"").slice(0,8)}`,createdAt:new Date().toISOString(),cwd:l.default.resolve(e),workspaceRoot:(0,m.resolveWorkspaceRoot)(e)?.root??null,...typeof i.workspaceId=="string"?{workspaceId:i.workspaceId}:{},...typeof i.workspacePathHash=="string"?{workspacePathHash:i.workspacePathHash}:{},...typeof i.sessionId=="string"?{sessionId:i.sessionId}:{},...typeof i.sessionSource=="string"?{sessionSource:i.sessionSource}:{},...f.length>0?{recentTraceCalls:f}:{},kind:r.kind,message:r.message,command:n},u=(0,a.feedbackFilePath)();return c.default.mkdirSync(l.default.dirname(u),{recursive:!0}),c.default.appendFileSync(u,`${JSON.stringify(o)}
2
+ `,"utf8"),(0,d.attachAgentText)({saved:o.id,kind:o.kind,topic:o.kind},C(o))}function A(e){const t=e.join(" ").trim();if(!t)throw new p.CliError("FEEDBACK_MESSAGE_REQUIRED",'Usage: aib feedback "kind | message"');const n=t.indexOf("|");if(n>=0){const r=t.slice(0,n).trim(),i=t.slice(n+1).trim();if(r&&i)return{kind:r,message:i}}throw new p.CliError("FEEDBACK_MESSAGE_REQUIRED",'Usage: aib feedback "kind | message"')}function I(e){const t=S(e),n=(0,a.feedbackFilePath)(),r=E(n).slice(-t).reverse();return{file:n,count:r.length,feedback:r}}function S(e){const t=e.indexOf("--limit");if(t<0)return 20;const n=Number(e[t+1]);return Number.isInteger(n)&&n>0?n:20}function E(e){return c.default.existsSync(e)?c.default.readFileSync(e,"utf8").split(/\r?\n/).filter(Boolean).map(t=>{try{const n=JSON.parse(t);return R(n)}catch{return null}}).filter(t=>t!==null):[]}function F(e){const t=Array.isArray(e.feedback)?e.feedback.filter(x):[];return t.length===0?"feedback empty":[`feedback ${t.length}`,...t.map(n=>`${String(n.id)} ${String(n.kind)}: ${String(n.message)}`)].join(`
3
+ `)}function x(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function R(e){if(!e||typeof e!="object")return null;const t=typeof e.kind=="string"?e.kind:e.topic;return typeof e.id!="string"||typeof e.createdAt!="string"||typeof e.cwd!="string"||typeof e.message!="string"||typeof t!="string"?null:{id:e.id,createdAt:e.createdAt,cwd:e.cwd,workspaceRoot:typeof e.workspaceRoot=="string"?e.workspaceRoot:null,kind:t,message:e.message,command:typeof e.command=="string"?e.command:"save"}}function C(e){const t=`${e.kind}|${e.message}`;let n=0;for(let r=0;r<t.length;r+=1)n=n*31+t.charCodeAt(r)>>>0;return g[n%g.length]}
@@ -0,0 +1 @@
1
+ "use strict";var c=exports&&exports.__createBinding||(Object.create?(function(a,e,r,t){t===void 0&&(t=r);var n=Object.getOwnPropertyDescriptor(e,r);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(a,t,n)}):(function(a,e,r,t){t===void 0&&(t=r),a[t]=e[r]})),o=exports&&exports.__setModuleDefault||(Object.create?(function(a,e){Object.defineProperty(a,"default",{enumerable:!0,value:e})}):function(a,e){a.default=e}),s=exports&&exports.__importStar||(function(){var a=function(e){return a=Object.getOwnPropertyNames||function(r){var t=[];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[t.length]=n);return t},a(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var t=a(e),n=0;n<t.length;n++)t[n]!=="default"&&c(r,e,t[n]);return o(r,e),r}})();Object.defineProperty(exports,"__esModule",{value:!0}),exports.runFindImporters=p;const f=s(require("node:path")),l=require("../client/http-client"),_=require("../shared/routes"),d=require("../shared/protocol"),i=require("./shared");async function p(a,e,r={}){const t=await(0,i.resolveCompatibleTargetInstance)(a,d.CLI_COMMAND_IDS.findImporters,r),n=f.normalize(e),u=await(0,l.postJson)(t.entry,_.EXTENSION_ROUTES.findImporters,{targetPath:n},(0,i.extensionRequestOptions)(r));return{ok:!0,selectedInstance:{instanceId:t.entry.instanceId,reason:t.reason,matchedWorkspace:t.matchedWorkspace,port:t.entry.port},response:u}}
@@ -0,0 +1 @@
1
+ "use strict";var l=exports&&exports.__createBinding||(Object.create?(function(o,e,r,t){t===void 0&&(t=r);var n=Object.getOwnPropertyDescriptor(e,r);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(o,t,n)}):(function(o,e,r,t){t===void 0&&(t=r),o[t]=e[r]})),f=exports&&exports.__setModuleDefault||(Object.create?(function(o,e){Object.defineProperty(o,"default",{enumerable:!0,value:e})}):function(o,e){o.default=e}),_=exports&&exports.__importStar||(function(){var o=function(e){return o=Object.getOwnPropertyNames||function(r){var t=[];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[t.length]=n);return t},o(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var t=o(e),n=0;n<t.length;n++)t[n]!=="default"&&l(r,e,t[n]);return f(r,e),r}})();Object.defineProperty(exports,"__esModule",{value:!0}),exports.runFindUnusedImports=h;const p=_(require("node:path")),I=require("../client/http-client"),O=require("../shared/routes"),b=require("../shared/protocol"),i=require("./shared"),s=require("../shared/metrics");async function h(o,e,r={},t){const n=(0,s.metricsNow)(),a=await(0,i.resolveCompatibleTargetInstance)(o,b.CLI_COMMAND_IDS.findUnusedImports,r);(0,s.recordSpan)(t,"command.findUnusedImports.resolveTargetInstance",n);const c=p.normalize(e),u=(0,s.metricsNow)(),d=await(0,I.postJson)(a.entry,O.EXTENSION_ROUTES.findUnusedImports,{sourceFile:c},(0,i.extensionRequestOptions)({...r,metricsEnabled:!!t}));return(0,s.recordSpan)(t,"command.findUnusedImports.transport",u),{ok:!0,selectedInstance:{instanceId:a.entry.instanceId,reason:a.reason,matchedWorkspace:a.matchedWorkspace,port:a.entry.port},response:d}}
@@ -0,0 +1,6 @@
1
+ "use strict";var m=exports&&exports.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),S=exports&&exports.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),g=exports&&exports.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(n[n.length]=i);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),i=0;i<n.length;i++)n[i]!=="default"&&m(r,e,n[i]);return S(r,e),r}})();Object.defineProperty(exports,"__esModule",{value:!0}),exports.runGenerateDocsCommand=b;const s=g(require("node:fs")),c=g(require("node:path")),w=require("./help-command"),p=require("../shared/agent-text"),l=require("../shared/errors"),E=c.join("docs","agent");function b(t,e){const r=j(e),n=(0,w.resolveHelpRoot)(),i=c.resolve(t,D(r.targetParent)),a=c.join(i,"aib"),o=s.existsSync(a),u=O(t,a);if(!r.yes)return(0,p.attachAgentText)({operation:"generate-docs",dryRun:!0,target:a,targetExists:o,helpSource:n.source},v(r,u,o));if(o&&!r.force)throw new l.CliError("GENERATED_DOCS_TARGET_EXISTS",`${u} already exists.`,{target:a,next:[`aib generate-docs ${d(r)}-y --force`.replace(/\s+/g," ").trim(),"aib generate-docs -t <other-path> -y"]});h(n.dir),o&&s.rmSync(a,{recursive:!0,force:!0});const f=A(n.dir,a),y=T(n.dir,`${P(u)}/README.md`),_=[`generated: ${u}`,`source: ${n.source}`,`${f.length} files written`,"","Add one of these to AGENTS.md or CLAUDE.md:","",y].join(`
2
+ `);return(0,p.attachAgentText)({operation:"generate-docs",dryRun:!1,target:a,helpSource:n.source,filesWritten:f},_)}function j(t){let e=E,r=!1,n=!1,i=!1;for(let a=0;a<t.length;a+=1){const o=t[a];if(o){if(o==="-y"||o==="--yes"){n=!0;continue}if(o==="--force"){i=!0;continue}if(o==="-t"||o==="--target"||o==="--to"){const u=t[a+1];if(!u)throw new l.CliError("MISSING_FLAG_VALUE",`Expected a value after ${o}.`);e=u,r=!0,a+=1;continue}if(o==="help"||o==="--help")return{targetParent:e,targetProvided:r,yes:n,force:i};throw new l.CliError("UNKNOWN_GENERATE_DOCS_FLAG",`Unknown aib generate-docs flag: ${o}`,{availableFlags:["-y","--yes","-t <path>","--target <path>","--force"]})}}return{targetParent:e,targetProvided:r,yes:n,force:i}}function v(t,e,r){return r?[`${e} already exists.`,"Refusing to overwrite generated docs.","","No files written.","","To replace it:",`aib generate-docs ${d(t)}-y --force`.replace(/\s+/g," ").trim(),"","For another parent path:","aib generate-docs -t docs2 -y"].join(`
3
+ `):t.targetProvided?[`target: ${e}`,"","No files written.","","To generate docs there:",`aib generate-docs ${d(t)}-y`.replace(/\s+/g," ").trim()].join(`
4
+ `):["path was not provided.",`Default target: ${e}`,"","No files written.","","To generate docs there:","aib generate-docs -y","","For another parent path:","aib generate-docs -t docs"].join(`
5
+ `)}function A(t,e){h(t);const r=c.join(t,"docs");s.mkdirSync(e,{recursive:!0});const n=[],i=c.join(t,"bootstrap.md");if(s.existsSync(i)){const o=c.join(e,"README.md");s.copyFileSync(i,o),n.push(o)}for(const o of s.readdirSync(r,{withFileTypes:!0}).sort((u,f)=>u.name.localeCompare(f.name))){if(!o.isFile()||!o.name.endsWith(".md"))continue;const u=c.join(r,o.name),f=c.join(e,o.name);s.copyFileSync(u,f),n.push(f)}const a=c.join(t,"help-meta.json");if(s.existsSync(a)){const o=c.join(e,"help-meta.json");s.copyFileSync(a,o),n.push(o)}return n}function h(t){const e=c.join(t,"docs");if(!s.existsSync(e))throw new l.CliError("HELP_DOCS_NOT_FOUND","Generated docs were not found in the active help bundle.",{docsDir:e})}function T(t,e){const r=c.join(t,"snippets","agents.md");return s.existsSync(r)?s.readFileSync(r,"utf8").trim().replaceAll("{{docsPath}}",e):["Recommended:",`For TS/JS code work, use aib. Start with ${e}.`,"","Minimal:",`Use ${e} when working with TS/JS code.`].join(`
6
+ `)}function d(t){return t.targetProvided?`-t ${t.targetParent} `:""}function D(t){const e=t.trim();if(!e)throw new l.CliError("MISSING_TARGET_PATH","Expected a target path.");return e.replace(/[\\/]+$/,"")}function O(t,e){const r=c.relative(t,e);return!r||r.startsWith("..")||c.isAbsolute(r)?e:r||"."}function P(t){return t.replace(/\\/g,"/")}
@@ -0,0 +1,3 @@
1
+ "use strict";var m=exports&&exports.__createBinding||(Object.create?(function(t,e,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,i,s)}):(function(t,e,n,i){i===void 0&&(i=n),t[i]=e[n]})),g=exports&&exports.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),u=exports&&exports.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var i=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(i[i.length]=s);return i},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var i=t(e),s=0;s<i.length;s++)i[s]!=="default"&&m(n,e,i[s]);return g(n,e),n}})();Object.defineProperty(exports,"__esModule",{value:!0}),exports.runHelpCommand=v,exports.resolveHelpRoot=l;const r=u(require("node:fs")),c=u(require("node:path")),a=require("../content/content-bundle"),p=require("../shared/agent-text"),y=require("../shared/errors"),_=new Map([["inspect file","inspect.file"],["inspect imports","inspect.imports"],["inspect exports","inspect.exports"],["inspect members","inspect.members"],["inspect code","inspect.code"],["inspect deps","inspect.deps"],["inspect dependencies","inspect.deps"],["inspect usages","inspect.usages"],["inspect usage","inspect.usages"],["inspect graph","inspect.graph"],["inspect tree","inspect.tree"],["inspect duplicates","inspect.duplicates"],["inspect duplicate","inspect.duplicates"],["refactor batch","refactor.batch"],["module plan","modulePlan"],["moduleplan","modulePlan"]]),d=["help-format","basics","dsl","patterns","session","prefs","selectors","inspect","inspect file","inspect imports","inspect exports","inspect members","inspect code","inspect deps","inspect usages","inspect graph","inspect tree","inspect duplicates","mutation","imports normalize","rename","move","modulePlan","refactor batch","view","qr"];function v(t){if(O(t))return C();const e=j(t);if(!e)return H();const n=l(),i=c.join(n.dir,e.file);if(!r.existsSync(i))throw new y.CliError("HELP_TOPIC_NOT_FOUND",`Help topic not found: ${e.id}`,{topic:e.id,helpRoot:n.dir,available:d});const s=r.readFileSync(i,"utf8").trim();return(0,p.attachAgentText)({operation:"help",topic:e.id,source:n.source},s)}function O(t){const e=t.filter(n=>n!=="help");return e.length===1&&e[0]==="status"}function H(){const t=["Start here if this is your first AIB pass:","aib help bootstrap","","Help conventions:","aib help help-format","","Recommended after context compaction:","aib help basics","aib help patterns","","Use focused help when you only need one area:","aib help session","aib help prefs","aib help selectors","aib help dsl","aib help inspect","aib help mutation","","Feature help:","aib help inspect file","aib help inspect imports","aib help inspect exports","aib help inspect members","aib help inspect code","aib help inspect deps","aib help inspect usages","aib help inspect graph","aib help inspect tree","aib help inspect duplicates","aib help imports normalize","aib help rename","aib help move","aib help modulePlan","aib help refactor batch","aib help view","aib help qr"].join(`
2
+ `);return(0,p.attachAgentText)({operation:"help",topic:"index",available:d},t)}function j(t){const e=t.filter(s=>s!=="help");if(e.length===0)return null;if(e.includes("--full"))return{id:"full",file:"full.md"};const n=e.filter(s=>!s.startsWith("--")).join(" ").trim();if(!n)return null;if(n==="bootstrap")return{id:"bootstrap",file:"bootstrap.md"};const i=_.get(n.toLowerCase())??n.replace(/\s+/g,".");return{id:i,file:c.join("topics",`${i}.md`)}}function C(){const t=l(),e=S(t.dir),n=(0,a.collectContentCandidates)(),i=e&&f(e.topics)?Object.keys(e.topics).length:$(t.dir),s=typeof e?.contentHash=="string"?e.contentHash:void 0,h=["aib help status","",`source: ${t.source}`,`path: ${t.dir}`,`assets: ${(0,a.directoryHasHelp)(t.dir)?"ok":"missing"}`,`metadata: ${e?"ok":"missing help-meta.json"}`,...typeof e?.helpVersion=="string"?[`version: ${e.helpVersion}`]:[],...typeof e?.generatedAt=="string"?[`generatedAt: ${e.generatedAt}`]:[],...typeof e?.sourceCommit=="string"?[`sourceCommit: ${e.sourceCommit}`]:[],...s?[`contentHash: ${P(s)}`]:[],`topics: ${i}`,"","checked:",...n.map(o=>{const b=o.valid?"ok":`skip (${o.reason??"invalid"})`;return`${o.source}: ${b} ${o.dir}`})].join(`
3
+ `);return(0,p.attachAgentText)({operation:"help.status",source:t.source,path:t.dir,assetsOk:(0,a.directoryHasHelp)(t.dir),metadataOk:e!==null,topicCount:i,meta:e??null,candidates:n},h)}function l(){return(0,a.resolveContentRoot)()}function S(t){const e=c.join(t,"help-meta.json");if(!r.existsSync(e))return null;try{const n=JSON.parse(r.readFileSync(e,"utf8"));return f(n)?n:null}catch{return null}}function $(t){const e=c.join(t,"topics");return r.existsSync(e)?r.readdirSync(e).filter(n=>n.endsWith(".md")).length:0}function P(t){return t.replace(/^sha256:/,"sha256:").slice(0,19)}function f(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.runImportsCommand=_;const o=require("../shared/errors"),d=require("./add-missing-imports"),u=require("./find-importers"),l=require("./find-unused-imports"),c=require("./normalize-imports");async function _(e,p,a,s={},m){const[n="help",...i]=p;switch(n){case"--help":case"help":return f();case"normalize":return(0,c.runNormalizeImports)(e,i,a);case"addMissing":case"add-missing":return(0,d.runAddMissingImports)(e,a,s,i);case"unused":{const r=i.find(t=>!t.startsWith("--"));if(!r)throw new o.CliError("MISSING_FILE_PATH","imports unused expects a source file path.");return(0,l.runFindUnusedImports)(e,r,s,m)}case"importers":{const r=i.find(t=>!t.startsWith("--"));if(!r)throw new o.CliError("MISSING_TARGET_PATH","imports importers expects a target file or directory path.");return(0,u.runFindImporters)(e,r,s)}default:throw new o.CliError("UNKNOWN_IMPORTS_COMMAND",`Unknown imports command: ${n}`,{availableCommands:["normalize","addMissing","unused","importers","help"]})}}function f(){return{ok:!0,command:"imports",usage:["aib imports normalize preview <file-or-dir> --to alias|shortestAlias|relative","aib imports normalize show <previewId> [--all]","aib imports normalize apply <previewId>","aib imports normalize execute <file-or-dir> --to alias|shortestAlias|relative","aib imports addMissing preview <file-or-dir>","aib imports addMissing apply <previewId>","aib imports addMissing execute <file-or-dir>","aib imports unused <file>","aib imports importers <file-or-directory>"],notes:["normalize is local and can preview/apply/execute path rewrites.","addMissing, unused, and importers are IDE-backed TypeScript/project queries."]}}
@@ -0,0 +1,3 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.runInitSkillUsage=I;const f=require("./shared"),C=require("../shared/protocol");function a(e,n,t){const s=e[n];return s&&s.trim().length>0?s.trim():t}function w(e,n,t,s){const i=a(n,"ping","ping"),r=a(n,"printConfig","printConfig"),c=a(n,"inspect","inspect"),l=a(n,"imports","imports"),p=a(n,"move","move"),u=a(n,"rename","rename"),$=t.class??"c",d=t.interface??"i",m=t.function??"f",g=t.type??"t",o=s||"-";return["# aib skill usage","","Используй этот CLI, когда нужно взаимодействовать с живым IDE instance, а не читать код только через shell.","","## Базовая диагностика","",`- \`${e} ${i}\``,`- \`${e} ${r}\``,`- \`${e} listInstances\``,"","## Полезные операции","",`- Показать сущности файла: \`${e} ${c} file src/foo.ts\``,`- Найти importers файла/директории: \`${e} ${l} importers src/utils\``,`- Найти unused imports: \`${e} ${l} unused src/foo.ts\``,"","## Selector DSL","","Используй compact selectors для сущностей, когда это уместно.","",`- class: \`${$}${o}MyClass\``,`- interface: \`${d}${o}IMyClass\``,`- function: \`${m}${o}helper\``,`- type: \`${g}${o}UserShape\``,"","Если имя в рамках файла уникально, можно передавать selector без kind. Если возникает ambiguity, используй kind-prefix.","","## Move","","Preview:","","```powershell","@'",`{"sourceFile":"src/foo.ts","targetFile":"src/bar.ts","entities":["${$}${o}MyClass","${d}${o}IMyClass","${m}${o}helper"]}`,`'@ | ${e} ${p} toFile preview --stdin`,"```","","Execute:","","```powershell",`${e} ${p} toFile apply <previewId>`,"```","","## Rename","","```powershell","@'",'{"sourceFile":"src/foo.ts","renames":[{"entity":"MyClass","newName":"RenamedClass"},{"entity":"helper","newName":"renamedHelper"}]}',`'@ | ${e} ${u} preview --stdin`,`${e} ${u} apply <previewId>`,"```","","## Notes","","- Запускай CLI из директории проекта или передавай `--cwd`, чтобы корректно выбрался нужный IDE instance.","- Если открыто несколько IDE окон, сначала посмотри `listInstances` или используй `--instance`."].join(`
2
+ `)}function y(e,n,t,s){return["# aib skill usage diagnostic","",`cliName: ${e}`,`selectorSeparator: ${JSON.stringify(s)}`,`methodAliases: ${JSON.stringify(n)}`,`entityKindAliases: ${JSON.stringify(t)}`,"","Diagnostic mode is intentionally compact. Full production output is in buildSkillMarkdownProd."].join(`
3
+ `)}async function I(e){const{cwd:n,resolveOptions:t={},cliName:s="aib"}=e,i=await(0,f.resolveCompatibleTargetInstance)(n,C.CLI_COMMAND_IDS.initSkillUsage,t),r=await(0,f.fetchEffectiveConfig)(i.entry),c=y(s,r.methodAliases,r.entityKindAliases,r.selectorSeparator);return{ok:!0,selectedInstance:{instanceId:i.entry.instanceId,reason:i.reason,matchedWorkspace:i.matchedWorkspace,port:i.entry.port},cliName:s,effectiveConfig:r,markdown:c}}
@@ -0,0 +1,3 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.runInitWorkspace=c;const o=require("../shared/errors"),r=require("../shared/agent-text"),a=require("../config/workspace-root");function c(e,t){const n=u(t),i=(0,a.initWorkspaceRoot)(e,n);return(0,r.attachAgentText)(i,f(i))}function u(e){const t={};for(let n=0;n<e.length;n+=1){if(e[n]==="--session-dir"){const s=e[n+1];if(!s||s.startsWith("--"))throw new o.CliError("MISSING_FLAG_VALUE","Expected a value after --session-dir.");t.sessionDir=s,n+=1;continue}throw new o.CliError("INIT_USAGE","Usage: aib init [--session-dir .tmp/aib]")}return t}function f(e){const t=typeof e.sessionDir=="string"?e.sessionDir:null,n=typeof e["session.ttlCleanMinutes"]=="number"?e["session.ttlCleanMinutes"]:60,i=typeof e["runtime.managedIdeTtlMinutes"]=="number"?e["runtime.managedIdeTtlMinutes"]:15;return t?["aib session defaults configured","","config: aib.json",`workspace.root: ${String(e["workspace.root"]??".")}`,`sessionDir: ${t}`,`new sessions: ${t.replace(/[\\/]+$/,"")}/<name>/**`,`session cleanup: after ${n} minutes of inactivity`,`runtime cleanup: after ${i} minutes of inactivity`,"","Create sessions without --dir:","aib session init --name <name>"].join(`
2
+ `):["aib config created","","created: aib.json",`workspace.root: ${String(e["workspace.root"]??".")}`,"","Set the default session directory:","aib config --session-dir .tmp/aib"].join(`
3
+ `)}
@@ -0,0 +1,5 @@
1
+ "use strict";var X=exports&&exports.__createBinding||(Object.create?(function(e,t,o,n){n===void 0&&(n=o);var s=Object.getOwnPropertyDescriptor(t,o);(!s||("get"in s?!t.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return t[o]}}),Object.defineProperty(e,n,s)}):(function(e,t,o,n){n===void 0&&(n=o),e[n]=t[o]})),Q=exports&&exports.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),Z=exports&&exports.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(o){var n=[];for(var s in o)Object.prototype.hasOwnProperty.call(o,s)&&(n[n.length]=s);return n},e(t)};return function(t){if(t&&t.__esModule)return t;var o={};if(t!=null)for(var n=e(t),s=0;s<n.length;s++)n[s]!=="default"&&X(o,t,n[s]);return Q(o,t),o}})();Object.defineProperty(exports,"__esModule",{value:!0}),exports.isInspectCyclesRequest=ce,exports.runInspectCycles=le,exports.buildCyclesViewResponse=B,exports.appendCycleComponentText=Y;const ee=Z(require("node:path")),te=require("node:crypto"),ne=require("../config/local-config"),E=require("../config/path-display"),A=require("../shared/agent-text"),y=require("../shared/errors"),oe=require("./inspect-graph"),N=require("./session-workspace"),S=10,se=6,O=8,ie=5e3,re=12e4;function ce(e,t){if(e[0]==="cycles")return!0;if(!e.includes("--stdin")||!f(t))return!1;const o=U(t);return o.length>0&&o.some(n=>h(n.op)==="cycles")}function le(e,t,o){const n=(0,E.buildDisplayPathAliases)(e,(0,N.readEffectiveSessionPathAliases)(e)),l=ue(t,o).map(r=>ae(e,r,n)),i=l.length===1?l[0]:{results:l};return(0,A.attachAgentText)(i,I(i))}function ue(e,t){if(e[0]==="cycles")return[fe(e.slice(1))];if(!e.includes("--stdin")||!f(t))throw new y.CliError("INSPECT_CYCLES_SCOPE_REQUIRED","inspect cycles expects scope or files.");const o=U(t);if(o.some(n=>h(n.op)!=="cycles"))throw new y.CliError("INSPECT_CYCLES_MIXED_BATCH_UNSUPPORTED","inspect cycles --stdin expects only cycles requests.");return o.map((n,s)=>de(n,s))}function fe(e){const o=[...e.filter(n=>!n.startsWith("--")&&!Fe(e,n)),...C(e,"--scope"),...C(e,"--scopes")];return L({scopes:o,files:[...C(e,"--file"),...C(e,"--files")],detail:w(R(e,"--detail")),kind:M(R(e,"--kind")),exclude:[...C(e,"--exclude"),...C(e,"--excludes")],limit:q(R(e,"--limit"))??S})}function de(e,t){return L({scopes:a(e.scope)??a(e.scopes)??[],files:a(e.file)??a(e.files)??[],detail:w(e.detail),kind:M(e.kind),exclude:a(e.exclude)??a(e.excludes)??[],limit:q(e.limit)??S,index:t})}function L(e){if(e.scopes.length===0&&e.files.length===0){const t=e.index!==void 0?` at index ${e.index}`:"";throw new y.CliError("INSPECT_CYCLES_SCOPE_REQUIRED",`inspect cycles request${t} expects scope or files.`)}return{scopes:j(e.scopes),files:j(e.files),detail:e.detail,kind:e.kind,exclude:j(e.exclude),limit:e.limit}}function ae(e,t,o){const n=(0,ne.resolveLocalCliConfig)(e),s=t.scopes.length>0?t.scopes:t.files,l=t.files.map(p=>Le(e,p)),i=me();i({phase:"graph",completed:0,message:"building import graph"});const r=(0,oe.buildInspectGraphModel)(e,{scopes:s,depth:t.scopes.length>0?0:se,excludePatterns:[...n.config.inspect.graph.exclude,...t.exclude],symbolUsage:t.detail==="imports"});i({phase:"graph",completed:r.files.length,total:r.files.length,message:"import graph built"});const u=new Set(l),c=pe(r.edges,{onProgress:i}).filter(p=>(u.size===0||p.nodes.some(J=>u.has(J)))&&(t.kind===null||p.kind===t.kind)),d=ke(t,r.files.length,r.edges.length,u.size,c),m=Me(d),g=De(e,t,o),x={ok:!0,op:"cycles",version:1,createdAt:new Date().toISOString(),target:g,request:{scopes:t.scopes,files:t.files,detail:t.detail,...t.kind?{kind:t.kind}:{},limit:t.limit,exclude:t.exclude},componentCount:c.length,summary:V(c),analysis:d,timeoutHint:m,components:c.map(p=>Ee(p,o)),...t.exclude.length>0?{exclude:t.exclude}:{}},D=Ne(JSON.stringify(x),o);D&&(x.paths=D);const W=Oe(x),P=(0,N.saveSessionResultViewJson)(e,W,x),_=B(x,{detail:t.detail,offset:0,limit:t.limit});if(P){_.result=P.saved,_.resultFile=P.file;const p=I(_);if(p)return(0,A.attachAgentText)(_,p)}return _}function me(){return()=>{}}function pe(e,t={}){const o=new Map;for(const i of e){const r=o.get(i.from)??[];r.push(i),o.set(i.from,r)}for(const i of o.values())i.sort((r,u)=>r.to.localeCompare(u.to));const n=Array.from(new Set(e.flatMap(i=>[i.from,i.to]))).sort();t.onProgress?.({phase:"components",completed:0,total:n.length,message:"finding cyclic components"});const s=ge(n,o).filter(i=>i.length>1||ye(i[0]??"",o));t.onProgress?.({phase:"components",completed:n.length,total:n.length,message:`${s.length} cyclic components found`});const l=[];return s.forEach((i,r)=>{const u=Ce(i,o);if(t.onProgress?.({phase:"representatives",completed:r+1,total:s.length,message:"building representative cycles"}),u){const c=he(i,o);l.push({nodes:i,representative:u,kind:T(c),counts:be(c)})}}),l.sort(_e)}function he(e,t){const o=new Set(e);return e.flatMap(n=>(t.get(n)??[]).filter(s=>o.has(s.to)))}function ge(e,t){let o=0;const n=[],s=new Set,l=new Map,i=new Map,r=[];for(const c of e)l.has(c)||u(c);return r.map(c=>c.sort());function u(c){l.set(c,o),i.set(c,o),o+=1,n.push(c),s.add(c);for(const m of t.get(c)??[]){const g=m.to;l.has(g)?s.has(g)&&i.set(c,Math.min(i.get(c)??0,l.get(g)??0)):(u(g),i.set(c,Math.min(i.get(c)??0,i.get(g)??0)))}if(i.get(c)!==l.get(c))return;const d=[];for(;n.length>0;){const m=n.pop();if(s.delete(m),d.push(m),m===c)break}r.push(d)}}function ye(e,t){return(t.get(e)??[]).some(o=>o.to===e)}function Ce(e,t){const o=new Set(e);let n=null;for(const s of e){const l=(t.get(s)??[]).filter(i=>o.has(i.to));for(const i of l){if(i.to===s){n=F(n,{nodes:[s,s],edges:[i],kind:T([i])});continue}const r=xe(i.to,s,t,o);r&&(n=F(n,{nodes:[s,...r.nodes],edges:[i,...r.edges],kind:T([i,...r.edges])}))}}return n}function xe(e,t,o,n){const s=[{node:e,nodes:[e],edges:[]}],l=new Set([e]);for(let i=0;i<s.length;i+=1){const r=s[i];for(const u of o.get(r.node)??[])if(n.has(u.to)){if(u.to===t)return{nodes:[...r.nodes,t],edges:[...r.edges,u]};l.has(u.to)||(l.add(u.to),s.push({node:u.to,nodes:[...r.nodes,u.to],edges:[...r.edges,u]}))}}return null}function F(e,t){return e?t.nodes.length!==e.nodes.length?t.nodes.length<e.nodes.length?t:e:$(t.nodes)<$(e.nodes)?t:e:t}function _e(e,t){const o=v(e.kind)-v(t.kind);if(o!==0)return o;const n=t.nodes.length-e.nodes.length;return n!==0?n:$(e.representative.nodes).localeCompare($(t.representative.nodes))}function v(e){return e==="runtime"?0:e==="mixed"?1:2}function T(e){const t=new Set(e.map(H));return t.size===0||t.has("mixed")||t.has("runtime")&&t.has("type-only")?"mixed":t.has("runtime")?"runtime":"type-only"}function H(e){const t=e.symbols??[];if(t.length===0)return"runtime";let o=!1,n=!1;for(const s of t){if(typeof s=="string"){n=!0;continue}s.usage==="type"?o=!0:n=!0}return o&&n?"mixed":o?"type-only":"runtime"}function be(e){const t={runtime:0,"type-only":0,mixed:0};for(const o of e)t[H(o)]+=1;return t}function $(e){return e.join("\0")}function Ee(e,t){const o=e.nodes.map(s=>k(s,t)),n=Se(e.representative,t);return{kind:e.kind,files:o,fileCount:o.length,edgeCounts:e.counts,cycle:n,chain:h(n.chain)}}function Se(e,t){const o=e.nodes.map(n=>k(n,t));return{kind:e.kind,path:o,chain:o.join(" -> "),imports:e.edges.map(n=>$e(n,t))}}function $e(e,t){const o=k(e.from,t),n=k(e.to,t),s=Ie(e.symbols);return s?`${o} -> ${n}: ${s}`:`${o} -> ${n}`}function Ie(e){const t=(e??[]).map(n=>typeof n=="string"?n:n.name).filter(n=>n.length>0);if(t.length===0)return"";const o=t.slice(0,4);return t.length>o.length?`${o.join(" ")} + ${t.length-o.length} more`:o.join(" ")}function B(e,t={}){if(e.op!=="cycles")throw new y.CliError("INVALID_CYCLES_RESULT","Expected a cycles result artifact.");const o=t.detail??w(ve(e.request,"detail")),n=Array.isArray(e.components)?e.components.filter(f):[],s=t.kind?n.filter(m=>m.kind===t.kind):n,l=s.length,i=Math.max(0,t.offset??0),r=Math.max(1,t.limit??S),u=t.index!==void 0?[s[t.index-1]].filter(f):s.slice(i,i+r),c=t.index!==void 0?0:Math.max(0,l-i-u.length),d={ok:!0,op:"cycles",target:h(e.target)??"",detail:o,componentCount:l,summary:Ae(s),...f(e.analysis)?{analysis:e.analysis}:{},...f(e.timeoutHint)?{timeoutHint:e.timeoutHint}:{},components:u,offset:i,limit:r,...t.index!==void 0?{index:t.index}:{},...c>0?{hidden:c}:{},...t.resultHandle?{result:t.resultHandle}:{},...e.paths?{paths:e.paths}:{}};return(0,A.attachAgentText)(d,I(d))}function ke(e,t,o,n,s){const l=V(s),i=s.reduce((u,c)=>Math.max(u,c.nodes.length),0),r=s.reduce((u,c)=>u+c.representative.edges.length,0);return{fileCount:t,edgeCount:o,focusFileCount:n,scopeCount:e.scopes.length,detail:e.detail,componentCount:s.length,largestComponentFileCount:i,representativeEdgeCount:r,runtimeComponentCount:l.runtime,mixedComponentCount:l.mixed,typeOnlyComponentCount:l["type-only"]}}function Me(e){const t=b(e.fileCount),o=b(e.edgeCount),n=b(e.componentCount),s=b(e.largestComponentFileCount),l=b(e.representativeEdgeCount),i=h(e.detail)??"summary";return{recommendedTimeoutMs:Pe({fileCount:t,edgeCount:o,componentCount:n,largestComponentFileCount:s,representativeEdgeCount:l,detail:i}),fileCount:t,edgeCount:o,componentCount:n,detail:i,message:"If cycle analysis runs as a post-mutation phase, inspect progress with: aib execution status last"}}function Pe(e){const t=e.detail==="imports"?1.25:e.detail==="files"?1.1:1,o=Math.round((750+e.fileCount*1.5+e.edgeCount*1.25+e.componentCount*4+e.largestComponentFileCount*2+e.representativeEdgeCount*1.5)*t);return Math.min(re,Math.max(ie,o))}function V(e){const t={runtime:0,"type-only":0,mixed:0};for(const o of e)t[o.kind]+=1;return t}function Ae(e){const t={runtime:0,"type-only":0,mixed:0};for(const o of e){const n=M(o.kind);n&&(t[n]+=1)}return t}function Oe(e){return`res_${(0,te.createHash)("sha256").update(JSON.stringify({target:e.target,request:e.request,componentCount:e.componentCount,components:e.components})).digest("hex").slice(0,8)}`}function I(e){if(Array.isArray(e.results)){const i=e.results.filter(f).map(I).filter(r=>!!r);return i.length>0?i.join(`
2
+
3
+ `):null}if(e.op!=="cycles")return null;const t=typeof e.target=="string"?e.target:"",o=typeof e.componentCount=="number"?e.componentCount:0,n=[`cycles ${t}`.trim()];if(o===0)return n.push(e.index?"selected component not found":"no cycles"),K(n,e.paths),n.join(`
4
+ `);n.push(Te(o,e.summary),""),z(o,e.summary)||je(n,e.summary);const s=Array.isArray(e.components)?e.components.filter(f):[];s.forEach((i,r)=>{const u=a(i.files)??[],c=typeof e.index=="number"?e.index:(typeof e.offset=="number"?e.offset:0)+r+1,d=o===1&&s.length===1&&!e.index?"":`${c}. `;Y(n,i,{detail:e.detail==="files"||e.detail==="imports"?e.detail:"summary",prefix:d,indent:d?" ":""})}),typeof e.hidden=="number"&&e.hidden>0&&n.push(`+ ${e.hidden} more cyclic ${e.hidden===1?"component":"components"}`);const l=h(e.result);if(l&&typeof e.hidden=="number"&&e.hidden>0){const i=(typeof e.offset=="number"?e.offset:0)+s.length,r=typeof e.limit=="number"?e.limit:S;n.push(`more: aib view ${l} --offset ${i} --limit ${r}`)}return K(n,e.paths),n.join(`
5
+ `)}function Y(e,t,o={}){const n=a(t.files)??[],s=M(t.kind)??"mixed",l=o.prefix??"",i=o.indent??"";if(e.push(`${l}${s}, ${n.length} ${n.length===1?"file":"files"}`),o.detail==="files"){for(const c of n.slice(0,O))e.push(`${i}${c}`);n.length>O&&e.push(`${i}+ ${n.length-O} more files`)}const r=f(t.cycle)?t.cycle:{},u=a(r.path)??Re(h(t.chain));if(u.length>0&&(e.push(`${i}cycle:`),we(e,u,i)),o.detail==="imports"){const c=a(r.imports)??a(t.imports)??[];if(c.length>0){e.push(`${i}imports:`);for(const d of c)e.push(`${i}${d}`)}}}function Te(e,t){const o=z(e,t);return o?`${e} ${o} ${e===1?"cycle":"cycles"}`:`${e} cyclic ${e===1?"component":"components"}`}function z(e,t){if(!f(t))return null;const n=["runtime","mixed","type-only"].filter(s=>t[s]===e);return n.length===1?n[0]:null}function Re(e){return e?e.split(" -> ").filter(t=>t.trim().length>0):[]}function we(e,t,o){if(t.length>4){e.push(`${o}${t[0]}`);for(const n of t.slice(1))e.push(`${o}-> ${n}`);return}e.push(`${o}${t.join(" -> ")}`)}function je(e,t){if(!f(t))return;const o=typeof t.runtime=="number"?t.runtime:0,n=typeof t.mixed=="number"?t.mixed:0,s=typeof t["type-only"]=="number"?t["type-only"]:0;e.push(`runtime ${o}, mixed ${n}, type-only ${s}`,"")}function K(e,t){if(!f(t))return;const o=Object.entries(t).filter(n=>typeof n[1]=="string").sort(([n],[s])=>n.localeCompare(s));if(o.length!==0){e.push("","paths:");for(const[n,s]of o)e.push(`${n} = ${s}`)}}function De(e,t,o){const s=(t.scopes.length>0?t.scopes:t.files).map(l=>(0,E.compactDisplayPath)(e,l,o));return s.length===1?s[0]:`[${s.join(",")}]`}function k(e,t){return(0,E.compactDisplayPath)("",e,t)}function Ne(e,t){const o={};for(const n of t)e.includes(n.token)&&(o[n.token]=n.prefix);return Object.keys(o).length>0?o:null}function Le(e,t){return(0,E.toDisplayPath)(e,ee.resolve(e,t))}function U(e){return f(e)?Array.isArray(e.requests)?e.requests.filter(f):[e]:[]}function R(e,t){const o=e.indexOf(t);if(o<0)return null;const n=e[o+1];return n&&!n.startsWith("--")?n:null}function C(e,t){const o=[];for(let n=0;n<e.length;n+=1){if(e[n]!==t)continue;const s=e[n+1];s&&!s.startsWith("--")&&(o.push(...G(s)),n+=1)}return o}function Fe(e,t){const o=e.indexOf(t);return o>0&&e[o-1]?.startsWith("--")===!0}function w(e){if(e==null||e==="summary"||e==="sum")return"summary";if(e==="imports")return"imports";if(e==="files")return"files";throw new y.CliError("INVALID_CYCLES_DETAIL","inspect cycles detail expects summary, imports, or files.")}function M(e){if(e==null||e==="")return null;if(e==="runtime"||e==="type-only"||e==="mixed")return e;throw new y.CliError("INVALID_CYCLES_KIND","inspect cycles kind expects runtime, type-only, or mixed.")}function q(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=="number"&&Number.isFinite(e)?e:0}function h(e){return typeof e=="string"&&e.length>0?e:null}function ve(e,t){return f(e)?h(e[t]):null}function a(e){return typeof e=="string"&&e.length>0?G(e):Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):null}function G(e){return e.split(",").map(t=>t.trim()).filter(Boolean)}function j(e){return Array.from(new Set(e)).sort()}function f(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}
@@ -0,0 +1,18 @@
1
+ "use strict";var st=exports&&exports.__createBinding||(Object.create?(function(e,r,t,n){n===void 0&&(n=t);var s=Object.getOwnPropertyDescriptor(r,t);(!s||("get"in s?!r.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return r[t]}}),Object.defineProperty(e,n,s)}):(function(e,r,t,n){n===void 0&&(n=t),e[n]=r[t]})),it=exports&&exports.__setModuleDefault||(Object.create?(function(e,r){Object.defineProperty(e,"default",{enumerable:!0,value:r})}):function(e,r){e.default=r}),ge=exports&&exports.__importStar||(function(){var e=function(r){return e=Object.getOwnPropertyNames||function(t){var n=[];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(n[n.length]=s);return n},e(r)};return function(r){if(r&&r.__esModule)return r;var t={};if(r!=null)for(var n=e(r),s=0;s<n.length;s++)n[s]!=="default"&&st(t,r,n[s]);return it(t,r),t}})();Object.defineProperty(exports,"__esModule",{value:!0}),exports.parseInspectSelector=mt,exports.formatInspectResponse=ht,exports.formatInspectMixedAgentText=Mt;const $=ge(require("node:path")),U=ge(require("node:fs")),ot=require("node:crypto"),x=require("./session-workspace"),me=require("../shared/agent-text"),ft=require("../shared/types"),ct=require("./inspect-graph"),at=require("./inspect-imports"),ut=require("../config/path-display"),lt=["class","interface","function","type","enum","variable","method","property","constructor"],pt=500,dt=500,q=10,Q=12,yt=12,gt=8;function mt(e,r){const t=e.trim();return t==="constructor"?{raw:t,symbolName:"constructor",symbolKind:"constructor"}:ue(t,r.selectorSeparator,r)??ue(t,":",r)??ue(t,"-",r)??{raw:t,symbolName:t,symbolKind:null}}function ht(e,r,t){const n=Array.isArray(e.results)?e.results:[],s=bt(t),i=er(n,t),o=n.map((u,p)=>_e(u,r,w(s,p),i));Ot(n,o,s,i),At(n,o,s,r,i),vt(n,o,s,r);const f=o.filter(u=>l(u)&&u.ok===!1).length;if(s.bundleSave)return xt(n,o,r,s,i,f);const c=f===0&&s.forceResults!==!0?St(n,o,r,i,s):null;if(c)return(0,me.attachAgentText)(c,Ae(n,c,s,i));const a={results:o};return i&&(a.file=i),(f>0||e.ok===!1)&&(a.ok=!1,a.summary={requestCount:o.length,failedCount:f}),(0,me.attachAgentText)(a,Ae(n,a,s,i))}function At(e,r,t,n,s){for(let i=0;i<r.length;i+=1){const o=e[i],f=r[i];if(!l(o)||!f||o.op!=="members"||y(o.hiddenMemberCount)<=0)continue;const c=se(o.hiddenMembers,n,w(t,i),"members").filter(g=>typeof g=="string"&&g!=="");if(c.length===0)continue;const a=typeof f.file=="string"?f.file:s??"",u=typeof f.entity=="string"?f.entity:F(o.entity,n),p=M({version:1,kind:"members",source:"inspect",file:a,entity:u,items:c.map(g=>M({text:g}))}),d=(0,x.saveSessionResultViewJson)(t.cwd,W(p),p);d&&(f.view=d.saved)}}function vt(e,r,t,n){for(let s=0;s<r.length;s+=1){const i=e[s],o=r[s];if(!l(i)||!o||i.op!=="duplicates"||y(i.hiddenItemCount)<=0)continue;const f=Array.isArray(i.hiddenDuplicateItems)?i.hiddenDuplicateItems.filter(l):Array.isArray(i.hiddenItems)?i.hiddenItems.filter(l):[];if(f.length===0)continue;const c=Ye(Je(f,C(i.targetPaths).map(g=>h(g,t)),t),C(i.targetPaths).map(g=>h(g,t))),a=typeof i.detail=="string"?i.detail:"locations",u=f.map(g=>{const A=Le(g,n,w(t,s),c);return M({name:typeof A.name=="string"?A.name:"",text:je(A,a).join(`
2
+ `).trim()})}).filter(g=>typeof g.text=="string"&&g.text!=="");if(u.length===0)continue;const p=M({version:1,kind:"duplicates",source:"inspect",detail:a,target:typeof o.target=="string"?o.target:"",items:u}),d=(0,x.saveSessionResultViewJson)(t.cwd,W(p),p);d&&(o.view=d.saved)}}function w(e,r){const t=e.toFiles?.[r],n=e.saves?.[r],s=e.shows?.[r],i=e.ranges?.[r],o=e.parentNames?.[r];if(t===void 0&&n===void 0&&s===void 0&&i===void 0&&o===void 0)return e;const f={...e};return delete f.toFiles,delete f.toFile,delete f.saves,delete f.save,delete f.shows,delete f.ranges,delete f.parentNames,delete f.parentName,t&&(f.toFile=t),n&&!e.sharedSaves?.has(n)&&(f.save=n),s!==void 0&&(f.show=s),i!==void 0&&(f.includeRanges=i),o&&(f.parentName=o),f}function bt(e){if(!e.saves||e.saves.length<2)return e;const r=new Map;for(const n of e.saves)n&&r.set(n,(r.get(n)??0)+1);const t=new Set(Array.from(r.entries()).filter(([,n])=>n>1).map(([n])=>n));return t.size>0?{...e,sharedSaves:t}:e}function xt(e,r,t,n,s,i){const o=n.bundleSave;if(!o)throw new Error("bundleSave is required for inspect bundle output.");const f={...n,maxCodeLines:Number.MAX_SAFE_INTEGER};delete f.toFile,delete f.toFiles,delete f.save,delete f.saves,delete f.bundleSave;const c=e.map((A,v)=>{const m=_e(A,t,f,s),b=r[v]?.saved;return typeof b=="string"&&(m.saved=b),delete m.next,delete m.last,m}),a=$t(c,s),u=(0,x.saveSessionOutputJson)(n.cwd,"inspect",o,a),p={saved:u.saved,last:u.last,items:c.length},d=r.map(A=>typeof A.saved=="string"?A.saved:"").filter(A=>A!=="");d.length>0&&(p.savedRows=d),i>0&&(p.ok=!1,p.summary={requestCount:c.length,failedCount:i});const g=(0,x.useSessionGuidance)(n.cwd,"inspect.bundle.read",`Read bundle with: aib session read ${u.saved}`);return g&&(p.next=g),p}function $t(e,r){const t={source:"inspect.bundle"};r&&(t.file=r);const n=e.map(o=>({...o})),s=he(n,"op"),i=he(n,"parent");return s&&(t.op=s,R(n,"op")),i&&(t.parent=i,R(n,"parent")),r&&R(n,"file"),t.items=n,t}function he(e,r){const t=e.map(s=>s[r]).filter(s=>typeof s=="string"&&s!=="");if(t.length!==e.length||t.length===0)return null;const[n]=t;return t.every(s=>s===n)?n??null:null}function R(e,r){for(const t of e)delete t[r]}function St(e,r,t,n,s){if(e.length===0||r.length===0)return null;const i=e.filter(l);if(i.length!==e.length||i.some(c=>c.ok===!1))return null;const o=Array.from(new Set(i.map(c=>typeof c.op=="string"?c.op:"")));if(o.length!==1)return{results:r.map(c=>I(c,{omitOp:!1,commonFile:n}))};const f=o[0];if(f==="modulePlan")return null;if(f==="usages")return e.length===1?I(r[0],{omitOp:!0,omitFile:!0}):{results:r.map(c=>I(c,{omitOp:!0,commonFile:n}))};if(e.length===1)return I(r[0],{omitOp:!0,omitFile:!0});if(f==="dependencies"){if(n){const c={};for(const a of i){const u=fe(a.entity);if(!u)return null;c[u]=mn(a,t)}return{file:n,deps:c}}return{results:r.map(c=>I(c,{omitOp:!0,commonFile:n}))}}if(f==="members"){if(n){const c={};for(const a of r){const u=typeof a.entity=="string"?a.entity:"";if(!u||!Array.isArray(a.members))return null;c[u]=kt(a)}return{file:n,members:c}}return{results:r.map(c=>I(c,{omitOp:!0,commonFile:n}))}}if(f==="code"||f==="slice"){const c=r.map(d=>I(d,{omitOp:!0,commonFile:n})),a={items:c};n&&(a.file=n);const u=Jt(f,e,s,t);if(u.length===1?a.saved=u[0].saved:u.length>1&&(a.saved=u.map(d=>d.saved)),u.length>0){const d=u.length===1?u[0].saved:"--stdin",g=(0,x.useSessionGuidance)(s.cwd,`inspect.${f}.read`,`Read saved artifact with: aib session read ${d}`);g&&(a.next=g)}if(Ct(c).length>1){for(const d of c)delete d.next;a.next="Read saved artifacts with: aib session read --stdin"}return a}return{results:r.map(c=>I(c,{omitOp:!0,commonFile:n}))}}function I(e,r){const t={...e};return r.omitOp?delete t.op:t.op==="dependencies"&&(t.op="deps"),(r.omitFile||typeof t.file=="string"&&t.file===r.commonFile)&&delete t.file,delete t.last,typeof t.entity=="string"&&(t.entity=qe(t.entity)),typeof t.count=="number"&&t.count<=q&&typeof t.page!="string"&&typeof t.hint!="string"&&delete t.count,t}function kt(e){const r={};return typeof e.count=="number"&&e.count>q&&(r.count=e.count),Array.isArray(e.members)&&(r.members=e.members),typeof e.hint=="string"&&(r.hint=e.hint),typeof e.page=="string"&&(r.page=e.page),r}function Ct(e){return e.map(r=>typeof r.saved=="string"?r.saved:"").filter(r=>r!=="")}function Ot(e,r,t,n){const s=new Map;for(let a=0;a<r.length;a+=1){const u=r[a],p=e[a];if(!u||!l(p)||!G(u))continue;const d=typeof p.op=="string"?p.op:"code";if(d!=="code"&&d!=="slice")continue;const g=ee(u,t,e,a),A=typeof u.file=="string"?u.file:n??"",v=[d,g,A,t.parentNames?.[a]??t.parentName??""].join("\0"),m=s.get(v)??[];m.push({raw:p,result:u,index:a}),s.set(v,m)}for(const a of s.values()){const u=a.map(({raw:A,result:v,index:m})=>{const b=typeof A.code=="string"?A.code:"",N=typeof v.rangeMeta=="string"?v.rangeMeta:typeof v.meta=="string"?v.meta:"",P=typeof v.file=="string"?v.file:n??"",T=typeof v.entity=="string"?v.entity:typeof A.entity=="string"?A.entity:"";return M({file:P,entity:T,meta:N,code:b,nonEmptyLines:typeof v.nonEmptyLines=="number"?v.nonEmptyLines:re(b),lineCount:b===""?y(A.lineCount):b.split(/\r?\n/).length,parent:t.parentNames?.[m]??t.parentName})});if(u.length===0)continue;const p=M({version:1,kind:"code",source:"inspect",items:u}),d=W(p),g=(0,x.saveSessionResultViewJson)(t.cwd,d,p);if(g)for(const A of a)A.result.view=g.saved}if(new Set(Array.from(s.values()).flatMap(a=>a.map(u=>typeof u.result.view=="string"?u.result.view:"")).filter(a=>a!=="")).size<=1)return;const o=Array.from(s.values()).flatMap(a=>a.map(u=>It(u.raw,u.result,u.index,t,n))),f=M({version:1,kind:"code",source:"inspect",items:o}),c=(0,x.saveSessionResultViewJson)(t.cwd,W(f),f);if(c)for(const a of s.values())for(const u of a)u.result.viewAllCode=c.saved}function It(e,r,t,n,s){const i=typeof e.code=="string"?e.code:"",o=typeof r.rangeMeta=="string"?r.rangeMeta:typeof r.meta=="string"?r.meta:"",f=typeof r.file=="string"?r.file:s??"",c=typeof r.entity=="string"?r.entity:typeof e.entity=="string"?e.entity:"";return M({file:f,entity:c,meta:o,code:i,nonEmptyLines:typeof r.nonEmptyLines=="number"?r.nonEmptyLines:re(i),lineCount:i===""?y(e.lineCount):i.split(/\r?\n/).length,parent:n.parentNames?.[t]??n.parentName})}function W(e){return`res_${(0,ot.createHash)("sha256").update(JSON.stringify(e)).digest("hex").slice(0,8)}`}function M(e){const r={};for(const[t,n]of Object.entries(e))n!==void 0&&n!==""&&(r[t]=n);return r}function Ae(e,r,t,n){if(O(e,"file"))return Me(r,"symbols",n);if(O(e,"exports"))return Me(r,"exports",n);if(O(e,"members"))return Vt(r,n);if(O(e,"dependencies"))return qt(r,n);if(O(e,"modulePlan"))return Nt(r);if(O(e,"usages"))return Pe(r);if(O(e,"duplicates"))return De(r);if(O(e,"directoryFallback"))return xe(r);if(!O(e,"code"))return ve(r,n);const s=Kt(r);if(s.length!==e.length||s.length===0||s.some(m=>typeof m.code!="string"&&typeof m.meta!="string"&&!D(m)&&!G(m)&&!te(m)))return null;const i=[],o=r.saved,f=s.some((m,b)=>ee(m,t,e,b)!=="");if(!f&&typeof o=="string")i.push(`// ${o}`);else if(!f&&Array.isArray(o))for(const m of o)typeof m=="string"&&i.push(`// ${m}`);let c="",a="",u="",p=[],d=[];const g=l(e[0])&&typeof e[0].op=="string"?e[0].op:"code",A=()=>{Ie(i,d,g),d=[]},v=()=>{p.length!==0&&(A(),i.push("// code:"),i.push(`not found symbols: ${p.join(", ")}`),p=[])};return s.forEach((m,b)=>{const N=l(e[b])?e[b]:{},P=ee(m,t,e,b);P&&P!==u&&(v(),A(),_(i),i.push(`// ${P}`),u=P,c="",a="");const T=zt(m,N,t,n);if(T&&T!==c&&(v(),A(),i.push(`// ${T}`),c=T,a=""),D(m)){p.push(...E(m));return}v();const B=t.parentNames?.[b]??t.parentName??"";if(B&&B!==a?(A(),i.push(`// ${B}:`),a=B):B||(a=""),G(m)){d.push(m);return}const pe=t.ranges?.[b]??t.includeRanges;if(t.codeMeta!==!1&&pe&&typeof m.meta=="string"&&m.meta!=="")i.push(`// ${m.meta}`);else if(t.codeMeta!==!1&&pe){const de=typeof m.code=="string"?m.code:"",rt=de===""?y(N.lineCount):de.split(/\r?\n/).length,ye=L(N.entity,rt);ye&&i.push(`// ${ye}`)}typeof m.code=="string"?i.push(m.code.trimEnd()):te(m)&&Oe(i,m)}),A(),v(),be(i,s,!1),i.length>0?i.join(`
3
+ `):null}function ee(e,r,t,n){if(typeof e.saved=="string"&&e.saved!=="")return e.saved;const s=r.saves?.[n];if(typeof s!="string"||s==="")return"";const i=l(t[n])?t[n]:{};return`aib:${typeof i.op=="string"&&i.op!==""?i.op==="dependencies"?"deps":i.op:"inspect"}:${s}`}function Mt(e,r=null){return ve(e,r)}function ve(e,r){if(!Array.isArray(e.results))return null;const t=[],n=z(t);let s=[];const i=()=>{s.length!==0&&(_(t),t.push("// code:"),t.push(`not found symbols: ${s.join(", ")}`),s=[])},o=c=>{i(),_(t),n(typeof c.file=="string"?c.file:r??"")},f=e.results.filter(l);for(let c=0;c<f.length;c+=1){const a=f[c];if(!l(a))return null;const u=typeof a.op=="string"?a.op:"";if((u==="code"||u==="slice")&&D(a)){s.push(...E(a));continue}if(i(),u==="file")o(a),ke(t,"file:",a.symbols),Ce(t,a);else if(u==="exports")o(a),ke(t,"exports:",a.exports);else if(u==="members")o(a),K(t,`members ${typeof a.entity=="string"?a.entity:""}`.trim(),a);else if(u==="deps"||u==="dependencies"){o(a);const p=[];for(;c<f.length;){const d=f[c],g=typeof d.op=="string"?d.op:"";if(g!=="deps"&&g!=="dependencies"){c-=1;break}p.push({entity:typeof d.entity=="string"?d.entity:"",missingSymbols:E(d),type:d.depsType,value:d.depsValue,unknown:d.depsUnknown}),c+=1}c>=f.length&&(c-=1),J(t,p)}else if(u==="code"||u==="slice"){o(a);const p=[],d=typeof a.file=="string"?a.file:r??"";for(;c<f.length;){const g=f[c],A=typeof g.op=="string"?g.op:"",v=typeof g.file=="string"?g.file:r??"";if(A!==u||v!==d||D(g)){c-=1;break}p.push(g),c+=1}c>=f.length&&(c-=1),Ut(t,u,p)}else if(u==="graph")o(a),Et(t,a);else if(u==="imports")(0,at.appendImportsBlock)(t,a);else if(u==="usages")o(a),Pt(t,a);else if(u==="duplicates")o(a),Ft(t,a);else if(u==="directoryFallback")o(a),_t(t,a);else return null}return i(),be(t,f,!0),t.length>0?t.join(`
4
+ `):null}function be(e,r,t){const n=Array.from(new Set(r.map(s=>typeof s.viewAllCode=="string"?s.viewAllCode:"").filter(s=>s!=="")));if(n.length!==0){if(_(e),t){e.push("view all:"),e.push(`code: ${n[0]}`);return}e.push(`view all code: ${n[0]}`)}}function Et(e,r){const t=(0,ct.formatGraphAgentText)({...r,operation:"inspect.graph"});t&&(e.push("// graph:"),e.push(...t.split(/\r?\n/).filter(n=>n!=="inspect.graph")))}function _t(e,r){const t=xe(r);t&&e.push(...t.split(/\r?\n/))}function xe(e){const r=Lt(Array.isArray(e.lines)?e.lines.filter(i=>typeof i=="string").filter((i,o)=>o!==0||!i.startsWith("tree ")):[]);if(r.length===0)return null;const t=typeof e.directory=="string"?e.directory:"directory",n=Array.isArray(e.skippedOps)?e.skippedOps.filter(i=>typeof i=="string"):[],s=[`inspect expected file, got directory: ${t}`];return n.length>0&&(s.push(""),s.push("Skipped file-based operations:"),s.push(n.join(", "))),typeof e.command=="string"&&e.command!==""&&(s.push(""),s.push("Showing tree instead:"),s.push(e.command)),s.push(""),s.push(...r),s.join(`
5
+ `)}function Lt(e){let r=0;for(;r<e.length&&e[r]==="";)r+=1;return e.slice(r)}function Pt(e,r){const t=typeof r.detail=="string"?r.detail:"",n=t==="locations"||t==="code"?Tt(r):Pe(r);n&&e.push(...n.split(/\r?\n/))}function Tt(e){const r=typeof e.detail=="string"?e.detail:"detail";if(y(e.referenceCount)===0){const s=typeof e.target=="string"?e.target:"",i=typeof e.scopeLabel=="string"?e.scopeLabel:"project",o=[s?`usages ${s}`:"usages",`0 refs in ${i}`];return Y(o,e),o.join(`
6
+ `)}const t=[`usages ${r}`];Y(t,e),r==="code"?jt(t,e):Dt(t,e),Ne(t,e,Array.isArray(e.items)?e.items.filter(l):[]);const n=typeof e.view=="string"?e.view:"";return n&&(_(t),t.push(`view: ${n}`)),t.join(`
7
+ `).replace(/\n{3,}/g,`
8
+
9
+ `).trimEnd()}function Dt(e,r){const t=Array.isArray(r.items)?r.items.filter(l).filter(i=>y(i.referenceCount)>0):[];t.length>0&&_(e);const{ownerGroups:n,standalone:s}=ne(t);for(const[i,o]of n){e.push(""),e.push(`// ${i}:`);for(const f of o)e.push(...$e(f,!1))}s.length>0&&n.length>0&&e.push("");for(const i of s)e.push(...$e(i,!0))}function $e(e,r){const t=typeof e.entity=="string"?e.entity:"",n=H(t),i=[`${r?t:n.name}: ${y(e.referenceCount)} refs`],o=Array.isArray(e.usedBy)?e.usedBy.filter(l):[];for(const f of o){const c=typeof f.file=="string"?f.file:"";c&&i.push(`${c}:`);const a=Array.isArray(f.locations)?f.locations.filter(l):[];for(const u of a){const p=typeof u.line=="number"?` l${u.line}`:"",d=typeof u.container=="string"?u.container:"";i.push(`${d}${p}`.trim())}}return typeof e.hidden=="string"&&i.push(e.hidden),i}function jt(e,r){const t=Array.isArray(r.blocks)?r.blocks.filter(l):[];t.length>0&&_(e);const{ownerGroups:n,standalone:s}=ne(t);for(const[o,f]of n){e.push(`// ${o}:`);for(const[c,a]of Te(f,u=>H(typeof u.entity=="string"?u.entity:"").name)){c&&e.push(`// ${c}`);for(const u of a)e.push(...Se(u,!1,!1))}}s.length>0&&n.length>0&&e.push("");for(const[o,f]of Te(s,c=>typeof c.entity=="string"?c.entity:"")){o&&e.push(`// ${o}`);for(const c of f)e.push(...Se(c,!1,!1))}const i=Array.isArray(r.hiddenBlocks)?r.hiddenBlocks.filter(l):[];for(const o of i){const f=typeof o.entity=="string"?o.entity:"",c=typeof o.hidden=="string"?o.hidden:"";c&&e.push(f?`${f}: ${c}`:c)}}function Se(e,r,t=!0){const n=typeof e.entity=="string"?e.entity:"",s=H(n),i=r?n:s.name,o=[];t&&i&&o.push(`// ${i}`);const f=typeof e.file=="string"?e.file:"",c=typeof e.line=="number"?` l${e.line}`:"";if((f||c)&&o.push(`// ${f}${c}`.trim()),typeof e.code=="string")o.push(e.code.trimEnd());else if(l(e.omitted)){const a=typeof e.omitted.reason=="string"?e.omitted.reason:"omitted";o.push(`// ${a}`)}return o}function Ft(e,r){const t=De(r);t&&e.push(...t.split(/\r?\n/))}function Nt(e){const r=Array.isArray(e.results)?e.results.filter(l):l(e)?[e]:[];if(r.length===0)return null;const t=[];for(const n of r){const s=typeof n.operation=="string"?n.operation:"modulePlan.preview",i=typeof n.planId=="string"?n.planId:"";if(t.push(i?`${s} ${i}`:s),n.ok===!1&&typeof n.code=="string"&&t.push(`blocked: ${n.code}`),typeof n.summary=="string"&&t.push(n.summary),typeof n.integrity=="string"&&t.push(n.integrity),l(n.api)&&typeof n.api.status=="string"){const o=typeof n.api.before=="number"?n.api.before:null,f=typeof n.api.after=="number"?n.api.after:null;t.push(o!==null&&f!==null?`api: ${n.api.status} ${o}->${f}`:`api: ${n.api.status}`)}if(typeof n.cycles=="string"&&t.push(`cycles: ${n.cycles}`),Array.isArray(n.targets)&&n.targets.length>0){t.push("targets:");for(const o of n.targets.filter(l)){const f=typeof o.file=="string"?o.file:"",c=typeof o.summary=="string"?o.summary:"";f&&c&&t.push(`${f}: ${c}`)}}if(Array.isArray(n.blocking)&&n.blocking.length>0){t.push("blocking:");for(const o of n.blocking.filter(l)){const f=typeof o.code=="string"?o.code:"MODULE_PLAN_BLOCKING",c=Array.isArray(o.symbols)?o.symbols.filter(a=>typeof a=="string"):[];t.push(c.length>0?`${f}: ${c.join(", ")}`:f),Array.isArray(o.suggestedFixes)&&o.suggestedFixes.length>0&&t.push(`suggestedFixes: ${o.suggestedFixes.length}`)}}if(Array.isArray(n.remainingBlocking)&&n.remainingBlocking.length>0&&t.push(`remainingBlocking: ${n.remainingBlocking.length}`),Array.isArray(n.resolved)&&n.resolved.length>0&&t.push(`resolved: ${n.resolved.length}`),Array.isArray(n.changes)&&n.changes.length>0){t.push("changes:");for(const o of n.changes.filter(f=>typeof f=="string"))t.push(o)}l(n.preview)&&typeof n.preview.summary=="string"&&t.push(`preview: ${n.preview.summary}`),typeof n.next=="string"&&t.push(`next: ${n.next}`)}return t.join(`
10
+ `)}function ke(e,r,t){const n=C(t);if(e.push(r),n.length===0){e.push(r==="exports:"?"no exports":"no top-level declarations");return}for(const s of n)e.push(s)}function Ce(e,r){r.hasNonDeclarationText===!0&&e.push("file has non-declaration text")}function Bt(e,r,t){const n=typeof t.entity=="string"?t.entity:"";if(e.push(`// ${[r,n].filter(s=>s!=="").join(" ")}:`),D(t)){e.push(`not found symbols: ${E(t).join(", ")}`);return}typeof t.meta=="string"&&t.meta!==""&&e.push(`// ${t.meta}`),typeof t.saved=="string"&&t.saved!==""&&e.push(`saved: ${t.saved}`),typeof t.code=="string"?e.push(t.code.trimEnd()):G(t)?Gt(e,t):te(t)&&Oe(e,t)}function Ut(e,r,t){const n=[];for(const s of t){if(G(s)){n.push(s);continue}Bt(e,r,s)}Ie(e,n,r)}function te(e){return typeof e.saved=="string"&&e.saved!==""}function Oe(e,r){e.push(`saved: ${r.saved}`),typeof r.next=="string"&&r.next!==""&&e.push(`next: ${r.next}`)}function G(e){return e.reason==="CODE_TOO_LARGE_FOR_STDOUT"||e.reason==="SLICE_TOO_LARGE_FOR_STDOUT"}function Gt(e,r){const t=typeof r.reason=="string"?r.reason:"CODE_TOO_LARGE_FOR_STDOUT",n=Ht(r)??t;e.push(`code omitted: ${n}`),typeof r.hint=="string"&&r.hint!==""&&e.push(`hint: ${r.hint}`)}function Ie(e,r,t){if(r.length===0)return;const n=t==="slice"?"slice":"code",s=Array.from(new Set(r.map(f=>typeof f.limit=="number"?f.limit:null).filter(f=>f!==null))),i=s.length===1?`; limit ${s[0]} non-empty lines`:"";e.push(`// ${n} omitted${i}`);for(const f of r){const c=typeof f.entity=="string"&&f.entity!==""?f.entity:"unknown",a=typeof f.meta=="string"?f.meta:typeof f.rangeMeta=="string"?f.rangeMeta:"",u=typeof f.nonEmptyLines=="number"&&f.nonEmptyLines>0?f.nonEmptyLines:typeof f.lineCount=="number"&&f.lineCount>0?f.lineCount:0,p=u>0?`${u}NEL`:"";e.push(`// ${[c,a,p].filter(d=>d!=="").join(" ")}`)}const o=Array.from(new Set(r.map(f=>typeof f.view=="string"?f.view:"").filter(f=>f!=="")));for(const f of o)e.push(`view: ${f}`)}function Ht(e){const r=typeof e.hint=="string"?e.hint:"";return/^(?:Code|Slice) is ([^.]+)\./.exec(r)?.[1]??null}function Me(e,r,t){const n=[],s=z(n);if(Array.isArray(e.results))for(const i of e.results)l(i)&&Ee(n,s,i,r,t);else Ee(n,s,e,r,t);return n.length>0?n.join(`
11
+ `):null}function Ee(e,r,t,n,s){r(typeof t.file=="string"?t.file:s??"");const i=C(t[n]);if(i.length===0)e.push(`${n==="exports"?"exports":"file"}:`),e.push(n==="exports"?"no exports":"no top-level declarations");else for(const f of i)e.push(f);n==="symbols"&&Ce(e,t),typeof t.summary=="string"&&e.push(`summary: ${t.summary}`);const o=C(t.reexports);o.length>0&&e.push(`reexports: ${o.join(", ")}`),typeof t.page=="string"&&e.push(`page: ${t.page}`),typeof t.hint=="string"&&e.push(`hint: ${t.hint}`)}function Vt(e,r){const t=[],n=z(t);if(l(e.members)&&!Array.isArray(e.members)){n(typeof e.file=="string"?e.file:r??"");for(const[s,i]of Object.entries(e.members))l(i)&&K(t,s,i)}else if(Array.isArray(e.results))for(const s of e.results)l(s)&&(n(typeof s.file=="string"?s.file:r??""),K(t,typeof s.entity=="string"?s.entity:"",s));else n(typeof e.file=="string"?e.file:r??""),K(t,typeof e.entity=="string"?e.entity:"",e);return t.length>0?t.join(`
12
+ `):null}function K(e,r,t){if(D(t)){e.push("members:"),e.push(`not found symbols: ${E(t).join(", ")}`);return}const n=C(t.members);if(!(!r&&n.length===0)){if(r&&e.push(`// ${r}:`),n.length===0){e.push("no members");return}typeof t.count=="number"&&e.push(`// count: ${t.count}`),typeof t.page=="string"&&e.push(`// page: ${t.page}`);for(const s of n)e.push(s);typeof t.view=="string"&&e.push(`view: ${t.view}`)}}function qt(e,r){const t=[],n=z(t);if(l(e.deps)){n(typeof e.file=="string"?e.file:r??"");const s=[];for(const[i,o]of Object.entries(e.deps))l(o)&&s.push({entity:i,type:o.type,value:o.value,unknown:o.unknown});J(t,s)}else if(Array.isArray(e.results)){const s=[];for(const i of e.results)l(i)&&(n(typeof i.file=="string"?i.file:r??""),s.push({entity:typeof i.entity=="string"?i.entity:"",missingSymbols:E(i),type:i.depsType,value:i.depsValue,unknown:i.depsUnknown}));J(t,s)}else n(typeof e.file=="string"?e.file:r??""),J(t,[{entity:typeof e.entity=="string"?e.entity:"",missingSymbols:E(e),type:e.depsType,value:e.depsValue,unknown:e.depsUnknown}]);return t.length>0?t.join(`
13
+ `):null}function _(e){e.length>0&&e[e.length-1]!==""&&e.push("")}function z(e){let r="";return t=>{t&&t!==r&&(e.push(`// ${t}`),r=t)}}function J(e,r){const t=[],n=[];let s=!1;for(const i of r){if(i.missingSymbols&&i.missingSymbols.length>0){n.push(...i.missingSymbols);continue}const o=C(i.type),f=C(i.value),c=C(i.unknown);if(o.length===0&&f.length===0&&c.length===0){i.entity&&t.push(i.entity);continue}s||(e.push("deps"),s=!0),Wt(e,i.entity,{type:o,value:f,unknown:c})}t.length>0&&(s||(e.push("deps"),s=!0),e.push(`No deps for: ${t.join(", ")}`)),n.length>0&&(s||e.push("deps"),e.push(`not found symbols: ${n.join(", ")}`))}function Wt(e,r,t){!r&&t.type.length===0&&t.value.length===0&&t.unknown.length===0||(r&&e.push(`${r}:`),t.type.length>0&&e.push(`type: ${t.type.join(", ")}`),t.value.length>0&&e.push(`value: ${t.value.join(", ")}`),t.unknown.length>0&&e.push(`unknown: ${t.unknown.join(", ")}`))}function C(e){return Array.isArray(e)?e.filter(r=>typeof r=="string"&&r!==""):[]}function O(e,r){return e.length>0&&e.every(t=>l(t)&&t.op===r)}function Kt(e){return Array.isArray(e.items)?e.items.filter(l):Array.isArray(e.results)?e.results.filter(l):[e]}function zt(e,r,t,n){return typeof e.file=="string"&&e.file!==""?e.file:n||(typeof r.sourceFile=="string"&&r.sourceFile!==""?h(r.sourceFile,t):"")}function Jt(e,r,t,n){if(e!=="code"&&e!=="slice")return[];const s=Yt(t.saves,t.sharedSaves,r.length);return s.length===0?[]:s.map(i=>{const o=r.map((a,u)=>({rawResult:a,save:t.saves?.[u]??null,includeRanges:t.ranges?.[u]??t.includeRanges})).filter(a=>a.save===i&&l(a.rawResult)).map(a=>({rawResult:a.rawResult,includeRanges:a.includeRanges})).map(({rawResult:a,includeRanges:u})=>{const p=typeof a.code=="string"?a.code:"",d=F(a.entity,n),g=p===""?y(a.lineCount):p.split(/\r?\n/).length,A=t.codeMeta===!1||!u?"":L(a.entity,g),v=[d,A].filter(m=>m!=="").join(" ");return v?`// ${v}
14
+ ${p}`:p}).filter(a=>a!==""),f=Zt(r),c=(0,x.saveSessionOutputText)(t.cwd,e,i,o.join(`
15
+
16
+ `),f);return{saved:c.saved,last:c.last}})}function Yt(e,r,t){return!e||!r||t<2||e.length<t?[]:Array.from(new Set(e.slice(0,t).filter(n=>typeof n=="string"&&n!==""&&r.has(n))))}function Zt(e){for(const r of e)if(l(r)&&typeof r.sourceFile=="string")return $.extname(r.sourceFile)||".ts";return".ts"}function _e(e,r,t,n){if(!l(e))return{ok:!1,code:"INVALID_INSPECT_RESULT",error:"Inspect result is not an object."};const s=typeof e.op=="string"?e.op:"unknown";if(e.ok===!1&&s!=="modulePlan")return zn(e,t,n);if(s==="file"){const i={...S(e,t,n),...We("count",y(e.symbolCount)),symbols:se(e.symbols,r,t,"file")};return(e.hasNonDeclarationText===!0||Array.isArray(i.symbols)&&i.symbols.length===0&&dn(e.sourceFile))&&(i.hasNonDeclarationText=!0),e.mode==="local"&&(i.mode="local",i.summary=Hn(e),i.localDeclarationCount=y(e.localDeclarationCount),i.reexports=Ve(e.reexports)),i}return s==="exports"?{...S(e,t,n),...We("count",y(e.exportCount)),exports:yn(e.exports,r,t)}:s==="members"?{...S(e,t,n),entity:F(e.entity,r),...Gn(e,r,t)}:s==="code"?pn(e,r,t,n):s==="dependencies"?{...S(e,t,n),entity:F(e.entity,r),...gn(e,r,t)}:s==="modulePlan"?hn(e,r,t,n):s==="usages"?Xt(e,r,t,n):s==="duplicates"?Qt(e,r,t,n):s==="directoryFallback"?{...e}:s==="slice"?ln(e,r,t,n):{...S(e,t,n),warning:"Unknown inspect operation result."}}function Xt(e,r,t,n){const s=typeof e.targetPath=="string"?h(e.targetPath,t):typeof e.sourceFile=="string"?h(e.sourceFile,t):n??"",i=Array.isArray(e.items)?e.items.filter(l):[],o=Zn(Yn(i,s,t)),f=en(i),c=e.targetMode==="directory"&&e.queryMode!=="explicit",a={...S(e,t,n),target:o.compactPath(s),summary:typeof e.summary=="string"?e.summary:`${f.length} symbols`,referenceCount:y(e.referenceCount),itemCount:y(e.itemCount),fileCount:y(e.fileCount),scopeLabel:sn(e,t),targetMode:typeof e.targetMode=="string"?e.targetMode:"",queryMode:typeof e.queryMode=="string"?e.queryMode:""};if(delete a.file,e.excludeTarget===!0&&e.targetLocalUsagesHidden!==!0&&(a.scope="excluding target"),e.targetLocalUsagesHidden===!0&&(a.targetLocalUsagesHidden=!0),c){const p=nn(f,r,o,t);a.usedBy=p.usedBy,p.hiddenConsumers>0&&(a.hiddenConsumers=`+ ${p.hiddenConsumers} files`)}else{const p=f.slice(0,Q);a.items=p.map(d=>tn(d,r,o,t,e.targetMode==="directory"))}const u=Qe(o,a);if(u&&(a.paths=u),!c&&f.length>Q&&(a.hidden=`+ ${f.length-Q} symbols`),t.save){const p=(0,x.saveSessionOutputJson)(t.cwd,"usages",t.save,e);a.saved=p.saved;const d=(0,x.useSessionGuidance)(t.cwd,"inspect.usages.focus",`Expand saved usages with: aib inspect usages --from-file ${p.saved} --focus <name> --detail locations|code`);d&&(a.next=d)}return a}function Qt(e,r,t,n){const s=Array.isArray(e.targetPaths)?e.targetPaths.filter(u=>typeof u=="string").map(u=>h(u,t)):[],i=Array.isArray(e.items)?e.items.filter(l):[],o=Ye(Je(i,s,t),s),f={...S(e,t,n),target:s.length===1?o.compactPath(s[0]):s.map(u=>o.compactPath(u)),summary:typeof e.summary=="string"?e.summary:`${i.length} names`,itemCount:y(e.itemCount),returnedItemCount:y(e.returnedItemCount),declarationCount:y(e.declarationCount),exactCopyCount:y(e.exactCopyCount),offset:y(e.offset),limit:y(e.limit),detail:typeof e.detail=="string"?e.detail:"locations",mode:typeof e.mode=="string"?e.mode:"both",items:i.map(u=>Le(u,r,t,o))},c=Qe(o,f);c&&(f.paths=c);const a=y(e.hiddenItemCount);if(a>0&&(f.hidden=`+ ${a} names`),t.save){const u=(0,x.saveSessionOutputJson)(t.cwd,"duplicates",t.save,e);f.saved=u.saved;const p=(0,x.useSessionGuidance)(t.cwd,"inspect.duplicates.read",`Read saved duplicates with: aib session read ${u.saved}`);p&&(f.next=p)}return f}function Le(e,r,t,n){const s=Array.isArray(e.variants)?e.variants.filter(l):[];return{name:typeof e.name=="string"?e.name:"",count:y(e.declarationCount),variants:y(e.variantCount),exactCopies:y(e.exactCopyCount),groups:s.map(i=>wt(i,r,t,n))}}function wt(e,r,t,n){const s=Array.isArray(e.declarations)?e.declarations.filter(l):[],i={count:y(e.count),declarations:s.map(o=>Rt(o,r,t,n))};return typeof e.code=="string"&&(i.code=e.code),i}function Rt(e,r,t,n){const s=l(e.symbol)?e.symbol:{},i=l(e.sameAs)?e.sameAs:null,o={file:typeof e.file=="string"?n.compactPath(h(e.file,t)):"",selector:j(s,r),meta:L(s)};if(i){const f=l(i.symbol)?i.symbol:{},c=typeof i.file=="string"?n.compactPath(h(i.file,t)):"";o.sameAs=[c,L(f)].filter(a=>a!=="").join(" ")}return o}function en(e){return[...e].sort((r,t)=>y(t.referenceCount)-y(r.referenceCount)||ze(X(r.entity),X(t.entity)))}function tn(e,r,t,n,s=!1){const i={entity:X(e.entity),summary:typeof e.summary=="string"?e.summary:`${y(e.referenceCount)} refs, ${y(e.fileCount)} files`,usedBy:rn(e.usedBy,t,n)};return s&&typeof e.declaredIn=="string"&&(i.declaredIn=t.compactPath(h(e.declaredIn,n))),e.role==="member"&&(i.role="member"),i}function nn(e,r,t,n){const s=new Map;for(const f of e){const c=X(f.entity),a=Array.isArray(f.usedBy)?f.usedBy.filter(l):[];for(const u of a){const p=typeof u.file=="string"?u.file:"";if(!p)continue;const d=y(u.count),g=s.get(p)??{refs:0,symbols:new Map};g.refs+=d,g.symbols.set(c,(g.symbols.get(c)??0)+d),s.set(p,g)}}const i=Array.from(s.entries()).sort(([f,c],[a,u])=>u.refs-c.refs||f.localeCompare(a)),o=i.slice(0,yt).map(([f,c])=>{const a=Array.from(c.symbols.entries()).sort(([p,d],[g,A])=>A-d||ze(p,g)),u=a.slice(0,gt).map(([p,d])=>d>1?`${p} x${d}`:p);return a.length>u.length&&u.push(`+ ${a.length-u.length} more`),{file:t.compactPath(h(f,n)),summary:`${c.refs} ${Ke(c.refs,"ref")}`,symbols:u}});return{usedBy:o,hiddenConsumers:Math.max(0,i.length-o.length)}}function rn(e,r,t){if(!Array.isArray(e))return[];const n=e.filter(l).map(s=>{const i=typeof s.file=="string"?r.compactPath(h(s.file,t)):"",o=y(s.count);return i?`${i} x${o}`:""}).filter(s=>s!=="");return ce(n)}function sn(e,r){const t=Array.isArray(e.usageScopes)?e.usageScopes.filter(n=>typeof n=="string"&&n.trim()!==""):[];return t.length===0?"project":t.length===1?h(t[0],r):`${t.length} scopes`}function Pe(e){const r=Array.isArray(e.results)?e.results.filter(l):[e];if(r.length===0)return null;const t=[];for(const n of r){const s=typeof n.detail=="string"?n.detail:"locations";if(l(n.paths)&&Object.keys(n.paths).length>0){t.push("paths:");for(const[c,a]of Object.entries(n.paths))t.push(`${c} = ${String(a)}`)}const i=typeof n.target=="string"?n.target:"";if(t.push(i?`usages ${i}`:"usages"),y(n.referenceCount)===0){t.push(`0 refs in ${typeof n.scopeLabel=="string"?n.scopeLabel:"project"}`),Y(t,n);const c=y(n.itemCount);(n.targetMode==="directory"||n.queryMode!=="explicit")&&c>0&&t.push(`symbols checked: ${c}`);continue}typeof n.summary=="string"&&t.push(n.summary),typeof n.scope=="string"&&t.push(n.scope),Y(t,n);const o=Array.isArray(n.usedBy)?n.usedBy.filter(l):[];for(const c of o){const a=typeof c.file=="string"?c.file:"",u=typeof c.summary=="string"?c.summary:"",p=Array.isArray(c.symbols)?c.symbols.filter(d=>typeof d=="string"):[];t.push(`${a}: ${u}; ${p.join(", ")}`.trim())}typeof n.hiddenConsumers=="string"&&t.push(n.hiddenConsumers);const f=Array.isArray(n.items)?n.items.filter(l):[];t.push(...an(f)),Ne(t,n,f),typeof n.hidden=="string"&&t.push(n.hidden),typeof n.view=="string"&&t.push(`view: ${n.view}`),typeof n.saved=="string"&&t.push(`saved: ${n.saved}`),typeof n.next=="string"&&t.push(`next: ${n.next}`)}return t.join(`
17
+ `)}function Y(e,r){r.targetLocalUsagesHidden===!0&&e.push("target-local usages hidden; use +includeTarget to show")}function Te(e,r){const t=new Map;for(const n of e){const s=r(n),i=t.get(s)??[];i.push(n),t.set(s,i)}return Array.from(t.entries())}function De(e){const r=Array.isArray(e.results)?e.results.filter(l):[e];if(r.length===0)return null;const t=[];for(const n of r){const s=typeof n.detail=="string"?n.detail:"locations",i=Array.isArray(n.target)?n.target.filter(c=>typeof c=="string").join(", "):typeof n.target=="string"?n.target:"",o=on(n.paths,s,i);if(o.length>0){t.push("paths:");for(const[c,a]of o)t.push(`${c} = ${a}`)}t.push(i?`duplicates ${i}`:"duplicates"),typeof n.summary=="string"&&t.push(n.summary);const f=Array.isArray(n.items)?n.items.filter(l):[];if(f.length===0){t.push("no duplicates");continue}for(const c of f)fn(t,c,s);typeof n.hidden=="string"&&t.push(n.hidden),typeof n.view=="string"&&t.push(`view: ${n.view}`),typeof n.saved=="string"&&t.push(`saved: ${n.saved}`),typeof n.next=="string"&&t.push(`next: ${n.next}`)}return t.join(`
18
+ `)}function on(e,r,t){if(!l(e))return[];const n=Object.entries(e).filter(s=>typeof s[1]=="string");return r!=="summary"?n:n.filter(([s])=>t.includes(s))}function fn(e,r,t){e.push(...je(r,t))}function je(e,r){const t=[],n=typeof e.name=="string"?e.name:"",s=y(e.count),i=y(e.variants),o=y(e.exactCopies);if(r!=="summary"&&t.push(""),t.push(`${n} x${s}, ${i} ${Ke(i,"variant")}${o>0?`, exact x${o}`:""}`),r==="summary")return t;const f=Array.isArray(e.groups)?e.groups.filter(l):[];if(r==="code")return f.forEach((c,a)=>cn(t,c,a+1)),t;for(const c of f){const u=(Array.isArray(c.declarations)?c.declarations.filter(l):[]).map(p=>Fe(p,!1));t.push(...ce(u))}return t}function cn(e,r,t){const n=Array.isArray(r.declarations)?r.declarations.filter(l):[],s=y(r.count);e.push(`// variant ${t} x${s}`);const i=ce(n.map(o=>Fe(o,!1)));i.length>0&&e.push(`// ${i.join(", ")}`),typeof r.code=="string"&&e.push(r.code.trimEnd())}function Fe(e,r){const t=typeof e.file=="string"?e.file:"",n=typeof e.meta=="string"?e.meta:"",s=r&&typeof e.sameAs=="string"&&e.sameAs!==""?` same as ${e.sameAs}`:"";return[t,n].filter(i=>i!=="").join(" ")+s}function Ne(e,r,t){const n=t.filter(s=>(typeof s.summary=="string"?s.summary:"").startsWith("0 refs")).map(s=>typeof s.entity=="string"?s.entity:"").filter(s=>s!=="");if(n.length!==0){if(r.queryMode==="explicit"){e.push(`unused: ${V(n,2,"more")}`);return}r.targetMode==="file"&&e.push(`unused symbols: ${n.length}`)}}function an(e){const r=[],t=e.filter(i=>!un(i)),{ownerGroups:n,standalone:s}=ne(t);for(const[i,o]of n){r.length>0&&r.push(""),r.push(`// ${i}:`);for(const f of o)r.push(...Be(f,!1))}s.length>0&&r.length>0&&r.push("");for(const i of s)r.push(...Be(i,!0));return r}function un(e){return typeof e.referenceCount=="number"?e.referenceCount===0:(typeof e.summary=="string"?e.summary:"").startsWith("0 refs")}function Be(e,r){const t=typeof e.entity=="string"?e.entity:"",n=H(t),s=r?t:n.name,i=typeof e.declaredIn=="string"?` [${e.declaredIn}]`:"",o=typeof e.summary=="string"?e.summary:"",f=[`${s}${i}: ${o}`.trim()],c=Array.isArray(e.usedBy)?e.usedBy.filter(a=>typeof a=="string"):[];return f.push(...c),f}function ne(e){const r=new Map,t=[];for(const n of e){const s=typeof n.entity=="string"?n.entity:"",i=H(s);if(!i.owner){t.push(n);continue}const o=r.get(i.owner)??[];o.push(n),r.set(i.owner,o)}return{ownerGroups:Array.from(r.entries()),standalone:t}}function H(e){const r=e.lastIndexOf(".");return r<=0||r>=e.length-1?{owner:null,name:e}:{owner:e.slice(0,r),name:e.slice(r+1)}}function ln(e,r,t,n){const s=typeof e.code=="string"?e.code:"",i=s===""?y(e.lineCount):s.split(/\r?\n/).length,o={...S(e,t,n),entity:F(e.entity,r)},f=L(e.entity,i);if(t.includeRanges&&f&&(o.meta=f),t.toFile){const c=et(t.cwd,t.toFile,s);if(o.writtenTo=c,!t.show)return o}if(t.save){const c=tt(t.cwd,"slice",t.save,e,s);o.saved=c.saved;const a=(0,x.useSessionGuidance)(t.cwd,"inspect.slice.read",`Read saved artifact with: aib session read ${c.saved}`);if(a&&(o.next=a),!t.show)return o}return t.show||i<=t.maxCodeLines?o.code=s:(o.reason="SLICE_TOO_LARGE_FOR_STDOUT",o.lineCount=i,o.limit=t.maxCodeLines,f&&(o.rangeMeta=f)),o}function pn(e,r,t,n){const s=typeof e.code=="string"?e.code:"",i=s===""?0:s.split(/\r?\n/).length,o=re(s),f={...S(e,t,n),entity:F(e.entity,r)},c=L(e.entity,i);if(t.codeMeta!==!1&&t.includeRanges&&c&&(f.meta=c),t.toFile){const a=et(t.cwd,t.toFile,s);if(f.writtenTo=a,!t.show)return f}if(t.save){const a=tt(t.cwd,"code",t.save,e,s);f.saved=a.saved;const u=(0,x.useSessionGuidance)(t.cwd,"inspect.code.read",`Read saved artifact with: aib session read ${a.saved}`);if(u&&(f.next=u),!t.show)return f}return t.show&&(o<=t.maxCodeLines?f.code=s:(f.reason="CODE_TOO_LARGE_FOR_STDOUT",f.nonEmptyLines=o,f.limit=t.maxCodeLines,c&&(f.rangeMeta=c))),f}function re(e){return e===""?0:e.split(/\r?\n/).filter(r=>r.trim()!=="").length}function dn(e){if(typeof e!="string"||e==="")return!1;try{return U.existsSync(e)&&U.statSync(e).isFile()&&U.readFileSync(e,"utf8").trim()!==""}catch{return!1}}function S(e,r,t){const n={op:typeof e.op=="string"?e.op:"unknown"};if(typeof e.id=="string"&&(n.id=e.id),typeof e.sourceFile=="string"){const s=h(e.sourceFile,r);s!==t&&(n.file=s)}return n}function se(e,r,t,n="generic"){return Array.isArray(e)?e.filter(l).map(s=>oe(s,r,t,n)):[]}function yn(e,r,t){if(!Array.isArray(e))return[];const n=e.filter(l);if(t.includeRanges)return n.map(f=>oe(f,r,t,"exports"));const s=[],i=new Map;for(const f of n){const c=oe(f,r,t,"exports"),a=typeof f.sourceModule=="string"?f.sourceModule:"";if(!a){s.push(c);continue}const u=c.replace(` from ${a}`,""),p=i.get(a)??[];p.push(u),i.set(a,p)}if(i.size===0)return s;const o=[];s.length>0&&o.push(`local: ${s.join(", ")}`);for(const[f,c]of i.entries())o.push(`${f}: ${c.join(", ")}`);return o}function k(e,r){return Array.isArray(e)?e.filter(l).map(t=>j(t,r)).filter(t=>t!==""):[]}function gn(e,r,t){const n=Ue(e,r,t),s={};return n.type.length>0&&(s.depsType=n.type),n.value.length>0&&(s.depsValue=n.value),n.unknown.length>0&&(s.depsUnknown=n.unknown),s}function mn(e,r){const t=Ue(e,r),n={};return t.type.length>0&&(n.type=t.type),t.value.length>0&&(n.value=t.value),t.unknown.length>0&&(n.unknown=t.unknown),n}function Ue(e,r,t){if(!(Array.isArray(e.typeOnlyDependencies)||Array.isArray(e.valueDependencies)||Array.isArray(e.unclassifiedDependencies))){const f=Z(e.dependencies,r,t);return{type:[],value:[],unknown:f}}const s=Z(e.typeOnlyDependencies,r,t),i=Z(e.valueDependencies,r,t),o=Z(e.unclassifiedDependencies,r,t);return{type:s,value:i,unknown:o}}function hn(e,r,t,n){const s=e.ok===!1,i={...S(e,t,n)};if(!s){const c=Cn(e.modules,r,t);c.length>0&&(i.targets=c,i.moduleCount=c.length),t.details===!0&&(i.modules=kn(e.modules,r,t))}for(const c of["planId","executable","next"])e[c]!==void 0&&(i[c]=e[c]);if(s&&(i.ok=!1,i.code=typeof e.code=="string"?e.code:"MODULE_PLAN_BLOCKED"),l(e.api)&&(i.api=An(e.api,r)),l(e.boundary)&&(i.boundary=vn(e.boundary,r,t),s&&l(i.boundary))){const c=bn(i.boundary);c.length>0&&(i.blocking=c,delete i.boundary)}const o=Sn(i.boundary);if(o.length>0?i.warnings=o:Array.isArray(e.warnings)&&e.warnings.length>0&&(i.warnings=e.warnings.filter(c=>typeof c=="string").map(c=>tr(c,t))),l(e.facade)){const c=Tn(e.facade,t);i.facade=s?xn(c):c}const f=Bn(e);if(f&&(i.integrity=f),Array.isArray(e.cycles)&&e.cycles.length>0?i.cycles=e.cycles:i.cycles="none",!s&&l(e.preview)&&(i.preview=Dn(e.preview,t,e)),Array.isArray(e.symbolErrors)&&e.symbolErrors.length>0&&(i.ok=!1,i.symbolErrors=e.symbolErrors),s){const c=$n(i);c.length>0&&(i.affected=c),i.next||(i.next="Revise the plan, then rerun modulePlan preview.")}return i}function An(e,r){const t={};typeof e.status=="string"&&(t.status=e.status),typeof e.before=="number"&&(t.before=e.before),typeof e.after=="number"&&(t.after=e.after);const n=k(e.removed,r),s=k(e.added,r);return n.length>0&&(t.removed=n),s.length>0&&(t.added=s),t}function vn(e,r,t){const s=(Array.isArray(e.nonExportedImports)?e.nonExportedImports:[]).filter(l).map(i=>{const o={code:typeof i.code=="string"?i.code:"MODULE_PLAN_BOUNDARY_WARNING",from:typeof i.importerFile=="string"?h(i.importerFile,t):"",source:typeof i.sourceFile=="string"?h(i.sourceFile,t):"",usage:typeof i.usageKind=="string"?i.usageKind:"unknown",symbols:k(i.symbols,r)},f=Ge(i.suggestedFixes,r,t);return f.length>0&&(o.suggestedFixes=f),typeof i.hint=="string"&&(o.hint=i.hint),o}).filter(i=>Array.isArray(i.symbols)&&i.symbols.length>0);return s.length>0?{nonExportedImports:s}:{}}function Ge(e,r,t){return Array.isArray(e)?e.filter(l).map(n=>{const s={kind:typeof n.kind=="string"?n.kind:"unknown"},i=j(n.symbol,r);if(i&&(s.symbol=i),typeof n.toFile=="string"&&(s.to=h(n.toFile,t)),typeof n.fromFile=="string"&&(s.from=h(n.fromFile,t)),typeof n.risk=="string"&&(s.risk=n.risk),typeof n.warning=="string"&&(s.warning=n.warning),l(n.saferAlternative)){const f=Ge([n.saferAlternative],r,t)[0];f&&(s.saferAlternative=f)}return s}).filter(n=>typeof n.symbol=="string"):[]}function bn(e){return(Array.isArray(e.nonExportedImports)?e.nonExportedImports.filter(l):[]).map(t=>{const n={code:t.code??"MODULE_PLAN_BOUNDARY_WARNING",from:t.from??"",source:t.source??"",usage:t.usage??"unknown",symbols:Array.isArray(t.symbols)?t.symbols:[]};return Array.isArray(t.suggestedFixes)&&t.suggestedFixes.length>0&&(n.suggestedFixes=t.suggestedFixes),typeof t.hint=="string"&&(n.hint=t.hint),n})}function xn(e){const r={};return typeof e.file=="string"&&(r.file=e.file),Array.isArray(e.exports)&&(r.exports=e.exports.length),r}function $n(e){const r=new Set,t=Array.isArray(e.blocking)?e.blocking.filter(l):[];for(const n of t)typeof n.from=="string"&&n.from&&r.add(n.from),typeof n.source=="string"&&n.source&&r.add(n.source);return Array.from(r)}function Sn(e){return!l(e)||!Array.isArray(e.nonExportedImports)?[]:e.nonExportedImports.filter(l).map(r=>{const t=typeof r.from=="string"?r.from:"",n=typeof r.source=="string"?r.source:"",s=Array.isArray(r.symbols)?r.symbols.filter(i=>typeof i=="string"):[];return t&&n&&s.length>0?`${t} imports non-exported ${s.join(", ")} from ${n}`:""}).filter(r=>r!=="")}function kn(e,r,t){if(!Array.isArray(e))return{};const n={};for(const s of e){if(!l(s)||typeof s.targetFile!="string")continue;const i=h(s.targetFile,t),o={owns:k(s.symbols,r)},f=_n(s.imports,r,t);Object.keys(f).length>0&&(o.uses=f);const c=k(s.internalDependencies,r);c.length>0&&(o.internalDeps=c);const a=Pn(s.unassignedDependencies,r);Object.keys(a).length>0&&(o.unassigned=a),n[i]=o}return n}function Cn(e,r,t){return Array.isArray(e)?e.filter(l).filter(n=>typeof n.targetFile=="string").map(n=>{const s={file:h(String(n.targetFile),t),summary:On(n,r,t)},i=En(n.unassignedDependencies);return i!==""&&(s.warning=`unassigned ${i}`),s}):[]}function On(e,r,t){const n=He(e.symbols,r,!0),s=He(e.symbols,r,!1),i=In(e.imports,r,t),o=k(e.internalDependencies,r).length,f=[`exports ${V(n,4)||"none"}`];return s.length>0&&f.push(`private ${V(s,3)}`),i!==""&&f.push(`imports ${i}`),o>0&&f.push(`internalDeps ${o}`),f.join("; ")}function He(e,r,t){return Array.isArray(e)?e.filter(l).filter(n=>n.exported===!0===t).map(n=>j(n,r)).filter(n=>n!==""):[]}function In(e,r,t){if(!l(e))return"";const n=[],s={typeOnly:"type",value:"run",unclassified:"unclassified"};for(const i of["typeOnly","value","unclassified"]){const o=Mn(e[i],r,t);o!==""&&n.push(`${s[i]} ${o}`)}return n.join("; ")}function Mn(e,r,t){if(!Array.isArray(e))return"";const n=e.filter(l).filter(s=>typeof s.targetFile=="string").map(s=>{const i=h(String(s.targetFile),t),o=k(s.symbols,r).filter(f=>typeof f=="string");return`${i}: ${V(o,3)||"none"}`});return V(n,2,"more imports")}function En(e){if(!l(e))return"";const r=[];for(const t of["typeOnly","value","unclassified"]){const n=e[t];Array.isArray(n)&&n.length>0&&r.push(`${t} ${n.length}`)}return r.join("; ")}function V(e,r,t="more"){if(e.length===0)return"";const n=e.slice(0,r),s=e.length-n.length;return s>0?`${n.join(", ")}, +${s} ${t}`:n.join(", ")}function _n(e,r,t){if(!l(e))return{};const n={},s={typeOnly:"type",value:"run",unclassified:"unclassified"};for(const i of["typeOnly","value","unclassified"]){const o=Ln(e[i],r,t);Object.keys(o).length>0&&(n[s[i]]=o)}return n}function Ln(e,r,t){if(!Array.isArray(e))return{};const n={};for(const s of e)!l(s)||typeof s.targetFile!="string"||(n[h(s.targetFile,t)]=k(s.symbols,r));return n}function Pn(e,r){if(!l(e))return{};const t={};for(const n of["typeOnly","value","unclassified"]){const s=k(e[n],r);s.length>0&&(t[n]=s)}return t}function Tn(e,r){const t={};return typeof e.file=="string"&&(t.file=h(e.file,r)),Array.isArray(e.exports)&&e.exports.length>0&&(t.exports=e.exports.filter(n=>typeof n=="string").map(n=>n.match(/from\s+"([^"]+)"/)?.[1]??n)),t}function Dn(e,r,t){const n={};typeof e.dir=="string"&&(n.dir=h(e.dir,r));const s=[];let i=0,o=0,f=0;if(Array.isArray(e.files)){const a={};for(const u of e.files){if(!l(u)||typeof u.targetFile!="string"||typeof u.previewFile!="string")continue;i+=1;const p=h(u.targetFile,r),d=y(u.lineCount);a[h(u.targetFile,r)]={file:h(u.previewFile,r),lines:d},d>=pt&&s.push(`${p} ${d}l`)}Object.keys(a).length>0&&(n.files=a)}l(e.facade)&&typeof e.facade.previewFile=="string"&&(o=y(e.facade.lineCount),n.facade={file:h(e.facade.previewFile,r),lines:o}),l(e.patch)&&typeof e.patch.file=="string"&&(f=y(e.patch.lineCount),n.patch={file:h(e.patch.file,r),lines:f},f>=dt&&s.push(`patch ${f}l`)),n.summary=jn(i,o,f,t),s.length>0&&(n.large=s);const c=Fn(t);return c.length>0&&(n.warnings=c),n.next=Nn(t,s.length>0),n}function jn(e,r,t,n){const s=[`${e} ${e===1?"file":"files"}`];return r>0&&s.push(`facade ${r}l`),t>0&&s.push(`patch ${t}l`),s.push(ie(n)?"cycles detected":"cycles none"),s.join("; ")}function Fn(e){return ie(e)?["runtime cycles detected"]:[]}function Nn(e,r){return ie(e)?["fix module plan before applying","rerun modulePlan"]:[r?"check summary/api/cycles/imports before reading large preview artifacts":"check summary/api/cycles/imports","read targeted preview artifacts only if a warning/check points there","use top-level next for apply/revise action"]}function ie(e){return Array.isArray(e.cycles)&&e.cycles.length>0}function Bn(e){const r=Array.isArray(e.modules)?e.modules.filter(l):[];if(r.length===0)return"";const t=r.reduce((o,f)=>o+(Array.isArray(f.symbols)?f.symbols.length:0),0),n=r.reduce((o,f)=>o+Un(f.imports),0),s=l(e.facade)&&Array.isArray(e.facade.exports)?e.facade.exports.length:0,i=[`${t} declarations moved unchanged`,`${n} imports generated`];return s>0&&i.push(`facade exports ${s}`),i.join("; ")}function Un(e){if(!l(e))return 0;let r=0;for(const t of["typeOnly","value","unclassified"]){const n=e[t];if(Array.isArray(n))for(const s of n)l(s)&&Array.isArray(s.symbols)&&(r+=s.symbols.length)}return r}function Z(e,r,t){return k(e,r)}function Gn(e,r,t){const n=y(e.memberCount),s=y(e.memberOffset),i=y(e.memberLimit),o=y(e.hiddenMemberCount),f=se(e.members,r,t,"members"),c=f.length;o>0&&f.push(`+ ${o} hidden members`);const a={members:f};return o>0?(a.count=n,a.page=`${s}..${s+c-1} of ${n}`,a.hint="Use --all to list all members, --offset <n> --limit <n> to page, or inspect code <member> --parent <entity>."):n>q&&(a.count=n),s>0&&o===0&&(a.page=`${s}..${s+f.length-1} of ${n}`),a}function Hn(e){const r=y(e.localDeclarationCount),t=Ve(e.reexports);return r===0&&t.length>0?`facade only; ${t.length} ${t.length===1?"re-export":"re-exports"}; 0 local declarations`:r===0?"0 local declarations":`${r} local ${r===1?"declaration":"declarations"}; ${t.length} ${t.length===1?"re-export":"re-exports"}`}function Ve(e){return Array.isArray(e)?e.filter(l).map(r=>typeof r.module=="string"?r.module:"").filter(r=>r!==""):[]}function oe(e,r,t,n){const s=j(e,r),i=typeof e.signature=="string"?e.signature:"",o=t.includeRanges?L(e):"",f=typeof e.sourceModule=="string"?`from ${e.sourceModule}`:"";return n==="file"||n==="exports"?Vn(e,s,i,o,f,n):n==="members"?Wn(e,s,i,o):s==="constructor"?[o,f,i||s].filter(a=>a!=="").join(" "):[s,o,f,i].filter(a=>a!=="").join(" ")}function Vn(e,r,t,n,s,i){const o=i==="file"&&e.exported===!0?"export ":"",f=qn(e,t);return[`${o}${r}${f}`,n,s].filter(a=>a!=="").join(" ")}function qn(e,r){const t=typeof e.name=="string"?e.name:"",n=typeof e.kind=="string"?le(e.kind):null;if(!t||!r||n!=="function"&&n!=="method")return"";const s=r.indexOf(t);if(s<0)return"";const i=r.slice(s+t.length).trim();return i.startsWith("(")?i:""}function Wn(e,r,t,n){const s=typeof e.kind=="string"?le(e.kind):null,i=typeof e.name=="string"?e.name:"";let o=t||qe(r);if(s==="property"&&i){o=r;const f=Kn(t,i);f&&(o+=f)}return[o,n].filter(f=>f!=="").join(" ")}function Kn(e,r){if(!e)return"";const t=e.indexOf(r);if(t<0)return"";const n=e.slice(t+r.length).trim();return n.startsWith(":")?n:""}function zn(e,r,t){const n=Rn(e,["id","op","ok","code","error"]);if(typeof e.sourceFile=="string"){const s=h(e.sourceFile,r);s!==t&&(n.file=s)}if(e.code==="INSPECT_SYMBOL_NOT_FOUND"){const s=Jn(e);s&&(n.missingSymbols=[s])}return n}function D(e){return e.code==="INSPECT_SYMBOL_NOT_FOUND"&&E(e).length>0}function E(e){return Array.isArray(e.missingSymbols)?e.missingSymbols.filter(r=>typeof r=="string"&&r.length>0):[]}function Jn(e){const r=typeof e.error=="string"?e.error:"",t="Symbol not found:";if(!r.startsWith(t))return null;const n=r.slice(t.length).trim();if(!n)return null;const s=n.indexOf(":");return s>0?n.slice(s+1).trim():n}function j(e,r){if(!l(e))return"";const t=typeof e.name=="string"?e.name:"",n=typeof e.kind=="string"?le(e.kind):null;return t?n==="constructor"?"constructor":n?`${Qn(n,r)}${wn(n,r)}${t}`:t:""}function F(e,r){return fe(e)||j(e,r)}function X(e){if(!l(e))return"";const r=Array.isArray(e.path)?e.path.filter(t=>typeof t=="string"&&t.trim()!==""):[];return r.length>0?r.join("."):fe(e)}function fe(e){return l(e)&&typeof e.name=="string"?e.name:""}function qe(e){const r=e.indexOf("-");if(r>0&&r<=3)return e.slice(r+1);const t=e.indexOf(":");return t>0?e.slice(t+1):e}function We(e,r){return r>q?{[e]:r}:{}}function Ke(e,r){return e===1?r:`${r}s`}function ze(e,r){return e.localeCompare(r,void 0,{numeric:!0})}function Yn(e,r,t){const n=new Set(r?[r]:[]);for(const s of e){typeof s.declaredIn=="string"&&n.add(h(s.declaredIn,t));const i=Array.isArray(s.usedBy)?s.usedBy.filter(l):[];for(const o of i)typeof o.file=="string"&&n.add(h(o.file,t))}return Array.from(n)}function Je(e,r,t){const n=new Set(r);for(const s of e){const i=Array.isArray(s.variants)?s.variants.filter(l):[];for(const o of i){const f=Array.isArray(o.declarations)?o.declarations.filter(l):[];for(const c of f){typeof c.file=="string"&&n.add(h(c.file,t));const a=l(c.sameAs)?c.sameAs:null;a&&typeof a.file=="string"&&n.add(h(a.file,t))}}}return Array.from(n)}function Zn(e){const r=Xe(e.map(t=>t.replace(/\\/g,"/")));return Ze(r)}function Ye(e,r){const t=e.map(s=>s.replace(/\\/g,"/")),n=Xe(t);for(const s of r.map(i=>ae(i)).filter(i=>i.includes("/"))){const i=`<${$.basename(s)}>`;n.some(o=>o.token===i||o.prefix===s)||t.some(o=>o===s||o.startsWith(`${s}/`))&&n.push({token:i,prefix:s})}return n.sort((s,i)=>i.prefix.length-s.prefix.length),Ze(n)}function Ze(e){return{aliases:e,compactPath(r){const t=ae(r),n=e.find(s=>t===s.prefix||t.startsWith(`${s.prefix}/`));return n?t===n.prefix?n.token:`${n.token}/${t.slice(n.prefix.length+1)}`:t}}}function Xe(e){const r=new Map;for(const n of e){const s=ae(n).split("/");for(let i=2;i<s.length;i+=1){const o=s.slice(0,i).join("/");o.length>=8&&r.set(o,(r.get(o)??0)+1)}}const t=new Set;return Array.from(r.entries()).map(([n,s])=>{const i=`<${$.basename(n)}>`;return{prefix:n,count:s,token:i,score:Math.max(0,n.length-i.length)*s}}).filter(n=>n.count>=2&&n.score>=12).sort((n,s)=>s.score-n.score||n.prefix.localeCompare(s.prefix)).filter(n=>t.has(n.token)?!1:(t.add(n.token),!0)).slice(0,6).sort((n,s)=>s.prefix.length-n.prefix.length).map(n=>({token:n.token,prefix:n.prefix}))}function Qe(e,r){if(e.aliases.length===0)return null;const t=JSON.stringify(r),n={};for(const s of e.aliases)t.includes(s.token)&&(n[s.token]=s.prefix);return Object.keys(n).length>0?n:null}function ce(e){const r=new Map,t=[];for(const n of e){const s=n.startsWith("<")?n.indexOf(">"):-1;if(s<=0){t.push(n);continue}const i=n.indexOf("/",s);if(i<0){t.push(n);continue}const o=n.slice(0,i),f=n.slice(i+1),c=r.get(o)??[];c.push(f),r.set(o,c)}return[...Array.from(r.entries()).map(([n,s])=>s.length===1?`${n}/${s[0]}`:`${n}/: ${s.join(", ")}`),...t].sort()}function ae(e){return e.replace(/\\/g,"/")}function ue(e,r,t){const n=e.indexOf(r);if(n<=0)return null;const s=e.slice(0,n).trim(),i=e.slice(n+r.length).trim();if(!s||!i)return null;const o=Xn(s,t);return o?{raw:e,symbolName:i,symbolKind:o}:null}function Xn(e,r){const t=e.toLowerCase();return we(t)?t:Object.entries(r.entityKindAliases).find(([,s])=>s===e)?.[0]??null}function Qn(e,r){return Re(e)?r.entityKindAliases[e]:e}function wn(e,r){return Re(e)?r.selectorSeparator:":"}function le(e){const r=e.toLowerCase();return we(r)?r:null}function we(e){return lt.includes(e)}function Re(e){return ft.ENTITY_KIND_IDS.includes(e)}function Rn(e,r){const t={};for(const n of r)e[n]!==void 0&&(t[n]=e[n]);return t}function er(e,r){const t=e.filter(l).map(s=>typeof s.sourceFile=="string"?h(s.sourceFile,r):null).filter(s=>!!s),n=Array.from(new Set(t));return n.length===1?n[0]??null:null}function h(e,r){const t=$.isAbsolute(e)?e:$.resolve(r.cwd,e),n=$.relative(r.cwd,t),i=(n&&!n.startsWith("..")&&!$.isAbsolute(n)?n:e).replace(/\\/g,"/"),o=(0,ut.compactDisplayPathWithMatch)(r.cwd,t,r.displayPathAliases??[]);return o.alias&&r.pathAliasHints&&(r.pathAliasHints.some(c=>c.alias===o.alias.token&&c.original===i&&c.display===o.displayPath)||r.pathAliasHints.push({alias:o.alias.token,original:i,display:o.displayPath})),o.displayPath}function tr(e,r){const t=$.resolve(r.cwd),n=t.replace(/\\/g,"/");return e.replaceAll(`${t}\\`,"").replaceAll(`${n}/`,"").replace(/\\/g,"/")}function et(e,r,t){const n=$.isAbsolute(r)?r:$.resolve(e,r);return U.mkdirSync($.dirname(n),{recursive:!0}),U.writeFileSync(n,t,"utf8"),$.relative(e,n).replace(/\\/g,"/")}function tt(e,r,t,n,s){const i=typeof n.sourceFile=="string"&&$.extname(n.sourceFile)||".ts",o=(0,x.saveSessionOutputText)(e,r,t,s,i);return{saved:o.saved,last:o.last}}function L(e,r){if(!l(e)||!l(e.range))return"";const t=nt(e.range,"start"),n=nt(e.range,"end");if(!t||!n)return"";const s=t.line+1,i=n.line+1;return`@${s}..${i}`}function nt(e,r){const t=e[r];return!l(t)||typeof t.line!="number"?null:{line:t.line}}function y(e){return typeof e=="number"?e:0}function l(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}
@@ -0,0 +1,9 @@
1
+ "use strict";var xe=exports&&exports.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(t,n);(!s||("get"in s?!t.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,s)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),Se=exports&&exports.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),k=exports&&exports.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(t!=null)for(var r=e(t),s=0;s<r.length;s++)r[s]!=="default"&&xe(n,t,r[s]);return Se(n,t),n}})();Object.defineProperty(exports,"__esModule",{value:!0}),exports.isInspectGraphRequest=Ae,exports.runInspectGraph=Ee,exports.formatGraphAgentText=H,exports.buildInspectGraphModel=Me;const x=k(require("node:fs")),d=k(require("node:path")),ve=require("../config/glob-match"),_e=require("../config/local-config"),J=require("../shared/agent-text"),y=require("../shared/errors"),A=require("./session-workspace"),we=require("./json-file-input"),j=[".ts",".tsx",".mts",".cts"],D=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],Pe=new Set(["node_modules",".git","dist","out","build",".tmp"]),Z=12,S=8,X="tsconfig.json";function Ae(e,t){return e[0]==="graph"}function Ee(e,t,n){const r=(0,_e.resolveLocalCliConfig)(e),s=Oe(e,t,n);if(s){const i=Ce(s).map((l,a)=>{if(!N(l))throw new y.CliError("INVALID_GRAPH_REQUEST",`inspect graph request at index ${a} must be an object.`);return Q(e,Ne(e,l,r.config.inspect.graph.exclude))});return i.length===1?i[0]:$e(i)}return Q(e,Le(e,t,r.config.inspect.graph.exclude))}function Q(e,t){const n=t.fromFile?dt(e,t.fromFile):ee(e,t),r=t.toFile?gt(e,t.toFile,n):null,s=t.save?(0,A.saveSessionOutputJson)(e,"graph",t.save,n):null,o=Qe(e,n,{focus:t.focus,depth:t.depth,writtenTo:r,symbols:t.symbols,symbolUsage:t.symbolUsage,sections:t.sections,...t.view!==void 0?{view:t.view}:{}});return s&&(o.saved=s.saved,o.next=`Focus with: aib inspect graph --from-file ${s.saved} --focus <file>`),(0,J.attachAgentText)(o,H(o))}function $e(e){const t=e.map(r=>typeof r.saved=="string"?r.saved:"").filter(r=>r!==""),n={operation:"inspect.graphBatch",summary:`${e.length} graph requests${t.length>0?`, ${t.length} saved`:""}`,results:e.map(Ie)};return t.length>0?(n.saved=t,n.next="Focus a saved graph with: aib inspect graph --from-file <saved> --focus <file>"):n.next="Focus files with --focus, or inspect exports/code on relevant files.",(0,J.attachAgentText)(n,H(n))}function Ie(e){const t=Object.entries(e).filter(([n])=>n!=="operation"&&n!=="last"&&n!=="next"&&!(n==="graphFile"&&typeof e.saved=="string"));return Object.fromEntries(t)}function H(e){const t=typeof e.operation=="string"?e.operation:"";if(t!=="inspect.graph"&&t!=="inspect.graphBatch")return null;const n=[t];typeof e.summary=="string"&&n.push(e.summary);const r=Array.isArray(e.results)?e.results:null;return r&&(O(n,"view",e.view),O(n,"excluded",e.excluded),Y(n,e.paths)),r?r.forEach((s,o)=>{N(s)&&(n.push(`[${o+1}] ${typeof s.summary=="string"?s.summary:"graph result"}`),K(n,s))}):K(n,e),r||_(n,"saved",e.saved),O(n,"next",e.next),n.join(`
2
+ `)}function K(e,t){O(e,"view",t.view),O(e,"excluded",t.excluded),Y(e,t.paths),_(e,"hubs",t.hubs),_(e,"scopeEntrypoints",t.scopeEntrypoints),_(e,"scopeLeaves",t.scopeLeaves),_(e,"edges",t.edges),Fe(e,t.focus),O(e,"saved",t.saved)}function Fe(e,t){if(!(!Array.isArray(t)||t.length===0)){e.push("focus:");for(const n of t){if(!N(n))continue;const r=typeof n.file=="string"?n.file:"unknown";e.push(`${r}:`),_(e,"imports",n.imports),_(e,"symbols",n.symbols),Ge(e,n.usage),_(e,"importsOther",n.importsOther),_(e,"importedBy",n.importedBy),_(e,"external",n.external),_(e,"omittedLocalImports",n.omittedLocalImports),O(e,"error",n.error)}}}function Ge(e,t){if(N(t))for(const n of["value","type","unknown"])_(e,`usage.${n}`,t[n])}function Y(e,t){if(!(!N(t)||Object.keys(t).length===0)){e.push("paths:");for(const[n,r]of Object.entries(t))typeof r=="string"&&e.push(`${n} = ${r}`)}}function O(e,t,n){typeof n=="string"&&n!==""&&e.push(`${t}: ${n}`)}function _(e,t,n){const r=Array.isArray(n)?n.filter(s=>typeof s=="string"&&s!==""):[];if(r.length!==0){e.push(`${t}:`);for(const s of r)e.push(s)}}function Oe(e,t,n){if(n!==void 0){if(!N(n))throw new y.CliError("INVALID_GRAPH_STDIN","inspect graph --stdin expects a JSON object payload.");return n}const r=St(t,"--from-json");return r?(0,we.readJsonObjectFile)(e,r,"INVALID_GRAPH_JSON_FILE"):null}function Ce(e){return Array.isArray(e.requests)?e.requests:[e]}function Le(e,t,n){const r=[],s=[],o=[],i=[];let l,a,f,h,c,g=(0,A.readSessionBooleanPref)(e,"inspect.graph.symbols",!1),v=(0,A.readSessionBooleanPref)(e,"inspect.graph.symbolUsage",!1);for(let u=1;u<t.length;u+=1){const m=t[u];if(m){if(m==="--focus"){const p=t[u+1];if(!p)throw new y.CliError("MISSING_FLAG_VALUE","Expected a value after --focus.");s.push(I(e,$(e,p))),u+=1;continue}if(m==="--depth"){const p=t[u+1],b=p===void 0?Number.NaN:Number.parseInt(p,10);if(!Number.isInteger(b)||b<0||b>2)throw new y.CliError("INVALID_GRAPH_DEPTH","inspect graph --depth expects 0, 1, or 2.");l=b,u+=1;continue}if(m==="--view"){const p=t[u+1];if(!p)throw new y.CliError("MISSING_FLAG_VALUE","Expected a value after --view.");a=ge(p),u+=1;continue}if(m==="--to-file"){const p=t[u+1];if(!p)throw new y.CliError("MISSING_FLAG_VALUE","Expected a value after --to-file.");f=p,u+=1;continue}if(m==="--from-file"){const p=t[u+1];if(!p)throw new y.CliError("MISSING_FLAG_VALUE","Expected a value after --from-file.");h=p,u+=1;continue}if(m==="--save"){const p=t[u+1];if(!p)throw new y.CliError("MISSING_FLAG_VALUE","Expected a value after --save.");c=p,u+=1;continue}if(m==="--exclude"){const p=t[u+1];if(!p)throw new y.CliError("MISSING_FLAG_VALUE","Expected a value after --exclude.");o.push(p),u+=1;continue}if(m==="--exclude-from"){const p=t[u+1];if(!p)throw new y.CliError("MISSING_FLAG_VALUE","Expected a value after --exclude-from.");i.push(p),u+=1;continue}if(m==="--symbols"){g=!0;continue}if(m==="--symbol-usage"){g=!0,v=!0;continue}if(m.startsWith("--"))throw new y.CliError("UNKNOWN_INSPECT_GRAPH_FLAG",`Unknown inspect graph flag: ${m}`);r.push(I(e,$(e,m)))}}if(h&&r.length>0)throw new y.CliError("GRAPH_INPUT_SOURCE_CONFLICT","Use either inspect graph <scopes...> or --from-file, not both.");if(f&&c)throw new y.CliError("GRAPH_OUTPUT_TARGET_CONFLICT","Use either inspect graph --to-file or --save, not both.");if(!h&&r.length===0)throw new y.CliError("GRAPH_SCOPE_REQUIRED","inspect graph expects at least one file or directory scope.");const E=l??ye(a??R(e,r,h)),P=l!==void 0?be(l):a??R(e,r,h);return{scopes:r,focus:s,depth:E,symbols:g||v,symbolUsage:v,sections:de(e),excludePatterns:U([...n,...i.flatMap(u=>ne(e,u)),...o]),...c!==void 0?{save:c}:{},...f!==void 0?{toFile:f}:{},...h!==void 0?{fromFile:h}:{},...P!==void 0?{view:P}:{}}}function Ne(e,t,n){const r=G(t.scopes)??G(t.scope)??G(t.files)??G(t.file)??[],s=G(t.focus)??[],o=G(t.exclude)??G(t.excludePatterns)??[],i=G(t.excludeFrom)??[],l=M(t.fromFile)??M(t.from),a=M(t.toFile)??M(t.outputFile),f=M(t.save),h=xt(t.depth),c=t.view!==void 0?ge(t.view):void 0,v=w(t.symbolUsage)??(0,A.readSessionBooleanPref)(e,"inspect.graph.symbolUsage",!1),E=v||(w(t.symbols)??(0,A.readSessionBooleanPref)(e,"inspect.graph.symbols",!1));if(l&&r.length>0)throw new y.CliError("GRAPH_INPUT_SOURCE_CONFLICT","Use either inspect graph scopes or fromFile/from, not both.");if(a&&f)throw new y.CliError("GRAPH_OUTPUT_TARGET_CONFLICT","Use either toFile or save, not both.");if(!l&&r.length===0)throw new y.CliError("GRAPH_SCOPE_REQUIRED","inspect graph JSON expects scope/scopes or fromFile/from.");const P=r.map(p=>I(e,$(e,p))),u=h??ye(c??R(e,P,l??void 0)),m=h!==void 0?be(h):c??R(e,P,l??void 0);return{scopes:P,focus:s.map(p=>I(e,$(e,p))),depth:u,symbols:E,symbolUsage:v,sections:bt(e,t),excludePatterns:U([...n,...i.flatMap(p=>ne(e,p)),...o]),...f?{save:f}:{},...a?{toFile:a}:{},...l?{fromFile:l}:{},...m!==void 0?{view:m}:{}}}function ee(e,t){const n=He(e),r=Te(e,t.excludePatterns),s=Be(e,t.scopes,r),o=new Set(s);let i=s;for(let u=0;u<t.depth;u+=1){const m=new Set;for(const p of i)for(const b of re(e,p,n).imports)!r.isExcluded(b)&&!o.has(b)&&(o.add(b),m.add(b));i=Array.from(m).sort()}const l=Array.from(o).sort(),a=new Set(l.map(u=>I(e,u))),f=new Map,h=new Map,c=new Map;for(const u of l){const m=re(e,u,n),p=I(e,u);h.set(p,m.external);const b=[];for(const C of m.imports){if(r.isExcluded(C))continue;const B=I(e,C);if(!a.has(B)){b.push(B);continue}f.set(`${p}
3
+ ${B}
4
+ ${m.specifiers.get(C)??""}`,{from:p,to:B,specifier:m.specifiers.get(C)??"",resolution:m.resolutions.get(C)??"relative",symbols:m.symbols.get(C)??[]})}b.length>0&&c.set(p,U(b))}const g=Array.from(f.values()).sort(wt),v=new Map;for(const u of l){const m=I(e,u),p={file:m,imports:[],importedBy:[],external:h.get(m)??[]},b=c.get(m);b&&b.length>0&&(p.omittedLocalImports=b),v.set(m,p)}for(const u of g)v.get(u.from)?.imports.push(u.to),v.get(u.to)?.importedBy.push(u.from);const E=U(Array.from(h.values()).flat()),P=r.excluded.size>0?{count:r.excluded.size,patterns:t.excludePatterns}:void 0;return{operation:"inspect.graph",version:1,root:d.resolve(e),scopes:t.scopes,generatedAt:new Date().toISOString(),files:Array.from(v.values()).sort((u,m)=>u.file.localeCompare(m.file)),edges:g,externalPackages:E,timeoutHint:Ue(v.size,g.length,t.view),...P?{excluded:P}:{}}}function Me(e,t){return ee(e,{scopes:t.scopes,focus:[],depth:t.depth,symbols:!0,symbolUsage:t.symbolUsage??!0,sections:{hubs:!1,entrypoints:!1,leaves:!1,edges:!0},excludePatterns:t.excludePatterns??[]})}function Ue(e,t,n){const r=n==="expanded"?2:n==="neighbors"?1.5:1;return{recommendedTimeoutMs:Math.min(6e5,Math.max(6e4,Math.round((3e4+e*250+t*100)*r))),fileCount:e,edgeCount:t,view:n??"local"}}function Be(e,t,n){const r=new Set;for(const s of t){const o=$(e,s);if(!x.existsSync(o))throw new y.CliError("GRAPH_SCOPE_NOT_FOUND",`Graph scope does not exist: ${s}`);const i=x.statSync(o);if(i.isDirectory()){for(const l of te(o))n.isExcluded(l)||r.add(l);continue}i.isFile()&&W(o)&&!n.isExcluded(o)&&r.add(o)}return Array.from(r).sort()}function Te(e,t){const n=U(t.map(s=>F(s.trim())).filter(Boolean)),r=new Set;return{patterns:n,excluded:r,isExcluded(s){if(n.length===0)return!1;const o=I(e,s),i=(0,ve.matchesAnyGlob)(o,n);return i&&r.add(o),i}}}function te(e){const t=[];for(const n of x.readdirSync(e,{withFileTypes:!0})){if(n.isDirectory()){Pe.has(n.name)||t.push(...te(d.join(e,n.name)));continue}const r=d.join(e,n.name);n.isFile()&&W(r)&&t.push(r)}return t}function ne(e,t){const n=$(e,t);try{return x.readFileSync(n,"utf8").split(/\r?\n/).map(r=>r.trim()).filter(r=>r.length>0&&!r.startsWith("#"))}catch{throw new y.CliError("GRAPH_EXCLUDE_FILE_NOT_FOUND",`Could not read inspect graph --exclude-from file: ${t}`)}}function re(e,t,n){const r=x.readFileSync(t,"utf8"),s=new Set,o=new Set,i=new Map,l=new Map,a=new Map;for(const f of Re(r)){const{specifier:h}=f;if(h.startsWith(".")){const g=De(t,h);g&&(s.add(g),i.set(g,h),l.set(g,"relative"),a.set(g,oe(a.get(g),f.symbols)));continue}const c=n.resolve(t,h);if(c){s.add(c),i.set(c,h),l.set(c,"tsconfig-paths"),a.set(c,oe(a.get(c),f.symbols));continue}o.add(vt(h))}return{imports:Array.from(s).sort(),external:Array.from(o).sort(),specifiers:i,resolutions:l,symbols:a}}function Re(e){const t=[],n=new Set,r=le(e),s=/\bimport\s+(type\s+)?(?:([$A-Z_a-z][$\w]*)\s*,\s*)?(\*\s+as\s+[$A-Z_a-z][$\w]*|\{[\s\S]*?\})\s+from\s+["']([^"']+)["']/g;for(const a of r.matchAll(s)){const f=a[2]?.trim(),h=a[3]?.trim()??"",c=a[4]?.trim();T(t,n,c,je(f,h,!!a[1]))}const o=/\bimport\s+(type\s+)?([$A-Z_a-z][$\w]*)\s+from\s+["']([^"']+)["']/g;for(const a of r.matchAll(o)){const f=a[2]?.trim(),h=a[3]?.trim();T(t,n,h,f?[L(`default:${f}`,a[1]?"type":"value")]:[])}const i=/\bexport\s+(type\s+)?(\{[\s\S]*?\}|\*)\s+from\s+["']([^"']+)["']/g;for(const a of r.matchAll(i)){const f=a[2]?.trim()??"",h=a[3]?.trim();T(t,n,h,f==="*"?[L("*",a[1]?"type":"value")]:se(f,!!a[1]))}const l=[/\bimport\s+["']([^"']+)["']/g,/\bimport\s*\(\s*["']([^"']+)["']\s*\)/g,/\brequire\s*\(\s*["']([^"']+)["']\s*\)/g];for(const a of l)for(const f of r.matchAll(a))T(t,n,f[1]?.trim(),[]);return t}function T(e,t,n,r){if(!n)return;const s=ie(r.filter(i=>i.name.trim()!=="")),o=`${n}
5
+ ${s.map(i=>`${i.usage}:${i.name}`).join(`
6
+ `)}`;t.has(o)||(t.add(o),e.push({specifier:n,symbols:s}))}function je(e,t,n){const r=n?"type":"value",s=[];e&&s.push(L(`default:${e}`,r));const o=t.match(/^\*\s+as\s+([$A-Z_a-z][$\w]*)$/);return o?.[1]?(s.push(L(`*:${o[1]}`,r)),s):[...s,...se(t,n)]}function se(e,t){const n=e.trim();return!n.startsWith("{")||!n.endsWith("}")?[]:n.slice(1,-1).split(",").map(r=>{const s=r.trim(),o=s.startsWith("type ");return{raw:o?s.replace(/^type\s+/,""):s,usage:t||o?"type":"value"}}).filter(r=>r.raw!=="").map(r=>{const s=r.raw.match(/^([$A-Z_a-z][$\w]*)\s+as\s+([$A-Z_a-z][$\w]*)$/),o=s?.[1]&&s[2]?`${s[1]} as ${s[2]}`:r.raw;return L(o,r.usage)})}function L(e,t){return{name:e,usage:t}}function oe(e,t){return ie([...e??[],...t])}function ie(e){const t=new Map;for(const n of e)t.set(`${n.usage}:${n.name}`,n);return Array.from(t.values()).sort((n,r)=>n.usage.localeCompare(r.usage)||n.name.localeCompare(r.name))}function De(e,t){const n=d.resolve(d.dirname(e),t);return ce(n)}function ce(e){const t=new Set;t.add(e);const n=d.extname(e);if(n){if([".js",".jsx",".mjs",".cjs"].includes(n)){const r=e.slice(0,-n.length);for(const s of j)t.add(`${r}${s}`)}if(!D.includes(n))for(const r of j)t.add(`${e}${r}`)}else for(const r of D)t.add(`${e}${r}`);for(const r of D)t.add(d.join(e,`index${r}`));for(const r of t)if(x.existsSync(r)&&x.statSync(r).isFile()&&W(r))return r;return null}function He(e){const t=new Map;return{resolve(n,r){const s=qe(d.dirname(n),e);if(!s)return null;const o=Ve(s,t);if(!o||o.mappings.length===0)return null;for(const i of o.mappings){const l=Xe(r,i);if(l!==null)for(const a of i.targets){const f=a.includes("*")?a.replace(/\*/g,l):a,h=d.resolve(o.baseUrl,f),c=ce(h);if(c)return c}}return null}}}function qe(e,t){let n=d.resolve(e);const r=d.parse(d.resolve(t)).root;for(;;){const s=d.join(n,X);if(x.existsSync(s)&&x.statSync(s).isFile())return s;const o=d.dirname(n);if(o===n||n===r)return null;n=o}}function Ve(e,t){const n=d.resolve(e);if(t.has(n))return t.get(n)??null;t.set(n,null);const r=ae(n);if(!r)return null;const s=d.dirname(n),o=r.baseUrl?d.resolve(s,r.baseUrl):s,i=Object.entries(r.paths??{}).flatMap(([a,f])=>Ze(a,f)).sort((a,f)=>f.specificity-a.specificity||a.pattern.localeCompare(f.pattern)),l={configPath:n,baseUrl:o,mappings:i};return t.set(n,l),l}function ae(e){try{const t=ke(x.readFileSync(e,"utf8")),n=ze(e,t.extends),r=q(t.compilerOptions)?t.compilerOptions:{},s=Je(r.paths),o=typeof r.baseUrl=="string"?d.resolve(d.dirname(e),r.baseUrl):void 0;return{...n??{},...o!==void 0?{baseUrl:o}:{},...s?{paths:s}:{}}}catch{return null}}function ze(e,t){if(typeof t!="string"||t.trim()==="")return null;const n=d.dirname(e),r=We(n,t.trim());for(const s of r)if(x.existsSync(s)&&x.statSync(s).isFile())return ae(s);return null}function We(e,t){const n=t.startsWith(".")||d.isAbsolute(t)?d.resolve(e,t):d.resolve(e,"node_modules",t),r=[n];return d.extname(n)||r.push(`${n}.json`,d.join(n,X)),r}function ke(e){const n=le(e).replace(/,\s*([}\]])/g,"$1"),r=JSON.parse(n);return q(r)?r:{}}function q(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function le(e){let t="",n=!1,r=!1;for(let s=0;s<e.length;s+=1){const o=e[s],i=e[s+1];if(n){t+=o,r?r=!1:o==="\\"?r=!0:o==='"'&&(n=!1);continue}if(o==='"'){n=!0,t+=o;continue}if(o==="/"&&i==="/"){for(;s<e.length&&e[s]!==`
7
+ `;)s+=1;t+=`
8
+ `;continue}if(o==="/"&&i==="*"){for(s+=2;s<e.length&&!(e[s]==="*"&&e[s+1]==="/");)s+=1;s+=1;continue}t+=o}return t}function Je(e){if(!q(e))return null;const t={};for(const[n,r]of Object.entries(e)){if(!Array.isArray(r))continue;const s=r.filter(o=>typeof o=="string"&&o.trim()!=="");s.length>0&&(t[n]=s)}return Object.keys(t).length>0?t:null}function Ze(e,t){if(typeof e!="string"||e.trim()==="")return[];const n=e.indexOf("*"),r=n>=0?e.slice(0,n):e,s=n>=0?e.slice(n+1):"";return[{pattern:e,prefix:r,suffix:s,targets:t,specificity:r.length+s.length}]}function Xe(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 Qe(e,t,n){const r=et(Ye(t,n)),s=fe(e,t,n,r),o=ot(s,r),i=o.length===r.aliases.length?r:pe(o),l=i===r?s:fe(e,t,n,i);return st(l,i)}function fe(e,t,n,r){const s={operation:"inspect.graph",summary:`${t.files.length} files, ${t.edges.length} local edges, ${t.externalPackages.length} external packages`};if(t.timeoutHint&&(s.timeoutHint=t.timeoutHint),n.view&&(s.view=n.view),t.excluded&&t.excluded.count>0&&(s.excluded=`${t.excluded.count} files by graph.exclude`),n.writtenTo&&(s.graphFile=n.writtenTo),n.focus.length>0)return s.focus=n.focus.slice(0,10).map(c=>Ke(t,F(c),r,n.symbols,n.symbolUsage)),s.next=ue(n,t),s;const o=t.files.map(c=>({file:c.file,total:c.imports.length+c.importedBy.length,imports:c.imports.length,importedBy:c.importedBy.length})).filter(c=>c.total>0).sort((c,g)=>g.total-c.total||c.file.localeCompare(g.file)).slice(0,S).map(c=>`${r.compactPath(c.file)} imports ${c.imports}, importedBy ${c.importedBy}`);n.sections.hubs&&o.length>0&&(s.hubs=o);const i=t.files.filter(c=>c.importedBy.length===0&&c.imports.length>0).sort((c,g)=>g.imports.length-c.imports.length||c.file.localeCompare(g.file)).map(c=>c.file),l=r.compactList(i,S);n.sections.entrypoints&&l.length>0&&(s.scopeEntrypoints=l);const a=t.files.filter(c=>c.imports.length===0&&c.importedBy.length>0).sort((c,g)=>g.importedBy.length-c.importedBy.length||c.file.localeCompare(g.file)).map(c=>c.file),f=r.compactList(a,S);n.sections.leaves&&f.length>0&&(s.scopeLeaves=f);const h=ft(t.edges,r,Z,n.symbols);return n.sections.edges&&h.length>0&&(s.edges=h),s.next=n.writtenTo?`Focus saved graph: aib inspect graph --from-file ${_t(e,n.writtenTo)} --focus <file>`:ue(n,t),s}function Ke(e,t,n,r,s){const o=e.files.find(l=>F(l.file)===t);if(!o)return{file:t,ok:!1,code:"GRAPH_FOCUS_NOT_FOUND",error:"Focus file is not present in this graph."};const i={file:n.compactPath(o.file)};if(o.imports.length>0)if(r){const l=e.edges.filter(a=>a.from===o.file);if(s){const a=pt(l,n,S);Object.keys(a).length>0&&(i.usage=a);const f=ht(o.imports,l,n);f.length>0&&(i.importsOther=f)}else i.symbols=ut(l,n,S)}else i.imports=n.compactList(o.imports,S);return o.importedBy.length>0&&(i.importedBy=n.compactList(o.importedBy,S)),o.external.length>0&&(i.external=Pt(o.external,S)),o.omittedLocalImports&&o.omittedLocalImports.length>0&&(i.omittedLocalImports=n.compactList(o.omittedLocalImports,S)),i}function ue(e,t){return e.depth===0&&t.files.some(n=>(n.omittedLocalImports??[]).length>0)?"Use --depth 1 to include direct local imports outside the initial scope.":"Use --depth 2 for a wider local neighborhood, or inspect exports/code on focused files."}function Ye(e,t){const n=new Set;if(t.focus.length>0){for(const r of t.focus.slice(0,10)){const s=F(r),o=e.files.find(i=>F(i.file)===s);if(o){n.add(o.file);for(const i of o.imports.slice(0,S))n.add(i);for(const i of o.importedBy.slice(0,S))n.add(i);for(const i of(o.omittedLocalImports??[]).slice(0,S))n.add(i);if(t.symbols)for(const i of e.edges.filter(l=>l.from===o.file).slice(0,S))n.add(i.to)}}return Array.from(n)}if(t.sections.hubs){const r=e.files.map(s=>({file:s.file,total:s.imports.length+s.importedBy.length,imports:s.imports.length,importedBy:s.importedBy.length})).filter(s=>s.total>0).sort((s,o)=>o.total-s.total||s.file.localeCompare(o.file)).slice(0,S);for(const s of r)n.add(s.file)}if(t.sections.entrypoints)for(const r of e.files.filter(s=>s.importedBy.length===0&&s.imports.length>0).sort((s,o)=>o.imports.length-s.imports.length||s.file.localeCompare(o.file)).map(s=>s.file).slice(0,S))n.add(r);if(t.sections.leaves)for(const r of e.files.filter(s=>s.imports.length===0&&s.importedBy.length>0).sort((s,o)=>o.importedBy.length-s.importedBy.length||s.file.localeCompare(o.file)).map(s=>s.file).slice(0,S))n.add(r);if(t.sections.edges)for(const r of e.edges.slice(0,Z))n.add(r.from),n.add(r.to);return Array.from(n)}function et(e){return pe(tt(e))}function pe(e){return{aliases:e,compactPath(t){return he(t,e)},compactList(t,n){return at(t,n,e)}}}function tt(e){const t=new Map;for(const s of e)for(const o of rt(s))t.set(o,(t.get(o)??0)+1);const n=new Set,r=Array.from(t.entries()).map(([s,o])=>{const i=`<${d.basename(s)}>`;return{prefix:s,count:o,token:i,score:Math.max(0,s.length-i.length)*o}}).filter(s=>s.count>=2&&(s.score>=16||s.count>=3)&&s.prefix!=="src/main").sort((s,o)=>o.score-s.score||o.count-s.count||o.prefix.length-s.prefix.length||s.prefix.localeCompare(o.prefix)).filter(s=>n.has(s.token)?!1:(n.add(s.token),!0));return nt(r).slice(0,6).sort((s,o)=>o.prefix.length-s.prefix.length).map(s=>({token:s.token,prefix:s.prefix}))}function nt(e){return e.filter(t=>!e.find(r=>r.prefix!==t.prefix&&t.prefix.startsWith(`${r.prefix}/`)&&r.count>=t.count&&r.score>=12&&t.score<40))}function rt(e){const t=F(e).split("/"),n=[];for(let r=2;r<t.length;r+=1){const s=t.slice(0,r).join("/");s.length>=8&&n.push(s)}return n}function st(e,t){const n=ct(t,e);return n?{operation:e.operation??"inspect.graph",summary:e.summary??"",paths:n,...Object.fromEntries(Object.entries(e).filter(([r])=>r!=="operation"&&r!=="summary"))}:e}function ot(e,t){const n=JSON.stringify(e);return t.aliases.filter(r=>it(n,r.token)>=2)}function it(e,t){let n=0,r=0;for(;;){const s=e.indexOf(t,r);if(s<0)return n;n+=1,r=s+t.length}}function ct(e,t){if(e.aliases.length===0)return null;const n=JSON.stringify(t),r={};for(const s of e.aliases)n.includes(s.token)&&(r[s.token]=s.prefix);return Object.keys(r).length>0?r:null}function he(e,t){const n=F(e),r=t.find(s=>n===s.prefix||n.startsWith(`${s.prefix}/`));return r?n===r.prefix?r.token:`${r.token}/${n.slice(r.prefix.length+1)}`:n}function at(e,t,n){const r=e.slice(0,t).map(i=>he(i,n)),s=lt(r),o=e.length-Math.min(e.length,t);return o>0?[...s,`+ ${o} more`]:s}function lt(e){const t=new Map,n=[];for(const r of e){const s=r.startsWith("<")?r.indexOf(">"):-1;if(s<=0){n.push(r);continue}const o=r.indexOf("/",s);if(o<0){n.push(r);continue}const i=r.slice(0,o),l=r.slice(o+1),a=t.get(i)??[];a.push(l),t.set(i,a)}return[...Array.from(t.entries()).map(([r,s])=>s.length===1?`${r}/${s[0]}`:`${r}/: ${s.join(", ")}`),...n].sort()}function ft(e,t,n,r){const s=e.slice(0,n),o=new Map,i=[];for(const f of s){const h=t.compactPath(f.from),c=t.compactPath(f.to),g=r?V(f.symbols):"",v=c.startsWith("<")?c.indexOf(">"):-1,E=v>0?c.indexOf("/",v):-1;if(E<0){i.push(`${h} -> ${c}${g}`);continue}const P=c.slice(0,E),u=`${c.slice(E+1)}${g}`,m=`${h} -> ${P}`,p=o.get(m)??[];p.push(u),o.set(m,p)}const l=[...Array.from(o.entries()).map(([f,h])=>h.length===1?`${f}/${h[0]}`:`${f}/: ${h.join(", ")}`),...i].sort(),a=e.length-Math.min(e.length,n);return a>0?[...l,`+ ${a} more`]:l}function ut(e,t,n){const r=e.slice(0,n).map(o=>`${t.compactPath(o.to)}${V(o.symbols)}`),s=e.length-Math.min(e.length,n);return s>0?[...r,`+ ${s} more files`]:r}function pt(e,t,n){const r=e.slice(0,n),s=r.flatMap(a=>me(a,t,"type")),o=r.flatMap(a=>me(a,t,"value")),i=e.length-Math.min(e.length,n),l={};return o.length>0&&(l.value=o),s.length>0&&(l.type=s),i>0&&(l.moreFiles=`+ ${i} more files`),l}function ht(e,t,n){const r=new Set(t.filter(o=>z(o.symbols).length>0).map(o=>o.to)),s=e.filter(o=>!r.has(o));return n.compactList(s,S)}function me(e,t,n){const r=z(e.symbols).filter(s=>s.usage===n);return r.length===0?[]:[`${t.compactPath(e.to)}${V(r)}`]}function V(e){const t=z(e);return t.length===0?"":`: ${mt(t,4).join(", ")}`}function mt(e,t){const n=e.slice(0,t).map(s=>s.name),r=e.length-Math.min(e.length,t);return r>0?[...n,`+ ${r} more symbols`]:n}function z(e){return(e??[]).map(t=>typeof t=="string"?L(t,"value"):t).filter(t=>t.name.trim()!=="")}function dt(e,t){const n=$(e,(0,A.resolveSessionFileArgument)(e,t)),r=JSON.parse(x.readFileSync(n,"utf8"));if(!yt(r))throw new y.CliError("INVALID_GRAPH_FILE","inspect graph --from-file expects a graph JSON file created by inspect graph --to-file.");return r}function gt(e,t,n){const r=$(e,t);return x.mkdirSync(d.dirname(r),{recursive:!0}),x.writeFileSync(r,`${JSON.stringify(n,null,2)}
9
+ `),r}function yt(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&e.operation==="inspect.graph"&&Array.isArray(e.files)&&Array.isArray(e.edges)}function M(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"&&t.trim()!=="").map(t=>t.trim()):null}function w(e){return typeof e=="boolean"?e:null}function de(e){return{hubs:(0,A.readSessionBooleanPref)(e,"inspect.graph.hubs",!0),entrypoints:(0,A.readSessionBooleanPref)(e,"inspect.graph.entrypoints",!0),leaves:(0,A.readSessionBooleanPref)(e,"inspect.graph.leaves",!0),edges:(0,A.readSessionBooleanPref)(e,"inspect.graph.edges",!0)}}function bt(e,t){const n=de(e);return{hubs:w(t.hubs)??w(t.showHubs)??n.hubs,entrypoints:w(t.entrypoints)??w(t.scopeEntrypoints)??w(t.showEntrypoints)??n.entrypoints,leaves:w(t.leaves)??w(t.scopeLeaves)??w(t.showLeaves)??n.leaves,edges:w(t.edges)??w(t.showEdges)??n.edges}}function xt(e){if(e===void 0)return;const t=typeof e=="number"?e:typeof e=="string"?Number.parseInt(e,10):Number.NaN;if(!Number.isInteger(t)||t<0||t>2)throw new y.CliError("INVALID_GRAPH_DEPTH","inspect graph depth expects 0, 1, or 2.");return t}function ge(e){if(e==="local"||e==="neighbors"||e==="expanded")return e;throw new y.CliError("INVALID_GRAPH_VIEW","inspect graph view expects local, neighbors, or expanded.")}function ye(e){return e==="local"?0:e==="expanded"?2:1}function be(e){return e===0?"local":e===2?"expanded":"neighbors"}function R(e,t,n){if(n)return;if(t.length!==1)return"neighbors";const r=$(e,t[0]);return x.existsSync(r)&&x.statSync(r).isDirectory()?"local":"neighbors"}function St(e,t){const n=e.indexOf(t);return n>=0?e[n+1]:void 0}function N(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function W(e){return j.includes(d.extname(e))&&!e.endsWith(".d.ts")}function vt(e){if(e.startsWith("node:"))return e;if(e.startsWith("@")){const t=e.split("/");return t.length>=2?`${t[0]}/${t[1]}`:e}return e.split("/")[0]??e}function $(e,t){return d.resolve(e,t)}function I(e,t){return F(d.relative(e,d.resolve(t)))}function F(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function _t(e,t){const n=d.relative(e,t);return n&&!n.startsWith("..")?F(n):t}function U(e){return Array.from(new Set(e)).sort()}function wt(e,t){return e.from.localeCompare(t.from)||e.to.localeCompare(t.to)||e.specifier.localeCompare(t.specifier)}function Pt(e,t){return At(e.slice(0,t),e.length)}function At(e,t){const n=t-e.length;return n>0?[...e,`+ ${n} more`]:e}function Et(e){return e.filter(t=>t.importedBy.length===0&&t.imports.length>0).length}function $t(e){return e.filter(t=>t.imports.length===0&&t.importedBy.length>0).length}
@@ -0,0 +1,2 @@
1
+ "use strict";var C=exports&&exports.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=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(t,r,i)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),M=exports&&exports.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),S=exports&&exports.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(r[r.length]=i);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),i=0;i<r.length;i++)r[i]!=="default"&&C(n,e,r[i]);return M(n,e),n}})(),$=exports&&exports.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.isInspectImportsRequest=k,exports.runInspectImports=v,exports.buildInspectImportsResult=R,exports.mergeDirectoryFallbackResults=q,exports.formatImportsResponse=P,exports.appendImportsBlock=y;const b=S(require("node:fs")),p=S(require("node:path")),o=$(require("typescript")),d=require("../config/path-display"),L=require("../shared/agent-text"),m=require("../shared/errors"),E=require("./inspect-tree"),O=require("./session-workspace");function k(t,e){if(t[0]==="imports")return!0;if(!t.includes("--stdin")||!a(e))return!1;const n=x(e);return n.length>0&&n.some(r=>c(r.op)==="imports")}function v(t,e,n){const r=(0,d.buildDisplayPathAliases)(t,(0,O.readEffectiveSessionPathAliases)(t)),i=N(t,e,n),s=q(i.map(l=>R(t,l,r))),u=s.length===1?s[0]:{results:s};return(0,L.attachAgentText)(u,P(u))}function R(t,e,n=(0,d.buildDisplayPathAliases)(t,(0,O.readEffectiveSessionPathAliases)(t))){const r={file:g(t,e.file),ranges:e.ranges!==!1,dynamic:e.dynamic===!0},i=(0,d.compactDisplayPath)(t,r.file,n),s=J(r.file);if(s?.isDirectory())return B(t,r.file,n);if(!s?.isFile())return{ok:!1,op:"imports",code:"FILE_NOT_FOUND",error:"file not found",sourceFile:r.file,file:i};const u=b.readFileSync(r.file,"utf8"),l=o.default.createSourceFile(r.file,u,o.default.ScriptTarget.Latest,!0,X(r.file)),_=[],h=[],I=f=>{o.default.isImportDeclaration(f)?_.push(A(l,u,f,r.ranges)):r.dynamic&&o.default.isCallExpression(f)&&f.expression.kind===o.default.SyntaxKind.ImportKeyword&&h.push(A(l,u,f,r.ranges)),o.default.forEachChild(f,I)};return o.default.forEachChild(l,I),{ok:!0,op:"imports",sourceFile:r.file,file:i,imports:_,...h.length>0?{dynamicImports:h}:{}}}function q(t){const e=[],n=new Map;for(const r of t){if(r.op!=="directoryFallback"){e.push(r);continue}const i=c(r.sourceFile)??c(r.directory);if(!i){e.push(r);continue}const s=n.get(i);if(s===void 0){n.set(i,e.length),e.push(r);continue}const u=e[s];u&&(u.skippedOps=z([...T(u.skippedOps),...T(r.skippedOps)]))}return e}function P(t){const e=[];if(Array.isArray(t.results))for(const n of t.results.filter(a))y(e,n);else y(e,t);return e.join(`
2
+ `)}function y(t,e){t.length>0&&t[t.length-1]!==""&&t.push("");const n=c(e.file);if(n){if(e.ok===!1){t.push(`// ${n} - ${c(e.error)??"request failed"}`);return}t.push(`// ${n}`)}const r=F(e.imports),i=F(e.dynamicImports);if(r.length===0&&i.length===0)t.push("no imports");else{if(r.length>0){t.push("imports:");for(const s of r)t.push(...D(s))}if(i.length>0){r.length>0&&t.push(""),t.push("dynamic imports:");for(const s of i)t.push(...D(s))}}}function B(t,e,n){const r=K(t,e),i=(0,d.compactDisplayPath)(t,e,n),s=(0,E.buildInspectTreeResult)(t,{scope:e,displayScope:i,depth:r,limit:40});return{ok:!0,op:"directoryFallback",sourceFile:e,directory:i,skippedOps:["imports"],command:`aib inspect tree ${i} --depth ${r}`,tree:s,lines:Array.isArray(s.lines)?s.lines:[]}}function K(t,e){for(let n=1;n<=4;n+=1){const r=(0,E.buildInspectTreeResult)(t,{scope:e,depth:n,limit:1});if(typeof r.files=="number"&&r.files>0)return n}return 2}function N(t,e,n){if(e[0]==="imports")return[U(t,e.slice(1))];if(!e.includes("--stdin")||!a(n))throw new m.CliError("INSPECT_IMPORTS_FILE_REQUIRED","inspect imports expects a file.");const r=x(n);if(r.some(i=>c(i.op)!=="imports"))throw new m.CliError("INSPECT_IMPORTS_MIXED_BATCH_UNSUPPORTED","inspect imports --stdin expects only imports requests.");return r.map((i,s)=>w(t,i,s))}function U(t,e){const n=e.find(r=>!r.startsWith("--")&&!W(e,r));if(!n)throw new m.CliError("INSPECT_IMPORTS_FILE_REQUIRED","inspect imports expects a file.");return{file:g(t,n),ranges:!e.includes("--no-ranges"),dynamic:!e.includes("--no-dynamic")}}function w(t,e,n){const r=c(e.file)??c(e.fromFile)??c(e.sourceFile);if(!r)throw new m.CliError("INSPECT_IMPORTS_FILE_REQUIRED",`Inspect imports request at index ${n} requires file.`);return{file:g(t,r),ranges:j(e.ranges)!==!1,dynamic:j(e.dynamic)!==!1}}function A(t,e,n,r){return{text:e.slice(n.getStart(t),n.getEnd()).trim(),...r?{range:Q(t,n)}:{}}}function Q(t,e){const n=t.getLineAndCharacterOfPosition(e.getStart(t)).line+1,r=t.getLineAndCharacterOfPosition(e.getEnd()).line+1;return n===r?`@${n}`:`@${n}..${r}`}function D(t){const e=t.text.split(/\r?\n/);return t.range?e.length===0?[t.range]:[`${t.range} ${e[0]??""}`,...e.slice(1)]:e}function F(t){return Array.isArray(t)?t.filter(a).map(e=>({text:c(e.text)??"",...typeof e.range=="string"?{range:e.range}:{}})).filter(e=>e.text!==""):[]}function x(t){return a(t)?Array.isArray(t.requests)?t.requests.filter(a):[t]:[]}function X(t){const e=p.extname(t).toLowerCase();return e===".tsx"?o.default.ScriptKind.TSX:e===".jsx"?o.default.ScriptKind.JSX:e===".js"||e===".cjs"||e===".mjs"?o.default.ScriptKind.JS:o.default.ScriptKind.TS}function g(t,e){return p.isAbsolute(e)?p.normalize(e):p.resolve(t,e)}function J(t){try{return b.statSync(t)}catch{return null}}function W(t,e){const n=t.indexOf(e);return n>0&&t[n-1]?.startsWith("--")===!0}function c(t){return typeof t=="string"&&t.trim()!==""?t:null}function T(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"&&e.trim()!=="").map(e=>e.trim()):[]}function j(t){return typeof t=="boolean"?t:null}function z(t){return Array.from(new Set(t.filter(e=>e!=="")))}function a(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.queryTopLevelInspectSymbols=n;const y=require("../client/http-client"),a=require("../shared/routes");async function n(o,t,l={}){const r=await(0,y.postJson)(o,a.EXTENSION_ROUTES.inspect,{requests:[{op:"file",sourceFile:t,ranges:!1,resolveStar:!1,localOnly:!1}]},l),e=Array.isArray(r.results)?r.results[0]:null;return(e&&typeof e=="object"&&!Array.isArray(e)&&Array.isArray(e.symbols)?e.symbols:[]).filter(s=>!!s&&typeof s=="object"&&!Array.isArray(s))}