@automaton-labs/aib 0.0.5 → 0.0.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/cli.js +4 -2
- package/dist/commands/apply-module-plan.js +3 -3
- package/dist/commands/background-command.js +2 -0
- package/dist/commands/captured-input.js +1 -2
- package/dist/commands/config-command.js +2 -1
- package/dist/commands/config-output.js +10 -8
- package/dist/commands/control-plane-command.js +1 -0
- package/dist/commands/declaration-command.js +7 -0
- package/dist/commands/declaration-execution-cache.js +1 -0
- package/dist/commands/declaration-format.js +1 -0
- package/dist/commands/declaration-preview-cache.js +2 -0
- package/dist/commands/doctor.js +3 -1
- package/dist/commands/execution-command.js +1 -1
- package/dist/commands/file-command.js +1 -0
- package/dist/commands/file-move-to-dir-execution-cache.js +1 -0
- package/dist/commands/file-move-to-dir-preview-cache.js +2 -0
- package/dist/commands/file-move-to-dir.js +5 -0
- package/dist/commands/file-mutation-runtime.js +1 -0
- package/dist/commands/file-refactor-batch-execution-cache.js +1 -0
- package/dist/commands/file-refactor-batch-preview-cache.js +2 -0
- package/dist/commands/file-refactor-batch.js +5 -0
- package/dist/commands/file-rename-execution-cache.js +1 -0
- package/dist/commands/file-rename-preview-cache.js +2 -0
- package/dist/commands/file-rename.js +5 -0
- package/dist/commands/help-command.js +5 -5
- package/dist/commands/host-command.js +1 -0
- package/dist/commands/inspect-cycles.js +3 -3
- package/dist/commands/inspect-format.js +15 -15
- package/dist/commands/inspect-tree.js +2 -2
- package/dist/commands/inspect.js +12 -12
- package/dist/commands/move-to-file.js +2 -2
- package/dist/commands/ota-command.js +2 -0
- package/dist/commands/quick-read.js +8 -8
- package/dist/commands/refactor-batch.js +4 -4
- package/dist/commands/rename-entities.js +4 -4
- package/dist/commands/result-view.js +6 -5
- package/dist/commands/session-workspace.js +7 -7
- package/dist/commands/worker-command.js +1 -0
- package/dist/config/defaults.js +1 -1
- package/dist/config/env-vars.js +1 -1
- package/dist/config/path-aliases.js +1 -1
- package/dist/config/resolve-command-alias.js +1 -1
- package/dist/config/workspace-root.js +3 -3
- package/dist/content/content-bundle.js +1 -1
- package/dist/dsl/aib-dsl.js +1 -1
- package/dist/dsl/declaration-dsl.js +1 -0
- package/dist/dsl/file-move-to-dir-dsl.js +1 -0
- package/dist/dsl/file-refactor-batch-dsl.js +1 -0
- package/dist/dsl/file-rename-dsl.js +1 -0
- package/dist/help/bootstrap.bash.md +907 -0
- package/dist/help/bootstrap.md +105 -144
- package/dist/help/{json/bootstrap.md → bootstrap.pwsh.md} +216 -397
- package/dist/help/docs/dsl.md +4 -3
- package/dist/help/docs/file.move.md +46 -0
- package/dist/help/docs/file.rename.md +35 -0
- package/dist/help/docs/help-format.md +4 -7
- package/dist/help/docs/inspect.code.md +5 -5
- package/dist/help/docs/inspect.deps.md +7 -7
- package/dist/help/docs/inspect.file.md +2 -1
- package/dist/help/docs/inspect.graph.md +3 -3
- package/dist/help/docs/inspect.md +5 -5
- package/dist/help/docs/mutation.md +23 -13
- package/dist/help/docs/patterns.md +1 -5
- package/dist/help/docs/qr.md +7 -22
- package/dist/help/docs/quick-map.md +1 -0
- package/dist/help/docs/recipe.file-layout.md +15 -0
- package/dist/help/docs/rg.md +22 -0
- package/dist/help/docs/selectors.md +3 -2
- package/dist/help/docs/session.md +1 -1
- package/dist/help/dsl/bootstrap.bash.md +907 -0
- package/dist/help/dsl/bootstrap.md +105 -144
- package/dist/help/{json/full.md → dsl/bootstrap.pwsh.md} +216 -397
- package/dist/help/dsl/docs/dsl.md +4 -3
- package/dist/help/dsl/docs/file.move.md +46 -0
- package/dist/help/dsl/docs/file.rename.md +35 -0
- package/dist/help/dsl/docs/help-format.md +4 -7
- package/dist/help/dsl/docs/inspect.code.md +5 -5
- package/dist/help/dsl/docs/inspect.deps.md +7 -7
- package/dist/help/dsl/docs/inspect.file.md +2 -1
- package/dist/help/dsl/docs/inspect.graph.md +3 -3
- package/dist/help/dsl/docs/inspect.md +5 -5
- package/dist/help/dsl/docs/mutation.md +23 -13
- package/dist/help/dsl/docs/patterns.md +1 -5
- package/dist/help/dsl/docs/qr.md +7 -22
- package/dist/help/dsl/docs/quick-map.md +1 -0
- package/dist/help/dsl/docs/recipe.file-layout.md +15 -0
- package/dist/help/dsl/docs/rg.md +22 -0
- package/dist/help/dsl/docs/selectors.md +3 -2
- package/dist/help/dsl/docs/session.md +1 -1
- package/dist/help/dsl/full.md +105 -144
- package/dist/help/dsl/help-index.md +44 -0
- package/dist/help/dsl/tokens/qr.inline.examples.md +2 -0
- package/dist/help/dsl/tokens/stdin.examples.bash.md +8 -0
- package/dist/help/dsl/tokens/stdin.examples.pwsh.md +8 -0
- package/dist/help/dsl/tokens/stdin.examples.with-qr.bash.md +12 -0
- package/dist/help/dsl/tokens/stdin.examples.with-qr.pwsh.md +12 -0
- package/dist/help/dsl/topics/dsl.md +4 -3
- package/dist/help/dsl/topics/file.move.md +44 -0
- package/dist/help/dsl/topics/file.rename.md +33 -0
- package/dist/help/dsl/topics/help-format.md +4 -7
- package/dist/help/dsl/topics/inspect.code.md +5 -5
- package/dist/help/dsl/topics/inspect.deps.md +7 -7
- package/dist/help/dsl/topics/inspect.file.md +2 -1
- package/dist/help/dsl/topics/inspect.graph.md +3 -3
- package/dist/help/dsl/topics/inspect.md +5 -5
- package/dist/help/dsl/topics/mutation.md +23 -13
- package/dist/help/dsl/topics/patterns.md +1 -5
- package/dist/help/dsl/topics/qr.md +7 -22
- package/dist/help/dsl/topics/quick-map.md +1 -0
- package/dist/help/dsl/topics/recipe.file-layout.md +13 -0
- package/dist/help/dsl/topics/rg.md +20 -0
- package/dist/help/dsl/topics/selectors.md +3 -2
- package/dist/help/dsl/topics/session.md +1 -1
- package/dist/help/full.md +105 -144
- package/dist/help/help-index.md +44 -0
- package/dist/help/help-meta.json +45 -29
- package/dist/help/index.md +32 -75
- package/dist/help/tokens/qr.inline.examples.md +2 -0
- package/dist/help/tokens/stdin.examples.bash.md +8 -0
- package/dist/help/tokens/stdin.examples.pwsh.md +8 -0
- package/dist/help/tokens/stdin.examples.with-qr.bash.md +12 -0
- package/dist/help/tokens/stdin.examples.with-qr.pwsh.md +12 -0
- package/dist/help/topics/dsl.md +4 -3
- package/dist/help/topics/file.move.md +44 -0
- package/dist/help/topics/file.rename.md +33 -0
- package/dist/help/topics/help-format.md +4 -7
- package/dist/help/topics/inspect.code.md +5 -5
- package/dist/help/topics/inspect.deps.md +7 -7
- package/dist/help/topics/inspect.file.md +2 -1
- package/dist/help/topics/inspect.graph.md +3 -3
- package/dist/help/topics/inspect.md +5 -5
- package/dist/help/topics/mutation.md +23 -13
- package/dist/help/topics/patterns.md +1 -5
- package/dist/help/topics/qr.md +7 -22
- package/dist/help/topics/quick-map.md +1 -0
- package/dist/help/topics/recipe.file-layout.md +13 -0
- package/dist/help/topics/rg.md +20 -0
- package/dist/help/topics/selectors.md +3 -2
- package/dist/help/topics/session.md +1 -1
- package/dist/host/capabilities.js +1 -0
- package/dist/ide-launch/common.cjs +162 -162
- package/dist/managed-host/extension-vsix-resolver.js +1 -1
- package/dist/managed-host/manage-serve-web-host.cjs +141 -141
- package/dist/managed-host/serve-web-autostart.js +1 -1
- package/dist/managed-host/serve-web-host.cjs +1985 -1660
- package/dist/observability/config.js +1 -1
- package/dist/payloads/read-stdin-json.js +1 -1
- package/dist/rg-wrapper/core.js +6 -0
- package/dist/rg-wrapper/options.js +1 -0
- package/dist/rtk-wrapper/core.js +2 -0
- package/dist/runtime/input-source.js +1 -1
- package/dist/runtime/managed-runtime-provisioning.js +1 -1
- package/dist/runtime/run-command.js +1 -1
- package/dist/selectors/parse-entities.js +1 -1
- package/dist/session/daemon-state.js +2 -0
- package/dist/session/server.js +7 -6
- package/dist/shared/errors.js +14 -13
- package/dist/shared/operations.js +1 -1
- package/dist/shared/protocol.js +1 -1
- package/dist/shared/routes.js +1 -1
- package/dist/shared/stdin-examples.js +1 -0
- package/dist/shared/types.js +1 -1
- package/dist/tool-runtime/runtime-tools.js +1 -0
- package/dist/tracing/trace.js +5 -3
- package/dist/workers/control-plane/aib-control-plane-worker.cjs +80 -0
- package/dist/workers/control-plane/client-config.default.json +3 -0
- package/dist/workers/product-storage.js +1 -0
- package/dist/workers/registry.js +1 -0
- package/extension/vscode-refactor-bridge-extension.vsix +0 -0
- package/package.json +6 -4
- package/runtimes/launcher/linux-x64/aib +0 -0
- package/runtimes/launcher/win-x64/aib.exe +0 -0
- package/runtimes/tools/rg/darwin-arm64/rg +0 -0
- package/runtimes/tools/rg/darwin-x64/rg +0 -0
- package/runtimes/tools/rg/linux-arm64/rg +0 -0
- package/runtimes/tools/rg/linux-x64/rg +0 -0
- package/runtimes/tools/rg/manifest.json +36 -0
- package/runtimes/tools/rg/win32-x64/rg.exe +0 -0
- package/runtimes/tools/rtk/darwin-arm64/rtk +0 -0
- package/runtimes/tools/rtk/darwin-x64/rtk +0 -0
- package/runtimes/tools/rtk/linux-arm64/rtk +0 -0
- package/runtimes/tools/rtk/linux-x64/rtk +0 -0
- package/runtimes/tools/rtk/manifest.json +36 -0
- package/runtimes/tools/rtk/win32-x64/rtk.exe +0 -0
- package/scripts/provision-runtime.cjs +25 -1
- package/dist/help/json/docs/basics.md +0 -15
- package/dist/help/json/docs/config-setup.aliases.md +0 -56
- package/dist/help/json/docs/config-setup.excludes.md +0 -45
- package/dist/help/json/docs/config-setup.import-normalize.md +0 -86
- package/dist/help/json/docs/config-setup.import-rules.md +0 -96
- package/dist/help/json/docs/config-setup.tsconfigs.md +0 -33
- package/dist/help/json/docs/dsl.md +0 -25
- package/dist/help/json/docs/first-setup.md +0 -292
- package/dist/help/json/docs/help-format.md +0 -12
- package/dist/help/json/docs/help-protocol.md +0 -26
- package/dist/help/json/docs/imports.normalize.md +0 -47
- package/dist/help/json/docs/inspect.code.md +0 -41
- package/dist/help/json/docs/inspect.cycles.md +0 -38
- package/dist/help/json/docs/inspect.deps.md +0 -46
- package/dist/help/json/docs/inspect.duplicates.md +0 -65
- package/dist/help/json/docs/inspect.exports.md +0 -40
- package/dist/help/json/docs/inspect.file.md +0 -38
- package/dist/help/json/docs/inspect.graph.md +0 -139
- package/dist/help/json/docs/inspect.imports.md +0 -15
- package/dist/help/json/docs/inspect.md +0 -88
- package/dist/help/json/docs/inspect.members.md +0 -32
- package/dist/help/json/docs/inspect.tree.md +0 -32
- package/dist/help/json/docs/inspect.usages.md +0 -61
- package/dist/help/json/docs/modulePlan.md +0 -73
- package/dist/help/json/docs/move.md +0 -56
- package/dist/help/json/docs/mutation.md +0 -65
- package/dist/help/json/docs/patterns.md +0 -76
- package/dist/help/json/docs/prefs.md +0 -40
- package/dist/help/json/docs/qr.md +0 -37
- package/dist/help/json/docs/quick-map.md +0 -30
- package/dist/help/json/docs/refactor.batch.md +0 -72
- package/dist/help/json/docs/rename.md +0 -47
- package/dist/help/json/docs/reveal.md +0 -30
- package/dist/help/json/docs/selectors.md +0 -23
- package/dist/help/json/docs/session.md +0 -77
- package/dist/help/json/docs/view.md +0 -30
- package/dist/help/json/snippets/agents.md +0 -14
- package/dist/help/json/topics/basics.md +0 -13
- package/dist/help/json/topics/config-setup.aliases.md +0 -54
- package/dist/help/json/topics/config-setup.excludes.md +0 -43
- package/dist/help/json/topics/config-setup.import-normalize.md +0 -84
- package/dist/help/json/topics/config-setup.import-rules.md +0 -94
- package/dist/help/json/topics/config-setup.tsconfigs.md +0 -31
- package/dist/help/json/topics/dsl.md +0 -23
- package/dist/help/json/topics/first-setup.md +0 -290
- package/dist/help/json/topics/help-format.md +0 -10
- package/dist/help/json/topics/help-protocol.md +0 -24
- package/dist/help/json/topics/imports.normalize.md +0 -45
- package/dist/help/json/topics/inspect.code.md +0 -39
- package/dist/help/json/topics/inspect.cycles.md +0 -36
- package/dist/help/json/topics/inspect.deps.md +0 -44
- package/dist/help/json/topics/inspect.duplicates.md +0 -37
- package/dist/help/json/topics/inspect.exports.md +0 -38
- package/dist/help/json/topics/inspect.file.md +0 -36
- package/dist/help/json/topics/inspect.graph.md +0 -137
- package/dist/help/json/topics/inspect.imports.md +0 -13
- package/dist/help/json/topics/inspect.md +0 -86
- package/dist/help/json/topics/inspect.members.md +0 -30
- package/dist/help/json/topics/inspect.tree.md +0 -22
- package/dist/help/json/topics/inspect.usages.md +0 -59
- package/dist/help/json/topics/modulePlan.md +0 -60
- package/dist/help/json/topics/move.md +0 -46
- package/dist/help/json/topics/mutation.md +0 -63
- package/dist/help/json/topics/patterns.md +0 -74
- package/dist/help/json/topics/prefs.md +0 -38
- package/dist/help/json/topics/qr.md +0 -35
- package/dist/help/json/topics/quick-map.md +0 -28
- package/dist/help/json/topics/refactor.batch.md +0 -61
- package/dist/help/json/topics/rename.md +0 -42
- package/dist/help/json/topics/reveal.md +0 -28
- package/dist/help/json/topics/selectors.md +0 -21
- package/dist/help/json/topics/session.md +0 -59
- package/dist/help/json/topics/view.md +0 -28
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.runFileCommand=u;const l=require("../shared/errors"),m=require("./file-move-to-dir"),f=require("./file-refactor-batch"),s=require("./file-rename");async function u(i,a,t,n={}){const[e="help",r="help",...o]=a;if(e==="help"||e==="--help")return c();if(e==="move"&&r==="toDir")return(0,m.runFileMoveToDir)(i,t,n,o);if(e==="rename")return(0,s.runFileRename)(i,t,n,r==="help"?["help"]:[r,...o]);if(e==="refactor"&&r==="batch")return(0,f.runFileRefactorBatch)(i,t,n,o);throw new l.CliError("UNKNOWN_FILE_COMMAND",`Unknown file command: ${[e,r].filter(Boolean).join(" ")}`,{availableCommands:["move toDir","rename","refactor batch"]})}function c(){return{ok:!0,command:"file",usage:"aib file move toDir preview --stdin | aib file rename preview --stdin | aib file refactor batch preview --stdin",notes:["file commands mutate filesystem layout.","file move toDir moves files into target directories and updates TypeScript imports.","file rename renames files and updates TypeScript imports."]}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var a=exports&&exports.__createBinding||(Object.create?(function(e,t,n,i){i===void 0&&(i=n);var o=Object.getOwnPropertyDescriptor(t,n);(!o||("get"in o?!t.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,o)}):(function(e,t,n,i){i===void 0&&(i=n),e[i]=t[n]})),c=exports&&exports.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),l=exports&&exports.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(n){var i=[];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(i[i.length]=o);return i},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(t!=null)for(var i=e(t),o=0;o<i.length;o++)i[o]!=="default"&&a(n,t,i[o]);return c(n,t),n}})();Object.defineProperty(exports,"__esModule",{value:!0}),exports.buildFileMoveToDirExecutionId=d,exports.createFileMoveToDirExecutionStatus=_,exports.readFileMoveToDirExecutionStatus=v,exports.tryReadFileMoveToDirExecutionStatus=E,exports.writeFileMoveToDirExecutionStatus=M,exports.fileMoveToDirExecutionPath=D,exports.fileMoveToDirExecutionLastPath=h;const s=l(require("node:path")),f=require("../config/product-storage"),r=require("./mutation-execution-cache");function d(){return(0,r.buildMutationExecutionId)()}function _(e,t,n,i){const o=new Date().toISOString();return{executionId:t,operation:n,cwd:s.resolve(e),status:"running",phase:"movingFile",startedAt:o,updatedAt:o,rowCount:Math.max(1,i.length),completedRows:0,failedRows:0,notRunRows:0,filesWritten:[],touchedFiles:[],plannedMoves:i,moves:[],rows:[],productStorageDir:(0,f.productStorageRoot)()}}function v(e,t){return(0,r.readMutationExecutionStatus)(e,t,u)}function E(e,t){return(0,r.tryReadMutationExecutionStatus)(e,t,u)}function M(e,t){(0,r.writeMutationExecutionStatus)(e,t,u)}function D(e,t,n){return(0,r.mutationExecutionPath)(e,u.namespace,t,n)}function h(e,t){return(0,r.mutationExecutionLastPath)(e,u.namespace,t)}const u={namespace:"file-move-to-dir-executions",notFoundCode:"FILE_MOVE_TO_DIR_EXECUTION_NOT_FOUND",notFoundLabel:"File move toDir"};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var v=exports&&exports.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var n=Object.getOwnPropertyDescriptor(e,t);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,n)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),d=exports&&exports.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),c=exports&&exports.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var i=[];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(i[i.length]=n);return i},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i=r(e),n=0;n<i.length;n++)i[n]!=="default"&&v(t,e,i[n]);return d(t,e),t}})();Object.defineProperty(exports,"__esModule",{value:!0}),exports.buildFileMoveToDirPreviewId=w,exports.buildFileMoveToDirPreviewHash=g,exports.readFileMoveToDirPreviewRecord=y,exports.writeFileMoveToDirPreviewRecord=p,exports.fileMoveToDirPreviewRecordPath=l,exports.readFileMoveStates=P,exports.validateFileMoveStates=E;const h=c(require("node:crypto")),o=c(require("node:fs")),F=c(require("node:path")),s=require("../shared/errors"),_=require("./workspace-cache");function w(r){return`apply_${f(u(r)).slice(0,10)}`}function g(r,e,t){return`sha256:${f(u({normalizedPayload:r,states:e,summary:t.summary,operationCount:t.operationCount}))}`}function y(r,e){const t=l(r,e);if(!o.existsSync(t))throw new s.CliError("FILE_MOVE_PREVIEW_NOT_FOUND",`File move preview not found: ${e}`,{previewId:e,expectedPath:t});return JSON.parse(o.readFileSync(t,"utf8"))}function p(r,e){const t=l(r,e.previewId);o.mkdirSync(F.dirname(t),{recursive:!0}),o.writeFileSync(t,`${JSON.stringify(e,null,2)}
|
|
2
|
+
`)}function l(r,e){return(0,_.workspaceCachePath)(r,"file-move-to-dir-previews",`${S(e)}.json`)}function P(r){return r.map(e=>({sourceFile:e.sourceFile,sourceHash:a(e.sourceFile),targetFile:e.targetFile,targetExisted:o.existsSync(e.targetFile),targetHash:a(e.targetFile)}))}function E(r){for(const e of r.states){if(a(e.sourceFile)!==e.sourceHash)throw new s.CliError("FILE_MOVE_PREVIEW_SOURCE_CHANGED","Source file changed after file move preview. Rerun preview.",{previewId:r.previewId,sourceFile:e.sourceFile});const i=o.existsSync(e.targetFile),n=a(e.targetFile);if(i!==e.targetExisted||n!==e.targetHash)throw new s.CliError("FILE_MOVE_PREVIEW_TARGET_CHANGED","Target file changed after file move preview. Rerun preview.",{previewId:r.previewId,targetFile:e.targetFile})}}function a(r){return o.existsSync(r)?f(o.readFileSync(r)):null}function f(r){return h.createHash("sha256").update(r).digest("hex")}function u(r){return r===null||typeof r!="object"?JSON.stringify(r):Array.isArray(r)?`[${r.map(e=>u(e)).join(",")}]`:`{${Object.entries(r).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${JSON.stringify(e)}:${u(t)}`).join(",")}}`}function S(r){return r.replace(/[^a-z0-9_-]+/gi,"-")}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
"use strict";var Me=exports&&exports.__createBinding||(Object.create?(function(e,t,o,r){r===void 0&&(r=o);var i=Object.getOwnPropertyDescriptor(t,o);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[o]}}),Object.defineProperty(e,r,i)}):(function(e,t,o,r){r===void 0&&(r=o),e[r]=t[o]})),De=exports&&exports.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),X=exports&&exports.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(o){var r=[];for(var i in o)Object.prototype.hasOwnProperty.call(o,i)&&(r[r.length]=i);return r},e(t)};return function(t){if(t&&t.__esModule)return t;var o={};if(t!=null)for(var r=e(t),i=0;i<r.length;i++)r[i]!=="default"&&Me(o,t,r[i]);return De(o,t),o}})();Object.defineProperty(exports,"__esModule",{value:!0}),exports.runFileMoveToDir=Ee,exports.readCachedFileMoveToDirExecution=Re;const F=X(require("node:fs")),f=X(require("node:path")),_=require("zod"),Fe=require("../client/http-client"),D=require("../config/env-vars"),_e=require("../config/product-storage"),V=require("../config/import-rules"),N=require("../shared/agent-text"),S=require("../shared/errors"),U=require("../shared/protocol"),we=require("../shared/routes"),K=require("./shared"),Y=require("./inspect-cycles"),A=require("./file-move-to-dir-preview-cache"),w=require("./file-move-to-dir-execution-cache"),M=require("./file-mutation-runtime"),Z=require("./mutation-execution-cache"),ee=_.z.object({base:_.z.string().min(1),moves:_.z.array(_.z.object({targetDir:_.z.string().min(1),files:_.z.array(_.z.string().min(1)).min(1)})).min(1),execute:_.z.boolean().optional()});async function Ee(e,t,o={},r=[]){const i=Ke(),n=r[0]??"preview";if(n==="help"||n==="--help")return Je();if(n==="apply"){const l=r[1];if(!l||l.startsWith("--"))throw new S.CliError("FILE_MOVE_PREVIEW_ID_REQUIRED","file move toDir apply expects a preview id.",{usage:"aib file move toDir apply <previewId>"});return Te(e,l,o,i)}if(n!=="preview"&&n!=="execute"&&n!=="validate")throw new S.CliError("UNKNOWN_FILE_MOVE_TO_DIR_COMMAND",`Unknown file move toDir command: ${n}`,{availableCommands:["preview","apply","execute","validate","help"]});const s=ee.parse(t);return n==="execute"&&G()>0?te(e,{...s,execute:!0},o,"execute",G(),i):oe(e,{...s,execute:n==="execute"},o,n,i)}async function Te(e,t,o,r){const i=(0,A.readFileMoveToDirPreviewRecord)(e,t);(0,A.validateFileMoveStates)(i);const n=ee.parse({...i.normalizedPayload,execute:!0}),s=G();if(s>0)return te(e,n,o,"apply",s,r,t);const l=await oe(e,n,o,"apply",r,t);return l.ok===!1?(0,N.attachAgentText)({...l,next:"Fix the file move request and rerun preview."},H({...l,next:"Fix the file move request and rerun preview."})):l}async function te(e,t,o,r,i,n,s){const l=se(e,t,!0),c=(0,w.buildFileMoveToDirExecutionId)(),u=`move.toDir.${r}`,p=(0,M.estimateFileMutationDurationMs)(qe(l.operations)),a=(0,w.createFileMoveToDirExecutionStatus)(e,c,u,Ue(e,l.operations));(0,w.writeFileMoveToDirExecutionStatus)(e,a);const T=Date.now(),y=Ge(),k=(0,M.startFileMutationBackgroundJob)(()=>(0,_e.runWithProductStorageOverride)(y[D.CLI_ENV.productStorageDir],()=>(0,M.withFileMutationBackgroundEnv)(y,async()=>{try{const m=await re(e,l,r,o,n,c,a,s),I=je(m);return a.status=m.ok===!1?"failed":"completed",a.phase="completed",a.completedRows=m.ok===!1?I.filter(x=>x.ok!==!1).length:a.rowCount,a.failedRows=m.ok===!1?I.filter(x=>x.ok===!1).length:0,a.notRunRows=m.ok===!1?Math.max(0,a.rowCount-I.length):0,a.filesWritten=O(m.filesWritten),a.touchedFiles=O(m.touchedFiles),a.moves=Array.isArray(m.moves)?m.moves.filter(v):[],a.rows=I,v(m.postMutation)&&(a.postMutation=m.postMutation),a.result=m,m.ok===!1&&(a.error=d(m.code)??ce(I)??"FILE_MOVE_TO_DIR_FAILED"),(0,w.writeFileMoveToDirExecutionStatus)(e,a),m}catch(m){throw a.status="failed",a.phase="completed",a.failedRows=Math.max(1,a.failedRows),a.notRunRows=Math.max(0,a.rowCount-a.completedRows-a.failedRows),a.error=m instanceof Error?m.message:String(m),(0,w.writeFileMoveToDirExecutionStatus)(e,a),m}}))),P=await(0,Z.waitForMutationDeadline)(k,i);return P.status==="result"?P.result:(k.catch(()=>{}),xe(e,c,u,p,Date.now()-T))}async function oe(e,t,o,r,i,n,s,l){await(0,M.maybeDelayFileMutationForTest)(process.env[D.CLI_ENV.testFileMoveToDirDelayMs]);const c=l??se(e,t,r==="execute"||r==="apply"),u=c.execute?await re(e,c,r==="apply"?"apply":"execute",o,i,s,void 0,n):be(c.operations),p=ae(e,u,c,r,n,s);if((r==="preview"||r==="validate")&&p.ok!==!1){const a=(0,A.buildFileMoveToDirPreviewId)(c.normalizedPayload),T=(0,A.readFileMoveStates)(c.operations),y=(0,A.buildFileMoveToDirPreviewHash)(c.normalizedPayload,T,p);(0,A.writeFileMoveToDirPreviewRecord)(e,{previewId:a,previewHash:y,createdAt:new Date().toISOString(),cwd:f.resolve(e),normalizedPayload:c.normalizedPayload,states:T,previewResult:p}),p.previewId=a,p.next=`aib file move toDir apply ${a}`}return(0,N.attachAgentText)(p,H(p))}async function re(e,t,o,r,i,n,s,l){const c=[],u=new Set,p=new Set,a=[],T=ue(e,t.operations.map(h=>h.sourceFile));let y=[],k=null;for(const h of t.operations){s&&(s.phase="movingFile",s.status="running",j(e,s,c,u,p),await B());const C=await Ie(e,h,r,i),L=Array.isArray(C.rows)&&v(C.rows[0])?C.rows[0]:R(h,"FILE_MOVE_TO_DIR_FAILED","Extension did not return a file move row.");c.push(L);for(const W of b(L.savedFiles))u.add(f.normalize(W));for(const W of b(L.touchedFiles))p.add(f.normalize(W));for(const W of Xe(L.importSnapshotBefore))a.push(W);if(s&&(j(e,s,c,u,p),await B()),L.ok===!1)break;await(0,M.delayFileMutationForTest)(i.testRowDelayMs)}const P=c.every(h=>h.ok!==!1)&&c.length===t.operations.length;if(c.some(h=>h.ok!==!1)&&i.postProcessImports&&p.size>0){s&&(s.phase="postProcessImports",j(e,s,c,u,p),await B()),await(0,M.delayFileMutationForTest)(i.testImportPostProcessDelayMs);const h=await Ce(e,Array.from(p),a,r);y=Array.isArray(h.cleanup)?h.cleanup.filter(v):[];for(const C of b(h.savedFiles))u.add(f.normalize(C))}const m=y.every(h=>h.ok!==!1);if(P&&m){s&&(s.phase="postMutation.cycles",j(e,s,c,u,p),await B()),await it(i.testPostMutationCyclesDelayMs);const h=ge([...Array.from(p),...Array.from(u)]),C=ue(e,h);k={cycles:Ye(T,C,new Set(de(e,h)))}}const I=J({...!P||!m?{ok:!1}:{},operation:U.CLI_COMMAND_IDS.fileMutation,execute:!0,rowCount:t.operations.length,appliedCount:c.filter(h=>h.applied===!0).length,savedFiles:Array.from(u),touchedFiles:Array.from(p),cleanup:y,rows:c,postMutation:k}),x=ae(e,I,t,o,l,n);return(0,N.attachAgentText)(x,H(x))}function j(e,t,o,r,i){const n=o.map(s=>le(e,s));t.rows=n,t.completedRows=n.filter(s=>s.ok!==!1).length,t.failedRows=n.filter(s=>s.ok===!1).length,t.notRunRows=t.failedRows>0?Math.max(0,t.rowCount-n.length):0,t.filesWritten=Array.from(r).sort((s,l)=>s.localeCompare(l)).map(s=>g(e,s)),t.touchedFiles=Array.from(i).sort((s,l)=>s.localeCompare(l)).map(s=>g(e,s)),t.failedRows>0&&(t.status="failed",t.error=ce(n)??"FILE_MOVE_TO_DIR_FAILED"),(0,w.writeFileMoveToDirExecutionStatus)(e,t)}async function Ie(e,t,o,r){const i=await(0,K.resolveCompatibleTargetInstance)(e,U.CLI_COMMAND_IDS.fileMutation,o),n=o.importRules??(0,V.readConfigImportRules)(e),s=r.testFailRequiredImportUpdate,c={operations:[s?{...t,testFailRequiredImportUpdate:s}:t],execute:!0,importRules:(0,V.importRulesToJson)(n),postProcessImports:!1};return s&&(c.testFailRequiredImportUpdate=s),ne(i.entry,c,o)}async function Ce(e,t,o,r){const i=await(0,K.resolveCompatibleTargetInstance)(e,U.CLI_COMMAND_IDS.fileMutation,r),n=r.importRules??(0,V.readConfigImportRules)(e);return ne(i.entry,{action:"postProcessImports",files:t,importRules:(0,V.importRulesToJson)(n),importSnapshotBefore:o},r)}function Re(e,t){const o=(0,w.readFileMoveToDirExecutionStatus)(e,t),r={operation:"execution.status",executionId:o.executionId,status:o.status,phase:o.phase,summary:q(o),progress:`${o.completedRows}/${o.rowCount}`,filesWritten:o.filesWritten,touchedFiles:o.touchedFiles,...o.postMutation?{postMutation:o.postMutation}:{},updatedAt:o.updatedAt,...o.error?{error:o.error}:{}};return(0,N.attachAgentText)(r,Ae(o))}function xe(e,t,o,r,i){const n=(0,w.readFileMoveToDirExecutionStatus)(e,t),s=Math.max(0,r-i),l={operation:"execution.status",executionId:n.executionId,status:n.status,phase:n.phase,summary:q(n),progress:`${n.completedRows}/${n.rowCount}`,filesWritten:n.filesWritten,touchedFiles:n.touchedFiles,...n.postMutation?{postMutation:n.postMutation}:{},updatedAt:n.updatedAt,estimatedRemainingMs:s};return(0,N.attachAgentText)(l,Se(o,n,s))}function Se(e,t,o){return[`${e} ${t.executionId}`,q(t),ie(t),o>0?`estimated remaining: ${(0,M.formatFileMutationDuration)(Math.max(o,5e3))}`:"estimated remaining: check status again soon"].join(`
|
|
2
|
+
`)}function Ae(e){const t=[q(e)];if(e.status==="running")return t.push(ie(e)),t.join(`
|
|
3
|
+
`);ze(t,e);const o=e.rows.filter(i=>i.ok===!1),r=o[0];if(r){const i=d(r.code)??e.error??"FILE_MOVE_TO_DIR_FAILED";t.push(`code: ${i}`),typeof r.error=="string"&&t.push(r.error),typeof r.rollback=="string"&&t.push(`rollback: ${r.rollback}`),typeof r.hint=="string"&&t.push(`hint: ${r.hint}`),t.push("failed:");for(const n of o)t.push(`${d(n.source)??"source"} -> ${d(n.target)??"target"}`)}else e.error&&t.push(e.error);return Be(t,e),e.filesWritten.length>0&&he(t,e.filesWritten,e.plannedMoves.map(i=>i.target)),v(e.postMutation)&&v(e.postMutation.cycles)&&ye(t,e.postMutation.cycles),e.status==="failed"&&t.push("next: Fix failed move row and rerun move.toDir preview."),t.join(`
|
|
4
|
+
`)}function ie(e){return e.phase==="postProcessImports"?"updating imports":e.phase==="postMutation.cycles"?"checking cycles":"moving files"}function q(e){const t=Math.floor(Math.max(0,e.completedRows)/Math.max(1,e.rowCount)*100);if(e.status==="completed")return`completed, ${e.completedRows}/${e.rowCount} rows, ${t}% files, ${e.filesWritten.length} files written`;if(e.status==="failed"){const o=[`failed, ${e.completedRows}/${e.rowCount} rows, ${t}% files`,`${e.failedRows} failed`];return e.notRunRows>0&&o.push(`${e.notRunRows} not run`),o.push(`${e.filesWritten.length} files written`),o.join(", ")}return`in progress, ${e.completedRows}/${e.rowCount} rows, ${t}% files`}async function ne(e,t,o){try{return await(0,Fe.postJson)(e,we.EXTENSION_ROUTES.fileMutation,t,(0,K.extensionRequestOptions)(o))}catch(r){if(r instanceof S.CliError&&r.code==="REMOTE_ERROR"){const i=v(r.details)?r.details:{},n=v(i.payload)?i.payload:null;if(n)return n}throw r}}function se(e,t,o){const r=We(e,t.base),i=[],n=new Set;for(const s of t.moves){const l=Le(r,s.targetDir);z(e,l,"FILE_MOVE_TARGET_OUTSIDE_CWD");for(const c of s.files){const u=Pe(e,r,c);z(e,u,"FILE_MOVE_SOURCE_OUTSIDE_CWD");const p=f.normalize(f.resolve(l,f.basename(u)));z(e,p,"FILE_MOVE_TARGET_OUTSIDE_CWD");const a=Q(p);if(n.has(a))throw new S.CliError("FILE_MOVE_DUPLICATE_TARGET","Several file moves resolve to the same target.",{targetFile:g(e,p)});n.add(a),i.push({id:`move-${i.length+1}`,kind:"fileMoveToDir",sourceFile:u,targetDir:l,targetFile:p,execute:o})}}if(i.length===0)throw new S.CliError("FILE_MOVE_ROWS_REQUIRED","file move toDir expects at least one file.");return{execute:o,baseDir:r,operations:i,normalizedPayload:{base:r,moves:ke(i),execute:o}}}function be(e){const t=[];for(const r of e){if(t.some(i=>i.ok===!1))break;t.push(Oe(r))}return{...t.every(r=>r.ok!==!1)&&t.length===e.length?{}:{ok:!1},operation:U.CLI_COMMAND_IDS.fileMutation,execute:!1,rowCount:e.length,appliedCount:0,savedFiles:[],rows:t}}function Oe(e){if(e.kind!=="fileMoveToDir")return R(e,"FILE_MUTATION_KIND_UNSUPPORTED",`Unsupported file mutation kind: ${e.kind}`);if(!F.existsSync(e.sourceFile))return R(e,"FILE_MOVE_SOURCE_NOT_FOUND","Source file does not exist.");try{if(!F.statSync(e.sourceFile).isFile())return R(e,"FILE_MOVE_SOURCE_DIRECTORY_UNSUPPORTED","file move toDir v1 supports files only, not directories.")}catch(t){return R(e,"FILE_MOVE_SOURCE_STAT_FAILED",t instanceof Error?t.message:String(t))}return F.existsSync(e.targetFile)?R(e,"FILE_MOVE_TARGET_EXISTS","Target file already exists.","Pick another target directory/name or remove the target collision."):$e(e.sourceFile)?R(e,"FILE_MOVE_SOURCE_ASSET_UNSUPPORTED","CSS/SCSS files cannot be moved with file move toDir v1."):{id:e.id,ok:!0,sourceFile:e.sourceFile,targetFile:e.targetFile,applied:!1}}function R(e,t,o,r){return{id:e.id,ok:!1,sourceFile:e.sourceFile,targetFile:e.targetFile,applied:!1,code:t,error:o,...r?{hint:r}:{}}}function $e(e){return[".css",".scss"].includes(f.extname(e).toLowerCase())}function ke(e){const t=new Map;for(const o of e){const r=t.get(o.targetDir)??{targetDir:o.targetDir,files:[]};r.files.push(o.sourceFile),t.set(o.targetDir,r)}return Array.from(t.values())}function Pe(e,t,o){const r=o.trim();if(f.isAbsolute(r))return f.normalize(r);const i=f.normalize(f.resolve(t,r));if(F.existsSync(i))return i;const n=f.normalize(f.resolve(e,r));return F.existsSync(n)?n:i}function Le(e,t){const o=t.trim();return f.normalize(f.isAbsolute(o)?o:f.resolve(e,o))}function We(e,t){const o=f.normalize(f.isAbsolute(t)?t:f.resolve(e,t));return z(e,o,"FILE_MOVE_PATH_OUTSIDE_CWD"),o}function z(e,t,o){const r=f.resolve(e),i=f.relative(r,t);if(!(i===""||!i.startsWith("..")&&!f.isAbsolute(i)))throw new S.CliError(o,"File move paths must stay inside the current workspace.",{cwd:r,filePath:t})}function ae(e,t,o,r,i,n){const s=Array.isArray(t.rows)?t.rows.filter(v).map(y=>le(e,y)):[],l=t.ok!==!1&&s.every(y=>y.ok!==!1),c=Qe(s,"target"),u=et(e,b(t.savedFiles)).map(y=>g(e,y)),p=tt(o.operations),a=r==="apply"?"move.toDir.apply":o.execute?"move.toDir.execute":"move.toDir.preview";return J({...l?{}:{ok:!1},operation:a,executionId:n??null,base:g(e,o.baseDir),operationCount:o.operations.length,summary:l?o.execute?`${o.operations.length} ${E(o.operations.length,"file","files")} moved, ${u.length} ${E(u.length,"file","files")} written`:`${o.operations.length} ${E(o.operations.length,"file","files")}, ${ve(o.operations)} target ${E(ve(o.operations),"dir","dirs")} ready`:Ve(s,o.operations.length,o.execute||r==="apply"),dirsToCreate:p,moves:Ne(e,o.operations),...o.execute||r==="apply"?{filesWritten:u,filesMoved:c}:{},...v(t.postMutation)?{postMutation:t.postMutation}:{},rows:l?null:s,previewId:i??null})}function le(e,t){return J({id:d(t.id),ok:t.ok!==!1,source:g(e,d(t.sourceFile)??""),target:g(e,d(t.targetFile)??""),applied:typeof t.applied=="boolean"?t.applied:null,rollback:d(t.rollback),savedFiles:ot(b(t.savedFiles).map(o=>g(e,o)),5),code:d(t.code),error:d(t.error),hint:d(t.hint)})}function Ne(e,t){const o=new Map;for(const r of t){const i=g(e,r.targetDir);o.set(i,[...o.get(i)??[],g(e,r.sourceFile)])}return Array.from(o.entries()).map(([r,i])=>({targetDir:r,files:i}))}function Ve(e,t,o){const r=e.filter(n=>n.ok===!1).length,i=Math.max(0,t-e.length);if(!o){const n=Math.min(t,e.length);return`${t} ${E(t,"file","files")}, validation blocked at row ${n}`}return`${t} ${E(t,"file","files")}, ${r} failed${i>0?`, ${i} not run`:""}`}function Ue(e,t){return t.map(o=>({source:g(e,o.sourceFile),target:g(e,o.targetFile),targetDir:g(e,o.targetDir)}))}function je(e){return Array.isArray(e.rows)?e.rows.filter(v):[]}function qe(e){const t=new Set(e.map(r=>r.targetDir));let o=0;for(const r of t)F.existsSync(r)||(o+=1);return{rowCount:e.length,targetDirCount:t.size,dirsToCreate:o}}function ce(e){const t=e.find(o=>o.ok===!1);return t?d(t.code):null}function ze(e,t){const o=new Set(t.rows.filter(i=>i.ok!==!1).map(i=>d(i.source)).filter(i=>!!i)),r=new Map;for(const i of t.plannedMoves)t.status!=="completed"&&!o.has(i.source)||r.set(i.targetDir,[...r.get(i.targetDir)??[],i.source]);if(r.size!==0){e.push("moves:");for(const[i,n]of r)e.push(`${i}: ${n.join(", ")}`)}}function Be(e,t){if(t.notRunRows<=0)return;const o=new Set(t.rows.map(i=>d(i.source)).filter(i=>!!i)),r=t.plannedMoves.filter(i=>!o.has(i.source));if(r.length!==0){e.push("not run:");for(const i of r)e.push(i.source)}}function G(){return(0,Z.readMutationSyncWaitMs)(process.env[D.CLI_ENV.fileMoveToDirSyncWaitMs],12e4)}function Ke(){return{postProcessImports:(0,M.isFileMutationImportPostProcessEnabled)(),testFailRequiredImportUpdate:d(process.env[D.CLI_ENV.testFileMoveToDirFailImports]),testRowDelayMs:(0,M.readFileMutationTestDelayMs)(process.env[D.CLI_ENV.testFileMoveToDirRowDelayMs],6e4),testImportPostProcessDelayMs:(0,M.readFileMutationTestDelayMs)(process.env[D.CLI_ENV.testFileMoveToDirImportsDelayMs],6e4),testPostMutationCyclesDelayMs:(0,M.readFileMutationTestDelayMs)(process.env[D.CLI_ENV.testPostMutationCyclesDelayMs],6e4)}}function Ge(){return(0,M.captureFileMutationBackgroundEnv)([D.CLI_ENV.testFileMoveToDirDelayMs,D.CLI_ENV.testFileMoveToDirRowDelayMs,D.CLI_ENV.testFileMoveToDirImportsDelayMs,D.CLI_ENV.testFileMoveToDirFailImports])}function H(e){const t=d(e.operation);if(!t?.startsWith("move.toDir."))return null;const o=[],r=d(e.previewId),i=d(e.executionId);o.push(e.ok===!1?`${t} failed`:r&&t==="move.toDir.preview"?`${t} ${r}`:i&&(t==="move.toDir.apply"||t==="move.toDir.execute")?`${t} ${i}`:t),typeof e.summary=="string"&&o.push(e.summary),t==="move.toDir.preview"&&$(e.dirsToCreate)>0&&o.push(`${$(e.dirsToCreate)} ${E($(e.dirsToCreate),"dir","dirs")} will be created`);const n=Array.isArray(e.moves)?e.moves.filter(v):[];if(n.length>0&&e.ok!==!1){o.push("moves:");for(const l of n){const c=d(l.targetDir),u=Array.isArray(l.files)?l.files.filter(p=>typeof p=="string"):[];c&&u.length>0&&o.push(`${c}: ${u.join(", ")}`)}}He(o,e);const s=Array.isArray(e.filesWritten)?e.filesWritten:[];return s.length>0&&he(o,s,Array.isArray(e.filesMoved)?e.filesMoved:[]),v(e.postMutation)&&v(e.postMutation.cycles)&&ye(o,e.postMutation.cycles),typeof e.next=="string"&&o.push(`next: ${e.next}`),o.join(`
|
|
5
|
+
`)}function He(e,t){if(t.ok!==!1||!Array.isArray(t.rows))return;const o=t.rows.filter(v).find(r=>r.ok===!1);o&&(e.push("failed:"),e.push(`${d(o.source)??"source"} -> ${d(o.target)??"target"}`),e.push(`code: ${d(o.code)??"FILE_MOVE_TO_DIR_FAILED"}`),typeof o.error=="string"&&e.push(o.error),typeof o.rollback=="string"&&e.push(`rollback: ${o.rollback}`),typeof o.hint=="string"&&e.push(`hint: ${o.hint}`))}function Je(){return{ok:!0,command:"file move toDir",usage:"aib file move toDir preview --stdin | aib file move toDir execute --stdin | aib file move toDir apply <previewId>",dsl:["@base packages/agent-project-tooling/src","moveToDir workspace-runner:"," workspace-runner-cli.ts"," workspace-runner-command-hints.ts"],notes:["preview validates planned file moves without writing.","execute moves files and updates TypeScript imports.","apply uses the cached preview id and refuses stale source/target state."]}}function Qe(e,t){return e.map(o=>d(o[t])).filter(o=>!!o)}function b(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function Xe(e){return Array.isArray(e)?e.filter(v):[]}function ue(e,t){const o=de(e,t).filter(i=>F.existsSync(me(e,i)));if(o.length===0)return{op:"cycles",componentCount:0,components:[]};const r=["cycles"];for(const i of o)r.push("--files",i);return r.push("--detail","imports","--limit","50"),(0,Y.runInspectCycles)(e,r,void 0)}function Ye(e,t,o){const r=new Set(fe(e).map(pe)),i=fe(t).filter(n=>O(n.files).some(s=>o.has(s))&&!r.has(pe(n)));return{status:i.length>0?"new-or-changed":"none",detail:"imports",newOrChangedCount:i.length,preComponentCount:$(e.componentCount),postComponentCount:$(t.componentCount),components:i}}function fe(e){return(Array.isArray(e.components)?e.components:[]).filter(v).map(t=>({kind:d(t.kind)??"mixed",files:O(t.files).sort(),chain:d(t.chain)??"",...v(t.cycle)?{cycle:t.cycle}:{},imports:Ze(t)}))}function Ze(e){const t=v(e.cycle)?e.cycle:{};return O(t.imports)}function pe(e){return`${d(e.kind)??"mixed"}:${O(e.files).sort().join("|")}`}function de(e,t){return ge(t.map(o=>g(e,me(e,o))))}function me(e,t){return f.normalize(f.isAbsolute(t)?t:f.resolve(e,t))}function O(e){return b(e)}function et(e,t){return t.filter(o=>{const r=f.isAbsolute(o)?o:f.resolve(e,o);return F.existsSync(r)})}function ve(e){return new Set(e.map(t=>Q(t.targetDir))).size}function tt(e){const t=new Map;for(const o of e)t.set(Q(o.targetDir),o.targetDir);return Array.from(t.values()).filter(o=>!F.existsSync(o)).length}function ot(e,t){const o=Array.from(new Set(e)).sort((n,s)=>n.localeCompare(s)),r=o.slice(0,t),i=o.length-r.length;return i>0?[...r,`+ ${i} more`]:r}function nt(e,t){const o=e.slice(0,t),r=e.length-o.length;return r>0?`${o.join(", ")}, + ${r} more`:o.join(", ")}function he(e,t,o){const r=t.filter(u=>typeof u=="string");if(r.length===0)return;const i=new Set(o.filter(u=>typeof u=="string")),n=r.filter(u=>i.has(u)),s=r.filter(u=>!i.has(u)),l=s.slice(0,8),c=s.length-l.length;e.push("filesWritten:");for(const u of[...n,...l])e.push(u);c>0&&e.push(`+ ${c} reference ${E(c,"file","files")}`)}function ye(e,t){e.push("cycles:");const o=$(t.newOrChangedCount);if(o===0){e.push("no new/changed cycles involving touched files");return}const r=Array.isArray(t.components)?t.components.filter(v):[];e.push(rt(o,r)),r.forEach((i,n)=>{(0,Y.appendCycleComponentText)(e,i,{detail:"imports",prefix:r.length===1?"":`${n+1}. `,indent:r.length===1?"":" "})})}function rt(e,t){const o=t.map(n=>d(n.kind)??"mixed"),r=Array.from(new Set(o)),i=r.length===1?`${r[0]} `:"";return`${e} new/changed ${i}${e===1?"cycle":"cycles"} involving touched files`}function E(e,t,o){return e===1?t:o}function d(e){return typeof e=="string"&&e.length>0?e:null}function $(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function J(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t==null?!1:!(Array.isArray(t)&&t.length===0)))}function v(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Q(e){const t=f.normalize(e);return process.platform==="win32"?t.toLowerCase():t}function ge(e){return Array.from(new Set(e))}function B(){return new Promise(e=>setImmediate(e))}async function it(e){e<=0||await new Promise(t=>setTimeout(t,e))}function g(e,t){return t?f.relative(e,t).replace(/\\/g,"/"):""}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.isFileMutationImportPostProcessEnabled=c,exports.readFileMutationTestDelayMs=s,exports.delayFileMutationForTest=a,exports.maybeDelayFileMutationForTest=l,exports.captureFileMutationBackgroundEnv=M,exports.withFileMutationBackgroundEnv=m,exports.startFileMutationBackgroundJob=f,exports.estimateFileMutationDurationMs=d,exports.formatFileMutationDuration=F;const n=require("../config/env-vars"),u=[n.CLI_ENV.productStorageDir,n.CLI_ENV.trace,n.CLI_ENV.traceDir,n.CLI_ENV.metrics,n.CLI_ENV.metricsDir,n.CLI_ENV.metricsTag,n.CLI_ENV.mutationImpactMetrics,n.CLI_ENV.mutationImpactStream,n.CLI_ENV.testPostMutationCyclesDelayMs,n.CLI_ENV.disableFileMutationImportPostProcess,n.CLI_ENV.disableFileMoveImportPostProcess];function c(){return process.env[n.CLI_ENV.disableFileMutationImportPostProcess]!=="1"&&process.env[n.CLI_ENV.disableFileMoveImportPostProcess]!=="1"}function s(e,t){if(!e)return 0;const o=Number.parseInt(e,10);return!Number.isFinite(o)||o<=0?0:Math.min(o,t)}async function a(e){e<=0||await new Promise(t=>setTimeout(t,e))}async function l(e,t=12e4){await a(s(e,t))}function M(e){const t={};for(const o of _([...u,...e]))t[o]=process.env[o];return t}async function m(e,t){const o={};for(const[r,i]of Object.entries(e))o[r]=process.env[r],i===void 0?delete process.env[r]:process.env[r]=i;try{return await t()}finally{for(const[r,i]of Object.entries(o))i===void 0?delete process.env[r]:process.env[r]=i}}function f(e){return new Promise((t,o)=>{setImmediate(()=>{e().then(t,o)})})}function d(e){const t=typeof e=="number"?e:e.rowCount,o=typeof e=="number"?0:e.targetDirCount??0,r=typeof e=="number"?0:e.dirsToCreate??0;return 24e3+Math.max(0,t)*3e3+Math.max(0,o)*1e3+Math.max(0,r)*1e3}function F(e){if(e<1e3)return"<1 sec";const t=Math.ceil(e/1e3);return t<60?`~${t} sec`:`~${Math.ceil(t/60)} min`}function _(e){return Array.from(new Set(e))}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var c=exports&&exports.__createBinding||(Object.create?(function(e,t,a,n){n===void 0&&(n=a);var r=Object.getOwnPropertyDescriptor(t,a);(!r||("get"in r?!t.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return t[a]}}),Object.defineProperty(e,n,r)}):(function(e,t,a,n){n===void 0&&(n=a),e[n]=t[a]})),o=exports&&exports.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),f=exports&&exports.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(a){var n=[];for(var r in a)Object.prototype.hasOwnProperty.call(a,r)&&(n[n.length]=r);return n},e(t)};return function(t){if(t&&t.__esModule)return t;var a={};if(t!=null)for(var n=e(t),r=0;r<n.length;r++)n[r]!=="default"&&c(a,t,n[r]);return o(a,t),a}})();Object.defineProperty(exports,"__esModule",{value:!0}),exports.buildFileRefactorBatchExecutionId=h,exports.createFileRefactorBatchExecutionStatus=d,exports.readFileRefactorBatchExecutionStatus=_,exports.tryReadFileRefactorBatchExecutionStatus=E,exports.writeFileRefactorBatchExecutionStatus=R,exports.FileRefactorBatchExecutionPath=F,exports.FileRefactorBatchExecutionLastPath=b;const l=f(require("node:path")),s=require("../config/product-storage"),u=require("./mutation-execution-cache");function h(){return(0,u.buildMutationExecutionId)()}function d(e,t,a,n){const r=new Date().toISOString();return{executionId:t,operation:a,cwd:l.resolve(e),status:"running",phase:"movingFile",startedAt:r,updatedAt:r,rowCount:Math.max(1,n.length),completedRows:0,failedRows:0,notRunRows:0,filesWritten:[],touchedFiles:[],plannedMoves:n,moves:[],rows:[],productStorageDir:(0,s.productStorageRoot)()}}function _(e,t){return(0,u.readMutationExecutionStatus)(e,t,i)}function E(e,t){return(0,u.tryReadMutationExecutionStatus)(e,t,i)}function R(e,t){(0,u.writeMutationExecutionStatus)(e,t,i)}function F(e,t,a){return(0,u.mutationExecutionPath)(e,i.namespace,t,a)}function b(e,t){return(0,u.mutationExecutionLastPath)(e,i.namespace,t)}const i={namespace:"file-refactor-batch-executions",notFoundCode:"FILE_REFACTOR_BATCH_EXECUTION_NOT_FOUND",notFoundLabel:"file refactor batch"};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var h=exports&&exports.__createBinding||(Object.create?(function(t,e,r,i){i===void 0&&(i=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(t,i,n)}):(function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]})),d=exports&&exports.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),o=exports&&exports.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var i=[];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(i[i.length]=n);return i},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i=t(e),n=0;n<i.length;n++)i[n]!=="default"&&h(r,e,i[n]);return d(r,e),r}})();Object.defineProperty(exports,"__esModule",{value:!0}),exports.buildFileRefactorBatchPreviewId=w,exports.buildFileRefactorBatchPreviewHash=g,exports.readFileRefactorBatchPreviewRecord=R,exports.writeFileRefactorBatchPreviewRecord=y,exports.FileRefactorBatchPreviewRecordPath=l,exports.readFileMoveStates=p,exports.validateFileMoveStates=P;const F=o(require("node:crypto")),a=o(require("node:fs")),_=o(require("node:path")),s=require("../shared/errors"),v=require("./workspace-cache");function w(t){return`apply_${f(u(t)).slice(0,10)}`}function g(t,e,r){return`sha256:${f(u({normalizedPayload:t,states:e,summary:r.summary,operationCount:r.operationCount}))}`}function R(t,e){const r=l(t,e);if(!a.existsSync(r))throw new s.CliError("FILE_REFACTOR_BATCH_PREVIEW_NOT_FOUND",`File move preview not found: ${e}`,{previewId:e,expectedPath:r});return JSON.parse(a.readFileSync(r,"utf8"))}function y(t,e){const r=l(t,e.previewId);a.mkdirSync(_.dirname(r),{recursive:!0}),a.writeFileSync(r,`${JSON.stringify(e,null,2)}
|
|
2
|
+
`)}function l(t,e){return(0,v.workspaceCachePath)(t,"file-refactor-batch-previews",`${E(e)}.json`)}function p(t){return t.map(e=>({sourceFile:e.sourceFile,sourceHash:c(e.sourceFile),targetFile:e.targetFile,targetExisted:a.existsSync(e.targetFile),targetHash:c(e.targetFile)}))}function P(t){for(const e of t.states){if(c(e.sourceFile)!==e.sourceHash)throw new s.CliError("FILE_REFACTOR_BATCH_PREVIEW_SOURCE_CHANGED","Source file changed after file move preview. Rerun preview.",{previewId:t.previewId,sourceFile:e.sourceFile});const i=a.existsSync(e.targetFile),n=c(e.targetFile);if(i!==e.targetExisted||n!==e.targetHash)throw new s.CliError("FILE_REFACTOR_BATCH_PREVIEW_TARGET_CHANGED","Target file changed after file move preview. Rerun preview.",{previewId:t.previewId,targetFile:e.targetFile})}}function c(t){return a.existsSync(t)?f(a.readFileSync(t)):null}function f(t){return F.createHash("sha256").update(t).digest("hex")}function u(t){return t===null||typeof t!="object"?JSON.stringify(t):Array.isArray(t)?`[${t.map(e=>u(e)).join(",")}]`:`{${Object.entries(t).sort(([e],[r])=>e.localeCompare(r)).map(([e,r])=>`${JSON.stringify(e)}:${u(r)}`).join(",")}}`}function E(t){return t.replace(/[^a-z0-9_-]+/gi,"-")}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
"use strict";var Fe=exports&&exports.__createBinding||(Object.create?(function(e,t,r,o){o===void 0&&(o=r);var n=Object.getOwnPropertyDescriptor(t,r);(!n||("get"in n?!t.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,o,n)}):(function(e,t,r,o){o===void 0&&(o=r),e[o]=t[r]})),Re=exports&&exports.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),Y=exports&&exports.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(r){var o=[];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(o[o.length]=n);return o},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(t!=null)for(var o=e(t),n=0;n<o.length;n++)o[n]!=="default"&&Fe(r,t,o[n]);return Re(r,t),r}})();Object.defineProperty(exports,"__esModule",{value:!0}),exports.runFileRefactorBatch=Ee,exports.readCachedFileRefactorBatchExecution=Ie;const w=Y(require("node:fs")),f=Y(require("node:path")),C=require("zod"),_e=require("../client/http-client"),_=require("../config/env-vars"),Ce=require("../config/product-storage"),q=require("../config/import-rules"),W=require("../shared/agent-text"),T=require("../shared/errors"),U=require("../shared/protocol"),we=require("../shared/routes"),K=require("./shared"),Z=require("./inspect-cycles"),D=require("./file-refactor-batch-preview-cache"),v=require("./file-refactor-batch-execution-cache"),R=require("./file-mutation-runtime"),ee=require("./mutation-execution-cache"),te=C.z.object({operations:C.z.array(C.z.object({kind:C.z.union([C.z.literal("fileMoveToDir"),C.z.literal("fileRename")]),sourceFile:C.z.string().min(1),targetDir:C.z.string().min(1),targetFile:C.z.string().min(1)})).min(1),execute:C.z.boolean().optional()});async function Ee(e,t,r={},o=[]){const n=qe(),i=o[0]??"preview";if(i==="help"||i==="--help")return ze();if(i==="apply"){const c=o[1];if(!c||c.startsWith("--"))throw new T.CliError("FILE_REFACTOR_BATCH_PREVIEW_ID_REQUIRED","file refactor batch apply expects a preview id.",{usage:"aib file refactor batch apply <previewId>"});return ve(e,c,r,n)}if(i!=="preview"&&i!=="execute"&&i!=="validate")throw new T.CliError("UNKNOWN_FILE_REFACTOR_BATCH_COMMAND",`Unknown file refactor batch command: ${i}`,{availableCommands:["preview","apply","execute","validate","help"]});const a=te.parse(t);return i==="execute"&&G()>0?re(e,{...a,execute:!0},r,"execute",G(),n):oe(e,{...a,execute:i==="execute"},r,i,n)}async function ve(e,t,r,o){const n=(0,D.readFileRefactorBatchPreviewRecord)(e,t);(0,D.validateFileMoveStates)(n);const i=te.parse({...n.normalizedPayload,execute:!0}),a=G();if(a>0)return re(e,i,r,"apply",a,o,t);const c=await oe(e,i,r,"apply",o,t);return c.ok===!1?(0,W.attachAgentText)({...c,next:"Fix the file refactor batch request and rerun preview."},J({...c,next:"Fix the file refactor batch request and rerun preview."})):c}async function re(e,t,r,o,n,i,a){const c=se(e,t,!0),s=(0,v.buildFileRefactorBatchExecutionId)(),u=`file.refactor.batch.${o}`,h=(0,R.estimateFileMutationDurationMs)(Le(c.operations)),l=(0,v.createFileRefactorBatchExecutionStatus)(e,s,u,Oe(e,c.operations));(0,v.writeFileRefactorBatchExecutionStatus)(e,l);const F=Date.now(),E=Ue(),$=(0,R.startFileMutationBackgroundJob)(()=>(0,Ce.runWithProductStorageOverride)(E[_.CLI_ENV.productStorageDir],()=>(0,R.withFileMutationBackgroundEnv)(E,async()=>{try{const d=await ne(e,c,o,r,i,s,l,a),M=Pe(d);return l.status=d.ok===!1?"failed":"completed",l.phase="completed",l.completedRows=d.ok===!1?M.filter(b=>b.ok!==!1).length:l.rowCount,l.failedRows=d.ok===!1?M.filter(b=>b.ok===!1).length:0,l.notRunRows=d.ok===!1?Math.max(0,l.rowCount-M.length):0,l.filesWritten=B(d.filesWritten),l.touchedFiles=B(d.touchedFiles),l.moves=Array.isArray(d.changes)?d.changes.filter(m):[],l.rows=M,m(d.postMutation)&&(l.postMutation=d.postMutation),l.result=d,d.ok===!1&&(l.error=p(d.code)??ue(M)??"FILE_REFACTOR_BATCH_FAILED"),(0,v.writeFileRefactorBatchExecutionStatus)(e,l),d}catch(d){throw l.status="failed",l.phase="completed",l.failedRows=Math.max(1,l.failedRows),l.notRunRows=Math.max(0,l.rowCount-l.completedRows-l.failedRows),l.error=d instanceof Error?d.message:String(d),(0,v.writeFileRefactorBatchExecutionStatus)(e,l),d}}))),O=await(0,ee.waitForMutationDeadline)($,n);return O.status==="result"?O.result:($.catch(()=>{}),xe(e,s,u,h,Date.now()-F))}async function oe(e,t,r,o,n,i,a,c){await(0,R.maybeDelayFileMutationForTest)(process.env[_.CLI_ENV.testFileRefactorBatchDelayMs]);const s=c??se(e,t,o==="execute"||o==="apply"),u=s.execute?await ne(e,s,o==="apply"?"apply":"execute",r,n,a,void 0,i):De(s.operations),h=ce(e,u,s,o,i,a);if((o==="preview"||o==="validate")&&h.ok!==!1){const l=(0,D.buildFileRefactorBatchPreviewId)(s.normalizedPayload),F=(0,D.readFileMoveStates)(s.operations),E=(0,D.buildFileRefactorBatchPreviewHash)(s.normalizedPayload,F,h);(0,D.writeFileRefactorBatchPreviewRecord)(e,{previewId:l,previewHash:E,createdAt:new Date().toISOString(),cwd:f.resolve(e),normalizedPayload:s.normalizedPayload,states:F,previewResult:h}),h.previewId=l,h.next=`aib file refactor batch apply ${l}`}return(0,W.attachAgentText)(h,J(h))}async function ne(e,t,r,o,n,i,a,c){const s=[],u=new Set,h=new Set,l=[],F=fe(e,t.operations.map(y=>y.sourceFile));let E=[],$=null;for(const y of t.operations){a&&(a.phase="movingFile",a.status="running",j(e,a,s,u,h),await V());const I=await Ae(e,y,o,n),P=Array.isArray(I.rows)&&m(I.rows[0])?I.rows[0]:x(y,"FILE_REFACTOR_BATCH_FAILED","Extension did not return a file refactor batch row.");s.push(P);for(const L of S(P.savedFiles))u.add(f.normalize(L));for(const L of S(P.touchedFiles))h.add(f.normalize(L));for(const L of Ve(P.importSnapshotBefore))l.push(L);if(a&&(j(e,a,s,u,h),await V()),P.ok===!1)break;await(0,R.delayFileMutationForTest)(n.testRowDelayMs)}const O=s.every(y=>y.ok!==!1)&&s.length===t.operations.length;if(s.some(y=>y.ok!==!1)&&n.postProcessImports&&h.size>0){a&&(a.phase="postProcessImports",j(e,a,s,u,h),await V()),await(0,R.delayFileMutationForTest)(n.testImportPostProcessDelayMs);const y=await Me(e,Array.from(h),l,o);E=Array.isArray(y.cleanup)?y.cleanup.filter(m):[];for(const I of S(y.savedFiles))u.add(f.normalize(I))}const d=E.every(y=>y.ok!==!1);if(O&&d){a&&(a.phase="postMutation.cycles",j(e,a,s,u,h),await V()),await Ye(n.testPostMutationCyclesDelayMs);const y=ge([...Array.from(h),...Array.from(u)]),I=fe(e,y);$={cycles:Ke(F,I,new Set(de(e,y)))}}const M=X({...!O||!d?{ok:!1}:{},operation:U.CLI_COMMAND_IDS.fileMutation,execute:!0,rowCount:t.operations.length,appliedCount:s.filter(y=>y.applied===!0).length,savedFiles:Array.from(u),touchedFiles:Array.from(h),cleanup:E,rows:s,postMutation:$}),b=ce(e,M,t,r,c,i);return(0,W.attachAgentText)(b,J(b))}function j(e,t,r,o,n){const i=r.map(a=>le(e,a));t.rows=i,t.completedRows=i.filter(a=>a.ok!==!1).length,t.failedRows=i.filter(a=>a.ok===!1).length,t.notRunRows=t.failedRows>0?Math.max(0,t.rowCount-i.length):0,t.filesWritten=Array.from(o).sort((a,c)=>a.localeCompare(c)).map(a=>g(e,a)),t.touchedFiles=Array.from(n).sort((a,c)=>a.localeCompare(c)).map(a=>g(e,a)),t.failedRows>0&&(t.status="failed",t.error=ue(i)??"FILE_REFACTOR_BATCH_FAILED"),(0,v.writeFileRefactorBatchExecutionStatus)(e,t)}async function Ae(e,t,r,o){const n=await(0,K.resolveCompatibleTargetInstance)(e,U.CLI_COMMAND_IDS.fileMutation,r),i=r.importRules??(0,q.readConfigImportRules)(e),a=o.testFailRequiredImportUpdate,s={operations:[a?{...t,testFailRequiredImportUpdate:a}:t],execute:!0,importRules:(0,q.importRulesToJson)(i),postProcessImports:!1};return a&&(s.testFailRequiredImportUpdate=a),ae(n.entry,s,r)}async function Me(e,t,r,o){const n=await(0,K.resolveCompatibleTargetInstance)(e,U.CLI_COMMAND_IDS.fileMutation,o),i=o.importRules??(0,q.readConfigImportRules)(e);return ae(n.entry,{action:"postProcessImports",files:t,importRules:(0,q.importRulesToJson)(i),importSnapshotBefore:r},o)}function Ie(e,t){const r=(0,v.readFileRefactorBatchExecutionStatus)(e,t),o={operation:"execution.status",executionId:r.executionId,status:r.status,phase:r.phase,summary:z(r),progress:`${r.completedRows}/${r.rowCount}`,filesWritten:r.filesWritten,touchedFiles:r.touchedFiles,...r.postMutation?{postMutation:r.postMutation}:{},updatedAt:r.updatedAt,...r.error?{error:r.error}:{}};return(0,W.attachAgentText)(o,Te(r))}function xe(e,t,r,o,n){const i=(0,v.readFileRefactorBatchExecutionStatus)(e,t),a=Math.max(0,o-n),c={operation:"execution.status",executionId:i.executionId,status:i.status,phase:i.phase,summary:z(i),progress:`${i.completedRows}/${i.rowCount}`,filesWritten:i.filesWritten,touchedFiles:i.touchedFiles,...i.postMutation?{postMutation:i.postMutation}:{},updatedAt:i.updatedAt,estimatedRemainingMs:a};return(0,W.attachAgentText)(c,be(r,i,a))}function be(e,t,r){return[`${e} ${t.executionId}`,z(t),ie(t),r>0?`estimated remaining: ${(0,R.formatFileMutationDuration)(Math.max(r,5e3))}`:"estimated remaining: check status again soon"].join(`
|
|
2
|
+
`)}function Te(e){const t=[z(e)];if(e.status==="running")return t.push(ie(e)),t.join(`
|
|
3
|
+
`);We(t,e);const r=e.rows.filter(n=>n.ok===!1),o=r[0];if(o){const n=p(o.code)??e.error??"FILE_REFACTOR_BATCH_FAILED";t.push(`code: ${n}`),typeof o.error=="string"&&t.push(o.error),typeof o.rollback=="string"&&t.push(`rollback: ${o.rollback}`),typeof o.hint=="string"&&t.push(`hint: ${o.hint}`),t.push("failed:");for(const i of r)t.push(`${p(i.source)??"source"} -> ${p(i.target)??"target"}`)}else e.error&&t.push(e.error);return Ne(t,e),e.filesWritten.length>0&&me(t,e.filesWritten,e.plannedMoves.map(n=>n.target)),m(e.postMutation)&&m(e.postMutation.cycles)&&ye(t,e.postMutation.cycles),e.status==="failed"&&t.push("next: Fix failed rename row and rerun file.refactor.batch preview."),t.join(`
|
|
4
|
+
`)}function ie(e){return e.phase==="postProcessImports"?"updating imports":e.phase==="postMutation.cycles"?"checking cycles":"moving/renaming files"}function z(e){const t=Math.floor(Math.max(0,e.completedRows)/Math.max(1,e.rowCount)*100);if(e.status==="completed")return`completed, ${e.completedRows}/${e.rowCount} rows, ${t}% files, ${e.filesWritten.length} files written`;if(e.status==="failed"){const r=[`failed, ${e.completedRows}/${e.rowCount} rows, ${t}% files`,`${e.failedRows} failed`];return e.notRunRows>0&&r.push(`${e.notRunRows} not run`),r.push(`${e.filesWritten.length} files written`),r.join(", ")}return`in progress, ${e.completedRows}/${e.rowCount} rows, ${t}% files`}async function ae(e,t,r){try{return await(0,_e.postJson)(e,we.EXTENSION_ROUTES.fileMutation,t,(0,K.extensionRequestOptions)(r))}catch(o){if(o instanceof T.CliError&&o.code==="REMOTE_ERROR"){const n=m(o.details)?o.details:{},i=m(n.payload)?n.payload:null;if(i)return i}throw o}}function se(e,t,r){const o=f.resolve(e),n=[],i=new Set;for(const a of t.operations){const c=N(e,a.sourceFile);H(e,c,"FILE_REFACTOR_BATCH_SOURCE_OUTSIDE_CWD");const s=N(e,a.targetFile);H(e,s,"FILE_REFACTOR_BATCH_TARGET_OUTSIDE_CWD");const u=N(e,a.targetDir);H(e,u,"FILE_REFACTOR_BATCH_TARGET_OUTSIDE_CWD");const h=A(s);if(i.has(h))throw new T.CliError("FILE_REFACTOR_BATCH_DUPLICATE_TARGET","Several file refactor batch rows resolve to the same target.",{targetFile:g(e,s)});i.add(h),n.push({id:`${a.kind==="fileRename"?"rename":"move"}-${n.length+1}`,kind:a.kind,sourceFile:c,targetDir:u,targetFile:s,execute:r})}if(n.length===0)throw new T.CliError("FILE_REFACTOR_BATCH_ROWS_REQUIRED","file refactor batch expects at least one operation.");return{execute:r,baseDir:o,operations:n,normalizedPayload:{operations:Be(n),execute:r}}}function De(e){const t=[],r=new Set,o=new Set,n=new Set;for(const a of e){if(t.some(s=>s.ok===!1))break;const c=Se(a,{virtualFiles:r,removedFiles:o,virtualDirs:n});t.push(c),c.ok!==!1&&(o.add(A(a.sourceFile)),r.delete(A(a.sourceFile)),r.add(A(a.targetFile)),n.add(A(a.targetDir)))}return{...t.every(a=>a.ok!==!1)&&t.length===e.length?{}:{ok:!1},operation:U.CLI_COMMAND_IDS.fileMutation,execute:!1,rowCount:e.length,appliedCount:0,savedFiles:[],rows:t}}function Se(e,t){if(e.kind!=="fileMoveToDir"&&e.kind!=="fileRename")return x(e,"FILE_MUTATION_KIND_UNSUPPORTED",`Unsupported file mutation kind: ${e.kind}`);const r=A(e.sourceFile),o=A(e.targetFile),n=A(e.targetDir);if(!(t?.virtualFiles.has(r)===!0||!t?.removedFiles.has(r)&&w.existsSync(e.sourceFile)))return x(e,"FILE_REFACTOR_BATCH_SOURCE_NOT_FOUND","Source file does not exist.");if(t?.virtualFiles.has(r)!==!0)try{if(!w.statSync(e.sourceFile).isFile())return x(e,"FILE_REFACTOR_BATCH_SOURCE_DIRECTORY_UNSUPPORTED","file refactor batch v1 supports files only, not directories.")}catch(s){return x(e,"FILE_REFACTOR_BATCH_SOURCE_STAT_FAILED",s instanceof Error?s.message:String(s))}if(t?.virtualFiles.has(o)===!0||!t?.removedFiles.has(o)&&w.existsSync(e.targetFile))return x(e,"FILE_REFACTOR_BATCH_TARGET_EXISTS","Target file already exists.","Pick another target directory/name or remove the target collision.");const c=t?.virtualDirs.has(n)===!0||w.existsSync(e.targetDir);return e.kind==="fileRename"&&!c?x(e,"FILE_REFACTOR_BATCH_TARGET_DIR_NOT_FOUND","Target parent directory does not exist."):{id:e.id,ok:!0,sourceFile:e.sourceFile,targetFile:e.targetFile,applied:!1}}function x(e,t,r,o){return{id:e.id,ok:!1,sourceFile:e.sourceFile,targetFile:e.targetFile,applied:!1,code:t,error:r,...o?{hint:o}:{}}}function Be(e){return e.map(t=>({kind:t.kind,sourceFile:t.sourceFile,targetDir:t.targetDir,targetFile:t.targetFile}))}function Ze(e,t,r){const o=r.trim();if(f.isAbsolute(o))return f.normalize(o);const n=f.normalize(f.resolve(t,o));if(w.existsSync(n))return n;const i=f.normalize(f.resolve(e,o));return w.existsSync(i)?i:n}function et(e,t,r,o){const n=o.trim();return f.isAbsolute(n)?f.normalize(n):n.includes("/")||n.includes("\\")?f.normalize(f.resolve(t,n)):f.normalize(f.resolve(f.dirname(r),n))}function tt(e,t){const r=f.normalize(f.isAbsolute(t)?t:f.resolve(e,t));return H(e,r,"FILE_REFACTOR_BATCH_PATH_OUTSIDE_CWD"),r}function H(e,t,r){const o=f.resolve(e),n=f.relative(o,t);if(!(n===""||!n.startsWith("..")&&!f.isAbsolute(n)))throw new T.CliError(r,"File move paths must stay inside the current workspace.",{cwd:o,filePath:t})}function ce(e,t,r,o,n,i){const a=Array.isArray(t.rows)?t.rows.filter(m).map(F=>le(e,F)):[],c=t.ok!==!1&&a.every(F=>F.ok!==!1),s=He(a,"target"),u=Je(e,S(t.savedFiles)).map(F=>g(e,F)),h=o==="apply"?"file.refactor.batch.apply":r.execute?"file.refactor.batch.execute":"file.refactor.batch.preview";return X({...c?{}:{ok:!1},operation:h,executionId:i??null,base:g(e,r.baseDir),operationCount:r.operations.length,summary:c?r.execute?`${r.operations.length} ${k(r.operations.length,"file","files")} changed, ${u.length} ${k(u.length,"file","files")} written`:`${r.operations.length} ${k(r.operations.length,"file","files")} ready`:$e(a,r.operations.length,r.execute||o==="apply"),changes:ke(e,r.operations),...r.execute||o==="apply"?{filesWritten:u,filesChanged:s}:{},...m(t.postMutation)?{postMutation:t.postMutation}:{},rows:c?null:a,previewId:n??null})}function le(e,t){return X({id:p(t.id),ok:t.ok!==!1,source:g(e,p(t.sourceFile)??""),target:g(e,p(t.targetFile)??""),applied:typeof t.applied=="boolean"?t.applied:null,rollback:p(t.rollback),savedFiles:Qe(S(t.savedFiles).map(r=>g(e,r)),5),code:p(t.code),error:p(t.error),hint:p(t.hint)})}function ke(e,t){return t.map(r=>({source:g(e,r.sourceFile),target:g(e,r.targetFile)}))}function $e(e,t,r){const o=e.filter(i=>i.ok===!1).length,n=Math.max(0,t-e.length);if(!r){const i=Math.min(t,e.length);return`${t} ${k(t,"file","files")}, validation blocked at row ${i}`}return`${t} ${k(t,"file","files")}, ${o} failed${n>0?`, ${n} not run`:""}`}function Oe(e,t){return t.map(r=>({source:g(e,r.sourceFile),target:g(e,r.targetFile),targetDir:g(e,r.targetDir)}))}function Pe(e){return Array.isArray(e.rows)?e.rows.filter(m):[]}function Le(e){const t=new Set(e.map(o=>o.targetDir));let r=0;for(const o of t)w.existsSync(o)||(r+=1);return{rowCount:e.length,targetDirCount:t.size,dirsToCreate:r}}function ue(e){const t=e.find(r=>r.ok===!1);return t?p(t.code):null}function We(e,t){const r=new Set(t.rows.filter(n=>n.ok!==!1).map(n=>p(n.source)).filter(n=>!!n)),o=[];for(const n of t.plannedMoves)t.status!=="completed"&&!r.has(n.source)||o.push(`${n.source} -> ${n.target}`);if(o.length!==0){e.push("changes:");for(const n of o)e.push(n)}}function Ne(e,t){if(t.notRunRows<=0)return;const r=new Set(t.rows.map(n=>p(n.source)).filter(n=>!!n)),o=t.plannedMoves.filter(n=>!r.has(n.source));if(o.length!==0){e.push("not run:");for(const n of o)e.push(n.source)}}function G(){return(0,ee.readMutationSyncWaitMs)(process.env[_.CLI_ENV.fileRefactorBatchSyncWaitMs],12e4)}function qe(){return{postProcessImports:(0,R.isFileMutationImportPostProcessEnabled)(),testFailRequiredImportUpdate:p(process.env[_.CLI_ENV.testFileRefactorBatchFailImports]),testRowDelayMs:(0,R.readFileMutationTestDelayMs)(process.env[_.CLI_ENV.testFileRefactorBatchRowDelayMs],6e4),testImportPostProcessDelayMs:(0,R.readFileMutationTestDelayMs)(process.env[_.CLI_ENV.testFileRefactorBatchImportsDelayMs],6e4),testPostMutationCyclesDelayMs:(0,R.readFileMutationTestDelayMs)(process.env[_.CLI_ENV.testPostMutationCyclesDelayMs],6e4)}}function Ue(){return(0,R.captureFileMutationBackgroundEnv)([_.CLI_ENV.testFileRefactorBatchDelayMs,_.CLI_ENV.testFileRefactorBatchRowDelayMs,_.CLI_ENV.testFileRefactorBatchImportsDelayMs,_.CLI_ENV.testFileRefactorBatchFailImports])}function J(e){const t=p(e.operation);if(!t?.startsWith("file.refactor.batch."))return null;const r=[],o=p(e.previewId),n=p(e.executionId);r.push(e.ok===!1?`${t} failed`:o&&t==="file.refactor.batch.preview"?`${t} ${o}`:n&&(t==="file.refactor.batch.apply"||t==="file.refactor.batch.execute")?`${t} ${n}`:t),typeof e.summary=="string"&&r.push(e.summary);const i=Array.isArray(e.changes)?e.changes.filter(m):[];if(i.length>0&&e.ok!==!1){r.push("changes:");for(const c of i){const s=p(c.source),u=p(c.target);s&&u&&r.push(`${s} -> ${u}`)}}je(r,e);const a=Array.isArray(e.filesWritten)?e.filesWritten:[];return a.length>0&&me(r,a,Array.isArray(e.filesChanged)?e.filesChanged:[]),m(e.postMutation)&&m(e.postMutation.cycles)&&ye(r,e.postMutation.cycles),typeof e.next=="string"&&r.push(`next: ${e.next}`),r.join(`
|
|
5
|
+
`)}function je(e,t){if(t.ok!==!1||!Array.isArray(t.rows))return;const r=t.rows.filter(m).find(o=>o.ok===!1);r&&(e.push("failed:"),e.push(`${p(r.source)??"source"} -> ${p(r.target)??"target"}`),e.push(`code: ${p(r.code)??"FILE_REFACTOR_BATCH_FAILED"}`),typeof r.error=="string"&&e.push(r.error),typeof r.rollback=="string"&&e.push(`rollback: ${r.rollback}`),typeof r.hint=="string"&&e.push(`hint: ${r.hint}`))}function ze(){return{ok:!0,command:"file refactor batch",usage:"aib file refactor batch preview --stdin | aib file refactor batch execute --stdin | aib file refactor batch apply <previewId>",dsl:["@base packages/agent-project-tooling/src","rename workspace-runner-cli.ts->cli.ts workspace-runner-command-hints.ts->command-hints.ts"],notes:["preview validates planned file refactor batchs without writing.","execute moves/renames files and updates TypeScript imports.","apply uses the cached preview id and refuses stale source/target state."]}}function He(e,t){return e.map(r=>p(r[t])).filter(r=>!!r)}function S(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function Ve(e){return Array.isArray(e)?e.filter(m):[]}function fe(e,t){const r=de(e,t).filter(n=>w.existsSync(N(e,n)));if(r.length===0)return{op:"cycles",componentCount:0,components:[]};const o=["cycles"];for(const n of r)o.push("--files",n);return o.push("--detail","imports","--limit","50"),(0,Z.runInspectCycles)(e,o,void 0)}function Ke(e,t,r){const o=new Set(pe(e).map(he)),n=pe(t).filter(i=>B(i.files).some(a=>r.has(a))&&!o.has(he(i)));return{status:n.length>0?"new-or-changed":"none",detail:"imports",newOrChangedCount:n.length,preComponentCount:Q(e.componentCount),postComponentCount:Q(t.componentCount),components:n}}function pe(e){return(Array.isArray(e.components)?e.components:[]).filter(m).map(t=>({kind:p(t.kind)??"mixed",files:B(t.files).sort(),chain:p(t.chain)??"",...m(t.cycle)?{cycle:t.cycle}:{},imports:Ge(t)}))}function Ge(e){const t=m(e.cycle)?e.cycle:{};return B(t.imports)}function he(e){return`${p(e.kind)??"mixed"}:${B(e.files).sort().join("|")}`}function de(e,t){return ge(t.map(r=>g(e,N(e,r))))}function N(e,t){return f.normalize(f.isAbsolute(t)?t:f.resolve(e,t))}function B(e){return S(e)}function Je(e,t){return t.filter(r=>{const o=f.isAbsolute(r)?r:f.resolve(e,r);return w.existsSync(o)})}function Qe(e,t){const r=Array.from(new Set(e)).sort((i,a)=>i.localeCompare(a)),o=r.slice(0,t),n=r.length-o.length;return n>0?[...o,`+ ${n} more`]:o}function rt(e,t){const r=e.slice(0,t),o=e.length-r.length;return o>0?`${r.join(", ")}, + ${o} more`:r.join(", ")}function me(e,t,r){const o=t.filter(u=>typeof u=="string");if(o.length===0)return;const n=new Set(r.filter(u=>typeof u=="string")),i=o.filter(u=>n.has(u)),a=o.filter(u=>!n.has(u)),c=a.slice(0,8),s=a.length-c.length;e.push("filesWritten:");for(const u of[...i,...c])e.push(u);s>0&&e.push(`+ ${s} reference ${k(s,"file","files")}`)}function ye(e,t){e.push("cycles:");const r=Q(t.newOrChangedCount);if(r===0){e.push("no new/changed cycles involving touched files");return}const o=Array.isArray(t.components)?t.components.filter(m):[];e.push(Xe(r,o)),o.forEach((n,i)=>{(0,Z.appendCycleComponentText)(e,n,{detail:"imports",prefix:o.length===1?"":`${i+1}. `,indent:o.length===1?"":" "})})}function Xe(e,t){const r=t.map(i=>p(i.kind)??"mixed"),o=Array.from(new Set(r)),n=o.length===1?`${o[0]} `:"";return`${e} new/changed ${n}${e===1?"cycle":"cycles"} involving touched files`}function k(e,t,r){return e===1?t:r}function p(e){return typeof e=="string"&&e.length>0?e:null}function Q(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function X(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t==null?!1:!(Array.isArray(t)&&t.length===0)))}function m(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function A(e){const t=f.normalize(e);return process.platform==="win32"?t.toLowerCase():t}function ge(e){return Array.from(new Set(e))}function V(){return new Promise(e=>setImmediate(e))}async function Ye(e){e<=0||await new Promise(t=>setTimeout(t,e))}function g(e,t){return t?f.relative(e,t).replace(/\\/g,"/"):""}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var o=exports&&exports.__createBinding||(Object.create?(function(t,e,u,n){n===void 0&&(n=u);var i=Object.getOwnPropertyDescriptor(e,u);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[u]}}),Object.defineProperty(t,n,i)}):(function(t,e,u,n){n===void 0&&(n=u),t[n]=e[u]})),c=exports&&exports.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),l=exports&&exports.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(u){var n=[];for(var i in u)Object.prototype.hasOwnProperty.call(u,i)&&(n[n.length]=i);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var u={};if(e!=null)for(var n=t(e),i=0;i<n.length;i++)n[i]!=="default"&&o(u,e,n[i]);return c(u,e),u}})();Object.defineProperty(exports,"__esModule",{value:!0}),exports.buildFileRenameExecutionId=d,exports.createFileRenameExecutionStatus=E,exports.readFileRenameExecutionStatus=_,exports.tryReadFileRenameExecutionStatus=R,exports.writeFileRenameExecutionStatus=m,exports.FileRenameExecutionPath=h,exports.FileRenameExecutionLastPath=F;const s=l(require("node:path")),f=require("../config/product-storage"),a=require("./mutation-execution-cache");function d(){return(0,a.buildMutationExecutionId)()}function E(t,e,u,n){const i=new Date().toISOString();return{executionId:e,operation:u,cwd:s.resolve(t),status:"running",phase:"movingFile",startedAt:i,updatedAt:i,rowCount:Math.max(1,n.length),completedRows:0,failedRows:0,notRunRows:0,filesWritten:[],touchedFiles:[],plannedMoves:n,moves:[],rows:[],productStorageDir:(0,f.productStorageRoot)()}}function _(t,e){return(0,a.readMutationExecutionStatus)(t,e,r)}function R(t,e){return(0,a.tryReadMutationExecutionStatus)(t,e,r)}function m(t,e){(0,a.writeMutationExecutionStatus)(t,e,r)}function h(t,e,u){return(0,a.mutationExecutionPath)(t,r.namespace,e,u)}function F(t,e){return(0,a.mutationExecutionLastPath)(t,r.namespace,e)}const r={namespace:"file-rename-executions",notFoundCode:"FILE_RENAME_EXECUTION_NOT_FOUND",notFoundLabel:"file rename"};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var d=exports&&exports.__createBinding||(Object.create?(function(r,e,t,i){i===void 0&&(i=t);var n=Object.getOwnPropertyDescriptor(e,t);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,i,n)}):(function(r,e,t,i){i===void 0&&(i=t),r[i]=e[t]})),h=exports&&exports.__setModuleDefault||(Object.create?(function(r,e){Object.defineProperty(r,"default",{enumerable:!0,value:e})}):function(r,e){r.default=e}),s=exports&&exports.__importStar||(function(){var r=function(e){return r=Object.getOwnPropertyNames||function(t){var i=[];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(i[i.length]=n);return i},r(e)};return function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var i=r(e),n=0;n<i.length;n++)i[n]!=="default"&&d(t,e,i[n]);return h(t,e),t}})();Object.defineProperty(exports,"__esModule",{value:!0}),exports.buildFileRenamePreviewId=w,exports.buildFileRenamePreviewHash=g,exports.readFileRenamePreviewRecord=y,exports.writeFileRenamePreviewRecord=p,exports.FileRenamePreviewRecordPath=l,exports.readFileMoveStates=E,exports.validateFileMoveStates=R;const F=s(require("node:crypto")),a=s(require("node:fs")),_=s(require("node:path")),o=require("../shared/errors"),v=require("./workspace-cache");function w(r){return`apply_${f(c(r)).slice(0,10)}`}function g(r,e,t){return`sha256:${f(c({normalizedPayload:r,states:e,summary:t.summary,operationCount:t.operationCount}))}`}function y(r,e){const t=l(r,e);if(!a.existsSync(t))throw new o.CliError("FILE_RENAME_PREVIEW_NOT_FOUND",`File move preview not found: ${e}`,{previewId:e,expectedPath:t});return JSON.parse(a.readFileSync(t,"utf8"))}function p(r,e){const t=l(r,e.previewId);a.mkdirSync(_.dirname(t),{recursive:!0}),a.writeFileSync(t,`${JSON.stringify(e,null,2)}
|
|
2
|
+
`)}function l(r,e){return(0,v.workspaceCachePath)(r,"file-rename-previews",`${P(e)}.json`)}function E(r){return r.map(e=>({sourceFile:e.sourceFile,sourceHash:u(e.sourceFile),targetFile:e.targetFile,targetExisted:a.existsSync(e.targetFile),targetHash:u(e.targetFile)}))}function R(r){for(const e of r.states){if(u(e.sourceFile)!==e.sourceHash)throw new o.CliError("FILE_RENAME_PREVIEW_SOURCE_CHANGED","Source file changed after file move preview. Rerun preview.",{previewId:r.previewId,sourceFile:e.sourceFile});const i=a.existsSync(e.targetFile),n=u(e.targetFile);if(i!==e.targetExisted||n!==e.targetHash)throw new o.CliError("FILE_RENAME_PREVIEW_TARGET_CHANGED","Target file changed after file move preview. Rerun preview.",{previewId:r.previewId,targetFile:e.targetFile})}}function u(r){return a.existsSync(r)?f(a.readFileSync(r)):null}function f(r){return F.createHash("sha256").update(r).digest("hex")}function c(r){return r===null||typeof r!="object"?JSON.stringify(r):Array.isArray(r)?`[${r.map(e=>c(e)).join(",")}]`:`{${Object.entries(r).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${JSON.stringify(e)}:${c(t)}`).join(",")}}`}function P(r){return r.replace(/[^a-z0-9_-]+/gi,"-")}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
"use strict";var ge=exports&&exports.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(t,n);(!o||("get"in o?!t.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,o)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),Re=exports&&exports.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),Q=exports&&exports.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(n){var r=[];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[r.length]=o);return r},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(t!=null)for(var r=e(t),o=0;o<r.length;o++)r[o]!=="default"&&ge(n,t,r[o]);return Re(n,t),n}})();Object.defineProperty(exports,"__esModule",{value:!0}),exports.runFileRename=Me,exports.readCachedFileRenameExecution=Ce;const _=Q(require("node:fs")),f=Q(require("node:path")),x=require("zod"),Fe=require("../client/http-client"),E=require("../config/env-vars"),Ee=require("../config/product-storage"),W=require("../config/import-rules"),O=require("../shared/agent-text"),S=require("../shared/errors"),U=require("../shared/protocol"),_e=require("../shared/routes"),B=require("./shared"),X=require("./inspect-cycles"),b=require("./file-rename-preview-cache"),w=require("./file-rename-execution-cache"),F=require("./file-mutation-runtime"),Y=require("./mutation-execution-cache"),Z=x.z.object({base:x.z.string().min(1),renames:x.z.array(x.z.object({source:x.z.string().min(1),target:x.z.string().min(1)})).min(1),execute:x.z.boolean().optional()});async function Me(e,t,n={},r=[]){const o=Be(),i=r[0]??"preview";if(i==="help"||i==="--help")return Ge();if(i==="apply"){const l=r[1];if(!l||l.startsWith("--"))throw new S.CliError("FILE_RENAME_PREVIEW_ID_REQUIRED","file rename apply expects a preview id.",{usage:"aib file rename apply <previewId>"});return we(e,l,n,o)}if(i!=="preview"&&i!=="execute"&&i!=="validate")throw new S.CliError("UNKNOWN_FILE_RENAME_COMMAND",`Unknown file rename command: ${i}`,{availableCommands:["preview","apply","execute","validate","help"]});const s=Z.parse(t);return i==="execute"&&K()>0?ee(e,{...s,execute:!0},n,"execute",K(),o):te(e,{...s,execute:i==="execute"},n,i,o)}async function we(e,t,n,r){const o=(0,b.readFileRenamePreviewRecord)(e,t);(0,b.validateFileMoveStates)(o);const i=Z.parse({...o.normalizedPayload,execute:!0}),s=K();if(s>0)return ee(e,i,n,"apply",s,r,t);const l=await te(e,i,n,"apply",r,t);return l.ok===!1?(0,O.attachAgentText)({...l,next:"Fix the file rename request and rerun preview."},G({...l,next:"Fix the file rename request and rerun preview."})):l}async function ee(e,t,n,r,o,i,s){const l=ie(e,t,!0),a=(0,w.buildFileRenameExecutionId)(),u=`file.rename.${r}`,d=(0,F.estimateFileMutationDurationMs)(qe(l.operations)),c=(0,w.createFileRenameExecutionStatus)(e,a,u,We(e,l.operations));(0,w.writeFileRenameExecutionStatus)(e,c);const R=Date.now(),M=Ve(),P=(0,F.startFileMutationBackgroundJob)(()=>(0,Ee.runWithProductStorageOverride)(M[E.CLI_ENV.productStorageDir],()=>(0,F.withFileMutationBackgroundEnv)(M,async()=>{try{const m=await ne(e,l,r,n,i,a,c,s),I=Ue(m);return c.status=m.ok===!1?"failed":"completed",c.phase="completed",c.completedRows=m.ok===!1?I.filter(A=>A.ok!==!1).length:c.rowCount,c.failedRows=m.ok===!1?I.filter(A=>A.ok===!1).length:0,c.notRunRows=m.ok===!1?Math.max(0,c.rowCount-I.length):0,c.filesWritten=$(m.filesWritten),c.touchedFiles=$(m.touchedFiles),c.moves=Array.isArray(m.renames)?m.renames.filter(h):[],c.rows=I,h(m.postMutation)&&(c.postMutation=m.postMutation),c.result=m,m.ok===!1&&(c.error=p(m.code)??le(I)??"FILE_RENAME_FAILED"),(0,w.writeFileRenameExecutionStatus)(e,c),m}catch(m){throw c.status="failed",c.phase="completed",c.failedRows=Math.max(1,c.failedRows),c.notRunRows=Math.max(0,c.rowCount-c.completedRows-c.failedRows),c.error=m instanceof Error?m.message:String(m),(0,w.writeFileRenameExecutionStatus)(e,c),m}}))),T=await(0,Y.waitForMutationDeadline)(P,o);return T.status==="result"?T.result:(P.catch(()=>{}),xe(e,a,u,d,Date.now()-R))}async function te(e,t,n,r,o,i,s,l){await(0,F.maybeDelayFileMutationForTest)(process.env[E.CLI_ENV.testFileRenameDelayMs]);const a=l??ie(e,t,r==="execute"||r==="apply"),u=a.execute?await ne(e,a,r==="apply"?"apply":"execute",n,o,s,void 0,i):be(a.operations),d=se(e,u,a,r,i,s);if((r==="preview"||r==="validate")&&d.ok!==!1){const c=(0,b.buildFileRenamePreviewId)(a.normalizedPayload),R=(0,b.readFileMoveStates)(a.operations),M=(0,b.buildFileRenamePreviewHash)(a.normalizedPayload,R,d);(0,b.writeFileRenamePreviewRecord)(e,{previewId:c,previewHash:M,createdAt:new Date().toISOString(),cwd:f.resolve(e),normalizedPayload:a.normalizedPayload,states:R,previewResult:d}),d.previewId=c,d.next=`aib file rename apply ${c}`}return(0,O.attachAgentText)(d,G(d))}async function ne(e,t,n,r,o,i,s,l){const a=[],u=new Set,d=new Set,c=[],R=ce(e,t.operations.map(y=>y.sourceFile));let M=[],P=null;for(const y of t.operations){s&&(s.phase="movingFile",s.status="running",q(e,s,a,u,d),await z());const C=await ve(e,y,r,o),L=Array.isArray(C.rows)&&h(C.rows[0])?C.rows[0]:v(y,"FILE_RENAME_FAILED","Extension did not return a file rename row.");a.push(L);for(const N of D(L.savedFiles))u.add(f.normalize(N));for(const N of D(L.touchedFiles))d.add(f.normalize(N));for(const N of Je(L.importSnapshotBefore))c.push(N);if(s&&(q(e,s,a,u,d),await z()),L.ok===!1)break;await(0,F.delayFileMutationForTest)(o.testRowDelayMs)}const T=a.every(y=>y.ok!==!1)&&a.length===t.operations.length;if(a.some(y=>y.ok!==!1)&&o.postProcessImports&&d.size>0){s&&(s.phase="postProcessImports",q(e,s,a,u,d),await z()),await(0,F.delayFileMutationForTest)(o.testImportPostProcessDelayMs);const y=await Ie(e,Array.from(d),c,r);M=Array.isArray(y.cleanup)?y.cleanup.filter(h):[];for(const C of D(y.savedFiles))u.add(f.normalize(C))}const m=M.every(y=>y.ok!==!1);if(T&&m){s&&(s.phase="postMutation.cycles",q(e,s,a,u,d),await z()),await nt(o.testPostMutationCyclesDelayMs);const y=ye([...Array.from(d),...Array.from(u)]),C=ce(e,y);P={cycles:Qe(R,C,new Set(pe(e,y)))}}const I=J({...!T||!m?{ok:!1}:{},operation:U.CLI_COMMAND_IDS.fileMutation,execute:!0,rowCount:t.operations.length,appliedCount:a.filter(y=>y.applied===!0).length,savedFiles:Array.from(u),touchedFiles:Array.from(d),cleanup:M,rows:a,postMutation:P}),A=se(e,I,t,n,l,i);return(0,O.attachAgentText)(A,G(A))}function q(e,t,n,r,o){const i=n.map(s=>ae(e,s));t.rows=i,t.completedRows=i.filter(s=>s.ok!==!1).length,t.failedRows=i.filter(s=>s.ok===!1).length,t.notRunRows=t.failedRows>0?Math.max(0,t.rowCount-i.length):0,t.filesWritten=Array.from(r).sort((s,l)=>s.localeCompare(l)).map(s=>g(e,s)),t.touchedFiles=Array.from(o).sort((s,l)=>s.localeCompare(l)).map(s=>g(e,s)),t.failedRows>0&&(t.status="failed",t.error=le(i)??"FILE_RENAME_FAILED"),(0,w.writeFileRenameExecutionStatus)(e,t)}async function ve(e,t,n,r){const o=await(0,B.resolveCompatibleTargetInstance)(e,U.CLI_COMMAND_IDS.fileMutation,n),i=n.importRules??(0,W.readConfigImportRules)(e),s=r.testFailRequiredImportUpdate,a={operations:[s?{...t,testFailRequiredImportUpdate:s}:t],execute:!0,importRules:(0,W.importRulesToJson)(i),postProcessImports:!1};return s&&(a.testFailRequiredImportUpdate=s),oe(o.entry,a,n)}async function Ie(e,t,n,r){const o=await(0,B.resolveCompatibleTargetInstance)(e,U.CLI_COMMAND_IDS.fileMutation,r),i=r.importRules??(0,W.readConfigImportRules)(e);return oe(o.entry,{action:"postProcessImports",files:t,importRules:(0,W.importRulesToJson)(i),importSnapshotBefore:n},r)}function Ce(e,t){const n=(0,w.readFileRenameExecutionStatus)(e,t),r={operation:"execution.status",executionId:n.executionId,status:n.status,phase:n.phase,summary:j(n),progress:`${n.completedRows}/${n.rowCount}`,filesWritten:n.filesWritten,touchedFiles:n.touchedFiles,...n.postMutation?{postMutation:n.postMutation}:{},updatedAt:n.updatedAt,...n.error?{error:n.error}:{}};return(0,O.attachAgentText)(r,Se(n))}function xe(e,t,n,r,o){const i=(0,w.readFileRenameExecutionStatus)(e,t),s=Math.max(0,r-o),l={operation:"execution.status",executionId:i.executionId,status:i.status,phase:i.phase,summary:j(i),progress:`${i.completedRows}/${i.rowCount}`,filesWritten:i.filesWritten,touchedFiles:i.touchedFiles,...i.postMutation?{postMutation:i.postMutation}:{},updatedAt:i.updatedAt,estimatedRemainingMs:s};return(0,O.attachAgentText)(l,Ae(n,i,s))}function Ae(e,t,n){return[`${e} ${t.executionId}`,j(t),re(t),n>0?`estimated remaining: ${(0,F.formatFileMutationDuration)(Math.max(n,5e3))}`:"estimated remaining: check status again soon"].join(`
|
|
2
|
+
`)}function Se(e){const t=[j(e)];if(e.status==="running")return t.push(re(e)),t.join(`
|
|
3
|
+
`);je(t,e);const n=e.rows.filter(o=>o.ok===!1),r=n[0];if(r){const o=p(r.code)??e.error??"FILE_RENAME_FAILED";t.push(`code: ${o}`),typeof r.error=="string"&&t.push(r.error),typeof r.rollback=="string"&&t.push(`rollback: ${r.rollback}`),typeof r.hint=="string"&&t.push(`hint: ${r.hint}`),t.push("failed:");for(const i of n)t.push(`${p(i.source)??"source"} -> ${p(i.target)??"target"}`)}else e.error&&t.push(e.error);return ze(t,e),e.filesWritten.length>0&&de(t,e.filesWritten,e.plannedMoves.map(o=>o.target)),h(e.postMutation)&&h(e.postMutation.cycles)&&he(t,e.postMutation.cycles),e.status==="failed"&&t.push("next: Fix failed rename row and rerun file.rename preview."),t.join(`
|
|
4
|
+
`)}function re(e){return e.phase==="postProcessImports"?"updating imports":e.phase==="postMutation.cycles"?"checking cycles":"renaming files"}function j(e){const t=Math.floor(Math.max(0,e.completedRows)/Math.max(1,e.rowCount)*100);if(e.status==="completed")return`completed, ${e.completedRows}/${e.rowCount} rows, ${t}% files, ${e.filesWritten.length} files written`;if(e.status==="failed"){const n=[`failed, ${e.completedRows}/${e.rowCount} rows, ${t}% files`,`${e.failedRows} failed`];return e.notRunRows>0&&n.push(`${e.notRunRows} not run`),n.push(`${e.filesWritten.length} files written`),n.join(", ")}return`in progress, ${e.completedRows}/${e.rowCount} rows, ${t}% files`}async function oe(e,t,n){try{return await(0,Fe.postJson)(e,_e.EXTENSION_ROUTES.fileMutation,t,(0,B.extensionRequestOptions)(n))}catch(r){if(r instanceof S.CliError&&r.code==="REMOTE_ERROR"){const o=h(r.details)?r.details:{},i=h(o.payload)?o.payload:null;if(i)return i}throw r}}function ie(e,t,n){const r=Le(e,t.base),o=[],i=new Set;for(const s of t.renames){const l=Pe(e,r,s.source);V(e,l,"FILE_RENAME_SOURCE_OUTSIDE_CWD");const a=Te(e,r,l,s.target);V(e,a,"FILE_RENAME_TARGET_OUTSIDE_CWD");const u=tt(a);if(i.has(u))throw new S.CliError("FILE_RENAME_DUPLICATE_TARGET","Several file renames resolve to the same target.",{targetFile:g(e,a)});i.add(u),o.push({id:`rename-${o.length+1}`,kind:"fileRename",sourceFile:l,targetDir:f.dirname(a),targetFile:a,execute:n})}if(o.length===0)throw new S.CliError("FILE_RENAME_ROWS_REQUIRED","file rename expects at least one rename pair.");return{execute:n,baseDir:r,operations:o,normalizedPayload:{base:r,renames:ke(o),execute:n}}}function be(e){const t=[];for(const r of e){if(t.some(o=>o.ok===!1))break;t.push(De(r))}return{...t.every(r=>r.ok!==!1)&&t.length===e.length?{}:{ok:!1},operation:U.CLI_COMMAND_IDS.fileMutation,execute:!1,rowCount:e.length,appliedCount:0,savedFiles:[],rows:t}}function De(e){if(e.kind!=="fileRename")return v(e,"FILE_MUTATION_KIND_UNSUPPORTED",`Unsupported file mutation kind: ${e.kind}`);if(!_.existsSync(e.sourceFile))return v(e,"FILE_RENAME_SOURCE_NOT_FOUND","Source file does not exist.");try{if(!_.statSync(e.sourceFile).isFile())return v(e,"FILE_RENAME_SOURCE_DIRECTORY_UNSUPPORTED","file rename v1 supports files only, not directories.")}catch(t){return v(e,"FILE_RENAME_SOURCE_STAT_FAILED",t instanceof Error?t.message:String(t))}return _.existsSync(e.targetFile)?v(e,"FILE_RENAME_TARGET_EXISTS","Target file already exists.","Pick another target directory/name or remove the target collision."):$e(e.sourceFile)?v(e,"FILE_RENAME_SOURCE_ASSET_UNSUPPORTED","CSS/SCSS files cannot be renamed with file rename v1."):_.existsSync(e.targetDir)?{id:e.id,ok:!0,sourceFile:e.sourceFile,targetFile:e.targetFile,applied:!1}:v(e,"FILE_RENAME_TARGET_DIR_NOT_FOUND","Target parent directory does not exist.")}function v(e,t,n,r){return{id:e.id,ok:!1,sourceFile:e.sourceFile,targetFile:e.targetFile,applied:!1,code:t,error:n,...r?{hint:r}:{}}}function $e(e){return[".css",".scss"].includes(f.extname(e).toLowerCase())}function ke(e){return e.map(t=>({source:t.sourceFile,target:t.targetFile}))}function Pe(e,t,n){const r=n.trim();if(f.isAbsolute(r))return f.normalize(r);const o=f.normalize(f.resolve(t,r));if(_.existsSync(o))return o;const i=f.normalize(f.resolve(e,r));return _.existsSync(i)?i:o}function Te(e,t,n,r){const o=r.trim();return f.isAbsolute(o)?f.normalize(o):o.includes("/")||o.includes("\\")?f.normalize(f.resolve(t,o)):f.normalize(f.resolve(f.dirname(n),o))}function Le(e,t){const n=f.normalize(f.isAbsolute(t)?t:f.resolve(e,t));return V(e,n,"FILE_RENAME_PATH_OUTSIDE_CWD"),n}function V(e,t,n){const r=f.resolve(e),o=f.relative(r,t);if(!(o===""||!o.startsWith("..")&&!f.isAbsolute(o)))throw new S.CliError(n,"File move paths must stay inside the current workspace.",{cwd:r,filePath:t})}function se(e,t,n,r,o,i){const s=Array.isArray(t.rows)?t.rows.filter(h).map(R=>ae(e,R)):[],l=t.ok!==!1&&s.every(R=>R.ok!==!1),a=He(s,"target"),u=Ye(e,D(t.savedFiles)).map(R=>g(e,R)),d=r==="apply"?"file.rename.apply":n.execute?"file.rename.execute":"file.rename.preview";return J({...l?{}:{ok:!1},operation:d,executionId:i??null,base:g(e,n.baseDir),operationCount:n.operations.length,summary:l?n.execute?`${n.operations.length} ${k(n.operations.length,"file","files")} renamed, ${u.length} ${k(u.length,"file","files")} written`:`${n.operations.length} ${k(n.operations.length,"file","files")} ready`:Oe(s,n.operations.length,n.execute||r==="apply"),renames:Ne(e,n.operations),...n.execute||r==="apply"?{filesWritten:u,filesRenamed:a}:{},...h(t.postMutation)?{postMutation:t.postMutation}:{},rows:l?null:s,previewId:o??null})}function ae(e,t){return J({id:p(t.id),ok:t.ok!==!1,source:g(e,p(t.sourceFile)??""),target:g(e,p(t.targetFile)??""),applied:typeof t.applied=="boolean"?t.applied:null,rollback:p(t.rollback),savedFiles:Ze(D(t.savedFiles).map(n=>g(e,n)),5),code:p(t.code),error:p(t.error),hint:p(t.hint)})}function Ne(e,t){return t.map(n=>({source:g(e,n.sourceFile),target:g(e,n.targetFile)}))}function Oe(e,t,n){const r=e.filter(i=>i.ok===!1).length,o=Math.max(0,t-e.length);if(!n){const i=Math.min(t,e.length);return`${t} ${k(t,"file","files")}, validation blocked at row ${i}`}return`${t} ${k(t,"file","files")}, ${r} failed${o>0?`, ${o} not run`:""}`}function We(e,t){return t.map(n=>({source:g(e,n.sourceFile),target:g(e,n.targetFile),targetDir:g(e,n.targetDir)}))}function Ue(e){return Array.isArray(e.rows)?e.rows.filter(h):[]}function qe(e){const t=new Set(e.map(r=>r.targetDir));let n=0;for(const r of t)_.existsSync(r)||(n+=1);return{rowCount:e.length,targetDirCount:t.size,dirsToCreate:n}}function le(e){const t=e.find(n=>n.ok===!1);return t?p(t.code):null}function je(e,t){const n=new Set(t.rows.filter(o=>o.ok!==!1).map(o=>p(o.source)).filter(o=>!!o)),r=[];for(const o of t.plannedMoves)t.status!=="completed"&&!n.has(o.source)||r.push(`${o.source} -> ${o.target}`);if(r.length!==0){e.push("renames:");for(const o of r)e.push(o)}}function ze(e,t){if(t.notRunRows<=0)return;const n=new Set(t.rows.map(o=>p(o.source)).filter(o=>!!o)),r=t.plannedMoves.filter(o=>!n.has(o.source));if(r.length!==0){e.push("not run:");for(const o of r)e.push(o.source)}}function K(){return(0,Y.readMutationSyncWaitMs)(process.env[E.CLI_ENV.fileRenameSyncWaitMs],12e4)}function Be(){return{postProcessImports:(0,F.isFileMutationImportPostProcessEnabled)(),testFailRequiredImportUpdate:p(process.env[E.CLI_ENV.testFileRenameFailImports]),testRowDelayMs:(0,F.readFileMutationTestDelayMs)(process.env[E.CLI_ENV.testFileRenameRowDelayMs],6e4),testImportPostProcessDelayMs:(0,F.readFileMutationTestDelayMs)(process.env[E.CLI_ENV.testFileRenameImportsDelayMs],6e4),testPostMutationCyclesDelayMs:(0,F.readFileMutationTestDelayMs)(process.env[E.CLI_ENV.testPostMutationCyclesDelayMs],6e4)}}function Ve(){return(0,F.captureFileMutationBackgroundEnv)([E.CLI_ENV.testFileRenameDelayMs,E.CLI_ENV.testFileRenameRowDelayMs,E.CLI_ENV.testFileRenameImportsDelayMs,E.CLI_ENV.testFileRenameFailImports])}function G(e){const t=p(e.operation);if(!t?.startsWith("file.rename."))return null;const n=[],r=p(e.previewId),o=p(e.executionId);n.push(e.ok===!1?`${t} failed`:r&&t==="file.rename.preview"?`${t} ${r}`:o&&(t==="file.rename.apply"||t==="file.rename.execute")?`${t} ${o}`:t),typeof e.summary=="string"&&n.push(e.summary);const i=Array.isArray(e.renames)?e.renames.filter(h):[];if(i.length>0&&e.ok!==!1){n.push("renames:");for(const l of i){const a=p(l.source),u=p(l.target);a&&u&&n.push(`${a} -> ${u}`)}}Ke(n,e);const s=Array.isArray(e.filesWritten)?e.filesWritten:[];return s.length>0&&de(n,s,Array.isArray(e.filesRenamed)?e.filesRenamed:[]),h(e.postMutation)&&h(e.postMutation.cycles)&&he(n,e.postMutation.cycles),typeof e.next=="string"&&n.push(`next: ${e.next}`),n.join(`
|
|
5
|
+
`)}function Ke(e,t){if(t.ok!==!1||!Array.isArray(t.rows))return;const n=t.rows.filter(h).find(r=>r.ok===!1);n&&(e.push("failed:"),e.push(`${p(n.source)??"source"} -> ${p(n.target)??"target"}`),e.push(`code: ${p(n.code)??"FILE_RENAME_FAILED"}`),typeof n.error=="string"&&e.push(n.error),typeof n.rollback=="string"&&e.push(`rollback: ${n.rollback}`),typeof n.hint=="string"&&e.push(`hint: ${n.hint}`))}function Ge(){return{ok:!0,command:"file rename",usage:"aib file rename preview --stdin | aib file rename execute --stdin | aib file rename apply <previewId>",dsl:["@base packages/agent-project-tooling/src","rename workspace-runner-cli.ts->cli.ts workspace-runner-command-hints.ts->command-hints.ts"],notes:["preview validates planned file renames without writing.","execute renames files and updates TypeScript imports.","apply uses the cached preview id and refuses stale source/target state."]}}function He(e,t){return e.map(n=>p(n[t])).filter(n=>!!n)}function D(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function Je(e){return Array.isArray(e)?e.filter(h):[]}function ce(e,t){const n=pe(e,t).filter(o=>_.existsSync(me(e,o)));if(n.length===0)return{op:"cycles",componentCount:0,components:[]};const r=["cycles"];for(const o of n)r.push("--files",o);return r.push("--detail","imports","--limit","50"),(0,X.runInspectCycles)(e,r,void 0)}function Qe(e,t,n){const r=new Set(ue(e).map(fe)),o=ue(t).filter(i=>$(i.files).some(s=>n.has(s))&&!r.has(fe(i)));return{status:o.length>0?"new-or-changed":"none",detail:"imports",newOrChangedCount:o.length,preComponentCount:H(e.componentCount),postComponentCount:H(t.componentCount),components:o}}function ue(e){return(Array.isArray(e.components)?e.components:[]).filter(h).map(t=>({kind:p(t.kind)??"mixed",files:$(t.files).sort(),chain:p(t.chain)??"",...h(t.cycle)?{cycle:t.cycle}:{},imports:Xe(t)}))}function Xe(e){const t=h(e.cycle)?e.cycle:{};return $(t.imports)}function fe(e){return`${p(e.kind)??"mixed"}:${$(e.files).sort().join("|")}`}function pe(e,t){return ye(t.map(n=>g(e,me(e,n))))}function me(e,t){return f.normalize(f.isAbsolute(t)?t:f.resolve(e,t))}function $(e){return D(e)}function Ye(e,t){return t.filter(n=>{const r=f.isAbsolute(n)?n:f.resolve(e,n);return _.existsSync(r)})}function Ze(e,t){const n=Array.from(new Set(e)).sort((i,s)=>i.localeCompare(s)),r=n.slice(0,t),o=n.length-r.length;return o>0?[...r,`+ ${o} more`]:r}function rt(e,t){const n=e.slice(0,t),r=e.length-n.length;return r>0?`${n.join(", ")}, + ${r} more`:n.join(", ")}function de(e,t,n){const r=t.filter(u=>typeof u=="string");if(r.length===0)return;const o=new Set(n.filter(u=>typeof u=="string")),i=r.filter(u=>o.has(u)),s=r.filter(u=>!o.has(u)),l=s.slice(0,8),a=s.length-l.length;e.push("filesWritten:");for(const u of[...i,...l])e.push(u);a>0&&e.push(`+ ${a} reference ${k(a,"file","files")}`)}function he(e,t){e.push("cycles:");const n=H(t.newOrChangedCount);if(n===0){e.push("no new/changed cycles involving touched files");return}const r=Array.isArray(t.components)?t.components.filter(h):[];e.push(et(n,r)),r.forEach((o,i)=>{(0,X.appendCycleComponentText)(e,o,{detail:"imports",prefix:r.length===1?"":`${i+1}. `,indent:r.length===1?"":" "})})}function et(e,t){const n=t.map(i=>p(i.kind)??"mixed"),r=Array.from(new Set(n)),o=r.length===1?`${r[0]} `:"";return`${e} new/changed ${o}${e===1?"cycle":"cycles"} involving touched files`}function k(e,t,n){return e===1?t:n}function p(e){return typeof e=="string"&&e.length>0?e:null}function H(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function J(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t==null?!1:!(Array.isArray(t)&&t.length===0)))}function h(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function tt(e){const t=f.normalize(e);return process.platform==="win32"?t.toLowerCase():t}function ye(e){return Array.from(new Set(e))}function z(){return new Promise(e=>setImmediate(e))}async function nt(e){e<=0||await new Promise(t=>setTimeout(t,e))}function g(e,t){return t?f.relative(e,t).replace(/\\/g,"/"):""}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
${
|
|
1
|
+
"use strict";var H=exports&&exports.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),O=exports&&exports.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),g=exports&&exports.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(n){var r=[];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(r[r.length]=i);return r},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(t!=null)for(var r=e(t),i=0;i<r.length;i++)r[i]!=="default"&&H(n,t,r[i]);return O(n,t),n}})();Object.defineProperty(exports,"__esModule",{value:!0}),exports.runHelpCommand=$,exports.resolveHelpRoot=d;const l=g(require("node:fs")),c=g(require("node:path")),p=require("../content/content-bundle"),f=require("../shared/agent-text"),m=require("../shared/errors"),S=require("../shared/stdin-examples"),b=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"],["inspect cycles","inspect.cycles"],["inspect cycle","inspect.cycles"],["refactor batch","refactor.batch"],["module plan","modulePlan"],["moduleplan","modulePlan"]]),y=["help-protocol","quick-map","help-format","basics","dsl","patterns","config-setup.aliases","config-setup.excludes","config-setup.import-normalize","config-setup.import-rules","config-setup.tsconfigs","session","prefs","selectors","inspect","inspect.file","inspect.imports","inspect.exports","inspect.members","inspect.code","inspect.deps","inspect.usages","inspect.graph","inspect.tree","inspect.duplicates","inspect.cycles","mutation","imports.normalize","rename","move","modulePlan","refactor.batch","view","qr","rg","reveal"];function $(e){if(C(e))return q();const t=T(e);if(t.length===0)return h();let r=d(),i=w(t,r);if(r.source==="cache"&&i.targets.length===0&&i.unknown.length>0){const o=j();if(o){const a=w(t,o);(a.targets.length>0||a.unknown.length<i.unknown.length)&&(r=o,i=a)}}if(i.targets.length===0&&i.unknown.length===0)return h();const u=i.targets.map(o=>{const a=c.join(r.dir,o.file);return l.existsSync(a)?{target:o,text:_(l.readFileSync(a,"utf8").trim(),r.dir)}:null}).filter(o=>o!==null);if(u.length===1&&i.unknown.length===0){const o=u[0];return o?(0,f.attachAgentText)({operation:"help",topic:o.target.id,source:r.source},o.text):h()}const s=[...u.map(o=>`// ${o.target.id}
|
|
2
|
+
${o.text}`),...i.unknown.length>0?[["Unknown help topics:",...i.unknown].join(`
|
|
3
3
|
`)]:[]].join(`
|
|
4
4
|
|
|
5
|
-
`);if(i.unknown.length>0)throw new
|
|
6
|
-
`);return(0,
|
|
7
|
-
`);return(0,
|
|
5
|
+
`);if(i.unknown.length>0)throw new m.CliError("HELP_TOPIC_NOT_FOUND",s,{topics:u.map(o=>o.target.id),unknown:i.unknown,helpRoot:r.dir,available:y});return(0,f.attachAgentText)({operation:"help",topics:u.map(o=>o.target.id),source:r.source},s)}function C(e){const t=e.filter(n=>n!=="help");return t.length===1&&t[0]==="status"}function h(){const e=k(),t=e?_(l.readFileSync(c.join(e.dir,"help-index.md"),"utf8").trim(),e.dir):["Run as: aib help <topic...>","","Start here if this is your first AIB pass:"," bootstrap","","After context compaction:"," aib help help-protocol quick-map"," aib config aliases"].join(`
|
|
6
|
+
`);return(0,f.attachAgentText)({operation:"help",topic:"index",available:y},t)}function k(){try{const t=d();if(l.existsSync(c.join(t.dir,"help-index.md")))return t}catch{}const e=j();return e&&l.existsSync(c.join(e.dir,"help-index.md"))?e:null}function _(e,t){return e.replace(/\{\{([a-z0-9_.-]+)\}\}/gi,(n,r)=>{try{return(0,S.formatHelpToken)(r,t)}catch(i){throw new m.CliError("HELP_TOKEN_NOT_FOUND",i instanceof Error?i.message:String(i),{token:r,helpRoot:t})}})}function T(e){return e.filter(t=>t!=="help")}function w(e,t){if(e.length===0)return{targets:[],unknown:[]};if(e.includes("--full"))return{targets:[{id:"full",input:"--full",file:"full.md"}],unknown:[]};const n=P(e,t);if(n)return{targets:[n],unknown:[]};const r=[],i=[];for(const u of e.filter(s=>!s.startsWith("--"))){const s=u.trim(),o=A(s,t);if(o){r.push(o);continue}i.push(s)}return{targets:r,unknown:i}}function P(e,t){const n=e.join(" ").trim();if(!n)return null;if(n==="bootstrap")return{id:"bootstrap",input:n,file:"bootstrap.md"};const r=b.get(n.toLowerCase());if(r)return{id:r,input:n,file:c.join("topics",`${r}.md`)};const i=n.replace(/\s+/g,".");return v(t,i)?{id:i,input:n,file:c.join("topics",`${i}.md`)}:null}function A(e,t){if(!e)return null;if(e==="bootstrap")return{id:"bootstrap",input:e,file:"bootstrap.md"};if(e==="full")return{id:"full",input:e,file:"full.md"};const n=b.get(e.toLowerCase());if(n)return{id:n,input:e,file:c.join("topics",`${n}.md`)};if(v(t,e))return{id:e,input:e,file:c.join("topics",`${e}.md`)};const r=E(t,e);return r?{id:r,input:e,file:c.join("topics",`${r}.md`)}:null}function q(){const e=d(),t=R(e.dir),n=(0,p.collectContentCandidates)(),r=t&&x(t.topics)?Object.keys(t.topics).length:M(e.dir),i=typeof t?.contentHash=="string"?t.contentHash:void 0,u=["aib help status","",`source: ${e.source}`,`path: ${e.dir}`,`assets: ${(0,p.directoryHasHelp)(e.dir)?"ok":"missing"}`,`metadata: ${t?"ok":"missing help-meta.json"}`,...typeof t?.helpVersion=="string"?[`version: ${t.helpVersion}`]:[],...typeof t?.generatedAt=="string"?[`generatedAt: ${t.generatedAt}`]:[],...typeof t?.sourceCommit=="string"?[`sourceCommit: ${t.sourceCommit}`]:[],...i?[`contentHash: ${L(i)}`]:[],`topics: ${r}`,"","checked:",...n.map(s=>{const o=s.valid?"ok":`skip (${s.reason??"invalid"})`;return`${s.source}: ${o} ${s.dir}`})].join(`
|
|
7
|
+
`);return(0,f.attachAgentText)({operation:"help.status",source:e.source,path:e.dir,assetsOk:(0,p.directoryHasHelp)(e.dir),metadataOk:t!==null,topicCount:r,meta:t??null,candidates:n},u)}function d(){return(0,p.resolveContentRoot)()}function j(){const e=(0,p.collectContentCandidates)().find(t=>t.source==="bundled"&&t.valid);return e?{dir:e.dir,source:e.source}:null}function R(e){const t=c.join(e,"help-meta.json");if(!l.existsSync(t))return null;try{const n=JSON.parse(l.readFileSync(t,"utf8"));return x(n)?n:null}catch{return null}}function M(e){const t=c.join(e,"topics");return l.existsSync(t)?l.readdirSync(t).filter(n=>n.endsWith(".md")).length:0}function v(e,t){return l.existsSync(c.join(e.dir,"topics",`${t}.md`))}function E(e,t){const n=I(e.dir),r=t.toLowerCase(),i=n.filter(u=>{const s=u.toLowerCase();return s.endsWith(`.${r}`)||s===r});return i.length===1?i[0]??null:null}function I(e){const t=c.join(e,"topics");return l.existsSync(t)?l.readdirSync(t).filter(n=>n.endsWith(".md")).map(n=>n.replace(/\.md$/,"")).sort():[]}function L(e){return e.replace(/^sha256:/,"sha256:").slice(0,19)}function x(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var a=exports&&exports.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.runHostCommand=r;const o=a(require("node:path")),n=require("../host/capabilities");function r(t){const e=t[0]??"status";if(e!=="status")return{ok:!1,command:"host",error:`Unknown host command: ${e}`,hint:"Usage: aib host status"};const s=o.default.resolve(__dirname,"..","..");return{ok:!0,command:"host",action:"status",packageRoot:s,host:JSON.parse(JSON.stringify((0,n.readHostCapabilities)(s)))}}
|
|
@@ -1,5 +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(`
|
|
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.formatCyclesResponse=b,exports.appendCycleComponentText=Y;const ee=Z(require("node:path")),te=require("node:crypto"),ne=require("../config/local-config"),S=require("../config/path-display"),A=require("../shared/agent-text"),y=require("../shared/errors"),oe=require("./inspect-graph"),N=require("./session-workspace"),$=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,S.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,b(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"))??$})}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)??$,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=b(_);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:I(t.nodes)<I(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:I(e.representative.nodes).localeCompare(I(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 I(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??$),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,b(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=E(e.fileCount),o=E(e.edgeCount),n=E(e.componentCount),s=E(e.largestComponentFileCount),l=E(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 b(e){if(Array.isArray(e.results)){const i=e.results.filter(f).map(b).filter(r=>!!r);return i.length>0?i.join(`
|
|
2
2
|
|
|
3
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
|
|
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,
|
|
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:$;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,S.compactDisplayPath)(e,l,o));return s.length===1?s[0]:`[${s.join(",")}]`}function k(e,t){return(0,S.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,S.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 E(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)}
|