diff --git a/docs/getting-started/cli.md b/docs/getting-started/cli.md index 1330bc6d91..7e9e225322 100644 --- a/docs/getting-started/cli.md +++ b/docs/getting-started/cli.md @@ -146,8 +146,8 @@ still emit metadata; an empty top-level array emits no lines. Bare top-level arrays have no synthetic coverage record. Command and output-validation failures emit `{"$rea":"jsonl/v1","type":"error","ok":false,"result":…}` -and retain the original diagnostic payload. SDK validation/sentinel errors use -the SDK's exit status rather than guessing from data fields. `$rea` is reserved +and retain the original diagnostic payload. The command owner reports failure +status; error-shaped caller data remains ordinary data. `$rea` is reserved at the top level of a data record, so control records are unambiguous; collisions are refused before rows are written. Nested `$rea` values are ordinary data. A missing final metadata record or nonzero exit can indicate an interrupted @@ -162,9 +162,7 @@ needs its normal resources. A single record must fit the runtime string limit for token estimation; remove `--token-count` to stream a larger record. Standalone version and MCP doctor diagnostics remain single JSON documents -in JSON Lines mode. Incur's streaming generator events and successful sentinel -responses retain their SDK protocol. MCP application results and Evidence -contracts are unchanged. +in JSON Lines mode. MCP application results and Evidence contracts are unchanged. ## Shell completion diff --git a/licenses/README.md b/licenses/README.md index b3d1b7f184..77a55b3447 100644 --- a/licenses/README.md +++ b/licenses/README.md @@ -35,6 +35,11 @@ without installing packages or executing lifecycle scripts. It includes optional platform packages that may not be present in one local installation. Temporary archives were removed after collection. +The `incur@0.6.1` notice remains for the CLI code derived from that release, +even though Incur is no longer an npm dependency. Its preserved MIT text and +the copyright headers in the derived source remain unchanged. Other remaining +runtime archive identities and notices are unchanged by this removal. + For releases that omit original documents, the collection uses pinned upstream texts, embedded source/README license sections, or the same release's parent notice for the `@lydell/node-pty` prebuilt family. `evmole@0.9.3` uses the existing diff --git a/licenses/npm-dependencies.txt b/licenses/npm-dependencies.txt index 37bffa6e9f..1fd84f06c9 100644 --- a/licenses/npm-dependencies.txt +++ b/licenses/npm-dependencies.txt @@ -2,7 +2,7 @@ REA npm dependency inventory Prepared from the root package-lock.json; refresh this inventory when locked dependencies change. License identifiers are upstream lockfile declarations, not a legal assessment. Runtime includes transitive and optional platform packages; development includes build, test and website tooling. -Locked package entries: 966; runtime: 175. +Locked package entries: 962; runtime: 171. Full runtime copyright/license/NOTICE texts: npm-runtime-notices.txt. @algolia/abtesting@1.25.0 | development | MIT @@ -340,11 +340,6 @@ obug@3.0.0 | development | MIT Package: https://www.npmjs.com/package/@bufbuild/protobuf/v/2.16.0 Archive: https://registry.npmjs.org/@bufbuild/protobuf/-/protobuf-2.16.0.tgz Integrity: sha512-FWa0sPlqYGJgpTs6OxBRcL/AW4JT0OIO+W1ajerluoTVh8CV0B7XM1qsNCRgnkSCkRCgOICKHRQlY17jrsm0+Q== -@cfworker/json-schema@4.1.1 | runtime | MIT - Lockfile path: node_modules/@cfworker/json-schema - Package: https://www.npmjs.com/package/@cfworker/json-schema/v/4.1.1 - Archive: https://registry.npmjs.org/@cfworker/json-schema/-/json-schema-4.1.1.tgz - Integrity: sha512-gAmrUZSGtKc3AiBL71iNWxDsyUC5uMaKKGdvzYsBoTW/xi42JQHl7eKV2OYzCUqvc+D2RCcf7EXY2iCyFIk6og== @clack/core@1.4.3 | runtime | MIT Lockfile path: node_modules/@clack/core Package: https://www.npmjs.com/package/@clack/core/v/1.4.3 @@ -1440,11 +1435,6 @@ commander@13.1.0 | development | MIT Package: https://www.npmjs.com/package/@rollup/rollup-win32-x64-msvc/v/4.64.1 Archive: https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.64.1.tgz Integrity: sha512-KpxCwRn1Qh3tmBHAqIAF4HtUCVKqZd0w57TsItWblx3QVeJLtXaSgeBFAj1WAvBSpBo+Mh9iZCjj6YW/HaBVMw== -@scalar/openapi-types@0.8.0 | runtime | MIT - Lockfile path: node_modules/@scalar/openapi-types - Package: https://www.npmjs.com/package/@scalar/openapi-types/v/0.8.0 - Archive: https://registry.npmjs.org/@scalar/openapi-types/-/openapi-types-0.8.0.tgz - Integrity: sha512-WmaxVSfvY5K/TwcG2B2TU1WOe1As1uc2s7myswtP6dBlcjU3hM08SApxv/jmyGaCE8t4gO5BBhmHY4pDUfmr2g== @sec-ant/readable-stream@0.4.1 | development | MIT Lockfile path: node_modules/@sec-ant/readable-stream Package: https://www.npmjs.com/package/@sec-ant/readable-stream/v/0.4.1 @@ -2965,16 +2955,6 @@ imurmurhash@0.1.4 | runtime | MIT Package: https://www.npmjs.com/package/imurmurhash/v/0.1.4 Archive: https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz Integrity: sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA== -incur@0.6.1 | runtime | MIT - Lockfile path: node_modules/incur - Package: https://www.npmjs.com/package/incur/v/0.6.1 - Archive: https://registry.npmjs.org/incur/-/incur-0.6.1.tgz - Integrity: sha512-QgaPKsKH+/3SLdUTSkCYwMWzL56vO3wn7iheEwKE0jOtWSa9Irzn8KeyhkRIkTzHW0ReiQwo0EtT8bBGR9PpMw== -@modelcontextprotocol/server@2.0.0-alpha.4 | runtime | MIT - Lockfile path: node_modules/incur/node_modules/@modelcontextprotocol/server - Package: https://www.npmjs.com/package/@modelcontextprotocol/server/v/2.0.0-alpha.4 - Archive: https://registry.npmjs.org/@modelcontextprotocol/server/-/server-2.0.0-alpha.4.tgz - Integrity: sha512-/KEo3ZJ50HlagHp0lz2vPgfBZFtXHu6zTBXT9XqPc+4O9i4+IbBVWKq/a9yAfv/ifp0u3+mRo8SUk5kMKzhN8A== indent-string@4.0.0 | development | MIT Lockfile path: node_modules/indent-string Package: https://www.npmjs.com/package/indent-string/v/4.0.0 diff --git a/licenses/npm-runtime-notices.txt b/licenses/npm-runtime-notices.txt index 5cc54ba9be..66cbe5d355 100644 --- a/licenses/npm-runtime-notices.txt +++ b/licenses/npm-runtime-notices.txt @@ -1,7 +1,7 @@ REA third-party npm runtime copyright, license and NOTICE texts Collected from integrity-verified locked npm archives. Release-specific supplements and upstream notice gaps are identified in their entries. External engines are separately obtained; see THIRD_PARTY_NOTICES.md. -Runtime dependency fingerprint (SHA-256): 0119b7e66d63524f25c35f294b3264a901b764282b7d3bd1d0b493a9143498d0 +Runtime dependency fingerprint (SHA-256): e400a6f327db9b91f6f4860cc6742b061e95097d04e2075b887810907cfee38c ===== @babel/helper-string-parser@8.0.6 ===== Declared license: MIT @@ -374,37 +374,6 @@ The locked archive omits standalone license files. The Apache license is preserv // support library is itself covered by the above license. -===== @cfworker/json-schema@4.1.1 ===== -Declared license: MIT -Archive: https://registry.npmjs.org/@cfworker/json-schema/-/json-schema-4.1.1.tgz -Integrity: sha512-gAmrUZSGtKc3AiBL71iNWxDsyUC5uMaKKGdvzYsBoTW/xi42JQHl7eKV2OYzCUqvc+D2RCcf7EXY2iCyFIk6og== -Scope: npm runtime dependency, including optional platform packages. - ---- licenses/cfworker-MIT.txt (license from the npm release's upstream gitHead; see upstream-sources.json) --- - -MIT License - -Copyright (c) 2020 Jeremy Danyow - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - - ===== @clack/core@1.4.3 ===== Declared license: MIT Archive: https://registry.npmjs.org/@clack/core/-/core-1.4.3.tgz @@ -1805,85 +1774,6 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -===== @scalar/openapi-types@0.8.0 ===== -Declared license: MIT -Archive: https://registry.npmjs.org/@scalar/openapi-types/-/openapi-types-0.8.0.tgz -Integrity: sha512-WmaxVSfvY5K/TwcG2B2TU1WOe1As1uc2s7myswtP6dBlcjU3hM08SApxv/jmyGaCE8t4gO5BBhmHY4pDUfmr2g== -Scope: npm runtime dependency, including optional platform packages. - ---- package/2.0/license.d.ts --- - -import type { Extensions } from './schema' -/** - * License object - * - * License information for the exposed API. - * - * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#license-object} - */ -export type LicenseObject = { - /** **Required.** The license name used for the API. */ - name: string - /** A URL to the license used for the API. MUST be in the format of a URL. */ - url?: string -} & Extensions - - ---- package/3.0/license.d.ts --- - -/** - * License object - * - * License information for the exposed API. - * - * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.4.md#license-object} - */ -export type LicenseObject = { - /** **REQUIRED**. The license name used for the API. */ - name: string - /** A URL for the license used for the API. This MUST be in the form of a URL. */ - url?: string -} & Record<`x-${string}`, unknown> - - ---- package/3.1/license.d.ts --- - -/** - * License object - * - * License information for the exposed API. - * - * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.2.md#license-object} - */ -export type LicenseObject = { - /** **REQUIRED**. The license name used for the API. */ - name: string - /** An [SPDX](https://spdx.org/licenses/) license expression for the API. The `identifier` field is mutually exclusive of the `url` field. */ - identifier?: string - /** A URI for the license used for the API. This MUST be in the form of a URI. The `url` field is mutually exclusive of the `identifier` field. */ - url?: string -} & Record<`x-${string}`, unknown> - - ---- package/3.2/license.d.ts --- - -/** - * License object - * - * License information for the exposed API. - * - * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.2.0.md#license-object} - */ -export type LicenseObject = { - /** **REQUIRED**. The license name used for the API. */ - name: string - /** An [SPDX](https://spdx.org/licenses/) license expression for the API. The `identifier` field is mutually exclusive of the `url` field. */ - identifier?: string - /** A URI for the license used for the API. This MUST be in the form of a URI. The `url` field is mutually exclusive of the `identifier` field. */ - url?: string -} & Record<`x-${string}`, unknown> - - ===== @toon-format/toon@2.3.1 ===== Declared license: MIT Archive: https://registry.npmjs.org/@toon-format/toon/-/toon-2.3.1.tgz @@ -4353,7 +4243,7 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Declared license: MIT Archive: https://registry.npmjs.org/incur/-/incur-0.6.1.tgz Integrity: sha512-QgaPKsKH+/3SLdUTSkCYwMWzL56vO3wn7iheEwKE0jOtWSa9Irzn8KeyhkRIkTzHW0ReiQwo0EtT8bBGR9PpMw== -Scope: npm runtime dependency, including optional platform packages. +Scope: Incur-derived CLI source retained by REA; the npm package is no longer a runtime dependency. --- package/LICENSE --- @@ -4379,232 +4269,6 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -===== @modelcontextprotocol/server@2.0.0-alpha.4 ===== -Declared license: MIT -Archive: https://registry.npmjs.org/@modelcontextprotocol/server/-/server-2.0.0-alpha.4.tgz -Integrity: sha512-/KEo3ZJ50HlagHp0lz2vPgfBZFtXHu6zTBXT9XqPc+4O9i4+IbBVWKq/a9yAfv/ifp0u3+mRo8SUk5kMKzhN8A== -Scope: npm runtime dependency, including optional platform packages. - ---- package/LICENSE --- - -The MCP project is undergoing a licensing transition from the MIT License to the Apache License, Version 2.0 ("Apache-2.0"). All new code and specification contributions to the project are licensed under Apache-2.0. Documentation contributions (excluding specifications) are licensed under CC-BY-4.0. - -Contributions for which relicensing consent has been obtained are licensed under Apache-2.0. Contributions made by authors who originally licensed their work under the MIT License and who have not yet granted explicit permission to relicense remain licensed under the MIT License. - -No rights beyond those granted by the applicable original license are conveyed for such contributions. - ---- - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to the Licensor for inclusion in the Work by the copyright - owner or by an individual or Legal Entity authorized to submit on behalf - of the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - ---- - -MIT License - -Copyright (c) 2024-2025 Model Context Protocol a Series of LF Projects, LLC. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - ---- - -Creative Commons Attribution 4.0 International (CC-BY-4.0) - -Documentation in this project (excluding specifications) is licensed under -CC-BY-4.0. See https://creativecommons.org/licenses/by/4.0/legalcode for -the full license text. - - ===== inherits@2.0.4 ===== Declared license: ISC Archive: https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz diff --git a/package-lock.json b/package-lock.json index 4e951be9e9..0e7270847f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -33,7 +33,6 @@ "graphql": "17.1.0", "har-schema": "2.0.0", "ignore": "7.0.6", - "incur": "0.6.1", "isomorphic-git": "1.38.7", "jsonc-parser": "3.3.1", "lossless-json": "4.3.1", @@ -1103,12 +1102,6 @@ "integrity": "sha512-FWa0sPlqYGJgpTs6OxBRcL/AW4JT0OIO+W1ajerluoTVh8CV0B7XM1qsNCRgnkSCkRCgOICKHRQlY17jrsm0+Q==", "license": "(Apache-2.0 AND BSD-3-Clause)" }, - "node_modules/@cfworker/json-schema": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/@cfworker/json-schema/-/json-schema-4.1.1.tgz", - "integrity": "sha512-gAmrUZSGtKc3AiBL71iNWxDsyUC5uMaKKGdvzYsBoTW/xi42JQHl7eKV2OYzCUqvc+D2RCcf7EXY2iCyFIk6og==", - "license": "MIT" - }, "node_modules/@clack/core": { "version": "1.4.3", "resolved": "https://registry.npmjs.org/@clack/core/-/core-1.4.3.tgz", @@ -4528,15 +4521,6 @@ "win32" ] }, - "node_modules/@scalar/openapi-types": { - "version": "0.8.0", - "resolved": "https://registry.npmjs.org/@scalar/openapi-types/-/openapi-types-0.8.0.tgz", - "integrity": "sha512-WmaxVSfvY5K/TwcG2B2TU1WOe1As1uc2s7myswtP6dBlcjU3hM08SApxv/jmyGaCE8t4gO5BBhmHY4pDUfmr2g==", - "license": "MIT", - "engines": { - "node": ">=22" - } - }, "node_modules/@sec-ant/readable-stream": { "version": "0.4.1", "resolved": "https://registry.npmjs.org/@sec-ant/readable-stream/-/readable-stream-0.4.1.tgz", @@ -8471,40 +8455,6 @@ "node": ">=0.8.19" } }, - "node_modules/incur": { - "version": "0.6.1", - "resolved": "https://registry.npmjs.org/incur/-/incur-0.6.1.tgz", - "integrity": "sha512-QgaPKsKH+/3SLdUTSkCYwMWzL56vO3wn7iheEwKE0jOtWSa9Irzn8KeyhkRIkTzHW0ReiQwo0EtT8bBGR9PpMw==", - "license": "MIT", - "dependencies": { - "@cfworker/json-schema": "^4.1.1", - "@modelcontextprotocol/server": "2.0.0-alpha.4", - "@scalar/openapi-types": "^0.8.0", - "@toon-format/toon": "^2.3.1", - "tokenx": "^1.3.0", - "yaml": "^2.8.2", - "zod": "^4.3.6" - }, - "bin": { - "incur": "dist/cli/index.js", - "incur.src": "src/cli/index.ts" - }, - "engines": { - "node": ">=22" - } - }, - "node_modules/incur/node_modules/@modelcontextprotocol/server": { - "version": "2.0.0-alpha.4", - "resolved": "https://registry.npmjs.org/@modelcontextprotocol/server/-/server-2.0.0-alpha.4.tgz", - "integrity": "sha512-/KEo3ZJ50HlagHp0lz2vPgfBZFtXHu6zTBXT9XqPc+4O9i4+IbBVWKq/a9yAfv/ifp0u3+mRo8SUk5kMKzhN8A==", - "license": "MIT", - "dependencies": { - "zod": "^4.2.0" - }, - "engines": { - "node": ">=20" - } - }, "node_modules/indent-string": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz", diff --git a/package.json b/package.json index 69e02a2f01..6c7372106f 100644 --- a/package.json +++ b/package.json @@ -394,7 +394,6 @@ "graphql": "17.1.0", "har-schema": "2.0.0", "ignore": "7.0.6", - "incur": "0.6.1", "isomorphic-git": "1.38.7", "jsonc-parser": "3.3.1", "lossless-json": "4.3.1", diff --git a/scripts/rea.mjs b/scripts/rea.mjs index fc15ea1923..080f7c069e 100755 --- a/scripts/rea.mjs +++ b/scripts/rea.mjs @@ -156,7 +156,7 @@ if (!(await compiledRuntimeExists(runtimeFiles))) { if (status === 0) status = 1; } try { - await finishOutput(status); + await finishOutput(); } catch (cause) { if (!stdoutClosed) process.stderr.write(`${cleanupFailureText(cause)}\n`); diff --git a/scripts/verify/baselines/incur-import.json b/scripts/verify/baselines/incur-import.json deleted file mode 100644 index 39e1429c3b..0000000000 --- a/scripts/verify/baselines/incur-import.json +++ /dev/null @@ -1,64 +0,0 @@ -{ - "src/cli/argumentErrors.ts": 1, - "src/cli/cliShell.ts": 1, - "src/cli/explicitSensitiveArguments.ts": 2, - "src/cli/strictPositionals.ts": 1, - "src/cli/types.ts": 1, - "src/cli/visitRegisteredCommands.ts": 1, - "tests/boundary/captures/captureProvider.test.ts": 1, - "tests/boundary/cli/analyzeFunctionDetail.test.ts": 1, - "tests/boundary/cli/browserScenarioSummaryCli.test.ts": 1, - "tests/boundary/cli/browserScenarioValidation.test.ts": 1, - "tests/boundary/cli/captureCleanup.test.ts": 1, - "tests/boundary/cli/cliContractCommandParity.test.ts": 1, - "tests/boundary/cli/cliContractSchemaParity.test.ts": 1, - "tests/boundary/cli/cliControlFlag.test.ts": 1, - "tests/boundary/cli/cliDecimalArguments.test.ts": 2, - "tests/boundary/cli/cliDomainFieldSchema.test.ts": 1, - "tests/boundary/cli/cliInputSchemaRequired.test.ts": 1, - "tests/boundary/cli/cliJsonCallerPath.test.ts": 1, - "tests/boundary/cli/cliLazyRegistration.test.ts": 1, - "tests/boundary/cli/cliOptionAliases.test.ts": 1, - "tests/boundary/cli/cliResultControls.test.ts": 1, - "tests/boundary/cli/cliTimingArguments.test.ts": 1, - "tests/boundary/cli/cliTokenWindowOutput.test.ts": 1, - "tests/boundary/cli/commandEvidenceDelivery.test.ts": 1, - "tests/boundary/cli/completions.test.ts": 1, - "tests/boundary/cli/contractCommandInputFields.test.ts": 1, - "tests/boundary/cli/contractCommandViewDelivery.test.ts": 1, - "tests/boundary/cli/contractJsonInputChecks.test.ts": 1, - "tests/boundary/cli/defaultAmpRegistration.test.ts": 1, - "tests/boundary/cli/directAnalysisStatus.test.ts": 1, - "tests/boundary/cli/emptyLocalTargetAdmission.test.ts": 1, - "tests/boundary/cli/filteredArrayOutput.test.ts": 1, - "tests/boundary/cli/filteredFailureOutput.test.ts": 1, - "tests/boundary/cli/formattingRecovery.test.ts": 1, - "tests/boundary/cli/javascriptApplicationPathAdmission.test.ts": 1, - "tests/boundary/cli/jebInputDiagnostics.test.ts": 1, - "tests/boundary/cli/jsonLinesOutput.test.ts": 1, - "tests/boundary/cli/jsonOutput.test.ts": 1, - "tests/boundary/cli/markdownArgumentErrors.test.ts": 2, - "tests/boundary/cli/markdownNestedFacts.test.ts": 1, - "tests/boundary/cli/nativeFeatureTraceDelivery.test.ts": 1, - "tests/boundary/cli/nativeLoadImageSummaryCli.test.ts": 1, - "tests/boundary/cli/overnightBatch1CliSchemas.test.ts": 1, - "tests/boundary/cli/procedureReferencesDelivery.test.ts": 1, - "tests/boundary/cli/reverseEngineeringCommands.test.ts": 1, - "tests/boundary/cli/routedCommand.test.ts": 1, - "tests/boundary/cli/scenarioManifestCoverage.test.ts": 1, - "tests/boundary/cli/searchBytesAdmission.test.ts": 1, - "tests/boundary/cli/signalCleanup.test.ts": 1, - "tests/boundary/cli/strictPositionals.test.ts": 1, - "tests/boundary/cli/traceNativeValuesCompletenessCli.test.ts": 1, - "tests/boundary/cli/traceNativeValuesEvidenceCli.test.ts": 1, - "tests/boundary/mcp/syntheticContractSurfaces.test.ts": 1, - "tests/boundary/signals/recordingProvider.test.ts": 1, - "tests/boundary/sqlite/sqliteDatabaseDescriptorCleanup.test.ts": 1, - "tests/process-global/browserScenarioCleanup.test.ts": 1, - "tests/process-global/commandFinalizationCancellation.test.ts": 1, - "tests/process-global/flutterCliCleanup.test.ts": 1, - "tests/process-global/javascriptRuntimeObservationCli.test.ts": 1, - "tests/process-global/oneShotSourceClosure.test.ts": 1, - "tests/support/cli/apktoolCli.ts": 1, - "tests/support/cli/processComparisonCli.ts": 1 -} diff --git a/scripts/verify/javascript/output.mjs b/scripts/verify/javascript/output.mjs index 83bce7ce70..b61c6bd3f8 100644 --- a/scripts/verify/javascript/output.mjs +++ b/scripts/verify/javascript/output.mjs @@ -10,7 +10,8 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { finished } from "node:stream/promises"; -import { Cli } from "incur"; +import { createCliShell } from "#dist/cli/cliShell.js"; +import { registerCliCommand } from "#dist/cli/commandRegistry.js"; import { estimateTokenCount } from "tokenx"; import { parseCliOutputArguments } from "#dist/cliOutput.js"; @@ -130,23 +131,24 @@ await withVerifierFixture(fixture, async () => { assert.ok(output); let unexpectedOutputBytes = 0; let exitCode = 0; - await Cli.create("rea-output-verifier", { sync: false }) - .command(metadata.command, { - run: async ({ format: selectedFormat }) => { - assert.equal( - await output.write(evidence, { ...metadata, format: selectedFormat }), - true, - ); - }, - }) - .serve(argv, { - stdout: (text) => { - if (!output.handled) unexpectedOutputBytes += Buffer.byteLength(text); - }, - exit: (code) => { - exitCode = code; - }, - }); + const cli = createCliShell({ + selectedEnvironment: {}, + registrations: [], + resultOutput: output, + }); + registerCliCommand(cli, metadata.command, { + run: async () => { + assert.equal(await output.write(evidence, metadata), true); + }, + }); + await cli.serve(argv, { + stdout: (text) => { + if (!output.handled) unexpectedOutputBytes += Buffer.byteLength(text); + }, + exit: (code) => { + exitCode = code; + }, + }); destination.end(); await finished(destination); assert.equal(exitCode, 0); @@ -187,7 +189,7 @@ await withVerifierFixture(fixture, async () => { counterDestination, ); assert.ok(counter); - assert.equal(await counter.write(evidence, { ...metadata, format }), true); + assert.equal(await counter.write(evidence, metadata), true); assert.equal(counter.error, undefined); assert.equal(counter.failed, false); counterDestination.end(); diff --git a/src/cli/argumentErrors.ts b/src/cli/argumentErrors.ts index 24d57d7469..3c1a50587d 100644 --- a/src/cli/argumentErrors.ts +++ b/src/cli/argumentErrors.ts @@ -1,14 +1,29 @@ -import { Errors } from "incur"; -import { z } from "zod"; - import { projectInputIssues } from "../domain/inputIssueProjection.js"; -import { encodeMarkdownTableCell } from "./cliOutputFormatter.js"; -import type { CliInstance } from "./types.js"; -import { visitRegisteredCommands } from "./visitRegisteredCommands.js"; +import { redactExplicitText } from "../domain/explicitSensitiveValues.js"; +import { + CLI_DOCUMENT_OUTPUT_FORMATS, + type ParsedCliOutputArguments, +} from "../cliOutput.js"; +import { estimateTokenCount } from "tokenx"; +import { formatCliOutput } from "./cliOutputFormatter.js"; +import type { CliArgvFailure, CliFieldError } from "./argvParser.js"; +import type { CliCommandEntry } from "./commandRegistry.js"; +import { formatCommandHelp } from "./help.js"; +import { optionFlagName } from "./optionFields.js"; +import { renderFailure, type CallToAction } from "./outputEnvelope.js"; const ARGUMENT_GUIDANCE = "REA could not read the command arguments. Check the named argument and its expected type, then try again."; +export interface CliCommandFailure { + readonly code: string; + readonly message: string; + readonly retryable?: boolean; + readonly fieldErrors?: readonly (CliFieldError & { + readonly maximum?: number; + })[]; +} + const adbPackageCommands = new Set([ "pull-adb-package", "inspect-adb-package", @@ -16,7 +31,6 @@ const adbPackageCommands = new Set([ "start-adb-app", "stop-adb-app", ]); - const isAdbSelector = (command: string, field: string): boolean => (command.includes("-adb-") && field === "serial") || (adbPackageCommands.has(command) && field === "package") || @@ -28,84 +42,128 @@ const isAdbSelector = (command: string, field: string): boolean => ["action", "component", "data-uri"].includes(field)) || (command === "read-adb-setting" && field === "key"); -/** Preserve parser correction fields without embedding its serialized cause. */ -export const presentCliArgumentErrors = (cli: CliInstance): void => { - visitRegisteredCommands(cli, (command, path) => { - command.middleware = [ - async (_context, next) => { - try { - await next(); - } catch (cause: unknown) { - if (!(cause instanceof Errors.ValidationError)) throw cause; - const failure = new Errors.ValidationError({ - message: ARGUMENT_GUIDANCE, - fieldErrors: adbSelectorConstraints(path, cause), - }); - // Incur's constructor appends cause.message as display details. Keep - // the original error separately, without copying it into the message. - Object.defineProperty(failure, "cause", { value: cause }); - throw failure; - } - }, - ...(command.middleware ?? []), - ]; - }); -}; - -/** Encode only at the final Markdown presentation boundary, after redaction. */ -export const encodeCliArgumentErrors = (cli: CliInstance): void => { - visitRegisteredCommands(cli, (command) => { - command.middleware = [ - async (context, next) => { - try { - await next(); - } catch (error: unknown) { - if ( - context.format === "md" && - error instanceof Errors.ValidationError - ) { - error.fieldErrors = error.fieldErrors.map((field) => ({ - ...field, - ...(field.code === undefined - ? {} - : { code: encodeMarkdownTableCell(field.code) }), - path: encodeMarkdownTableCell(field.path), - expected: encodeMarkdownTableCell(field.expected), - received: encodeMarkdownTableCell(field.received), - message: encodeMarkdownTableCell(field.message), - })); - } - throw error; - } - }, - ...(command.middleware ?? []), - ]; - }); -}; - -/** Retain safe selector constraints dropped by Incur's parser projection. */ -const adbSelectorConstraints = ( +/** Project the parser's retained facts, without serializing an exception cause. */ +export const cliArgumentFailure = ( + cli: string, command: string, - error: Errors.ValidationError, -): Errors.FieldError[] => { - if (!command.includes("-adb-") || !(error.cause instanceof z.ZodError)) - return error.fieldErrors; - return error.fieldErrors.map((field, index) => { - const issue = - error.cause instanceof z.ZodError ? error.cause.issues[index] : undefined; - if ( - issue === undefined || - issue.path.length !== 1 || - issue.path[0] !== field.path || - issue.code !== field.code || - !isAdbSelector(command, field.path) || - (issue.code !== "too_big" && issue.code !== "invalid_format") - ) - return field; - const projected = projectInputIssues([issue], undefined)[0]; - if (projected?.maximum !== undefined) - return { ...field, maximum: projected.maximum }; - if (projected?.expected === "regex") return { ...field, expected: "regex" }; - return field; - }); + failure: CliArgvFailure, +): CliCommandFailure => { + if (failure.kind === "dry_run") + return { code: "PARSE_ERROR", message: failure.message, retryable: false }; + if (failure.kind !== "validation") + return { + code: "UNKNOWN", + message: + failure.message + + (failure.kind === "surplus" + ? ` Use '${cli} ${command} --help' for the declared argument shape.` + : ""), + }; + return { + code: "VALIDATION_ERROR", + message: ARGUMENT_GUIDANCE, + fieldErrors: failure.fieldErrors.map((field, index) => { + const issue = failure.issues[index]; + if ( + !command.includes("-adb-") || + issue === undefined || + issue.path.length !== 1 || + issue.path[0] !== field.path || + issue.code !== field.code || + !isAdbSelector(command, field.path) || + (issue.code !== "too_big" && issue.code !== "invalid_format") + ) + return field; + const projected = projectInputIssues([issue], undefined)[0]; + if (projected?.maximum !== undefined) + return { ...field, maximum: projected.maximum }; + return projected?.expected === "regex" + ? { ...field, expected: "regex" } + : field; + }), + }; +}; + +/** Paths and expectations remain schema facts; caller text is redacted before rendering. */ +export const redactCliCommandFailure = ( + failure: CliCommandFailure, + values: readonly string[], +): CliCommandFailure => ({ + ...failure, + message: redactExplicitText(failure.message, values), + ...(failure.fieldErrors === undefined + ? {} + : { + fieldErrors: failure.fieldErrors.map((field) => ({ + ...field, + received: redactExplicitText(field.received, values), + message: redactExplicitText(field.message, values), + })), + }), +}); + +const validationUsage = ( + cli: string, + entry: CliCommandEntry, + fields: NonNullable, +): string => { + const lines = fields.map((field) => { + const [head, ...tail] = field.path.split("."); + const option = + head !== undefined && entry.definition.options?.shape[head] !== undefined; + const label = option + ? `--${optionFlagName(head!)}${tail.length === 0 ? "" : `.${tail.join(".")}`}` + : `<${field.path}>`; + return field.missing + ? `Error: missing required ${option ? "option" : "argument"} ${label}` + : `Error: invalid value for ${label}: ${field.message}`; + }); + return [ + ...lines, + "See below for usage.", + "", + formatCommandHelp(`${cli} ${entry.name}`, { + ...entry.definition, + globalOptions: { formats: CLI_DOCUMENT_OUTPUT_FORMATS }, + }), + ].join("\n"); +}; + +/** Preserve ordinary-command diagnostic presentation while removing SDK middleware. */ +export const renderCliCommandFailure = ( + failure: CliCommandFailure, + input: { + readonly cli: string; + readonly entry: CliCommandEntry; + readonly duration: string; + readonly stdoutIsTerminal: boolean; + readonly controls: ParsedCliOutputArguments; + readonly cta?: CallToAction | undefined; + }, +): string => { + const { controls, stdoutIsTerminal, cta } = input; + const human = stdoutIsTerminal && !controls.formatExplicit; + if (human && failure.fieldErrors !== undefined) + return `${validationUsage(input.cli, input.entry, failure.fieldErrors)}\n`; + const format = + controls.format === "csv" || controls.format === "tsv" + ? "json" + : controls.format; + // Preserve the ordinary command's established count policy. JSONL errors + // remain diagnostic records; the common renderer owns their framing. + if (controls.tokenCount && format !== "jsonl") + return `${estimateTokenCount(formatCliOutput(failure, format))}\n`; + return renderFailure( + failure, + { command: input.entry.name, duration: input.duration }, + cta, + { + format, + human, + fullOutput: controls.fullOutput, + tokenCount: false, + tokenLimit: controls.tokenLimit, + tokenOffset: controls.tokenOffset, + }, + ); }; diff --git a/src/cli/argvParser.ts b/src/cli/argvParser.ts index 484145daca..7fde12b103 100644 --- a/src/cli/argvParser.ts +++ b/src/cli/argvParser.ts @@ -38,10 +38,14 @@ export interface CliFieldError { */ export type CliArgvFailure = | { readonly kind: "parse"; readonly message: string } + | { readonly kind: "surplus"; readonly message: string } + | { readonly kind: "dry_run"; readonly message: string } | { readonly kind: "validation"; readonly message: string; readonly fieldErrors: readonly CliFieldError[]; + /** Original parser facts for command-specific safe constraint projection. */ + readonly issues: readonly z.core.$ZodIssue[]; }; const parseFailure = (message: string): Result => @@ -117,6 +121,7 @@ export const validateCliInputs = ( const { issues } = parsed.error; return err({ kind: "validation", + issues, message: issues.map(({ message }) => message).join("; ") || "Validation failed", fieldErrors: issues.map((issue) => ({ @@ -159,7 +164,10 @@ export const parseCliArgv = ( ); const positionals: string[] = []; const options: Record = {}; + let invalidDryRun = false; const set = (name: string, value: string): void => { + if (name === "dryRun" && isBoolean(optionsSchema, name)) + invalidDryRun ||= value !== "true" && value !== "false"; if (!isArray(optionsSchema, name)) { options[name] = value; return; @@ -225,9 +233,26 @@ export const parseCliArgv = ( positionals.push(token); } } + // Check retained token facts before defaults or transforms can run. A later + // valid occurrence must not hide an earlier invalid dry-run literal. + if (invalidDryRun) + return err({ + kind: "dry_run", + message: "Invalid --dry-run value; use true or false.", + }); + const keys = Object.keys(argsSchema?.shape ?? {}); + const last = keys.at(-1); + const variadic = last !== undefined && isArray(argsSchema, last); + if (!variadic && positionals.length > keys.length) + return err({ + kind: "surplus", + message: `Unexpected positional arguments: ${positionals + .slice(keys.length) + .map((value) => JSON.stringify(value)) + .join(" ")}.`, + }); const rawArgs: Record = {}; if (argsSchema !== undefined) { - const keys = Object.keys(argsSchema.shape); for (const [position, key] of keys.entries()) { if (isArray(argsSchema, key)) { if (position !== keys.length - 1) diff --git a/src/cli/cliLoader.ts b/src/cli/cliLoader.ts index 28a9142fce..a68ee25cc7 100644 --- a/src/cli/cliLoader.ts +++ b/src/cli/cliLoader.ts @@ -24,7 +24,7 @@ const isRegistrationId = (id: string): id is CliCommandRegistrationId => * complete CLI must answer, as it does for shell completion, which has no * global arguments. A standalone version or retired per-command MCP query * needs no registrar. Help, schemas, `--llms`, completions, other - * Incur builtins, unknown names ("did you mean"), and a missing or unusable + * CLI builtins, unknown names ("did you mean"), and a missing or unusable * recording all describe or search every command. */ export const selectCliRegistrations = ( diff --git a/src/cli/cliResultOutput.ts b/src/cli/cliResultOutput.ts index 16dd1f7ef0..7f4f3c3c8a 100644 --- a/src/cli/cliResultOutput.ts +++ b/src/cli/cliResultOutput.ts @@ -5,7 +5,6 @@ import { estimateTokenCount } from "tokenx"; import { analysisErrorProjectionSchema } from "../domain/analysisErrorProjectionSchema.js"; import type { ParsedCliOutputArguments } from "../cliOutput.js"; -import { parseCliGlobalArguments } from "../cliBuiltinArguments.js"; import { cliOperationFailureIdentity, cliOperationFailurePayload, @@ -32,13 +31,9 @@ import { import { cliEvidencePublicationReceipt, retainCliPublicationOnError, - withCliEvidencePublication, } from "./cliEvidencePublication.js"; -import { - cliResultControls, - withCliResultControls, - type CliResultControls, -} from "./cliResultControls.js"; +import type { CliResultControls } from "./cliResultControls.js"; +import { formatCliCallToAction, type CallToAction } from "./outputEnvelope.js"; import { jsonLinesErrorRecord } from "./jsonLines.js"; import type { OutputFilterPath } from "./outputFilter.js"; import { writeCliJsonLines } from "./jsonLinesOutput.js"; @@ -49,20 +44,13 @@ import { writeOutputParts, writeOutputText, } from "./jsonOutput.js"; -import type { CliInstance } from "./types.js"; -import { - visitRegisteredCommands, - type RegisteredCommand, -} from "./visitRegisteredCommands.js"; - /** Result metadata supplied by the command that actually ran. */ export interface CliResultOutputMetadata { readonly command: string; readonly duration: string; - readonly format: string; + /** Terminal update notice; selected views and owned envelopes omit it. */ + readonly cta?: CallToAction | undefined; readonly renderOutput?: boolean; - /** Render commands that do not have an Incur output fallback. */ - readonly forceOutput?: boolean; /** The producer owns a failure document whose complete facts must survive filtering. */ readonly failure?: boolean; /** @@ -78,6 +66,7 @@ export interface CliResultOutputMetadata { const resultMeta = (metadata: CliResultOutputMetadata) => ({ command: metadata.command, duration: metadata.duration, + ...(metadata.cta === undefined ? {} : { cta: metadata.cta }), ...(metadata.cliControls === undefined ? {} : { cli_controls: { ...metadata.cliControls } }), @@ -90,81 +79,14 @@ export interface CliResultOutput { readonly error: AnalysisErrorProjection | undefined; /** Start another completed invocation on a reusable command registry. */ begin(options: ParsedCliOutputArguments): void; - /** Preserve caller output controls while adapting SDK builtin flags. */ - sdkArguments(args: readonly string[]): string[]; - /** SDK generators retain their own streaming event protocol. */ - delegateStreaming(): void; - /** Retain one-shot SDK output until the SDK supplies its authoritative status. */ - captureSdkOutput(text: string): boolean; - finishSdkOutput(exitCode: number): Promise; + /** Wait for all queued destination writes before its process owner exits. */ + finish(): Promise; write(value: unknown, metadata: CliResultOutputMetadata): Promise; - /** Recover only before any delegated stdout has been written. */ + /** Recover only before any stdout has been written. */ recoverFormattingFailure(cause: unknown): Promise; } -/** Install formatting once, after registration, for every ordinary CLI result. */ -export const streamCliCommandResults = ( - cli: CliInstance, - output: CliResultOutput, -): void => { - visitRegisteredCommands(cli, (command, path, inheritedPolicy) => - wrapCommand(command, path, output, inheritedPolicy), - ); - const serve = cli.serve.bind(cli); - cli.serve = (args = process.argv.slice(2), serveOptions) => - serve(output.sdkArguments(args), serveOptions); -}; - -const wrapCommand = ( - command: Pick, - name: string, - output: CliResultOutput, - inheritedPolicy?: "all" | "agent-only", -): void => { - const run = command.run; - command.run = (context) => - withCliEvidencePublication(() => - withCliResultControls(() => { - const started = performance.now(); - const result: unknown = run(context); - // Generator results and Incur's sentinel responses retain their own protocol. - if ( - typeof result === "object" && - result !== null && - Symbol.asyncIterator in result - ) { - output.delegateStreaming(); - return result; - } - return Promise.resolve(result).then(async (value: unknown) => { - if ( - typeof value === "object" && - value !== null && - Symbol.for("incur.sentinel") in value - ) - return value; - if ( - !(await output.write(value, { - command: name, - format: context.format, - renderOutput: context.agent || inheritedPolicy !== "agent-only", - duration: `${Math.round(performance.now() - started)}ms`, - collectCliControls: cliResultControls, - })) - ) - return value; - if (output.error !== undefined) - return context.error({ - code: output.error.code, - message: output.error.message, - }); - return undefined; - }); - }), - ); -}; - -/** Preserve Incur output controls and stream JSON while framing failures. */ +/** Own result presentation, streaming writes and formatting recovery. */ export const createCliResultOutput = ( initialOptions: ParsedCliOutputArguments, destination: Writable, @@ -182,10 +104,6 @@ export const createCliResultOutput = ( let handled = false; let failed = false; let error: AnalysisErrorProjection | undefined; - let streaming = false; - let sdkDocumentControls = false; - const sdkParts: string[] = []; - let sdkCompletion: Promise | undefined; let completed: | { readonly metadata: CliResultOutputMetadata; @@ -262,23 +180,57 @@ export const createCliResultOutput = ( metadata: CliResultOutputMetadata, ): Promise => { completed = undefined; - if ( - metadata.format !== format && - !((format === "csv" || format === "tsv") && metadata.format === "json") - ) - return false; // Only the full-output envelope shows the result's control flags, so the // result is read for them only then. const cliControls = options.fullOutput ? metadata.collectCliControls?.() : undefined; + const selectedMetadata = + cliControls === undefined ? metadata : { ...metadata, cliControls }; + const filterPaths = options.filterPaths?.ok + ? options.filterPaths.value + : undefined; + const operationFailure = metadata.failure + ? value + : format === "jsonl" || options.fullOutput || filterPaths !== undefined + ? cliOperationFailurePayload(value) + : undefined; + // These presentations own complete documents. A terminal notice must not + // become part of their selected view, retained envelope or token count. + const ownsDocument = + operationFailure !== undefined || + (filterPaths !== undefined && filterPaths.length > 0) || + (options.tokenWindow && !options.tokenCount) || + (options.fullOutput && + (options.tokenCount || selectedMetadata.cliControls !== undefined)); + const presentedMetadata = + ownsDocument && selectedMetadata.cta !== undefined + ? { ...selectedMetadata, cta: undefined } + : selectedMetadata; try { - return await writeResult( + const written = await writeResult( value, - cliControls === undefined ? metadata : { ...metadata, cliControls }, + presentedMetadata, + operationFailure, ); + if ( + metadata.cta !== undefined && + (!written || !ownsDocument) && + error === undefined && + !options.fullOutput && + !options.tokenCount + ) { + handled = true; + await writeOutputText( + destination, + `${formatCliCallToAction(metadata.cta)}\n`, + ); + return true; + } + return written; } catch (cause: unknown) { if (await recoverFormattingFailure(cause)) return true; + if (handled) failed = true; throw cause; } }; @@ -299,149 +251,9 @@ export const createCliResultOutput = ( failed = false; error = undefined; completed = undefined; - streaming = false; - sdkDocumentControls = false; - sdkParts.length = 0; - sdkCompletion = undefined; }, - sdkArguments(args) { - const split = parseCliGlobalArguments(args); - const normalized = split.arguments; - const values = new Set(split.outputValues.map(({ index }) => index)); - const hasFlag = (flag: string) => - normalized.some((token, index) => token === flag && !values.has(index)); - // Incur emits these documents outside command result handlers. Manifest - // flags precede help; schema follows help and version in its dispatcher. - sdkDocumentControls = - (options.tokenCount || options.tokenWindow) && - (hasFlag("--llms") || - hasFlag("--llms-full") || - (hasFlag("--schema") && - !["completions", "mcp", "skills"].includes( - split.command[0] ?? "", - ) && - !hasFlag("--help") && - !hasFlag("-h") && - !hasFlag("--version"))); - // The caller's parsed controls remain authoritative: the CLI may adapt - // CSV/TSV to JSON for Incur without changing the requested presentation. - if (format !== "jsonl" || !options.tokenCount) return [...normalized]; - // Incur counts errors before REA can retain their diagnostic payload. - // Preserve operands using the shared builtin consumption rules. - return normalized.filter( - (token, index) => token !== "--token-count" || values.has(index), - ); - }, - delegateStreaming() { - streaming = true; - }, - captureSdkOutput(text) { - // JSONL always buffers for framing. Piped/redirected JSON also buffers so - // Incur's always-indented Formatter output can be rewritten compactly. - // Terminal JSON stays with Incur, which already matches the indent contract. - // sdkDocumentControls also buffers one-shot SDK documents for token windows. - const captureJson = format === "json" && !isTerminalOutput(destination); - if ( - (format !== "jsonl" && !sdkDocumentControls && !captureJson) || - streaming || - handled - ) - return false; - // Incur already materializes one-shot documents. Retain references only; - // generator events bypass this buffer and remain incremental. - if (text.length > 0) sdkParts.push(text); - return true; - }, - finishSdkOutput(exitCode) { - return (sdkCompletion ??= (async () => { - const parts = sdkParts.splice(0); - try { - if (parts.length === 0) { - // SDK writes outside the JSONL buffer still share this destination. - // A write callback runs after earlier queued writes have completed, - // so the launcher's explicit exit cannot discard a pending pipe tail. - await writeOutputText(destination, ""); - return; - } - if (format === "json") { - const text = parts.join(""); - let result: unknown; - try { - result = JSON.parse(text); - } catch { - // Preserve non-JSON SDK output (e.g. completion hooks). Token-count - // only for SDK documents that opted into sdkDocumentControls. - if (exitCode === 0 && options.tokenCount && sdkDocumentControls) { - await writeOutputText( - destination, - `${estimateTokenCount(text)}\n`, - ); - return; - } - await writeOutputText(destination, text); - return; - } - // Compact rewrite must not skip token controls for SDK documents - // (`--llms` / `--schema` with --token-count on a pipe). - if (exitCode === 0 && options.tokenCount) { - const compact = [...jsonOutputParts(result, "json", false)].join( - "", - ); - await writeOutputText( - destination, - `${estimateTokenCount(compact)}\n`, - ); - return; - } - await writeJsonOutput(result, destination, "json"); - return; - } - if (exitCode === 0) { - if (options.tokenCount) - await writeOutputText( - destination, - `${estimateTokenCount(parts.join(""))}\n`, - ); - else if (sdkDocumentControls && options.tokenWindow) { - const text = parts.join(""); - const window = sliceTextByTokenWindow( - text, - options.tokenOffset ?? 0, - options.tokenLimit, - ); - await writeOutputText( - destination, - window.truncated - ? `${window.text}\n[truncated: showing tokens ${window.start}–${window.end} of ${window.total}]\n` - : text, - ); - } else - for (const part of parts) - await writeOutputText(destination, part); - } else { - const text = parts.join(""); - if (format !== "jsonl") { - await writeOutputText(destination, text); - return; - } - let result: unknown = text; - try { - result = JSON.parse(text); - } catch { - /* Preserve non-JSON SDK diagnostics verbatim. */ - } - await writeJsonOutput( - jsonLinesErrorRecord(result), - destination, - "jsonl", - ); - } - } catch (cause: unknown) { - handled = true; - failed = true; - throw cause; - } - })()); + finish() { + return writeOutputText(destination, ""); }, write, recoverFormattingFailure, @@ -450,6 +262,7 @@ export const createCliResultOutput = ( async function writeResult( value: unknown, metadata: CliResultOutputMetadata, + operationFailure: unknown, ): Promise { completed = { metadata, @@ -459,17 +272,21 @@ export const createCliResultOutput = ( const filterPaths = options.filterPaths?.ok ? options.filterPaths.value : undefined; - const operationFailure = metadata.failure - ? value - : format === "jsonl" || options.fullOutput || filterPaths !== undefined - ? cliOperationFailurePayload(value) - : undefined; const failure = options.fullOutput ? operationFailure : undefined; const ownsFilteredOutput = operationFailure === undefined && filterPaths !== undefined && filterPaths.length > 0; - // Incur owns suppressed human presentation, but a filter must never erase + if ( + (format === "toon" || format === "yaml") && + value == null && + !options.fullOutput && + !options.tokenCount && + !options.tokenWindow && + !ownsFilteredOutput + ) + return false; + // Suppressed human presentation must never erase // the typed failure that this boundary already owns. if ( operationFailure === undefined && @@ -651,33 +468,12 @@ export const createCliResultOutput = ( Array.isArray(selected) ? normalizeJsonArrayValues(selected) : selected; - // A full-output envelope that shows the result's control flags is written - // here in every format; Incur's envelope cannot carry them. - const ownsControlEnvelope = - options.fullOutput && metadata.cliControls !== undefined; const ownsSuccessfulTokenWindow = operationFailure === undefined && options.tokenWindow && !options.tokenCount && format !== "json" && format !== "jsonl"; - // Delegate other human formats to Incur. Markdown stays here so admission - // and emitted table text use the same safe formatter. A full-output token - // count stays here too: Incur counts only the selected data, so delegating - // it would report the bare result instead of the emitted envelope. - if ( - !metadata.forceOutput && - format !== "md" && - format !== "json" && - format !== "jsonl" && - operationFailure === undefined && - !ownsFilteredOutput && - !ownsSuccessfulTokenWindow && - !(options.tokenCount && options.fullOutput) && - // Incur's own envelope cannot carry the result's control flags. - !ownsControlEnvelope - ) - return false; if (format === "jsonl") { handled = true; try { @@ -727,9 +523,9 @@ export const createCliResultOutput = ( ? {} : filtered; if (options.tokenCount) { - // Incur/tokenx materialize JSON. Measure its UTF-16 expansion before + // Token counting materializes JSON. Measure its UTF-16 expansion before // allowing that allocation, independently of UTF-8 bytes. Other formats - // retain Incur's materializing behavior. + // require a complete formatted string. const tokenValue = document; let characters = 0; if ( @@ -801,7 +597,7 @@ export const createCliResultOutput = ( options.tokenOffset ?? 0, options.tokenLimit, ); - // Keep Incur's empty human/agent presentation semantics. Nonempty text + // Keep the established empty human/agent presentation. Nonempty text // already belongs to this formatter, even when the whole result fits. if (!window.truncated && !options.fullOutput && formatted === "") return false; @@ -842,16 +638,9 @@ export const createCliResultOutput = ( } return true; } - // Once writing starts, a failed destination must not receive a second - // document from Incur's error formatter. + // Once writing starts, a failed destination must not receive another document. const formattedText = - format === "md" || - ((metadata.forceOutput === true || ownsControlEnvelope) && - format !== "json") || - ((operationFailure !== undefined || ownsFilteredOutput) && - format !== "json") - ? formatCliOutput(document, format) - : undefined; + format === "json" ? undefined : formatCliOutput(document, format); if ( format === "md" && formattedText === "" && @@ -863,8 +652,7 @@ export const createCliResultOutput = ( handled = true; try { if (formattedText !== undefined) { - // Incur's error sentinel only carries code/message/retryable. Render - // the owned projection or caller-visible failure at this boundary. + // Retain the complete owned projection at the output boundary. await writeOutputText(destination, `${formattedText}\n`); } else { await writeJsonOutput( @@ -1004,7 +792,7 @@ const delimitedMetadata = ( }; }; -/** Apply Incur's parsed path grammar while merging sibling array selections. */ +/** Apply the parsed output path grammar while merging sibling array selections. */ type FilterProjection = Result; const applyCliOutputFilter = ( @@ -1019,7 +807,7 @@ const applyCliOutputFilter = ( paths.flatMap((path) => { const first = path[0]; if (first === undefined || "start" in first) return [path]; - // Root keys retain Incur's implicit per-record traversal, including + // Root keys retain implicit per-record traversal, including // numeric keys. Only nested array keys address array positions. return expandImplicitArrayPath(value, path); }), diff --git a/src/cli/cliShell.ts b/src/cli/cliShell.ts index e836e3a695..1e769265bd 100644 --- a/src/cli/cliShell.ts +++ b/src/cli/cliShell.ts @@ -1,43 +1,26 @@ -import { Cli } from "incur"; import { HOST_PLATFORM } from "../platform/HostPlatform.js"; import type { FridaInstrumentationPort } from "../ports/frida/FridaInstrumentationPort.js"; import { currentClientRegistrationCommand } from "../application/ClientRegistrationIdentity.js"; -import { - adaptCliOutputArgumentsForIncur, - parseCliGlobalArguments, -} from "../cliBuiltinArguments.js"; +import { parseCliGlobalArguments } from "../cliBuiltinArguments.js"; import type { DirectAnalysis } from "../composition/directAnalysis.js"; import { parseLogLevel } from "../config/processStart.js"; import { parseClientRegistrationCommand } from "../domain/clientRegistrationCommand.js"; import { PRODUCT_IDENTITY } from "../identity.js"; import { createLogger } from "../logger.js"; import { snapshotEnvironment } from "../process/snapshotEnvironment.js"; -import { - encodeCliArgumentErrors, - presentCliArgumentErrors, -} from "./argumentErrors.js"; import type { CliCommandRegistration, CliRegistrationContext, } from "./cliCommandRegistration.js"; -import { - streamCliCommandResults, - type CliResultOutput, -} from "./cliResultOutput.js"; +import type { CliResultOutput } from "./cliResultOutput.js"; +import { runCliCommand } from "./runCliCommand.js"; import { completionHelpNote, createCliCompletions } from "./completions.js"; -import { excludeDeclaredSensitiveArguments } from "./explicitSensitiveArguments.js"; -import { - CLI_CUSTOM_GLOBAL_OPTIONS, - CLI_DESCRIPTION, - CLI_UPDATE_REFUSAL, - serveDiscovery, -} from "./discovery.js"; +import { serveDiscovery } from "./discovery.js"; import { reportUnknownMcpSubcommand } from "./mcpBuiltinCommands.js"; import { serveMcpRegistration } from "./mcpRegistration.js"; import { presentOmittableDefaults } from "./omittableDefaults.js"; -import { validateCliArguments } from "./strictPositionals.js"; -import type { CliInstance } from "./types.js"; +import type { CliInstance, CliServeOptions } from "./types.js"; /** A registrar and the module it was loaded from. */ export interface LoadedCliCommandRegistration { @@ -76,7 +59,7 @@ const registerCommands = ( }; /** - * Build the Incur CLI around the given registrars. Identity, global options, + * Build REA's CLI around the given registrars. Identity, global options, * argument policy, completions, and registration builtins are the same for * every set of registrars; they apply to whichever commands were registered. */ @@ -98,40 +81,10 @@ export const createCliShell = (options: CliShellOptions): CliInstance => { "cli", level?.ok === true ? level.value : "silent", ); - const timedCli = Cli.create(PRODUCT_IDENTITY.cliBinary, { - version: PRODUCT_IDENTITY.packageVersion, - description: CLI_DESCRIPTION, - globals: CLI_CUSTOM_GLOBAL_OPTIONS, - mcp: { - instructions: - "Ask what software, artifact, protocol, or behavior the user wants to understand, then choose the available investigation capabilities that can produce evidence.", - }, - sync: false, - update: { - // Incur still supplies ordinary-command notices. Keep its installer - // disabled while REA owns the update refusal and verified update command. - install: () => { - throw new Error(CLI_UPDATE_REFUSAL.message); - }, - }, - }); - - timedCli.use(async (context, next) => { - if (!context.globals.timings) return next(); - const started = performance.now(); - try { - await next(); - } finally { - // This interval covers CLI command dispatch, including result delivery. - // It is not a provider-only or analysis-only measurement. - process.stderr.write( - `${JSON.stringify({ rea_timings: { version: 1, command_ms: Math.round(performance.now() - started) } })}\n`, - ); - } - }); - // Command registrars do not inspect global options; preserve their existing - // type while Incur owns parsing and the middleware owns this added flag. - const cli = timedCli as unknown as CliInstance; + const cli: CliInstance = { + name: PRODUCT_IDENTITY.cliBinary, + serve, + }; registerCommands( { @@ -144,25 +97,15 @@ export const createCliShell = (options: CliShellOptions): CliInstance => { ); presentOmittableDefaults(cli); - // Discovery reads the arguments the dispatcher would, after result output - // has adapted them, so its documents are counted and buffered alike. - const dispatch = cli.serve.bind(cli); const updateEnvironment = { variables: environment, platform: HOST_PLATFORM.platform, }; - cli.serve = (arguments_ = process.argv.slice(2), serveOptions) => - serveDiscovery(cli, arguments_, serveOptions ?? {}, updateEnvironment) ?? - dispatch(arguments_, serveOptions); - if (options.resultOutput !== undefined) - streamCliCommandResults(cli, options.resultOutput); - const serveStrict = validateCliArguments(cli); - presentCliArgumentErrors(cli); - const serveDeclared = excludeDeclaredSensitiveArguments(cli); - encodeCliArgumentErrors(cli); - const serve = cli.serve.bind(cli); const completions = createCliCompletions(cli, environment); - cli.serve = (arguments_ = process.argv.slice(2), serveOptions) => { + function serve( + arguments_: readonly string[] = process.argv.slice(2), + serveOptions?: CliServeOptions, + ): Promise { if (completions.complete(arguments_, serveOptions ?? {})) return Promise.resolve(); const global = parseCliGlobalArguments(arguments_); @@ -175,16 +118,26 @@ export const createCliShell = (options: CliShellOptions): CliInstance => { serveOptions ?? {}, ); if (registration !== undefined) return registration; - const result = serveStrict(global, serveOptions ?? {}, (selected) => - serveDeclared(global, selected, (declaredOptions) => - reportUnknownMcpSubcommand(cli.name, global, declaredOptions) - ? Promise.resolve() - : serve( - adaptCliOutputArgumentsForIncur(global.arguments), - declaredOptions, - ), - ), - ); + const result = reportUnknownMcpSubcommand( + cli.name, + global, + serveOptions ?? {}, + ) + ? Promise.resolve() + : (serveDiscovery( + cli, + global.arguments, + serveOptions ?? {}, + updateEnvironment, + global, + ) ?? + runCliCommand( + cli, + global, + serveOptions ?? {}, + updateEnvironment, + options.resultOutput, + )); const note = completionHelpNote(global); if (note === undefined) return result; return result.then(() => { @@ -192,6 +145,6 @@ export const createCliShell = (options: CliShellOptions): CliInstance => { serveOptions?.stdout ?? ((text: string) => process.stdout.write(text)); write(`\n${note}`); }); - }; + } return cli; }; diff --git a/src/cli/commandRegistry.ts b/src/cli/commandRegistry.ts index 25e75ebb3e..d246683945 100644 --- a/src/cli/commandRegistry.ts +++ b/src/cli/commandRegistry.ts @@ -68,8 +68,8 @@ export interface CliCommandEntry { readonly name: string; /** * The definition the dispatcher runs. Shell owners may still replace its - * inputs and handler in place before serving (omittable defaults, result - * output, argument policy), so readers see what is served. + * input schemas in place before serving (omittable defaults), so readers + * see what is served. */ readonly definition: CliCommandDefinition< z.ZodObject | undefined, @@ -84,7 +84,7 @@ const registries = new WeakMap(); /** * Register one command: record it in REA's command table, in registration - * order, and hand it to the dispatcher. Every command is registered here. + * order. The dispatcher reads this table; every command is registered here. */ export const registerCliCommand = < const Args extends z.ZodObject | undefined = undefined, @@ -101,11 +101,6 @@ export const registerCliCommand = < const entries = registries.get(cli) ?? []; if (entries.some((entry) => entry.name === name)) throw new Error(`CLI command ${name} is registered twice`); - // The dispatcher keeps this object, so in-place changes reach both. - (cli.command as (name: string, definition: object) => unknown)( - name, - definition, - ); entries.push({ name, definition: definition as CliCommandEntry["definition"], @@ -119,6 +114,13 @@ export const registerCliCommand = < export const cliCommands = (cli: CliInstance): readonly CliCommandEntry[] => registries.get(cli) ?? []; +/** Resolve a command identity from the same records the dispatcher serves. */ +export const cliCommand = ( + cli: CliInstance, + name: string, +): CliCommandEntry | undefined => + cliCommands(cli).find((entry) => entry.name === name); + /** * The operations one contract description runs: its own contract, the * contract that opens its session target, and the source of its Evidence diff --git a/src/cli/completions.ts b/src/cli/completions.ts index ae439be353..c53dcda282 100644 --- a/src/cli/completions.ts +++ b/src/cli/completions.ts @@ -25,7 +25,7 @@ import { MCP_DOCTOR_ALIAS, MCP_DOCTOR_OPTIONS } from "../mcpDoctorOptions.js"; type ServeOptions = NonNullable[1]>; const ROOT_FLAGS = new Set(["--mcp", "--update", "--version"]); -/** Supplement Incur's built-in setup instructions without replacing its help. */ +/** Supplement the completion setup page with Zsh initialization guidance. */ export const completionHelpNote = ( global: CliGlobalArguments, ): string | undefined => { @@ -109,7 +109,6 @@ const completionCommands = ( description: COMPLETIONS_DESCRIPTION, commands: new Map(CLI_COMPLETION_SHELLS.map((shell) => [shell, {}])), }); - // REA uses sync:false, so the framework's skills integration is disabled. return commands; }; @@ -146,7 +145,7 @@ export const createCliCompletions = ( if (!Number.isSafeInteger(index) || index < 0 || index > words.length) return true; // Consume global option values before scope resolution. A value named - // 'mcp' is still data; leave an unfinished flag for Incur's enum hints. + // 'mcp' is still data; retain an unfinished flag for enum hints. const before = parseCliGlobalArguments(words.slice(1, index)).command; if (before.includes("--")) return true; const input = [cli.name, ...before, words[index] ?? ""]; @@ -178,14 +177,15 @@ export const createCliCompletions = ( ); if (command[offset] !== "completions" || selected === undefined) return false; - // Help/manifests/schema/version and server controls keep framework precedence. + // Help, manifests and server controls precede a completion script. const values = new Set(global.outputValues.map(({ index }) => index)); if ( global.arguments.some( (token, index) => !values.has(index) && - ((CLI_BUILTIN_FLAGS.has(token) && !OUTPUT_SWITCHES.has(token)) || - token === "--version"), + CLI_BUILTIN_FLAGS.has(token) && + token !== "--schema" && + !OUTPUT_SWITCHES.has(token), ) ) return false; diff --git a/src/cli/contractCommand.ts b/src/cli/contractCommand.ts index f1a7f7fc59..f74cabe50d 100644 --- a/src/cli/contractCommand.ts +++ b/src/cli/contractCommand.ts @@ -69,9 +69,9 @@ import { isRecord } from "../kernel/isRecord.js"; import { optionFlagName } from "./optionFields.js"; /** - * Incur adapter for contract commands. The command itself is described in + * CLI adapter for contract commands. The command itself is described in * `contractCliDescription.ts`; this module only renders that description as - * Incur args and options and runs the handler. + * CLI args and options and runs the handler. */ /** What a contract command's handler receives besides the contract input. */ @@ -564,7 +564,7 @@ export const contractCommandDescriptions = ( source.kind === "contract" ? [source.description] : [], ); -const incurOptions = (description: ContractCliDescription): z.ZodType => { +const commandOptions = (description: ContractCliDescription): z.ZodType => { const object = z.object( Object.fromEntries([ ...description.parameters @@ -646,7 +646,7 @@ export const registerContractCommand = < ), ), }), - options: incurOptions(description), + options: commandOptions(description), ...(Object.keys(alias).length === 0 ? {} : { alias }), run: ({ args, @@ -857,7 +857,7 @@ const commandShape = (description: ContractCliDescription) => ({ // Routed descriptions declare no object-level rules, so this is the object. options: Object.fromEntries( Object.entries( - (incurOptions(description) as z.ZodObject).shape as Readonly< + (commandOptions(description) as z.ZodObject).shape as Readonly< Record >, ).map(([key, schema]) => [key, withoutDefault(schema)]), diff --git a/src/cli/discovery.ts b/src/cli/discovery.ts index 553640063c..3c9c4fadc6 100644 --- a/src/cli/discovery.ts +++ b/src/cli/discovery.ts @@ -11,9 +11,14 @@ import { CLI_DOCUMENT_OUTPUT_FORMATS, CLI_OUTPUT_FORMATS, readCliOutputArguments, + renderCliDocument, + type CliOutputFormat, } from "../cliOutput.js"; -import { PRODUCT_IDENTITY } from "../identity.js"; import { formatCliOutput } from "./cliOutputFormatter.js"; +import { estimateTokenCount } from "tokenx"; +import { jsonLinesErrorRecord } from "./jsonLines.js"; +import { sliceTextByTokenWindow } from "./tokenWindow.js"; +import { PRODUCT_IDENTITY } from "../identity.js"; import { commandSchemaDocument, formatLlmsFull, @@ -129,15 +134,84 @@ const integrationIndex = ( : -1; /** A document REA writes instead of running a command, and the status it ends with. */ -interface DiscoveryAnswer { - readonly text: string; - readonly exitCode: number; -} +type DiscoveryAnswer = + | { + readonly kind: "text"; + readonly text: string; + readonly exitCode: number; + } + | { + readonly kind: "rendered"; + readonly text: string; + readonly exitCode: number; + } + | { readonly kind: "markup"; readonly text: string; readonly exitCode: 0 } + | { + readonly kind: "document"; + readonly value: unknown; + readonly format: CliOutputFormat; + readonly tokens: boolean; + readonly exitCode: number; + }; const answer = (text: string, exitCode = 0): DiscoveryAnswer => ({ + kind: "text", text: text.endsWith("\n") ? text : `${text}\n`, exitCode, }); +const renderedAnswer = (text: string, exitCode = 0): DiscoveryAnswer => ({ + kind: "rendered", + text, + exitCode, +}); +const markupAnswer = (text: string): DiscoveryAnswer => ({ + kind: "markup", + text, + exitCode: 0, +}); +const documentAnswer = ( + value: unknown, + format: CliOutputFormat, + tokens = true, + exitCode = 0, +): DiscoveryAnswer => ({ kind: "document", value, format, tokens, exitCode }); + +const presentDiscoveryAnswer = ( + result: DiscoveryAnswer, + global: CliGlobalArguments, +): string => { + if (result.kind === "rendered") return result.text; + const controls = readCliOutputArguments(global); + if (result.kind === "text") + return result.exitCode !== 0 && controls.format === "jsonl" + ? renderCliDocument(jsonLinesErrorRecord(result.text), "jsonl", false) + : result.text; + let encoded: string; + if (result.kind === "markup") encoded = result.text; + else { + const value = + result.format === "jsonl" && result.exitCode !== 0 + ? jsonLinesErrorRecord(result.value) + : result.value; + encoded = + result.format === "json" || result.format === "jsonl" + ? renderCliDocument(value, result.format, process.stdout.isTTY === true) + : formatCliOutput(value, result.format); + } + const text = encoded.endsWith("\n") ? encoded : `${encoded}\n`; + if ((result.kind === "document" && !result.tokens) || result.exitCode !== 0) + return text; + if (controls.tokenCount) return `${estimateTokenCount(text)}\n`; + if (!controls.tokenWindow) return text; + const window = sliceTextByTokenWindow( + text, + controls.tokenOffset ?? 0, + controls.tokenLimit, + ); + return window.truncated + ? `${window.text}\n[truncated: showing tokens ${window.start}–${window.end} of ${window.total}]\n` + : text; +}; const sortedCommands = (cli: CliInstance): readonly CliCommandEntry[] => [...cliCommands(cli)].sort((left, right) => @@ -159,18 +233,16 @@ const llmsAnswer = ( ); const commands = scoped === undefined ? sortedCommands(cli) : [scoped]; if (!formatExplicit || format === "md") - return answer( + return markupAnswer( full ? formatLlmsFull(cli.name, commands) : formatLlmsIndex(cli.name, commands, CLI_DESCRIPTION), ); - return answer( - formatCliOutput( - full - ? llmsFullManifest(commands, CLI_CUSTOM_GLOBAL_OPTIONS) - : llmsIndexManifest(commands, CLI_CUSTOM_GLOBAL_OPTIONS), - format, - ), + return documentAnswer( + full + ? llmsFullManifest(commands, CLI_CUSTOM_GLOBAL_OPTIONS) + : llmsIndexManifest(commands, CLI_CUSTOM_GLOBAL_OPTIONS), + format, ); }; @@ -198,11 +270,9 @@ const schemaAnswer = ( return answer(`Error: ${failure.message}`, 1); } const { format, formatExplicit } = readCliOutputArguments(global); - return answer( - formatCliOutput( - commandSchemaDocument(entry, CLI_CUSTOM_GLOBAL_OPTIONS), - formatExplicit ? format : "toon", - ), + return documentAnswer( + commandSchemaDocument(entry, CLI_CUSTOM_GLOBAL_OPTIONS), + formatExplicit ? format : "toon", ); }; @@ -227,12 +297,9 @@ const updateRefusalAnswer = ( declaredSensitiveValues(global.command), ), }; - return answer( - invocation.stdoutIsTerminal && !controls.formatExplicit - ? `Error (${failure.code}): ${failure.message}` - : formatCliOutput(failure, controls.format), - 1, - ); + return invocation.stdoutIsTerminal && !controls.formatExplicit + ? answer(`Error (${failure.code}): ${failure.message}`, 1) + : documentAnswer(failure, controls.format, false, 1); }; /** The production MCP entry owns server startup; a command cannot start another. */ @@ -244,7 +311,7 @@ const retiredMcpAnswer = ( const controls = readCliOutputArguments(global); const sensitive = declaredSensitiveValues(global.command); const text = (value: string): string => redactExplicitText(value, sensitive); - return answer( + return renderedAnswer( renderFailure( { code: "MCP_MODE_REMOVED", @@ -287,8 +354,12 @@ const unknownCommandAnswer = ( { environment, stdoutIsTerminal, started }: Invocation, ): DiscoveryAnswer | undefined => { const controls = readCliOutputArguments(global); - const format = controls.formatExplicit ? controls.format : "toon"; - if (format === "csv" || format === "tsv") return undefined; + const selectedFormat = controls.formatExplicit ? controls.format : "toon"; + // Delimited exports require rows; a command diagnostic remains a document. + const format = + selectedFormat === "csv" || selectedFormat === "tsv" + ? "json" + : selectedFormat; const human = stdoutIsTerminal && !controls.formatExplicit; const unknown = global.command[0]!; const suggestion = suggestCommand(unknown, [ @@ -308,7 +379,7 @@ const unknownCommandAnswer = ( suggestion, additionalCommands: notice, }); - return answer( + return renderedAnswer( renderFailure( failure, { @@ -388,7 +459,7 @@ const discoveryAnswer = ( const mcp = integrationIndex(command, cli.name, "mcp"); if (mcp >= 0) { const subcommand = command[mcp + 1]; - if (subcommand === undefined) + if (!subcommand) return answer( formatCommandListHelp(`${cli.name} mcp`, { description: MCP_GROUP_DESCRIPTION, @@ -443,8 +514,9 @@ export const serveDiscovery = ( arguments_: readonly string[], options: ServeOptions, environment: UpdateEnvironment, + parsed?: CliGlobalArguments, ): Promise | undefined => { - const global = parseCliGlobalArguments(arguments_); + const global = parsed ?? parseCliGlobalArguments(arguments_); // The refresh writes nothing and answers before every other flag. if (global.flags.has(UPDATE_CHECK_FLAG)) return refreshUpdateCache( @@ -459,7 +531,7 @@ export const serveDiscovery = ( }); if (result === undefined) return undefined; (options.stdout ?? ((text: string) => process.stdout.write(text)))( - result.text, + presentDiscoveryAnswer(result, global), ); if (result.exitCode !== 0) (options.exit ?? ((code: number) => process.exit(code)))(result.exitCode); diff --git a/src/cli/explicitSensitiveArguments.ts b/src/cli/explicitSensitiveArguments.ts index 573f941518..56849ceca1 100644 --- a/src/cli/explicitSensitiveArguments.ts +++ b/src/cli/explicitSensitiveArguments.ts @@ -1,20 +1,5 @@ -import { AsyncLocalStorage } from "node:async_hooks"; - -import { Errors, type MiddlewareHandler } from "incur"; import { z } from "zod"; -import { - readCliOutputArguments, - renderCliOutputArgumentError, -} from "../cliOutput.js"; -import { - declaredSensitiveValues, - type CliGlobalArguments, -} from "../cliBuiltinArguments.js"; -import { redactExplicitText } from "../domain/explicitSensitiveValues.js"; -import type { CliInstance } from "./types.js"; -import { visitRegisteredCommands } from "./visitRegisteredCommands.js"; - /** Repeatable option whose literals the command and its CLI diagnostics exclude. */ export const explicitSensitiveValueOptions = { sensitiveValue: z @@ -24,107 +9,3 @@ export const explicitSensitiveValueOptions = { "Literal string values explicitly marked sensitive; repeat as needed", ), }; - -const OPTION = - "sensitiveValue" satisfies keyof typeof explicitSensitiveValueOptions; -type ServeOptions = NonNullable[1]>; - -/** Share the executable boundary's output admission and structured diagnostics. */ -const reportDeclaredOutputRejection = ( - global: CliGlobalArguments, - options: ServeOptions, -): boolean => { - const validation = readCliOutputArguments(global).validation; - if (validation.ok) return false; - (options.stdout ?? ((text: string) => process.stdout.write(text)))( - renderCliOutputArgumentError(validation), - ); - (options.exit ?? ((code: number) => process.exit(code)))(1); - return true; -}; - -/** Keep the thrown type, code and exit status; exclude declared literals from text. */ -const withoutDeclaredText = ( - error: unknown, - values: readonly string[], -): unknown => { - const text = (value: string): string => redactExplicitText(value, values); - if (!(error instanceof Error)) { - const description = String(error); - return text(description) === description ? error : text(description); - } - const message = text(error.message); - if (error instanceof Errors.ValidationError) { - // Paths and expectations name the command's own schema. - const fieldErrors = error.fieldErrors.map((field) => ({ - ...field, - received: text(field.received), - message: text(field.message), - })); - return message === error.message && - fieldErrors.every( - (field, index) => - field.received === error.fieldErrors[index]!.received && - field.message === error.fieldErrors[index]!.message, - ) - ? error - : new Errors.ValidationError({ message, fieldErrors }); - } - if (error instanceof Errors.IncurError) { - const hint = error.hint === undefined ? undefined : text(error.hint); - return message === error.message && hint === error.hint - ? error - : new Errors.IncurError({ - code: error.code, - message, - ...(hint === undefined ? {} : { hint }), - retryable: error.retryable, - ...(error.exitCode === undefined ? {} : { exitCode: error.exitCode }), - }); - } - if (message === error.message) return error; - return error instanceof Errors.ParseError - ? new Errors.ParseError({ message }) - : new Error(message); -}; - -/** - * Apply `--sensitive-value` declarations to diagnostics produced before the - * command's own service sees them: rejected output values and the parse, - * validation and thrown failures of every command that accepts the option. - * Diagnostic text is redacted whole; codes, keys and rendering stay intact. - * Returns the serve step; command results keep their own redaction owners. - */ -export const excludeDeclaredSensitiveArguments = ( - cli: CliInstance, -): (( - global: CliGlobalArguments, - options: ServeOptions, - serve: (options: ServeOptions) => Promise, -) => Promise) => { - const declarations = new AsyncLocalStorage(); - const excludeFromFailures: MiddlewareHandler = async (_context, next) => { - const values = declarations.getStore(); - if (values === undefined) return next(); - try { - await next(); - } catch (error) { - throw withoutDeclaredText(error, values); - } - }; - visitRegisteredCommands(cli, (command) => { - if ( - command.options instanceof z.ZodObject && - Object.hasOwn(command.options.shape, OPTION) - ) - // Outside the command middleware, so its failures are covered as well - // as the parsing and run that Incur executes inside the chain. - command.middleware = [excludeFromFailures, ...(command.middleware ?? [])]; - }); - return async (global, options, serve) => { - const values = declaredSensitiveValues(global.command); - if (values.length === 0) return serve(options); - if (reportDeclaredOutputRejection(global, options)) return; - return declarations.run(values, () => serve(options)); - }; -}; diff --git a/src/cli/jsonInputArgument.ts b/src/cli/jsonInputArgument.ts index 3d829e2ef2..685eb51669 100644 --- a/src/cli/jsonInputArgument.ts +++ b/src/cli/jsonInputArgument.ts @@ -59,7 +59,7 @@ export const jsonInputContentSchema = ( return type === "unknown" || type === "any" ? {} : undefined; }; -/** Keep the positional string and attach the document contract Incur can see. */ +/** Keep the positional string and attach the document contract the CLI advertises. */ export const jsonInputArgument = ( description: string, schema: z.ZodType, diff --git a/src/cli/mcpBuiltinCommands.ts b/src/cli/mcpBuiltinCommands.ts index 3640141b4b..95c61dbbed 100644 --- a/src/cli/mcpBuiltinCommands.ts +++ b/src/cli/mcpBuiltinCommands.ts @@ -1,15 +1,8 @@ import { mcpRegistrationOptionsSchema } from "../contracts/mcpRegistration.js"; -import { - adaptCliOutputArgumentsForIncur, - parseCliGlobalArguments, - type CliGlobalArguments, -} from "../cliBuiltinArguments.js"; -import { - readCliOutputArguments, - renderCliDocument, - type CliOutputFormat, -} from "../cliOutput.js"; +import type { CliGlobalArguments } from "../cliBuiltinArguments.js"; +import { readCliOutputArguments, renderCliDocument } from "../cliOutput.js"; +import { jsonLinesErrorRecord } from "./jsonLines.js"; import { renderFailure } from "./outputEnvelope.js"; import { suggestCommand } from "./commandSuggestion.js"; import { unknownCommandReply } from "./unknownCommandReply.js"; @@ -30,7 +23,7 @@ export const MCP_SUBCOMMANDS = new Map([ ["doctor", { description: "Validate MCP server startup and tool listing" }], ]); -/** Incur 0.6.1 builtins that it serves before its `mcp` subcommand branch. */ +/** Global documents take precedence over an unknown MCP subcommand. */ const PRECEDING_BUILTIN_FLAGS: ReadonlySet = new Set([ "--incur-update-check", "--update", @@ -40,12 +33,8 @@ const PRECEDING_BUILTIN_FLAGS: ReadonlySet = new Set([ ]); /** - * Incur 0.6.1 rejects an unknown `mcp` subcommand in TOON regardless of the - * selected format. Report the same document in the explicitly selected format, - * or preserve the default TOON/human presentation. Both paths honor explicit - * sensitive-value declarations before rendering. - * The caller's arguments are read before REA adapts output flags for Incur, - * so the suggested command keeps the caller's selection. + * Report an unknown MCP subcommand through REA's diagnostic renderer, retaining + * caller arguments for suggestions and explicit sensitive-value declarations. */ export const reportUnknownMcpSubcommand = ( name: string, @@ -55,30 +44,22 @@ export const reportUnknownMcpSubcommand = ( const started = performance.now(); const { arguments: arguments_, command } = global; const [entry, subcommand] = command; - // Incur receives JSON for REA's delimited formats and no `--columns`. - const incur = parseCliGlobalArguments( - adaptCliOutputArgumentsForIncur(arguments_), - ); - const incurArguments = incur.arguments; - const incurOutputValues = new Set( - incur.outputValues.map(({ index }) => index), - ); + const outputValues = new Set(global.outputValues.map(({ index }) => index)); if ( entry !== "mcp" || - // Incur shows group help for an empty token and owns flag-shaped globals. + // An empty token shows group help. !subcommand || - subcommand.startsWith("-") || MCP_SUBCOMMANDS.has(subcommand) || - // Incur serves these builtins before its `mcp` subcommand branch. An + // Global documents precede the MCP subcommand branch. An // output flag's value is data, even when it is spelled like a builtin. - incurArguments.some( + arguments_.some( (token, index) => - !incurOutputValues.has(index) && PRECEDING_BUILTIN_FLAGS.has(token), + !outputValues.has(index) && PRECEDING_BUILTIN_FLAGS.has(token), ) ) return false; - const output = readCliOutputArguments(incur); - // Invalid output controls keep Incur's own parse diagnostic. + const output = readCliOutputArguments(global); + // The invocation boundary owns invalid output controls. if (!output.validation.ok) return false; // Preserve the existing explicit-format prefix policy and the default // dispatcher's edit-distance ranking while moving both replies to one owner. @@ -98,12 +79,15 @@ export const reportUnknownMcpSubcommand = ( commandIndex: 1, suggestion, }); + const diagnostic = { ...failure, cta }; + const format = + output.format === "csv" || output.format === "tsv" ? "json" : output.format; (options.stdout ?? ((value: string) => process.stdout.write(value)))( // REA's document renderer owns JSON layout and Markdown escaping. output.formatExplicit ? renderCliDocument( - { ...failure, cta }, - output.format as CliOutputFormat, + format === "jsonl" ? jsonLinesErrorRecord(diagnostic) : diagnostic, + format, process.stdout.isTTY === true, ) : renderFailure( diff --git a/src/cli/mcpRegistration.ts b/src/cli/mcpRegistration.ts index 4c2e8a8afe..dd4d88fdf5 100644 --- a/src/cli/mcpRegistration.ts +++ b/src/cli/mcpRegistration.ts @@ -96,7 +96,7 @@ const precedingFlags = [ "--incur-update-check", ]; -/** Route only the named REA registration operation; other Incur commands remain theirs. */ +/** Route only the named REA registration operation; other builtin commands keep their owners. */ export const serveMcpRegistration = ( global: CliGlobalArguments, environment: Readonly, @@ -186,8 +186,6 @@ const createRegistrationPresentation = ( const handled = await result?.write(value, { command: "mcp add", duration: "0ms", - format: output.format, - forceOutput: true, failure, }); if (!handled) diff --git a/src/cli/omittableDefaults.ts b/src/cli/omittableDefaults.ts index 54897b5ce5..ca32b89b61 100644 --- a/src/cli/omittableDefaults.ts +++ b/src/cli/omittableDefaults.ts @@ -1,23 +1,23 @@ import { z } from "zod"; import type { CliInstance } from "./types.js"; -import { visitRegisteredCommands } from "./visitRegisteredCommands.js"; +import { cliCommands } from "./commandRegistry.js"; type CommandInputs = Partial>; -const INPUT_GROUPS = ["args", "env", "options"] as const; +const INPUT_GROUPS = ["args", "options"] as const; /** * Advertise parser-filled defaults as omittable CLI inputs. * - * Incur derives `--schema`, the `--llms` manifests, and help synopses from + * The CLI derives `--schema`, the `--llms` manifests, and help synopses from * Zod's output view, where a defaulted field always has a value and is * therefore listed as required. Callers may omit such a field, so each one is * wrapped as optional while its default, constraints, metadata, and parsed * value stay unchanged. */ export const presentOmittableDefaults = (cli: CliInstance): void => { - visitRegisteredCommands(cli, (command) => presentInputs(command)); + for (const { definition } of cliCommands(cli)) presentInputs(definition); }; const presentInputs = (command: CommandInputs): void => { @@ -42,7 +42,7 @@ const withOmittableDefaults = (schema: z.ZodObject): z.ZodObject => { return metadata === undefined ? result : result.meta(metadata); }; -/** Let the object parser decide omission; Incur advertises required outputs. */ +/** Let the object parser decide omission; the CLI advertises required outputs. */ const fillsOmission = (field: z.ZodType): boolean => field._zod.optout === undefined && z.object({ value: field }).safeParse({}).success; diff --git a/src/cli/options.ts b/src/cli/options.ts index 95efec333e..212c66ccb2 100644 --- a/src/cli/options.ts +++ b/src/cli/options.ts @@ -28,7 +28,7 @@ const unwrapSchema = (field: { unwrap: () => unknown }): z.ZodType => field.unwrap() as z.ZodType; /** - * Incur advertises Zod's output view. Publish the input view so an argv token + * Command schemas advertise Zod's output view. Publish the input view so an argv token * grammar that transforms text survives `--schema` and other SDK conversions. */ export const publishArgvInput = ( diff --git a/src/cli/outputEnvelope.ts b/src/cli/outputEnvelope.ts index 2e6a483282..c947770434 100644 --- a/src/cli/outputEnvelope.ts +++ b/src/cli/outputEnvelope.ts @@ -23,8 +23,8 @@ */ import { estimateTokenCount, sliceByTokens } from "tokenx"; -import type { CliOutputFormat } from "../cliOutput.js"; -import { formatCliOutput } from "./cliOutputFormatter.js"; +import { renderCliDocument, type CliOutputFormat } from "../cliOutput.js"; +import { jsonLinesErrorRecord } from "./jsonLines.js"; /** Suggested commands that follow a document. */ export interface CallToAction { @@ -56,7 +56,10 @@ const humanError = ({ code, message }: CliFailure): string => `${code === "UNKNOWN" || code === "COMMAND_NOT_FOUND" ? "Error" : `Error (${code})`}: ${message}`; /** A blank line, the description, then each command with its aligned comment. */ -const humanCallToAction = ({ description, commands }: CallToAction): string => { +export const formatCliCallToAction = ({ + description, + commands, +}: CallToAction): string => { const width = Math.max(...commands.map(({ command }) => command.length)); return [ "", @@ -108,16 +111,30 @@ export const renderFailure = ( command, duration, }: { readonly command: string; readonly duration: string }, - cta: CallToAction, + cta: CallToAction | undefined, presentation: EnvelopePresentation, ): string => { const { format } = presentation; - const meta = { command, cta, duration }; + const encode = (value: unknown): string => + renderCliDocument(value, format, process.stdout.isTTY === true).replace( + /\n$/u, + "", + ); + const meta = { command, ...(cta === undefined ? {} : { cta }), duration }; + const bare = cta === undefined ? failure : { ...failure, cta }; + if (format === "jsonl") + return renderCliDocument( + jsonLinesErrorRecord( + presentation.fullOutput ? { ok: false, error: failure, meta } : bare, + ), + "jsonl", + false, + ); if (presentation.tokenCount) { const document = presentation.fullOutput ? { ok: false, error: failure, meta } - : { ...failure, cta }; - return line(String(estimateTokenCount(formatCliOutput(document, format)))); + : bare; + return line(String(estimateTokenCount(encode(document)))); } if ( presentation.human && @@ -125,11 +142,14 @@ export const renderFailure = ( presentation.tokenLimit === undefined && presentation.tokenOffset === undefined ) - return line(humanError(failure)) + line(humanCallToAction(cta)); + return ( + line(humanError(failure)) + + (cta === undefined ? "" : line(formatCliCallToAction(cta))) + ); if (presentation.fullOutput) { - const window = tokenWindow(formatCliOutput(failure, format), presentation); + const window = tokenWindow(encode(failure), presentation); return line( - formatCliOutput( + encode( window.truncated ? { ok: false, @@ -142,12 +162,8 @@ export const renderFailure = ( }, } : { ok: false, error: failure, meta }, - format, ), ); } - return line( - tokenWindow(formatCliOutput({ ...failure, cta }, format), presentation) - .text, - ); + return line(tokenWindow(encode(bare), presentation).text); }; diff --git a/src/cli/runCliCommand.ts b/src/cli/runCliCommand.ts new file mode 100644 index 0000000000..58fbb1ad2f --- /dev/null +++ b/src/cli/runCliCommand.ts @@ -0,0 +1,156 @@ +import { Writable } from "node:stream"; + +import { + declaredSensitiveValues, + type CliGlobalArguments, +} from "../cliBuiltinArguments.js"; +import { + readCliOutputArguments, + renderCliOutputArgumentError, +} from "../cliOutput.js"; +import { PRODUCT_IDENTITY } from "../identity.js"; +import { errorMessage } from "../kernel/errorMessage.js"; +import { + cliArgumentFailure, + redactCliCommandFailure, + renderCliCommandFailure, + type CliCommandFailure, +} from "./argumentErrors.js"; +import { parseCliArgv } from "./argvParser.js"; +import { cliCommand } from "./commandRegistry.js"; +import { withCliEvidencePublication } from "./cliEvidencePublication.js"; +import { + cliResultControls, + withCliResultControls, +} from "./cliResultControls.js"; +import { + createCliResultOutput, + type CliResultOutput, +} from "./cliResultOutput.js"; +import { + availableUpdate, + updateNoticeCta, + type UpdateEnvironment, +} from "./updateNotice.js"; +import type { CliInstance, CliServeOptions } from "./types.js"; + +const writer = (options: CliServeOptions) => + options.stdout ?? + ((text: string) => { + process.stdout.write(text); + }); +const exit = (options: CliServeOptions, code: number) => { + if (options.exit !== undefined) options.exit(code); + else process.exitCode = code; +}; + +/** A callback owns captured output; otherwise the process owns stdout directly. */ +const destinationFor = (options: CliServeOptions): Writable => { + if (options.stdout === undefined) return process.stdout; + const destination = new Writable({ + write(chunk: Buffer, _encoding, done) { + try { + options.stdout!(chunk.toString("utf8")); + done(); + } catch (cause) { + done(cause instanceof Error ? cause : new Error(String(cause))); + } + }, + }); + Object.defineProperty(destination, "isTTY", { + value: process.stdout.isTTY === true, + }); + return destination; +}; + +/** Bind, admit and run one registered command, retaining output/publication ownership. */ +export const runCliCommand = async ( + cli: CliInstance, + global: CliGlobalArguments, + options: CliServeOptions, + environment: UpdateEnvironment, + providedOutput: CliResultOutput | undefined, +): Promise => { + const controls = readCliOutputArguments(global); + if (!controls.validation.ok) { + writer(options)(renderCliOutputArgumentError(controls.validation)); + exit(options, 1); + return; + } + const entry = cliCommand(cli, global.command[0] ?? ""); + if (entry === undefined) { + writer(options)( + "Start REA's MCP server with 'rea mcp' through the public executable.\n", + ); + exit(options, 1); + return; + } + const output = + providedOutput ?? createCliResultOutput(controls, destinationFor(options)); + if (output === undefined) + throw new Error("Admitted CLI output has no output owner"); + output.begin(controls); + const started = performance.now(); + const human = process.stdout.isTTY === true && !controls.formatExplicit; + const update = human + ? availableUpdate(cli.name, PRODUCT_IDENTITY.packageVersion, environment) + : undefined; + const cta = + update === undefined ? undefined : updateNoticeCta(cli.name, update); + const sensitive = + entry.definition.options?.shape.sensitiveValue === undefined + ? [] + : declaredSensitiveValues(global.command); + const report = (failure: CliCommandFailure) => { + writer(options)( + renderCliCommandFailure(redactCliCommandFailure(failure, sensitive), { + cli: cli.name, + entry, + duration: `${Math.round(performance.now() - started)}ms`, + stdoutIsTerminal: process.stdout.isTTY === true, + controls, + cta, + }), + ); + exit(options, 1); + }; + try { + const parsed = parseCliArgv(global.command.slice(1), entry.definition); + if (!parsed.ok) { + report(cliArgumentFailure(cli.name, entry.name, parsed.error)); + return; + } + await withCliEvidencePublication(() => + withCliResultControls(async () => { + const value = await entry.definition.run({ + ...parsed.value, + formatExplicit: controls.formatExplicit, + }); + if (!output.handled) + await output.write(value, { + command: entry.name, + duration: `${Math.round(performance.now() - started)}ms`, + renderOutput: + !human || entry.definition.outputPolicy !== "agent-only", + collectCliControls: cliResultControls, + cta, + }); + }), + ); + if (output.error !== undefined) exit(options, 1); + } catch (cause: unknown) { + // A started or failed destination retains ownership; never write a second + // diagnostic into a partial document or replace a publication receipt. + if (output.handled) throw cause; + report({ + code: "UNKNOWN", + message: errorMessage(cause), + }); + } finally { + if (providedOutput === undefined) await output.finish(); + if (global.timings) + process.stderr.write( + `${JSON.stringify({ rea_timings: { version: 1, command_ms: Math.round(performance.now() - started) } })}\n`, + ); + } +}; diff --git a/src/cli/strictPositionals.ts b/src/cli/strictPositionals.ts deleted file mode 100644 index 09e0d47a96..0000000000 --- a/src/cli/strictPositionals.ts +++ /dev/null @@ -1,144 +0,0 @@ -import { AsyncLocalStorage } from "node:async_hooks"; - -import { Errors } from "incur"; -import { z } from "zod"; - -import type { CliGlobalArguments } from "../cliBuiltinArguments.js"; -import { parseCliArgv } from "./argvParser.js"; -import type { CliInstance } from "./types.js"; -import { visitRegisteredCommands } from "./visitRegisteredCommands.js"; -import { declaredOptionType, isCountOption } from "./optionFields.js"; - -type ServeOptions = NonNullable[1]>; - -/** Preserve flag consumption without evaluating command defaults or transforms. */ -const optionTokenShape = ( - schema: z.ZodObject, - strictDryRun: boolean, -): z.ZodObject => - z.object( - Object.fromEntries( - Object.entries(schema.shape).map(([name, field]) => { - const inner = declaredOptionType(field); - const token = - inner instanceof z.ZodBoolean && !(strictDryRun && name === "dryRun") - ? z.boolean().optional() - : inner instanceof z.ZodArray || (strictDryRun && name === "dryRun") - ? z.array(z.unknown()).optional() - : z.unknown().optional(); - return [ - name, - isCountOption(field) ? token.meta({ count: true }) : token, - ]; - }), - ), - ); - -/** - * Incur 0.6.1 drops unbound positionals and coerces arbitrary boolean text to - * false. Its public parser owns token binding; inert schemas retain the - * unbound tail and every dryRun literal before this lossy conversion. Original - * schemas still own validation, transforms, defaults and actual execution. - */ -export const validateCliArguments = ( - cli: CliInstance, -): (( - global: CliGlobalArguments, - options: ServeOptions, - serve: (options: ServeOptions) => Promise, -) => Promise) => { - const invocation = new AsyncLocalStorage(); - visitRegisteredCommands(cli, (command) => { - const fields = - command.args instanceof z.ZodObject ? command.args.shape : {}; - const entries = Object.entries(fields); - const optionsSchema = - command.options instanceof z.ZodObject ? command.options : undefined; - const dryRunField = optionsSchema?.shape["dryRun"]; - const strictDryRun = - dryRunField !== undefined && - declaredOptionType(dryRunField) instanceof z.ZodBoolean; - const final = entries.at(-1)?.[1]; - const variadic = - final !== undefined && declaredOptionType(final) instanceof z.ZodArray; - // A final array consumes the tail, but must still admit dry-run literals. - if (variadic && !strictDryRun) return; - let tail = "__rea_unbound_positionals"; - while (Object.hasOwn(fields, tail)) tail += "_"; - command.middleware = [ - async (context, next) => { - const tokens = invocation.getStore(); - if (tokens !== undefined) { - // Only the resolved command needs an inert token-binding schema. - // Keep the original schema references, but do not prepare every - // registered command for each one-shot invocation. - const args = z.object({ - ...Object.fromEntries( - entries.map(([name, field]) => [ - name, - declaredOptionType(field) instanceof z.ZodArray - ? z.array(z.unknown()).optional() - : z.unknown().optional(), - ]), - ), - ...(variadic ? {} : { [tail]: z.array(z.string()).optional() }), - }); - const options = - optionsSchema === undefined - ? undefined - : optionTokenShape(optionsSchema, strictDryRun); - // Incur supplies the invoked path, including aliases, after resolving - // groups. No second router decides which command receives the tokens. - const rest = tokens.slice(context.command.split(" ").length); - // Only this preflight copy expands bare booleans. Array binding keeps - // all explicit literals without coercion, including overridden ones. - // Flag-shaped string data still belongs to its consuming option. - const admitted = strictDryRun - ? rest.map((token) => - token === "--dry-run" || token === "--dryRun" - ? "--dry-run=true" - : token === "--no-dry-run" || token === "--no-dryRun" - ? "--dry-run=false" - : token, - ) - : rest; - const bound = parseCliArgv(admitted, { - args, - options, - alias: command.alias as Record | undefined, - }); - // The dispatcher already bound these tokens with the real schemas, - // so a refusal here is reported as the dispatcher reports its own. - if (!bound.ok) - throw bound.error.kind === "parse" - ? new Errors.ParseError({ message: bound.error.message }) - : new Errors.ValidationError({ - message: bound.error.message, - fieldErrors: [...bound.error.fieldErrors], - }); - const parsed = bound.value; - const dryRunValues: unknown = - "dryRun" in parsed.options ? parsed.options.dryRun : undefined; - if ( - strictDryRun && - Array.isArray(dryRunValues) && - dryRunValues.some((value) => value !== "true" && value !== "false") - ) - throw new Errors.IncurError({ - code: "PARSE_ERROR", - message: "Invalid --dry-run value; use true or false.", - }); - const surplus: unknown = parsed.args[tail]; - if (Array.isArray(surplus) && surplus.length > 0) - throw new Errors.ParseError({ - message: `Unexpected positional arguments: ${surplus.map((value) => JSON.stringify(value)).join(" ")}. Use '${context.displayName} ${context.command} --help' for the declared argument shape.`, - }); - } - await next(); - }, - ...(command.middleware ?? []), - ]; - }); - return (global, options, serve) => - invocation.run(global.command, () => serve(options)); -}; diff --git a/src/cli/types.ts b/src/cli/types.ts index 4406eb9226..342c59b325 100644 --- a/src/cli/types.ts +++ b/src/cli/types.ts @@ -1,3 +1,16 @@ -import type { Cli } from "incur"; +/** Output and status surfaces selected by the invocation's process owner. */ +export interface CliServeOptions { + readonly stdout?: ((text: string) => void) | undefined; + readonly exit?: ((code: number) => void) | undefined; + /** Retained for in-process callers; command environment is selected at composition. */ + readonly env?: Readonly> | undefined; +} -export type CliInstance = ReturnType; +/** REA's flat command registry and its one-shot invocation boundary. */ +export interface CliInstance { + readonly name: string; + serve( + arguments_?: readonly string[], + options?: CliServeOptions, + ): Promise; +} diff --git a/src/cli/visitRegisteredCommands.ts b/src/cli/visitRegisteredCommands.ts deleted file mode 100644 index efe7989e8f..0000000000 --- a/src/cli/visitRegisteredCommands.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { Cli } from "incur"; - -import type { CliInstance } from "./types.js"; - -type CommandMap = NonNullable>; -type CommandEntry = CommandMap extends Map ? Entry : never; -export type RegisteredCommand = Extract; -type OutputPolicy = "all" | "agent-only"; - -// Incur types its router key without vars, env, or globals; accept any CLI. -const registeredCommands: WeakMap = Cli.toCommands; - -/** Visit ordinary commands in map order, children before each group's root. */ -export const visitRegisteredCommands = ( - cli: CliInstance, - visit: ( - command: RegisteredCommand, - path: string, - outputPolicy: OutputPolicy | undefined, - ) => void, -): void => { - const commands = registeredCommands.get(cli); - if (commands !== undefined) visitCommands(commands, [], undefined, visit); -}; - -const visitCommands = ( - commands: CommandMap, - parents: readonly string[], - inheritedPolicy: OutputPolicy | undefined, - visit: ( - command: RegisteredCommand, - path: string, - outputPolicy: OutputPolicy | undefined, - ) => void, -): void => { - for (const [name, entry] of commands) { - const path = [...parents, name]; - if ("_group" in entry) { - const policy = entry.outputPolicy ?? inheritedPolicy; - visitCommands(entry.commands, path, policy, visit); - if (entry.root !== undefined) - visit(entry.root, path.join(" "), entry.root.outputPolicy ?? policy); - } else if (!("_alias" in entry) && !("_fetch" in entry)) { - visit(entry, path.join(" "), entry.outputPolicy ?? inheritedPolicy); - } - } -}; diff --git a/src/cliBuiltinArguments.ts b/src/cliBuiltinArguments.ts index acff2cc8f7..440f0793aa 100644 --- a/src/cliBuiltinArguments.ts +++ b/src/cliBuiltinArguments.ts @@ -172,36 +172,6 @@ export const parseCliGlobalArguments = ( }; }; -/** Keep REA-owned delimited formats out of Incur's narrower formatter surface. */ -export const adaptCliOutputArgumentsForIncur = ( - arguments_: readonly string[], -): string[] => { - const adapted: string[] = []; - for (let index = 0; index < arguments_.length; index += 1) { - const argument = arguments_[index]!; - const value = arguments_[index + 1]; - if (VALUED_OUTPUT_FLAGS.has(argument)) { - if (argument === "--columns") { - if (value !== undefined) index += 1; - continue; - } - if (argument === "--format" && (value === "csv" || value === "tsv")) { - adapted.push("--format", "json"); - index += 1; - continue; - } - adapted.push(argument); - if (value) { - adapted.push(value); - index += 1; - } - continue; - } - adapted.push(argument); - } - return adapted; -}; - type McpAddArgumentError = | { readonly kind: "missing_value"; diff --git a/src/cliOneShot.ts b/src/cliOneShot.ts index bae4b455fb..47666bb33b 100644 --- a/src/cliOneShot.ts +++ b/src/cliOneShot.ts @@ -38,9 +38,9 @@ export interface OneShotCliHost { ownCliResources(close: () => Promise): void; /** * The command asked to end the process with `code`. The host owns that - * exit and must call `finishOutput` with the status it reports. + * exit and must drain `finishOutput` after closing the owned resources. */ - exit(code: number, finishOutput: (status: number) => Promise): void; + exit(code: number, finishOutput: () => Promise): void; /** Whether `exit` has run. Its host then owns the pending result write. */ exitRequested(): boolean; } @@ -69,7 +69,7 @@ export const runOneShotCli = async ( : readCliOutputArguments(global); const outputArguments = outputOptions.validation; // `--version` with an explicit format reports the runtime as a document; - // plain `--version` stays Incur's bare version string. + // plain `--version` stays a bare version string. const versionOutput = renderVersionReport( outputOptions, host.runtime, @@ -141,12 +141,11 @@ export const runOneShotCli = async ( return; } if (output.length > 0) wroteOutput = true; - if (resultOutput?.captureSdkOutput(output)) return; host.writeStdout(output); }, exit: (code) => { - host.exit(typeof code === "number" ? code : 0, async (status) => - resultOutput?.finishSdkOutput(status), + host.exit(typeof code === "number" ? code : 0, async () => + resultOutput?.finish(), ); }, }); @@ -155,7 +154,7 @@ export const runOneShotCli = async ( const recovered = await resultOutput ?.recoverFormattingFailure(cause) .catch((writeFailure: unknown) => { - // Recovery writes outside Incur's command boundary. A reader that + // Recovery writes outside the command boundary. A reader that // declined this document keeps the same quiet closed-pipe outcome. if (!host.stdoutClosed()) throw writeFailure; return true; @@ -166,6 +165,5 @@ export const runOneShotCli = async ( if (!wroteOutput && !resultOutput?.handled) host.writeStdout(renderEmptyFilteredCliOutput(outputOptions) ?? ""); // A requested exit is finished by the host, which owns its pending write. - if (!host.exitRequested()) - await resultOutput?.finishSdkOutput(host.exitCode()); + if (!host.exitRequested()) await resultOutput?.finish(); }; diff --git a/tests/acceptance/cliBuiltinDocumentTokens.test.ts b/tests/acceptance/cliBuiltinDocumentTokens.test.ts index 97669593ab..61c27bf2f5 100644 --- a/tests/acceptance/cliBuiltinDocumentTokens.test.ts +++ b/tests/acceptance/cliBuiltinDocumentTokens.test.ts @@ -4,7 +4,7 @@ import { expect } from "vitest"; import { workspaceCliTest } from "../support/cli/workspaceCliFixture.js"; workspaceCliTest( - "applies token controls to SDK manifest and schema documents", + "applies token controls to manifest and schema documents", async ({ cli }) => { const run = async (...arguments_: string[]) => { const invocation = { arguments: arguments_ }; @@ -47,7 +47,7 @@ workspaceCliTest( await run("inspect-devicetree", "--schema", "--token-limit", "1"), ).toMatch(/\[truncated: showing tokens 0–1 of \d+\]\n$/); - // Schema does not outrank help or plain version in Incur's dispatch. + // Schema does not outrank help or plain version in CLI dispatch. expect( await run("inspect-devicetree", "--schema", "--help", "--token-count"), ).toBe(await run("inspect-devicetree", "--schema", "--help")); @@ -58,6 +58,13 @@ workspaceCliTest( await run("completions", "bash", "--schema"), ); + expect(await run("completions", "bash", "--json", "--token-count")).toBe( + await run("completions", "bash", "--json"), + ); + const bash = await run("completions", "bash"); + expect(await run("completions", "bash", "--schema")).toBe(bash); + expect(await run("completions", "bash", "--version")).toBe(bash); + const unknown = await cli.run({ arguments: ["no-such-command", "--schema"], }); diff --git a/tests/acceptance/cliTerminalNotices.test.ts b/tests/acceptance/cliTerminalNotices.test.ts new file mode 100644 index 0000000000..71a6aaea74 --- /dev/null +++ b/tests/acceptance/cliTerminalNotices.test.ts @@ -0,0 +1,56 @@ +import { expect } from "vitest"; + +import { PRODUCT_IDENTITY } from "../../src/identity.js"; +import { workspaceCliTest } from "../support/cli/workspaceCliFixture.js"; + +workspaceCliTest.skipIf(process.platform === "win32")( + "keeps terminal update notices outside selected result documents", + async ({ cli, workspace }) => { + await workspace.write("sample.bin", Buffer.from("notice fixture")); + await workspace.write( + `cache/incur/updates/${PRODUCT_IDENTITY.packageName}.json`, + JSON.stringify({ checkedAt: Date.now(), latest: "999.0.0" }), + ); + const environment = { + ...workspace.environment, + XDG_CACHE_HOME: workspace.path("cache"), + npm_config_registry: "http://127.0.0.1:9/", + }; + const run = async ( + arguments_: readonly string[], + stderrContains?: string, + ) => { + const result = await cli.run({ + arguments: arguments_, + cwd: workspace.root, + environment, + terminal: true, + }); + expect(result.exitCode, result.stderr).toBe(0); + if (stderrContains === undefined) expect(result.stderr).toBe(""); + else expect(result.stderr).toContain(stderrContains); + return result.stdout; + }; + const entropy = ["inspect-byte-entropy", workspace.path("sample.bin")]; + const notice = "Update available for rea-agents:"; + expect(await run(entropy)).toContain(notice); + expect(await run([...entropy, "--full-output"])).toContain(notice); + for (const flags of [[], ["--full-output"], ["--token-limit", "10"]]) { + const output = await run([ + ...entropy, + "--filter-output", + "normalized_result.window", + ...flags, + ]); + expect(output).toContain("offset"); + expect(output).not.toContain(notice); + } + // Suppressed agent-only output leaves the terminal notice visible. + expect( + await run( + ["setup", "--dry-run", "--client", "codex", "--token-limit", "1"], + "Dry run complete. No changes were made.", + ), + ).toContain(notice); + }, +); diff --git a/tests/acceptance/setup/updateAliasCli.test.ts b/tests/acceptance/setup/updateAliasCli.test.ts index f4ba6bf367..d1d7e2966b 100644 --- a/tests/acceptance/setup/updateAliasCli.test.ts +++ b/tests/acceptance/setup/updateAliasCli.test.ts @@ -103,6 +103,25 @@ cliTest( data: "current", meta: { command: expect.stringContaining("update") }, }); + let canonicalJsonl: string | undefined; + for (const arguments_ of [ + ["update", "--format", "jsonl"], + ["--format", "jsonl", "--update"], + ]) { + const result = await run(arguments_); + expect(result.exitCode, result.stderr).toBe(1); + expect(JSON.parse(result.stdout)).toMatchObject({ + $rea: "jsonl/v1", + type: "error", + ok: false, + result: { + code: "invalid_request", + remediation: { action: expect.stringContaining("--format json") }, + }, + }); + if (canonicalJsonl === undefined) canonicalJsonl = result.stdout; + else expect(result.stdout).toBe(canonicalJsonl); + } const failed = await run(["--update", "--json"], true); expect(failed.exitCode).toBe(1); expect(failed.json).toMatchObject({ diff --git a/tests/boundary/captures/captureProvider.test.ts b/tests/boundary/captures/captureProvider.test.ts index 1c86d82950..864bca660c 100644 --- a/tests/boundary/captures/captureProvider.test.ts +++ b/tests/boundary/captures/captureProvider.test.ts @@ -1,3 +1,4 @@ +import { createCommandCli } from "../../support/cli/commandCli.js"; import { spawnFailure } from "../../support/process/spawnFailure.js"; import { AnalysisResourceConstraintError } from "../../../src/domain/analysisErrorCore.js"; import { packetFieldsCatalogSchema } from "../../../src/domain/captures/packetFields.js"; @@ -13,7 +14,6 @@ import { PrivateRuntimeRoot } from "../../../src/process/PrivateRuntimeRoot.js"; import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { createDeferred } from "../../fixtures/binarySession.js"; -import { Cli } from "incur"; import { registerCaptureCommands } from "../../../src/cli/captureCommands.js"; import { silentLogger } from "../../../src/logger.js"; import { analysisErrorRemediationAction } from "../../../src/domain/analysisErrorPresentation.js"; @@ -236,7 +236,7 @@ it("recovers the same capture with CLI producer budgets and retains a tighter in expect(analysisErrorRemediationAction(refused.error)).toContain( "producer_limits.input_bytes", ); - const cli = Cli.create("capture-producer-budget", { sync: false }); + const cli = createCommandCli(); registerCaptureCommands(cli, silentLogger, {}, f.service); let stdout = ""; await cli.serve( @@ -348,7 +348,7 @@ it("refuses producer frames outside the selected input read scope before paging" it("returns canonical alias output through the public packet-capture CLI", async () => { const f = await fixture("alias-canonical"); - const cli = Cli.create("capture-alias-test", { sync: false }); + const cli = createCommandCli(); registerCaptureCommands(cli, silentLogger, {}, f.service); let stdout = ""; await cli.serve( @@ -1044,7 +1044,7 @@ it("retains completed discovery on late cancellation and cleanup failure", async it("preserves discovery resource ownership through CLI shutdown retries", async () => { const f = await fixture("cleanup", true); - const cli = Cli.create("discovery-cleanup", { sync: false }); + const cli = createCommandCli(); registerCaptureCommands(cli, silentLogger, {}, f.service); let stdout = ""; try { diff --git a/tests/boundary/cli/analyzeFunctionDetail.test.ts b/tests/boundary/cli/analyzeFunctionDetail.test.ts index c1aa0469f8..b327198e60 100644 --- a/tests/boundary/cli/analyzeFunctionDetail.test.ts +++ b/tests/boundary/cli/analyzeFunctionDetail.test.ts @@ -1,8 +1,10 @@ -import { Cli } from "incur"; +import { cliCommand } from "../../../src/cli/commandRegistry.js"; +import { createCommandCli } from "../../support/cli/commandCli.js"; import pino from "pino"; import { stat } from "node:fs/promises"; import { join } from "node:path"; import { expect, it, vi } from "vitest"; +import { z } from "zod"; import { inspectAnalysisView } from "../../../src/application/analysisView/AnalysisViewService.js"; import { registerCoreBinaryCommands } from "../../../src/cli/coreBinaryCommands.js"; @@ -32,28 +34,31 @@ const harness = () => { const runDirectAnalysis = vi.fn< Parameters[2] >(async () => ok(cannedCompleteEvidence())); - const cli = Cli.create("rea-fn-detail-test", { version: "1", sync: false }); + const cli = createCommandCli(); registerCoreBinaryCommands( cli as unknown as CliInstance, pino({ enabled: false }), runDirectAnalysis, {}, ); - const command = Cli.toCommands.get(cli)?.get(CLI_COMMANDS.function); + const command = cliCommand(cli, CLI_COMMANDS.function)?.definition; if (command === undefined) throw new Error("function command was not registered"); - const argsSchema = Reflect.get(command, "args"); - const optionsSchema = Reflect.get(command, "options"); - const execute = Reflect.get(command, "run"); - if (typeof execute !== "function") - throw new Error("function command has no run callback"); - const invoke = (options: Record): Promise => - execute({ - args: (argsSchema as { parse(v: unknown): unknown }).parse({ + const argsSchema = command.args; + const optionsSchema = command.options; + if ( + !(argsSchema instanceof z.ZodObject) || + !(optionsSchema instanceof z.ZodObject) + ) + throw new Error("function command has no input schemas"); + const invoke = async (options: Record): Promise => + command.run({ + args: argsSchema.parse({ path: "/fixtures/native.exe", address: "main", }), - options: (optionsSchema as { parse(v: unknown): unknown }).parse(options), + options: optionsSchema.parse(options), + formatExplicit: false, }); return { runDirectAnalysis, invoke }; }; diff --git a/tests/boundary/cli/argvParser.test.ts b/tests/boundary/cli/argvParser.test.ts index c8e09df5a1..3bdc7a3a4d 100644 --- a/tests/boundary/cli/argvParser.test.ts +++ b/tests/boundary/cli/argvParser.test.ts @@ -79,7 +79,7 @@ describe("parseCliArgv", () => { it("reports schema failures as field errors", () => { // Positionals are validated first, so the missing path is reported alone. - expect(failure(["--block-size", "abc", "--mode", "c"])).toEqual({ + expect(failure(["--block-size", "abc", "--mode", "c"])).toMatchObject({ kind: "validation", message: "Invalid input: expected string, received undefined", fieldErrors: [ @@ -94,7 +94,9 @@ describe("parseCliArgv", () => { ], }); // Captured from incur 0.6.1's Parser.parse with the same schema and argv. - expect(failure(["file", "--block-size", "abc", "--mode", "c"])).toEqual({ + expect( + failure(["file", "--block-size", "abc", "--mode", "c"]), + ).toMatchObject({ kind: "validation", message: 'Invalid input: expected number, received NaN; Invalid option: expected one of "a"|"b"', diff --git a/tests/boundary/cli/browserScenarioSummaryCli.test.ts b/tests/boundary/cli/browserScenarioSummaryCli.test.ts index 2a184d616a..e2a042830b 100644 --- a/tests/boundary/cli/browserScenarioSummaryCli.test.ts +++ b/tests/boundary/cli/browserScenarioSummaryCli.test.ts @@ -1,6 +1,6 @@ +import { createCommandCli } from "../../support/cli/commandCli.js"; import { access } from "node:fs/promises"; import { join } from "node:path"; -import { Cli } from "incur"; import pino from "pino"; import { expect, it } from "vitest"; @@ -33,7 +33,7 @@ it.each([false, true])( ); }, ); - const cli = Cli.create("rea-browser-startup-cleanup-test", { sync: false }); + const cli = createCommandCli(); let stdout = ""; registerBrowserScenarioCommands( cli, @@ -101,7 +101,7 @@ it.each(["complete", "summary"] as const)( const destination = join(root, "evidence.json"); const originalExit = process.exitCode; const listeners = new Set(process.listeners("SIGINT")); - const cli = Cli.create("rea-browser-summary-test", { sync: false }); + const cli = createCommandCli(); let stdout = ""; let closed = false; registerBrowserScenarioCommands( @@ -173,7 +173,7 @@ it.each(["complete", "summary"] as const)( it("keeps the provider's cleanup failure and completed Evidence without publishing a summary bundle", async () => { const root = await createTestTempDirectory("rea-browser-summary-cleanup-"); const destination = join(root, "evidence.json"); - const cli = Cli.create("rea-browser-cleanup-test", { sync: false }); + const cli = createCommandCli(); let stdout = ""; const failure = new ProviderCleanupError( "owned-browser", diff --git a/tests/boundary/cli/browserScenarioValidation.test.ts b/tests/boundary/cli/browserScenarioValidation.test.ts index b318a39845..f4da0575ad 100644 --- a/tests/boundary/cli/browserScenarioValidation.test.ts +++ b/tests/boundary/cli/browserScenarioValidation.test.ts @@ -1,7 +1,7 @@ +import { createCommandCli } from "../../support/cli/commandCli.js"; import { writeFile } from "node:fs/promises"; import { join } from "node:path"; -import { Cli } from "incur"; import pino from "pino"; import { expect, it, vi } from "vitest"; @@ -30,7 +30,7 @@ const serveJson = async ( /** Register only the scenario commands, with a provider that must never run. */ const registerValidatingCli = () => { - const cli = Cli.create("rea-scenario-validation-test", { sync: false }); + const cli = createCommandCli(); const createProvider = vi.fn((): never => { throw new Error("validation must not construct a browser provider"); }); diff --git a/tests/boundary/cli/captureCleanup.test.ts b/tests/boundary/cli/captureCleanup.test.ts index 1e28f280e2..50bc492ca2 100644 --- a/tests/boundary/cli/captureCleanup.test.ts +++ b/tests/boundary/cli/captureCleanup.test.ts @@ -1,5 +1,5 @@ +import { createCommandCli } from "../../support/cli/commandCli.js"; import { unknownTarget } from "../../../src/domain/targetIdentity.js"; -import { Cli } from "incur"; import { expect, it } from "vitest"; import { registerCaptureCommands } from "../../../src/cli/captureCommands.js"; import { silentLogger } from "../../../src/logger.js"; @@ -28,7 +28,7 @@ it.each([false, true])( { operation: "inspect_packet_capture", partialObservation: evidence }, ); let closed = false; - const cli = Cli.create("capture-cleanup-test", { sync: false }); + const cli = createCommandCli(); registerCaptureCommands( cli, silentLogger, @@ -85,7 +85,7 @@ it.each([false, true])( ); it("keeps the primary CLI failure when close throws an untyped error", async () => { - const cli = Cli.create("capture-cleanup-primary-test", { sync: false }); + const cli = createCommandCli(); registerCaptureCommands( cli, silentLogger, @@ -135,7 +135,7 @@ it("keeps the primary CLI failure when close throws an untyped error", async () }); it("closes the service and retains an unexpected producer rejection", async () => { - const cli = Cli.create("capture-producer-rejection-test", { sync: false }); + const cli = createCommandCli(); let closed = false; registerCaptureCommands( cli, @@ -194,7 +194,7 @@ const rejectBeforeService = async ( name: string, args: string[], ): Promise => { - const cli = Cli.create(name, { sync: false }); + const cli = createCommandCli(); let called = false; registerCaptureCommands( cli, diff --git a/tests/boundary/cli/cliCommandRegistry.test.ts b/tests/boundary/cli/cliCommandRegistry.test.ts index 2e7e6970a9..8b8cffdc05 100644 --- a/tests/boundary/cli/cliCommandRegistry.test.ts +++ b/tests/boundary/cli/cliCommandRegistry.test.ts @@ -2,7 +2,6 @@ import { describe, expect, it } from "vitest"; import { createCli } from "../../../src/cli.js"; import { cliCommands } from "../../../src/cli/commandRegistry.js"; -import { visitRegisteredCommands } from "../../../src/cli/visitRegisteredCommands.js"; const cli = createCli({}); const entries = cliCommands(cli); @@ -13,19 +12,6 @@ const entry = (name: string) => { }; describe("REA's CLI command table", () => { - it("holds every dispatched command, in registration order, with the served definition", () => { - const dispatched: { path: string; command: object }[] = []; - visitRegisteredCommands(cli, (command, path) => - dispatched.push({ path, command }), - ); - expect(entries.map(({ name }) => name)).toEqual( - dispatched.map(({ path }) => path), - ); - // Shell owners rewrite inputs and handlers in place; the table sees them. - for (const [index, { command }] of dispatched.entries()) - expect(entries[index]!.definition).toBe(command); - }); - it("names the operations a direct-analysis command runs and the flag of each field", () => { expect(entry("function").operations).toEqual([ { name: "analyze_function", flags: expect.any(Object) }, diff --git a/tests/boundary/cli/cliContractCommandParity.test.ts b/tests/boundary/cli/cliContractCommandParity.test.ts index e483d5ede9..3731de4173 100644 --- a/tests/boundary/cli/cliContractCommandParity.test.ts +++ b/tests/boundary/cli/cliContractCommandParity.test.ts @@ -1,4 +1,4 @@ -import { Parser } from "incur"; +import { parseCliArgv } from "../../../src/cli/argvParser.js"; import { z } from "zod"; import { describe, expect, it } from "vitest"; @@ -21,9 +21,9 @@ import { } from "../../../src/cli/contractCommand.js"; import { jsonInputContentSchema } from "../../../src/cli/jsonInputArgument.js"; import { - visitRegisteredCommands, - type RegisteredCommand, -} from "../../../src/cli/visitRegisteredCommands.js"; + cliCommands, + type CliCommandEntry, +} from "../../../src/cli/commandRegistry.js"; import { absoluteCallerPath } from "../../../src/filesystem/callerPath.js"; import { presentRootDiscriminator } from "../../../src/domain/schemaAnnotations.js"; import { @@ -34,8 +34,8 @@ import { const DECIMAL_TOKEN = /^[0-9]+$/u; const cli = createCli({}); -const registered = new Map(); -visitRegisteredCommands(cli, (command, path) => { +const registered = new Map(); +cliCommands(cli).forEach(({ definition: command, name: path }) => { registered.set(path, command); }); // A routed command contributes one description per contract it runs. @@ -588,8 +588,9 @@ describe("CLI commands projected from tool contracts", () => { [parameter.key]: registeredField(description, parameter), }); const flag = `--${parameter.key.replaceAll(/[A-Z]/gu, (c) => `-${c.toLowerCase()}`)}`; - expect(Parser.parse([flag], { options }).options, flag).toEqual({ - [parameter.key]: true, + expect(parseCliArgv([flag], { options }), flag).toMatchObject({ + ok: true, + value: { options: { [parameter.key]: true } }, }); } }, diff --git a/tests/boundary/cli/cliContractSchemaParity.test.ts b/tests/boundary/cli/cliContractSchemaParity.test.ts index 6e89379f99..1134a2722c 100644 --- a/tests/boundary/cli/cliContractSchemaParity.test.ts +++ b/tests/boundary/cli/cliContractSchemaParity.test.ts @@ -1,5 +1,5 @@ import { readFileSync } from "node:fs"; -import { Cli } from "incur"; +import { cliCommands } from "../../../src/cli/commandRegistry.js"; import { describe, expect, it } from "vitest"; import { z } from "zod"; @@ -175,10 +175,7 @@ const cliAdmittedValue = ( const collectParity = () => { const cli = createCli(); - const commands = Cli.toCommands.get( - cli as unknown as Parameters[0], - ); - if (commands === undefined) throw new Error("No CLI commands registered"); + const commands = cliCommands(cli); const contracts = new Map( TOOL_CONTRACTS.map((contract) => [contract.name, contract.inputSchema]), ); @@ -187,8 +184,7 @@ const collectParity = () => { let compared = 0; let commandsCompared = 0; let unmatchedFields = 0; - for (const [name, entry] of commands) { - if ("_alias" in entry) continue; + for (const { name, definition: entry } of commands) { const contractNames: readonly string[] = CLI_COMMAND_TOOL_ALIASES[ name as keyof typeof CLI_COMMAND_TOOL_ALIASES ] ?? [snake(name)]; diff --git a/tests/boundary/cli/cliControlFlag.test.ts b/tests/boundary/cli/cliControlFlag.test.ts index 37258037fd..7aa5a85350 100644 --- a/tests/boundary/cli/cliControlFlag.test.ts +++ b/tests/boundary/cli/cliControlFlag.test.ts @@ -1,4 +1,5 @@ -import { Cli } from "incur"; +import { cliCommand } from "../../../src/cli/commandRegistry.js"; +import { createCommandCli } from "../../support/cli/commandCli.js"; import { expect, it } from "vitest"; import { z } from "zod"; @@ -42,7 +43,7 @@ it("names the service's per-call control by field over MCP and by flag on the CL expect(mcp.details?.limit).not.toHaveProperty("cli_flag"); expect(JSON.stringify(mcp)).not.toContain("--"); - const cli = Cli.create("rea-control-flag", { version: "1", sync: false }); + const cli = createCommandCli(); registerContractCommand( cli as unknown as CliInstance, silentLogger, @@ -54,7 +55,7 @@ it("names the service's per-call control by field over MCP and by flag on the CL }, async () => deadlineFailure(), ); - const command = Cli.toCommands.get(cli)?.get("inspect-control-fixture"); + const command = cliCommand(cli, "inspect-control-fixture")?.definition; if (command === undefined) throw new Error("command is not registered"); const parse = (key: "args" | "options", value: unknown) => (Reflect.get(command, key) as { parse(v: unknown): unknown }).parse(value); diff --git a/tests/boundary/cli/cliDecimalArguments.test.ts b/tests/boundary/cli/cliDecimalArguments.test.ts index 77db5b4aa1..ba7d865721 100644 --- a/tests/boundary/cli/cliDecimalArguments.test.ts +++ b/tests/boundary/cli/cliDecimalArguments.test.ts @@ -1,10 +1,11 @@ import { Ajv2020 } from "ajv/dist/2020.js"; -import { Parser, Schema } from "incur"; +import { parseCliArgv } from "../../../src/cli/argvParser.js"; import { z } from "zod"; import { describe, expect, it } from "vitest"; import { createCli } from "../../../src/cli.js"; -import { visitRegisteredCommands } from "../../../src/cli/visitRegisteredCommands.js"; +import { cliCommands } from "../../../src/cli/commandRegistry.js"; +import { commandInputJsonSchema } from "../../../src/cli/commandManifests.js"; const NON_DECIMAL = ["0x10", "1e3"] as const; @@ -85,11 +86,11 @@ describe("decimal integer CLI admission", () => { const ajv = new Ajv2020({ strict: false, allErrors: true }); const failures: string[] = []; const checked: string[] = []; - visitRegisteredCommands(cli, (command, path) => { + cliCommands(cli).forEach(({ definition: command, name: path }) => { for (const group of ["args", "options"] as const) { const parser = command[group]; if (!(parser instanceof z.ZodObject)) continue; - const advertised = Schema.toJsonSchema(parser); + const advertised = commandInputJsonSchema(parser); if (!isRecord(advertised) || !isRecord(advertised.properties)) continue; for (const [name, property] of Object.entries(advertised.properties)) { const field = parser.shape[name]; @@ -107,10 +108,13 @@ describe("decimal integer CLI admission", () => { const read = (token: string): unknown => { const parsed = group === "options" - ? Parser.parse([flagName(name), token], { options: isolated }) - .options[name] - : Parser.parse([token], { args: isolated }).args[name]; - return repeated && Array.isArray(parsed) ? parsed[0] : parsed; + ? parseCliArgv([flagName(name), token], { options: isolated }) + : parseCliArgv([token], { args: isolated }); + if (!parsed.ok) throw new Error(parsed.error.message); + const value = ( + group === "options" ? parsed.value.options : parsed.value.args + )[name]; + return repeated && Array.isArray(value) ? value[0] : value; }; const readsNumber = (token: string): boolean => { try { @@ -138,7 +142,7 @@ describe("decimal integer CLI admission", () => { for (const token of NON_DECIMAL) { try { read(token); - failures.push(`${label}: Parser.parse accepts ${token}`); + failures.push(`${label}: CLI parser accepts ${token}`); } catch { // Decimal tokens are the only numeric spelling. } diff --git a/tests/boundary/cli/cliDomainFieldSchema.test.ts b/tests/boundary/cli/cliDomainFieldSchema.test.ts index e06d74a24f..e089c4010a 100644 --- a/tests/boundary/cli/cliDomainFieldSchema.test.ts +++ b/tests/boundary/cli/cliDomainFieldSchema.test.ts @@ -1,15 +1,12 @@ +import { cliCommand } from "../../../src/cli/commandRegistry.js"; import { Ajv2020 } from "ajv/dist/2020.js"; import type { AnySchema } from "ajv"; -import { Cli } from "incur"; import { z } from "zod"; import { expect, it } from "vitest"; import { createCli } from "../../../src/cli.js"; type CliInstance = ReturnType; -type CommandMap = NonNullable>; - -const registeredCommands: WeakMap = Cli.toCommands; const serve = async (cli: CliInstance, argv: readonly string[]) => { let stdout = ""; @@ -157,7 +154,7 @@ it("advertises the domain constraints for android, adb settings, and browser sel }), ).toBe(true); - const parser = registeredCommands.get(cli)?.get("inspect-android-class"); + const parser = cliCommand(cli, "inspect-android-class")?.definition; expect(parser && "args" in parser && parser.args instanceof z.ZodObject).toBe( true, ); diff --git a/tests/boundary/cli/cliFullOutputTokenCount.test.ts b/tests/boundary/cli/cliFullOutputTokenCount.test.ts index 38dda1f83e..e2c93a0f64 100644 --- a/tests/boundary/cli/cliFullOutputTokenCount.test.ts +++ b/tests/boundary/cli/cliFullOutputTokenCount.test.ts @@ -10,6 +10,7 @@ import { createCliResultOutput } from "../../../src/cli/cliResultOutput.js"; const countFor = async ( value: unknown, format: "toon" | "yaml", + notice = false, ): Promise<{ readonly handled: boolean; readonly text: string }> => { const chunks: Buffer[] = []; const destination = new Writable({ @@ -32,17 +33,28 @@ const countFor = async ( const handled = await output.write(value, { command: "fixture", duration: "0ms", - format, + ...(notice + ? { + cta: { + description: "Update available", + commands: [{ command: "rea --update" }], + }, + } + : {}), }); return { handled, text: Buffer.concat(chunks).toString("utf8") }; }; -describe("full-output token counts for delegated formats", () => { - it.each(["toon", "yaml"] as const)( - "counts the emitted envelope, not just the selected data (%s)", - async (format) => { +describe("full-output token counts", () => { + it.each( + (["toon", "yaml"] as const).flatMap((format) => + [false, true].map((notice) => ({ format, notice })), + ), + )( + "counts the emitted envelope without a terminal notice ($format, notice: $notice)", + async ({ format, notice }) => { const value = { imported: 0, unknowns_added: 0, total: 0 }; - const counted = await countFor(value, format); + const counted = await countFor(value, format, notice); expect(counted.handled).toBe(true); expect(counted.text).toBe( `${estimateTokenCount( @@ -59,7 +71,5 @@ describe("full-output token counts for delegated formats", () => { }, ); - // Bare counts stay delegated to Incur and are covered by the CLI replay - // (bare toon/yaml report the selected result before and after this fix); - // this boundary owns only the full-output envelope count. + // The public CLI replay also covers bare counts for these formats. }); diff --git a/tests/boundary/cli/cliInputSchemaRequired.test.ts b/tests/boundary/cli/cliInputSchemaRequired.test.ts index ab91308c18..367c739567 100644 --- a/tests/boundary/cli/cliInputSchemaRequired.test.ts +++ b/tests/boundary/cli/cliInputSchemaRequired.test.ts @@ -1,11 +1,15 @@ +import { + cliCommand, + registerCliCommand, + cliCommands, +} from "../../../src/cli/commandRegistry.js"; +import { createCommandCli } from "../../support/cli/commandCli.js"; import { Ajv2020 } from "ajv/dist/2020.js"; -import { Cli } from "incur"; import { z } from "zod"; import { resolve } from "node:path"; import { describe, expect, it, vi } from "vitest"; import { createCli } from "../../../src/cli.js"; -import { cliCommands } from "../../../src/cli/commandRegistry.js"; import { createCliInventory } from "../../../scripts/lib/catalog-cli.mjs"; import { registerAdbCommands } from "../../../src/cli/adbCommands.js"; import { AnalysisInputError } from "../../../src/domain/analysisErrorCore.js"; @@ -20,10 +24,8 @@ import { presentOmittableDefaults } from "../../../src/cli/omittableDefaults.js" import { dataTypeSelectorGuidance } from "../../../src/cli/analysisSelector.js"; type CliInstance = ReturnType; -type CommandMap = NonNullable>; const INPUT_GROUPS = ["args", "options"] as const; -const registeredCommands: WeakMap = Cli.toCommands; const advertisedGroupSchema = z .object({ @@ -65,7 +67,7 @@ const parserSchema = ( command: string, group: (typeof INPUT_GROUPS)[number], ): z.ZodObject | undefined => { - const entry = registeredCommands.get(cli)?.get(command); + const entry = cliCommand(cli, command)?.definition; if (entry === undefined || !(group in entry)) return undefined; const schema: unknown = Reflect.get(entry, group); return schema instanceof z.ZodObject ? schema : undefined; @@ -250,18 +252,18 @@ describe("CLI advertised input schemas", () => { ); }); - it("advertises defaults as omittable on a mounted group root", async () => { - const group = Cli.create("group", { + it("advertises defaulted command inputs as omittable", async () => { + const cli = createCommandCli(); + registerCliCommand(cli, "fixture", { args: z.object({ scope: z.enum(["all", "selected"]).default("all") }), run: () => ({ ok: true }), - }).command("child", { run: () => ({ ok: true }) }); - const cli = Cli.create("group-root-test", { sync: false }).command(group); + }); presentOmittableDefaults(cli as unknown as CliInstance); const advertised = await advertisedSchema( cli as unknown as CliInstance, - "group", + "fixture", ); expect(advertised.args?.properties.scope).toBeDefined(); expect(advertised.args?.required ?? []).not.toContain("scope"); @@ -537,7 +539,7 @@ describe("ADB selector input schemas: package and activity", () => { describe("ADB selector input schemas: dispatch", () => { it("rejects malformed CLI selectors before an inert provider is called", async () => { - const cli = Cli.create("rea-adb-selector-test", { sync: false }); + const cli = createCommandCli(); const provider = { inspectAvailability: vi.fn(async (): Promise => { throw new Error("unexpected availability probe"); @@ -616,7 +618,7 @@ describe("ADB selector input schemas: dispatch", () => { }); it("preserves optional activity mapping and colon-containing extra values", async () => { - const cli = Cli.create("rea-adb-selector-valid-test", { sync: false }); + const cli = createCommandCli(); const provider = { inspectAvailability: vi.fn(async (): Promise => { throw new Error("unexpected availability probe"); diff --git a/tests/boundary/cli/cliJsonCallerPath.test.ts b/tests/boundary/cli/cliJsonCallerPath.test.ts index 11a68442b4..528953b0ff 100644 --- a/tests/boundary/cli/cliJsonCallerPath.test.ts +++ b/tests/boundary/cli/cliJsonCallerPath.test.ts @@ -1,3 +1,4 @@ +import { createCommandCli } from "../../support/cli/commandCli.js"; import { chmod, mkdir, @@ -11,7 +12,6 @@ import { import { tmpdir } from "node:os"; import { join } from "node:path"; -import { Cli } from "incur"; import pino from "pino"; import { expect, it } from "vitest"; @@ -35,7 +35,7 @@ const providerIdentity = { } as const; const serveJson = async ( - cli: ReturnType, + cli: ReturnType, command: string, input: unknown, ): Promise => { @@ -88,9 +88,7 @@ it.skipIf(process.platform === "win32")( }, close: async () => undefined, }; - const electronCli = Cli.create("rea-path-electron-test", { - sync: false, - }); + const electronCli = createCommandCli(); registerElectronCommands( electronCli, pino({ level: "silent" }), @@ -138,9 +136,7 @@ it.skipIf(process.platform === "win32")( }, close: async () => undefined, }; - const browserCli = Cli.create("rea-path-browser-test", { - sync: false, - }); + const browserCli = createCommandCli(); registerBrowserScenarioCommands( browserCli, pino({ level: "silent" }), @@ -202,9 +198,7 @@ it.skipIf(process.platform === "win32")( JSON.parse(await readFile(`${root}/link/../evidence.json`, "utf8")), ).evidence_id, ).toBe(selectedEvidence.evidence_id); - const analysisViewCli = Cli.create("rea-path-evidence-test", { - sync: false, - }); + const analysisViewCli = createCommandCli(); registerAnalysisViewCommands(analysisViewCli, pino({ level: "silent" })); for (const path of [ "link/../evidence.json", diff --git a/tests/boundary/cli/cliLazyRegistration.test.ts b/tests/boundary/cli/cliLazyRegistration.test.ts index 10889bbeee..e6f6b5e789 100644 --- a/tests/boundary/cli/cliLazyRegistration.test.ts +++ b/tests/boundary/cli/cliLazyRegistration.test.ts @@ -1,6 +1,6 @@ import { join, resolve } from "node:path"; import { pathToFileURL } from "node:url"; -import { Cli } from "incur"; +import { cliCommands } from "../../../src/cli/commandRegistry.js"; import { describe, expect, it } from "vitest"; import { createCli } from "../../../src/cli.js"; @@ -29,7 +29,7 @@ const selectFor = ( ); import { createCliShell } from "../../../src/cli/cliShell.js"; import type { CliInstance } from "../../../src/cli/types.js"; -import { visitRegisteredCommands } from "../../../src/cli/visitRegisteredCommands.js"; + import { createDirectAnalysis } from "../../../src/composition/directAnalysis.js"; import { PRODUCT_IDENTITY } from "../../../src/identity.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; @@ -38,21 +38,8 @@ import { serveInProcessCli } from "../../support/cli/serveInProcessCli.js"; const ENVIRONMENT = { PATH: process.env.PATH }; -// Incur types its router key without vars, env, or globals; accept any CLI. -const registeredCommands: WeakMap< - object, - Map -> = Cli.toCommands; - -const topLevelNames = (cli: CliInstance): readonly string[] => [ - ...(registeredCommands.get(cli)?.keys() ?? []), -]; - -const commandPaths = (cli: CliInstance): readonly string[] => { - const paths: string[] = []; - visitRegisteredCommands(cli, (_command, path) => paths.push(path)); - return paths; -}; +const topLevelNames = (cli: CliInstance): readonly string[] => + cliCommands(cli).map(({ name }) => name); const createRegistrarCli = async ( id: CliCommandRegistrationId, @@ -98,11 +85,11 @@ describe("lazy CLI registration", () => { it("gives each command the same definition alone as in the complete CLI", async () => { const complete = createCli(ENVIRONMENT); - const completePaths = new Set(commandPaths(complete)); + const completePaths = new Set(topLevelNames(complete)); const covered = new Set(); for (const id of CLI_REGISTRATION_ORDER) { const alone = await createRegistrarCli(id); - for (const path of commandPaths(alone)) { + for (const path of topLevelNames(alone)) { expect(completePaths.has(path), path).toBe(true); covered.add(path); expect(await help(alone, path), path).toEqual( diff --git a/tests/boundary/cli/cliOptionAliases.test.ts b/tests/boundary/cli/cliOptionAliases.test.ts index 61a008b203..c148464624 100644 --- a/tests/boundary/cli/cliOptionAliases.test.ts +++ b/tests/boundary/cli/cliOptionAliases.test.ts @@ -1,18 +1,14 @@ -import { Cli } from "incur"; +import { cliCommand, cliCommands } from "../../../src/cli/commandRegistry.js"; import { describe, expect, it } from "vitest"; import { z } from "zod"; import { createCli } from "../../../src/cli.js"; -import { cliCommands } from "../../../src/cli/commandRegistry.js"; import { cliCommandOptionNames, createCliInventory, } from "../../../scripts/lib/catalog-cli.mjs"; type CliInstance = ReturnType; -type CommandMap = NonNullable>; - -const registeredCommands: WeakMap = Cli.toCommands; const serve = async ( cli: CliInstance, @@ -36,7 +32,7 @@ const registeredAliases = ( cli: CliInstance, command: string, ): Record => { - const entry = registeredCommands.get(cli)?.get(command); + const entry = cliCommand(cli, command)?.definition; const alias: unknown = entry === undefined ? undefined : Reflect.get(entry, "alias"); return typeof alias === "object" && alias !== null ? { ...alias } : {}; @@ -67,7 +63,7 @@ describe("CLI option aliases", () => { for (const match of help.stdout.matchAll(/(?:^|[\s,])-([a-z][\w-]+)/gmu)) invalid.push(`${command} help: -${match[1] ?? ""}`); const options = /^Options:\n((?: {2}.*\n?)*)/mu.exec(help.stdout)?.[1]; - const entry = registeredCommands.get(cli)?.get(command); + const entry = cliCommand(cli, command)?.definition; expect(entry, `${command} registration`).toBeDefined(); const schema: unknown = entry && Reflect.get(entry, "options"); if (schema !== undefined) diff --git a/tests/boundary/cli/cliOutput.test.ts b/tests/boundary/cli/cliOutput.test.ts index 53aae401f5..8740bc21e2 100644 --- a/tests/boundary/cli/cliOutput.test.ts +++ b/tests/boundary/cli/cliOutput.test.ts @@ -7,10 +7,7 @@ import { describe, expect, it } from "vitest"; import { workspaceCliTest } from "../../support/cli/workspaceCliFixture.js"; -import { - adaptCliOutputArgumentsForIncur, - parseCliGlobalArguments, -} from "../../../src/cliBuiltinArguments.js"; +import { parseCliGlobalArguments } from "../../../src/cliBuiltinArguments.js"; import { renderCliOutputArgumentError, renderCliDocument, @@ -78,26 +75,6 @@ describe("CLI output argument boundary", () => { ).toMatchObject({ ok: false, code: "UNSUPPORTED_OUTPUT_COMBINATION" }); }); - it("adapts REA-owned delimited options only at the Incur boundary", () => { - expect( - adaptCliOutputArgumentsForIncur([ - "inspect-analysis-view", - "--format", - "csv", - "--columns", - "name,version", - "--filter-output", - "normalized_result.items", - ]), - ).toEqual([ - "inspect-analysis-view", - "--format", - "json", - "--filter-output", - "normalized_result.items", - ]); - }); - it("uses the shared Markdown table formatter for standalone reports", () => { const value = { text: "left|right\\path\nnext" }; expect(renderCliDocument(value, "md", false)).toContain( @@ -179,12 +156,12 @@ it("formats arrays of empty objects without column keys as JSON in Markdown", () it("preserves flag-shaped values consumed by valued output options", () => { expect( - adaptCliOutputArgumentsForIncur([ + parseCliGlobalArguments([ "--filter-output", "--columns", "providers", "--json", - ]), + ]).arguments, ).toEqual(["--filter-output", "--columns", "providers", "--json"]); }); diff --git a/tests/boundary/cli/cliResultControls.test.ts b/tests/boundary/cli/cliResultControls.test.ts index e85e3215c2..dc49735ebf 100644 --- a/tests/boundary/cli/cliResultControls.test.ts +++ b/tests/boundary/cli/cliResultControls.test.ts @@ -1,6 +1,7 @@ +import { cliCommand } from "../../../src/cli/commandRegistry.js"; +import { createCommandCli } from "../../support/cli/commandCli.js"; import { Writable } from "node:stream"; -import { Cli } from "incur"; import { expect, it, vi } from "vitest"; import { z } from "zod"; @@ -219,7 +220,7 @@ const runFixtureCommand = async (produce: () => unknown) => { }), outputSchema: partialResultSchema, }; - const cli = Cli.create("rea-result-controls", { version: "1", sync: false }); + const cli = createCommandCli(); registerContractCommand( cli as unknown as CliInstance, silentLogger, @@ -231,7 +232,7 @@ const runFixtureCommand = async (produce: () => unknown) => { }, async () => produce() as never, ); - const command = Cli.toCommands.get(cli)?.get("inspect-control-fixture"); + const command = cliCommand(cli, "inspect-control-fixture")?.definition; if (command === undefined) throw new Error("command is not registered"); const parse = (key: "args" | "options", value: unknown) => (Reflect.get(command, key) as { parse(v: unknown): unknown }).parse(value); @@ -287,13 +288,11 @@ const written = async ( destination, ); if (output === undefined) throw new Error("Missing output surface"); - const format = argv[argv.indexOf("--format") + 1] ?? "json"; let collected = 0; // The ordinary command path: no forced output, controls collected on demand. const handled = await output.write(partialResult(), { command: "fixture", duration: "0ms", - format, collectCliControls: () => { collected += 1; return cliControls; diff --git a/tests/boundary/cli/cliTimingArguments.test.ts b/tests/boundary/cli/cliTimingArguments.test.ts index fd41f4813e..979f3786cc 100644 --- a/tests/boundary/cli/cliTimingArguments.test.ts +++ b/tests/boundary/cli/cliTimingArguments.test.ts @@ -1,34 +1,77 @@ import { it, expect } from "vitest"; -import { Parser } from "incur"; -import { z } from "zod"; import { parseCliGlobalArguments, productionMcpDoctorArguments, } from "../../../src/cliBuiltinArguments.js"; +// Observed with Incur 0.6.1 before removing the dependency. it.each([ - [], - ["--timings"], - ["--no-timings"], - ["--timings=false"], - ["--timings=true"], - ["--timings=other"], - ["--timings="], - ["--timings", "--no-timings"], - ["--no-timings", "--timings=true"], - ["--timings=false", "--timings"], - ["--", "--timings"], -])("matches pinned boolean global parsing for %j", (...input: string[]) => { - const actual = parseCliGlobalArguments(input); - const parsed = Parser.parseGlobals( - input, - z.object({ timings: z.boolean().default(false) }), - ); - expect({ arguments: actual.command, enabled: actual.timings }).toEqual({ - arguments: parsed.rest, - enabled: parsed.parsed.timings, - }); -}); + { + input: [], + rest: [], + enabled: false, + }, + { + input: ["--timings"], + rest: [], + enabled: true, + }, + { + input: ["--no-timings"], + rest: [], + enabled: false, + }, + { + input: ["--timings=false"], + rest: [], + enabled: false, + }, + { + input: ["--timings=true"], + rest: [], + enabled: true, + }, + { + input: ["--timings=other"], + rest: [], + enabled: false, + }, + { + input: ["--timings="], + rest: [], + enabled: false, + }, + { + input: ["--timings", "--no-timings"], + rest: [], + enabled: false, + }, + { + input: ["--no-timings", "--timings=true"], + rest: [], + enabled: true, + }, + { + input: ["--timings=false", "--timings"], + rest: [], + enabled: true, + }, + { + input: ["--", "--timings"], + rest: ["--", "--timings"], + enabled: false, + }, +])( + "preserves the recorded boolean global grammar for %j", + ({ input, rest, enabled }) => { + const actual = parseCliGlobalArguments(input); + expect({ arguments: actual.command, enabled: actual.timings }).toEqual({ + arguments: rest, + enabled, + }); + }, +); + it.each([ "--timings", "--no-timings", diff --git a/tests/boundary/cli/cliTokenWindowOutput.test.ts b/tests/boundary/cli/cliTokenWindowOutput.test.ts index bd35ee0531..03f388066a 100644 --- a/tests/boundary/cli/cliTokenWindowOutput.test.ts +++ b/tests/boundary/cli/cliTokenWindowOutput.test.ts @@ -1,15 +1,13 @@ +import { registerCliCommand } from "../../../src/cli/commandRegistry.js"; +import { createCommandCli } from "../../support/cli/commandCli.js"; import { Writable } from "node:stream"; -import { Cli } from "incur"; import { estimateTokenCount } from "tokenx"; import { describe, expect, it } from "vitest"; import { formatCliOutput } from "../../../src/cli/cliOutputFormatter.js"; import { parseCliOutputArguments } from "../../../src/cliOutput.js"; -import { - createCliResultOutput, - streamCliCommandResults, -} from "../../../src/cli/cliResultOutput.js"; +import { createCliResultOutput } from "../../../src/cli/cliResultOutput.js"; const renderWindow = async ( value: unknown, @@ -44,7 +42,6 @@ const renderWindow = async ( const handled = await output.write(value, { command: "fixture", duration: "0ms", - format: "toon", }); return { handled, text: Buffer.concat(chunks).toString("utf8") }; }; @@ -217,7 +214,6 @@ describe("token windows through Incur output policies", () => { { command: "fixture", duration: "0ms", - format: "toon", renderOutput: false, }, ); @@ -244,14 +240,8 @@ describe("token windows through Incur output policies", () => { configurable: true, }); try { - for (const grouped of [false, true]) { - const argv = [ - ...(grouped ? ["group"] : []), - "fixture", - "--token-limit", - "2", - ...flags, - ]; + { + const argv = ["fixture", "--token-limit", "2", ...flags]; let text = ""; const destination = new Writable({ write(chunk, _encoding, callback) { @@ -263,23 +253,11 @@ describe("token windows through Incur output policies", () => { parseCliOutputArguments(argv), destination, )!; - const cli = Cli.create("policy-test", { sync: false }); - if (grouped) { - const group = Cli.create("group", { - sync: false, - outputPolicy: "agent-only", - }); - group.command("fixture", { - run: () => ({ value: "😀é".repeat(100) }), - }); - cli.command(group); - } else { - cli.command("fixture", { - outputPolicy: "agent-only", - run: () => ({ value: "😀é".repeat(100) }), - }); - } - streamCliCommandResults(cli, output); + const cli = createCommandCli(output); + registerCliCommand(cli, "fixture", { + outputPolicy: "agent-only", + run: () => ({ value: "😀é".repeat(100) }), + }); await cli.serve(argv, { stdout: (chunk) => { if (!output.handled) text += chunk; diff --git a/tests/boundary/cli/cliUpdateNoticeOutput.test.ts b/tests/boundary/cli/cliUpdateNoticeOutput.test.ts new file mode 100644 index 0000000000..ca25f52687 --- /dev/null +++ b/tests/boundary/cli/cliUpdateNoticeOutput.test.ts @@ -0,0 +1,47 @@ +import { Writable } from "node:stream"; +import { expect, it } from "vitest"; + +import { createCliResultOutput } from "../../../src/cli/cliResultOutput.js"; +import { parseCliOutputArguments } from "../../../src/cliOutput.js"; + +it("retains failed output ownership when a terminal notice cannot be written", async () => { + const cause = Object.assign(new Error("broken pipe during notice"), { + code: "EPIPE", + }); + let written = ""; + const output = createCliResultOutput( + parseCliOutputArguments([]), + new Writable({ + write(chunk: Buffer, _encoding, done) { + const text = chunk.toString("utf8"); + if (text.includes("Update available")) done(cause); + else { + written += text; + done(); + } + }, + }), + ); + if (output === undefined) throw new Error("Missing output owner"); + await expect( + output.write( + { answer: 42 }, + { + command: "fixture", + duration: "0ms", + cta: { + description: "Update available", + commands: [{ command: "rea --update" }], + }, + }, + ), + ).rejects.toBe(cause); + expect(written).toBe("answer: 42\n"); + expect(output.handled).toBe(true); + expect(output.failed).toBe(true); + expect( + await output.recoverFormattingFailure( + new RangeError("Invalid string length"), + ), + ).toBe(false); +}); diff --git a/tests/boundary/cli/commandEvidenceDelivery.test.ts b/tests/boundary/cli/commandEvidenceDelivery.test.ts index ae8a346d5a..7d9844828a 100644 --- a/tests/boundary/cli/commandEvidenceDelivery.test.ts +++ b/tests/boundary/cli/commandEvidenceDelivery.test.ts @@ -1,6 +1,7 @@ +import { cliCommand } from "../../../src/cli/commandRegistry.js"; +import { createCommandCli } from "../../support/cli/commandCli.js"; import { unknownTarget } from "../../../src/domain/targetIdentity.js"; import { closeVerifierResources } from "../../../scripts/lib/verifier-cleanup.mjs"; -import { Cli } from "incur"; import { z } from "zod"; import pino from "pino"; import { readFile, readdir, writeFile } from "node:fs/promises"; @@ -71,10 +72,7 @@ const fixture = async (kind: (typeof kinds)[number]) => { .mockResolvedValue(ok({ target_state: "none_observed" })); const closeAll = vi.spyOn(manager, "closeAll").mockResolvedValue(undefined); const createManager = vi.fn(() => manager); - const cli = Cli.create("rea-cli-delivery-test", { - version: "1", - sync: false, - }); + const cli = createCommandCli(); registerReverseEngineeringCommands( cli as unknown as CliInstance, pino({ enabled: false }), @@ -91,7 +89,7 @@ const fixture = async (kind: (typeof kinds)[number]) => { : kind === "objdump" ? cliCommandFor("inspect_with_objdump") : CLI_COMMANDS.listObjdumpArchitectures; - const command = Cli.toCommands.get(cli)?.get(commandName); + const command = cliCommand(cli, commandName)?.definition; if (command === undefined) throw new Error("CLI command was not registered"); // A command without positionals registers no argument schema. const argsSchema: unknown = Reflect.get(command, "args") ?? z.object({}); @@ -112,6 +110,7 @@ const fixture = async (kind: (typeof kinds)[number]) => { const invoke = async (options: Record): Promise => execute({ args: argsSchema.parse(args), + formatExplicit: false, options: optionsSchema.parse({ ...(kind === "gdb" ? { inferiorTty: "/dev/pts/caller-fixture" } : {}), ...options, diff --git a/tests/boundary/cli/completions.test.ts b/tests/boundary/cli/completions.test.ts index 0b699629a6..8a58bd1814 100644 --- a/tests/boundary/cli/completions.test.ts +++ b/tests/boundary/cli/completions.test.ts @@ -1,5 +1,5 @@ +import { createCommandCli } from "../../support/cli/commandCli.js"; import { resolve } from "node:path"; -import { Cli } from "incur"; import { z } from "zod"; import { expect, it } from "vitest"; @@ -12,7 +12,7 @@ type ServeOptions = NonNullable[1]>; import { workspaceCliTest } from "../../support/cli/workspaceCliFixture.js"; const registry = () => { - const cli = Cli.create("rea", { sync: false }) as unknown as CliInstance; + const cli = createCommandCli() as unknown as CliInstance; registerCliCommand(cli, "instructions", { options: z.object({ procedure: z.string().optional(), @@ -134,7 +134,17 @@ it("shares Bash registration across ordinary and protocol routes while retaining expect(direct).toContain("type compopt"); expect(direct).toContain("||\n complete -o default -o bashdefault"); expect(ordinary(["completions", "bash", "--help"], {})).toBe(false); - expect(ordinary(["completions", "bash", "--schema"], {})).toBe(false); + for (const flag of ["--schema", "--version"]) { + let script = ""; + expect( + ordinary(["completions", "bash", flag], { + stdout: (text) => { + script += text; + }, + }), + ).toBe(true); + expect(script).toBe(direct); + } }); workspaceCliTest( diff --git a/tests/boundary/cli/contractCommandInputFields.test.ts b/tests/boundary/cli/contractCommandInputFields.test.ts index 89e7a41d89..375cc7fe5d 100644 --- a/tests/boundary/cli/contractCommandInputFields.test.ts +++ b/tests/boundary/cli/contractCommandInputFields.test.ts @@ -1,4 +1,5 @@ -import { Cli } from "incur"; +import { cliCommand } from "../../../src/cli/commandRegistry.js"; +import { createCommandCli } from "../../support/cli/commandCli.js"; import { z } from "zod"; import pino from "pino"; import { expect, it } from "vitest"; @@ -27,10 +28,7 @@ const lookupFailure = { * returning the provider's failure through the shared Evidence delivery. */ const harness = () => { - const cli = Cli.create("rea-input-fields-test", { - version: "1", - sync: false, - }); + const cli = createCommandCli(); registerContractCommand( cli as unknown as CliInstance, pino({ enabled: false }), @@ -59,7 +57,7 @@ const harness = () => { }, ), ); - const registered = Cli.toCommands.get(cli)?.get("probe"); + const registered = cliCommand(cli, "probe")?.definition; if (registered === undefined) throw new Error("probe was not registered"); const execute = Reflect.get(registered, "run") as ( value: unknown, @@ -96,10 +94,7 @@ it("names a delivered provider failure's input field by its CLI key", async () = }); it("keeps a branch-only default out of the branch the caller selects", async () => { - const cli = Cli.create("rea-branch-default-test", { - version: "1", - sync: false, - }); + const cli = createCommandCli(); const received: unknown[] = []; registerContractCommand( cli as unknown as CliInstance, @@ -124,7 +119,7 @@ it("keeps a branch-only default out of the branch the caller selects", async () return {}; }, ); - const registered = Cli.toCommands.get(cli)?.get("branch-probe"); + const registered = cliCommand(cli, "branch-probe")?.definition; if (registered === undefined) throw new Error("branch-probe is missing"); const parse = (value: unknown) => ( @@ -140,10 +135,7 @@ it("keeps a branch-only default out of the branch the caller selects", async () }); it("hands a whole-input handler the contract's parse, or its refusal, without parsing again", async () => { - const cli = Cli.create("rea-admitted-input-test", { - version: "1", - sync: false, - }); + const cli = createCommandCli(); const received: unknown[] = []; // Counts evaluations of the whole contract schema; argv option parsing // checks field schemas only. @@ -182,7 +174,7 @@ it("hands a whole-input handler the contract's parse, or its refusal, without pa async () => ({}), ); const command = (name: string) => { - const registered = Cli.toCommands.get(cli)?.get(name); + const registered = cliCommand(cli, name)?.definition; if (registered === undefined) throw new Error(`${name} is missing`); const options = (value: unknown) => ( @@ -216,10 +208,7 @@ it("hands a whole-input handler the contract's parse, or its refusal, without pa }); it("hands a JSON-document handler the contract's parse of its document, once, only when read", async () => { - const cli = Cli.create("rea-admitted-document-test", { - version: "1", - sync: false, - }); + const cli = createCommandCli(); const received: unknown[] = []; let wholeParses = 0; const inputSchema = z @@ -264,7 +253,7 @@ it("hands a JSON-document handler the contract's parse of its document, once, on async () => ({}), ); const command = (name: string) => { - const registered = Cli.toCommands.get(cli)?.get(name); + const registered = cliCommand(cli, name)?.definition; if (registered === undefined) throw new Error(`${name} is missing`); const args = (value: unknown) => (Reflect.get(registered, "args") as { parse(v: unknown): unknown }).parse( diff --git a/tests/boundary/cli/contractCommandViewDelivery.test.ts b/tests/boundary/cli/contractCommandViewDelivery.test.ts index 0470808044..dd02b5dc33 100644 --- a/tests/boundary/cli/contractCommandViewDelivery.test.ts +++ b/tests/boundary/cli/contractCommandViewDelivery.test.ts @@ -1,4 +1,5 @@ -import { Cli } from "incur"; +import { cliCommand } from "../../../src/cli/commandRegistry.js"; +import { createCommandCli } from "../../support/cli/commandCli.js"; import { z } from "zod"; import pino from "pino"; import { expect, it } from "vitest"; @@ -18,10 +19,7 @@ const detailSchema = z.enum(["complete", "summary"]).default("complete"); * counts as opening its target. */ const harness = () => { - const cli = Cli.create("rea-view-delivery-test", { - version: "1", - sync: false, - }); + const cli = createCommandCli(); const opened: string[] = []; const logger = pino({ enabled: false }); const target = { @@ -120,7 +118,7 @@ const harness = () => { args: Record, options: Record, ) => { - const registered = Cli.toCommands.get(cli)?.get(command); + const registered = cliCommand(cli, command)?.definition; if (registered === undefined) throw new Error(`${command} is missing`); const parse = (key: "args" | "options", value: unknown) => (Reflect.get(registered, key) as { parse(v: unknown): unknown }).parse( diff --git a/tests/boundary/cli/contractJsonInputChecks.test.ts b/tests/boundary/cli/contractJsonInputChecks.test.ts index eba63213e9..1400ce97af 100644 --- a/tests/boundary/cli/contractJsonInputChecks.test.ts +++ b/tests/boundary/cli/contractJsonInputChecks.test.ts @@ -1,4 +1,5 @@ -import { Cli } from "incur"; +import { cliCommand } from "../../../src/cli/commandRegistry.js"; +import { createCommandCli } from "../../support/cli/commandCli.js"; import { expect, it } from "vitest"; import { z } from "zod"; @@ -21,10 +22,7 @@ it("admits a checked JSON input through its check only, and the rest through the }), }; const received: unknown[] = []; - const cli = Cli.create("rea-checked-json-input", { - version: "1", - sync: false, - }); + const cli = createCommandCli(); registerContractCommand( cli as unknown as CliInstance, silentLogger, @@ -43,7 +41,7 @@ it("admits a checked JSON input through its check only, and the rest through the return {}; }, ); - const command = Cli.toCommands.get(cli)?.get("compare-checked-fixture"); + const command = cliCommand(cli, "compare-checked-fixture")?.definition; if (command === undefined) throw new Error("command is not registered"); const parse = (key: "args" | "options", value: unknown) => (Reflect.get(command, key) as { parse(v: unknown): unknown }).parse(value); diff --git a/tests/boundary/cli/defaultAmpRegistration.test.ts b/tests/boundary/cli/defaultAmpRegistration.test.ts index f18bb47cdd..3a88498a94 100644 --- a/tests/boundary/cli/defaultAmpRegistration.test.ts +++ b/tests/boundary/cli/defaultAmpRegistration.test.ts @@ -1,8 +1,6 @@ import { mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { expect, it } from "vitest"; -import { Parser } from "incur"; -import { z } from "zod"; import { decode } from "@toon-format/toon"; import { mcpRegistrationReportSchema } from "../../../src/contracts/mcpRegistration.js"; @@ -99,7 +97,7 @@ cliTest( "null\n", '{"amp.mcpServers":[]}\n', original, - ]) { + ] as const) { const f = await fixture(initial); if (initial === original) await mkdir(`${f.settings}.rea.backup`); for (const json of [false, true]) { @@ -187,7 +185,7 @@ cliTest( }, ); -it("timing splitting matches Incur after output values and before the terminator", () => { +it("preserves recorded timing consumption before the terminator and retains following data", () => { for (const flag of [ "--timings", "--no-timings", @@ -195,18 +193,24 @@ it("timing splitting matches Incur after output values and before the terminator "--timings=true", "--timings=other", ]) { - for (const command of [ - [flag, "mcp", "add"], - ["mcp", "add", "--agent", flag, "amp"], - ["mcp", "add", "--command", flag], - ["mcp", "add", "--", flag], - ]) { - const expected = Parser.parseGlobals( - command, - z.object({ timings: z.boolean().default(false) }), - undefined, - { validate: false }, - ).rest; + for (const [command, expected] of [ + [ + [flag, "mcp", "add"], + ["mcp", "add"], + ], + [ + ["mcp", "add", "--agent", flag, "amp"], + ["mcp", "add", "--agent", "amp"], + ], + [ + ["mcp", "add", "--command", flag], + ["mcp", "add", "--command"], + ], + [ + ["mcp", "add", "--", flag], + ["mcp", "add", "--", flag], + ], + ] as const) { expect(parseCliGlobalArguments(command).command).toEqual(expected); expect( parseCliGlobalArguments(["--filter-output", flag, ...command]).command, diff --git a/tests/boundary/cli/directAnalysisStatus.test.ts b/tests/boundary/cli/directAnalysisStatus.test.ts index 3d70555ed6..e3a71cc345 100644 --- a/tests/boundary/cli/directAnalysisStatus.test.ts +++ b/tests/boundary/cli/directAnalysisStatus.test.ts @@ -1,7 +1,7 @@ +import { createCommandCli } from "../../support/cli/commandCli.js"; import { createCatalogIdentity } from "../../../src/contracts/catalog/catalogIdentity.js"; import { contractsForToolFamilies } from "../../../src/contracts/toolFamilies.js"; import { promptsForToolFamilies } from "../../../src/contracts/promptToolFamilyScope.js"; -import { Cli } from "incur"; import { expect, it, vi } from "vitest"; import { runSessionStatus } from "../../../src/application/DirectAnalysisStatus.js"; import { registerUtilityCommands } from "../../../src/cli/utilityCommands.js"; @@ -32,7 +32,7 @@ it.each(["capabilities", "providers"])( const close = vi .spyOn(session, "close") .mockResolvedValueOnce(err(cleanup)); - const cli = Cli.create({ name: "rea" }); + const cli = createCommandCli(); registerUtilityCommands( cli, silentLogger, @@ -116,7 +116,7 @@ it.each(["capabilities", "providers"])( promptContracts: promptsForToolFamilies(families), outputSchemaProfile: "compact", }); - const cli = Cli.create({ name: "rea" }); + const cli = createCommandCli(); registerUtilityCommands( cli, silentLogger, @@ -207,7 +207,7 @@ it.each(["capabilities", "providers"])( }, ], }); - const cli = Cli.create({ name: "rea" }); + const cli = createCommandCli(); registerUtilityCommands( cli, silentLogger, diff --git a/tests/boundary/cli/dispatcher.test.ts b/tests/boundary/cli/dispatcher.test.ts index 6783dadc54..3278092eb0 100644 --- a/tests/boundary/cli/dispatcher.test.ts +++ b/tests/boundary/cli/dispatcher.test.ts @@ -249,12 +249,12 @@ describe("runtime admission dispatch", () => { describe("executable dispatcher", () => { workspaceCliTest( - "does not append recovery output after delegated stdout has begun", + "does not append recovery output after stdout has begun", async ({ processes, workspace }) => { await installCliRuntime( workspace, 'export const closeCliResources = () => {}; export const createCli = () => ({ serve: (_args, options) => { options.stdout("first document\\n"); throw new RangeError("Invalid string length"); } });\n', - 'export const createCliResultOutput = () => ({ handled: false, failed: false, captureSdkOutput: () => false, finishSdkOutput: async () => {}, recoverFormattingFailure: () => { process.stdout.write("unexpected second document"); return true; } });\n', + 'export const createCliResultOutput = () => ({ handled: false, failed: false, finish: async () => {}, recoverFormattingFailure: () => { process.stdout.write("unexpected second document"); return true; } });\n', ); const result = await processes.run( process.execPath, @@ -404,7 +404,7 @@ describe("executable dispatcher JavaScript shutdown", () => { "write-failure", "closed-pipe", ] as const)( - "awaits SDK output after cleanup and retains finalization status: %s", + "awaits result output after cleanup and retains finalization status: %s", async (scenario, { processes, workspace }) => { const cleanupFails = scenario === "cleanup-failure"; const finish = @@ -416,7 +416,7 @@ describe("executable dispatcher JavaScript shutdown", () => { await installCliRuntime( workspace, `export const closeCliResources = () => { globalThis.cleaned = true; ${cleanupFails ? 'return Promise.reject(new Error("worker still owned"));' : ""} }; export const createCli = () => ({ serve: (_args, options) => { options.stdout("pending document"); options.exit(0); } });\n`, - `export const createCliResultOutput = () => ({ handled: false, failed: false, captureSdkOutput: () => true, finishSdkOutput: async (status) => { if (!globalThis.cleaned) throw new Error("output preceded cleanup"); if (status !== ${cleanupFails ? 1 : 0}) throw new Error("unexpected finish status: " + status); await new Promise(resolve => setTimeout(resolve, 10)); ${finish} } });\n`, + `export const createCliResultOutput = () => ({ handled: true, failed: false, finish: async () => { if (!globalThis.cleaned) throw new Error("output preceded cleanup"); await new Promise(resolve => setTimeout(resolve, 10)); ${finish} } });\n`, ); const result = await processes.run( process.execPath, @@ -430,7 +430,6 @@ describe("executable dispatcher JavaScript shutdown", () => { scenario === "success" || cleanupFails ? "complete document\n" : "", ); expect(result.stderr).not.toContain("output preceded cleanup"); - expect(result.stderr).not.toContain("unexpected finish status"); if (cleanupFails) expect(result.stderr).toContain("worker still owned"); if (scenario === "write-failure") expect(result.stderr).toContain("final write failed"); @@ -456,12 +455,12 @@ describe("executable dispatcher JavaScript shutdown", () => { ); workspaceCliTest( - "reports a failed JavaScript worker shutdown when exit is called without a code and passes failure status to SDK output", + "reports a failed JavaScript worker shutdown when exit is called without a code and retains failure status through output completion", async ({ processes, workspace }) => { await installCliRuntime( workspace, - 'export const closeCliResources = () => Promise.reject(new Error("worker still owned")); export const createCli = () => ({ serve: (_args, options) => { options.exit(); } });\n', - 'export const createCliResultOutput = () => ({ handled: false, failed: false, captureSdkOutput: () => false, finishSdkOutput: async (status) => { if (status !== 1) throw new Error("unexpected finish status: " + status); } });\n', + 'export const closeCliResources = () => { globalThis.cleaned = true; return Promise.reject(new Error("worker still owned")); }; export const createCli = () => ({ serve: (_args, options) => { options.exit(); } });\n', + 'export const createCliResultOutput = () => ({ handled: false, failed: false, finish: async () => { if (!globalThis.cleaned) throw new Error("output preceded cleanup"); } });\n', ); const result = await processes.run( process.execPath, @@ -470,17 +469,17 @@ describe("executable dispatcher JavaScript shutdown", () => { ); expect(result.exitCode).toBe(1); expect(result.stderr).toContain("worker still owned"); - expect(result.stderr).not.toContain("unexpected finish status"); + expect(result.stderr).not.toContain("output preceded cleanup"); }, ); workspaceCliTest( - "reports a failed SDK finalization when exit is called without a code", + "reports a failed output completion when exit is called without a code", async ({ processes, workspace }) => { await installCliRuntime( workspace, "export const closeCliResources = () => Promise.resolve(); export const createCli = () => ({ serve: (_args, options) => { options.exit(); } });\n", - 'export const createCliResultOutput = () => ({ handled: false, failed: false, captureSdkOutput: () => false, finishSdkOutput: async (status) => { if (status !== 0) throw new Error("unexpected finish status: " + status); throw new Error("SDK finalization failed"); } });\n', + 'export const createCliResultOutput = () => ({ handled: false, failed: false, finish: async () => { throw new Error("output completion failed"); } });\n', ); const result = await processes.run( process.execPath, @@ -488,8 +487,8 @@ describe("executable dispatcher JavaScript shutdown", () => { { cwd: workspace.root }, ); expect(result.exitCode).toBe(1); - expect(result.stderr).toContain("SDK finalization failed"); - expect(result.stderr).not.toContain("unexpected finish status"); + expect(result.stderr).toContain("output completion failed"); + expect(result.stderr).not.toContain("output preceded cleanup"); }, ); diff --git a/tests/boundary/cli/emptyLocalTargetAdmission.test.ts b/tests/boundary/cli/emptyLocalTargetAdmission.test.ts index 2c4678f726..1abe0c1981 100644 --- a/tests/boundary/cli/emptyLocalTargetAdmission.test.ts +++ b/tests/boundary/cli/emptyLocalTargetAdmission.test.ts @@ -1,4 +1,4 @@ -import { Cli } from "incur"; +import { createCommandCli } from "../../support/cli/commandCli.js"; import { Ajv2020 } from "ajv/dist/2020.js"; import { expect, it, vi } from "vitest"; import { registerArtifactCommands } from "../../../src/cli/artifactCommands.js"; @@ -31,7 +31,7 @@ const registry = () => { ]), }) as const, ); - const cli = Cli.create("empty-target-admission", { sync: false }); + const cli = createCommandCli(); registerArtifactCommands(cli, silentLogger, runProviderAnalysis); registerCoreBinaryCommands(cli, silentLogger, runDirectAnalysis, {}); registerCoreNativeCommands(cli, silentLogger, runDirectAnalysis); diff --git a/tests/boundary/cli/filteredArrayOutput.test.ts b/tests/boundary/cli/filteredArrayOutput.test.ts index 77d42db646..ebc91a5770 100644 --- a/tests/boundary/cli/filteredArrayOutput.test.ts +++ b/tests/boundary/cli/filteredArrayOutput.test.ts @@ -1,6 +1,7 @@ +import { registerCliCommand } from "../../../src/cli/commandRegistry.js"; +import { createCommandCli } from "../../support/cli/commandCli.js"; import { Writable } from "node:stream"; -import { Cli } from "incur"; import { estimateTokenCount } from "tokenx"; import { expect, it } from "vitest"; @@ -9,11 +10,7 @@ import { parseCliOutputArguments, renderCliDocument, } from "../../../src/cliOutput.js"; -import { adaptCliOutputArgumentsForIncur } from "../../../src/cliBuiltinArguments.js"; -import { - createCliResultOutput, - streamCliCommandResults, -} from "../../../src/cli/cliResultOutput.js"; +import { createCliResultOutput } from "../../../src/cli/cliResultOutput.js"; const source = [{ selected: 1 }, { other: 2 }, { selected: null }]; @@ -31,8 +28,6 @@ const runFilteredCli = async ( fields?: readonly string[], expectedExitCode = 0, ): Promise => { - const cli = Cli.create("filtered-array-test", { sync: false }); - cli.command("rows", { run: () => value }); const args = [ "rows", "--format", @@ -51,9 +46,10 @@ const runFilteredCli = async ( }), ); if (output === undefined) throw new Error("Missing CLI output owner"); - streamCliCommandResults(cli, output); + const cli = createCommandCli(output); + registerCliCommand(cli, "rows", { run: () => value }); let fallback = ""; - await cli.serve(adaptCliOutputArgumentsForIncur(args), { + await cli.serve(args, { exit: (code) => { expect(code).toBe(expectedExitCode); }, @@ -256,8 +252,6 @@ it.each( const value = Object.freeze( source.map((item) => Object.freeze({ ...item })), ); - const cli = Cli.create("filtered-array-test", { sync: false }); - cli.command("rows", { run: () => value }); const args = [ "rows", "--format", @@ -277,7 +271,8 @@ it.each( }), ); if (output === undefined) throw new Error("Missing CLI output owner"); - streamCliCommandResults(cli, output); + const cli = createCommandCli(output); + registerCliCommand(cli, "rows", { run: () => value }); let fallback = ""; let status = 0; await cli.serve(args, { @@ -321,8 +316,6 @@ it.each( it.each(["json", "jsonl"] as const)( "counts the normalized filtered %s records", async (format) => { - const cli = Cli.create("filtered-count-test", { sync: false }); - cli.command("rows", { run: () => source }); const args = [ "rows", "--format", @@ -342,7 +335,8 @@ it.each(["json", "jsonl"] as const)( }), ); if (output === undefined) throw new Error("Missing CLI output owner"); - streamCliCommandResults(cli, output); + const cli = createCommandCli(output); + registerCliCommand(cli, "rows", { run: () => source }); let fallback = ""; await cli.serve(args, { exit: (code) => { @@ -377,7 +371,6 @@ it.each(["selected", "toString", "constructor"])( await output?.write(value, { command: "rows", duration: "0ms", - format: "json", }); expect(JSON.parse(Buffer.concat(chunks).toString())).toEqual( filter === "selected" @@ -410,7 +403,6 @@ it("finishes JSONL after a bounded large record before a missing selection", asy await output.write(value, { command: "rows", duration: "0ms", - format: "jsonl", }); const lines = Buffer.concat(chunks).toString().trimEnd().split("\n"); expect(lines.map((line) => JSON.parse(line))).toEqual([ @@ -684,10 +676,7 @@ it.each(["json", "jsonl", "yaml", "toon", "md"] as const)( }, }), ); - await output?.write( - { rows: [1, 2] }, - { command: "rows", duration: "0ms", format }, - ); + await output?.write({ rows: [1, 2] }, { command: "rows", duration: "0ms" }); expect(output?.error).toMatchObject({ code: "invalid_request", message: expect.stringContaining("non-index property"), diff --git a/tests/boundary/cli/filteredFailureOutput.test.ts b/tests/boundary/cli/filteredFailureOutput.test.ts index 0726b3e6ae..fa64a5499f 100644 --- a/tests/boundary/cli/filteredFailureOutput.test.ts +++ b/tests/boundary/cli/filteredFailureOutput.test.ts @@ -1,16 +1,14 @@ +import { registerCliCommand } from "../../../src/cli/commandRegistry.js"; +import { createCommandCli } from "../../support/cli/commandCli.js"; import { randomUUID } from "node:crypto"; import { Writable } from "node:stream"; -import { Cli } from "incur"; import { z } from "zod"; import { parse as parseYaml } from "yaml"; import { expect, it } from "vitest"; import { parseCliOutputArguments } from "../../../src/cliOutput.js"; -import { - createCliResultOutput, - streamCliCommandResults, -} from "../../../src/cli/cliResultOutput.js"; +import { createCliResultOutput } from "../../../src/cli/cliResultOutput.js"; import { parseCliJsonInput } from "../../../src/cli/cliJsonInput.js"; import { logCliCommand } from "../../../src/cliLogging.js"; import { silentLogger } from "../../../src/logger.js"; @@ -28,8 +26,8 @@ const runCli = async (arguments_: readonly string[]) => { destination, ); if (output === undefined) throw new Error("Missing CLI result output owner"); - const cli = Cli.create("filtered-failure-test", { sync: false }); - cli.command("trace-application-feature", { + const cli = createCommandCli(output); + registerCliCommand(cli, "trace-application-feature", { args: z.object({ path: z.string() }), run: ({ args }) => logCliCommand(silentLogger, "trace-application-feature", async () => { @@ -40,7 +38,6 @@ const runCli = async (arguments_: readonly string[]) => { return input.ok ? input.value : input.error; }), }); - streamCliCommandResults(cli, output); let fallback = ""; await cli.serve([...arguments_], { stdout: (text) => { @@ -185,9 +182,8 @@ it("keeps successful scalar filtering available", async () => { destination, ); if (output === undefined) throw new Error("Missing CLI result output owner"); - const cli = Cli.create("filtered-failure-test", { sync: false }); - cli.command("open-control", { run: () => ({ open: false }) }); - streamCliCommandResults(cli, output); + const cli = createCommandCli(output); + registerCliCommand(cli, "open-control", { run: () => ({ open: false }) }); const previousExitCode = process.exitCode; process.exitCode = 0; try { diff --git a/tests/boundary/cli/formattingRecovery.test.ts b/tests/boundary/cli/formattingRecovery.test.ts index 7b49433b1b..11eaab5d1e 100644 --- a/tests/boundary/cli/formattingRecovery.test.ts +++ b/tests/boundary/cli/formattingRecovery.test.ts @@ -1,13 +1,11 @@ +import { registerCliCommand } from "../../../src/cli/commandRegistry.js"; +import { createCommandCli } from "../../support/cli/commandCli.js"; import { Writable } from "node:stream"; -import { Cli } from "incur"; import { describe, expect, it } from "vitest"; import { parseCliOutputArguments } from "../../../src/cliOutput.js"; -import { - createCliResultOutput, - streamCliCommandResults, -} from "../../../src/cli/cliResultOutput.js"; +import { createCliResultOutput } from "../../../src/cli/cliResultOutput.js"; import { cliOperationFailureIdentity, cliOperationFailurePayload, @@ -21,7 +19,20 @@ import { withCliEvidencePublication, } from "../../../src/cli/cliEvidencePublication.js"; -const metadata = { command: "fixture", duration: "1ms", format: "toon" }; +const metadata = { command: "fixture", duration: "1ms" }; + +/** Fail at the formatter boundary after the command has returned its result. */ +const formattingFailureValue = ( + cause = new RangeError("Invalid string length"), +) => + new Proxy( + {}, + { + ownKeys: () => { + throw cause; + }, + }, + ); it("keeps receipts isolated across concurrent invocations", async () => { const results = await Promise.all( @@ -40,7 +51,7 @@ it("keeps receipts isolated across concurrent invocations", async () => { expect(cliEvidencePublicationReceipt()).toBeUndefined(); }); -it("retains a publication receipt when formatting fails after the invocation context ends", async () => { +it("retains a publication receipt after formatting recovery leaves the invocation context", async () => { const chunks: Buffer[] = []; const output = createCliResultOutput( parseCliOutputArguments([]), @@ -54,13 +65,14 @@ it("retains a publication receipt when formatting fails after the invocation con if (output === undefined) throw new Error("Missing output owner"); await withCliEvidencePublication(async () => { recordCliEvidencePublication({ path: "/tmp/result.json", bytes: 123 }); - expect(await output.write({ result: "completed" }, metadata)).toBe(false); + expect(await output.write(formattingFailureValue(), metadata)).toBe(true); }); + expect(cliEvidencePublicationReceipt()).toBeUndefined(); expect( await output.recoverFormattingFailure( new RangeError("Invalid string length"), ), - ).toBe(true); + ).toBe(false); expect(output.error).toMatchObject({ code: "resource_constraint", details: { @@ -97,7 +109,7 @@ it.each([ if (output === undefined) throw new Error("Missing output owner"); await withCliEvidencePublication(async () => { recordCliEvidencePublication(receipt); - expect(await output.write({ value }, { ...metadata, format })).toBe(true); + expect(await output.write({ value }, metadata)).toBe(true); }); expect(output.error).toMatchObject({ code: "invalid_request", @@ -108,36 +120,6 @@ it.each([ ); describe("CLI formatting stage admission", () => { - it("preserves native CTA sentinel output", async () => { - const replies: string[] = []; - for (const wrapped of [false, true]) { - const cli = Cli.create("rea-output-test", { sync: false }); - cli.command("fixture", { - run: (context) => - context.ok( - { value: 42 }, - { cta: { commands: [{ command: "next" }] } }, - ), - }); - const output = createCliResultOutput( - parseCliOutputArguments(["fixture"]), - new Writable(), - ); - if (output === undefined) throw new Error("Missing output owner"); - if (wrapped) streamCliCommandResults(cli, output); - let reply = ""; - await cli.serve(["fixture"], { - stdout: (text) => { - reply += text; - }, - }); - expect(output.handled).toBe(false); - replies.push(reply); - } - expect(replies[1]).toBe(replies[0]); - expect(replies[0]).toContain("next"); - }); - it("captures thrown integrity failures without re-reading diagnostics during recovery", async () => { const previousExitCode = process.exitCode; try { @@ -170,7 +152,11 @@ describe("CLI formatting stage admission", () => { it("declines errors before a result or from a different failure class", async () => { const output = createCliResultOutput( parseCliOutputArguments([]), - new Writable(), + new Writable({ + write(_chunk, _encoding, done) { + done(); + }, + }), ); expect(output).toBeDefined(); expect( @@ -185,22 +171,21 @@ describe("CLI formatting stage admission", () => { new Error("operation failed"), ]) expect(await output?.recoverFormattingFailure(cause)).toBe(false); - expect(output?.handled).toBe(false); + expect(output?.handled).toBe(true); }); - it("leaves command RangeErrors under Incur's command failure protocol", async () => { - const cli = Cli.create("rea-output-test", { sync: false }); - cli.command("fixture", { - run: () => { - throw new RangeError("Invalid string length"); - }, - }); + it("keeps command RangeErrors distinct from post-result formatting capacity failures", async () => { const output = createCliResultOutput( parseCliOutputArguments([]), new Writable(), ); if (output === undefined) throw new Error("Missing output owner"); - streamCliCommandResults(cli, output); + const cli = createCommandCli(output); + registerCliCommand(cli, "fixture", { + run: () => { + throw new RangeError("Invalid string length"); + }, + }); let text = ""; let status = 0; await cli.serve(["fixture"], { @@ -240,9 +225,7 @@ describe("CLI formatting recovery outcomes", () => { }, ); - expect(await output?.write(value, { ...metadata, format: "md" })).toBe( - true, - ); + expect(await output?.write(value, { ...metadata })).toBe(true); expect(output?.error).toMatchObject({ code: "resource_constraint" }); const text = Buffer.concat(chunks).toString("utf8"); expect(text).toContain("resource_constraint"); @@ -260,8 +243,9 @@ describe("CLI formatting recovery outcomes", () => { }, }), ); - await output?.write({ result: "completed" }, metadata); - await expect(output?.recoverFormattingFailure(cause)).rejects.toBe(cause); + await expect( + output?.write(formattingFailureValue(cause), metadata), + ).rejects.toBe(cause); expect(output?.handled).toBe(true); expect(output?.failed).toBe(true); expect(await output?.recoverFormattingFailure(cause)).toBe(false); @@ -278,7 +262,7 @@ describe("CLI formatting recovery outcomes", () => { }), ); await expect( - output?.write({ result: "completed" }, { ...metadata, format: "json" }), + output?.write({ result: "completed" }, { ...metadata }), ).rejects.toBe(cause); expect(output?.handled).toBe(true); expect(output?.failed).toBe(true); @@ -306,12 +290,12 @@ describe("CLI formatting recovery outcomes", () => { remediation: { action: "Check the selected path." }, details: { partial_observation: { text: "captured" } }, })); - expect(await output?.write(value, metadata)).toBe(false); - expect( - await output?.recoverFormattingFailure( - new RangeError("Invalid string length"), - ), - ).toBe(true); + Object.defineProperty(value, "details", { + get() { + throw new RangeError("Invalid string length"); + }, + }); + expect(await output?.write(value, metadata)).toBe(true); expect(output?.error).toMatchObject({ code: "resource_constraint", details: { diff --git a/tests/boundary/cli/gdbStartupCleanupCli.test.ts b/tests/boundary/cli/gdbStartupCleanupCli.test.ts index 5344243460..1a6d3ee124 100644 --- a/tests/boundary/cli/gdbStartupCleanupCli.test.ts +++ b/tests/boundary/cli/gdbStartupCleanupCli.test.ts @@ -1,3 +1,5 @@ +import { createCommandCli } from "../../support/cli/commandCli.js"; +import { cliCommand } from "../../../src/cli/commandRegistry.js"; import { EventEmitter } from "node:events"; import { PassThrough } from "node:stream"; import { spawnFailure } from "../../support/process/spawnFailure.js"; @@ -9,45 +11,15 @@ import { AnalysisOutputError } from "../../../src/domain/analysisErrorCore.js"; import { err } from "../../../src/domain/result.js"; import { registerReverseEngineeringCommands } from "../../../src/cli/reverseEngineeringCommands.js"; import { CLI_COMMANDS } from "../../../src/contracts/cliCommandNames.js"; -import type { CliInstance } from "../../../src/cli/types.js"; import { GdbSessionManager } from "../../../src/gdb/GdbSessionManager.js"; import { answerFakeGdbStartup } from "../providers/gdbTestHelpers.js"; -const registerGdbCommand = ( - createManager: () => GdbSessionManager, -): { - run(input: { - args: { command: string }; - options: { inferiorTty: string }; - }): Promise; -} => { - const commands = new Map< - string, - { - run(input: { - args: { command: string }; - options: { inferiorTty: string }; - }): Promise; - } - >(); - const cli = { - command: ( - name: string, - definition: { - run(input: { - args: { command: string }; - options: { inferiorTty: string }; - }): Promise; - }, - ) => { - commands.set(name, definition); - return cli; - }, - } as unknown as CliInstance; +const registerGdbCommand = (createManager: () => GdbSessionManager) => { + const cli = createCommandCli(); registerReverseEngineeringCommands(cli, pino({ enabled: false }), {}, () => createManager(), ); - const command = commands.get(CLI_COMMANDS.debugWithGdb); + const command = cliCommand(cli, CLI_COMMANDS.debugWithGdb)?.definition; if (command === undefined) throw new Error("GDB CLI command was not registered"); return command; @@ -67,6 +39,7 @@ it.each([ } as unknown as GdbSessionManager; const command = registerGdbCommand(() => manager); const result = await command.run({ + formatExplicit: false, args: { command: inputCommand }, options: { inferiorTty: "/dev/pts/42" }, }); @@ -97,6 +70,7 @@ it("retries retained GDB cleanup when CLI session startup fails", async () => { try { const result = await command.run({ + formatExplicit: false, args: { command: "info files" }, options: { inferiorTty: "/dev/pts/42" }, }); @@ -125,6 +99,7 @@ it("marks the CLI failed when retained GDB cleanup remains incomplete", async () try { const result = await command.run({ + formatExplicit: false, args: { command: "info files" }, options: { inferiorTty: "/dev/pts/42" }, }); @@ -158,6 +133,7 @@ it.each(["ENOENT", "EACCES", "EPERM"] as const)( const previousExitCode = process.exitCode; try { const result = await command.run({ + formatExplicit: false, args: { command: "show version" }, options: { inferiorTty: "/dev/pts/42" }, }); @@ -293,6 +269,7 @@ it.each(["incomplete", "interrupt", "control"] as const)( try { process.exitCode = 0; const result = await command.run({ + formatExplicit: false, args: { command: "info files" }, options: { inferiorTty: "/dev/pts/7" }, }); diff --git a/tests/boundary/cli/javascriptApplicationPathAdmission.test.ts b/tests/boundary/cli/javascriptApplicationPathAdmission.test.ts index ea7d45ec40..1bc37a2331 100644 --- a/tests/boundary/cli/javascriptApplicationPathAdmission.test.ts +++ b/tests/boundary/cli/javascriptApplicationPathAdmission.test.ts @@ -1,12 +1,10 @@ -import { Cli } from "incur"; +import { createCommandCli } from "../../support/cli/commandCli.js"; import { expect, it } from "vitest"; import { registerElectronCommands } from "../../../src/cli/electronCommands.js"; import { silentLogger } from "../../../src/logger.js"; const serve = async (argv: readonly string[]): Promise => { - const cli = Cli.create("javascript-application-path-admission", { - sync: false, - }); + const cli = createCommandCli(); registerElectronCommands(cli, silentLogger, {}); let stdout = ""; await cli.serve([...argv, "--json"], { diff --git a/tests/boundary/cli/jebInputDiagnostics.test.ts b/tests/boundary/cli/jebInputDiagnostics.test.ts index 984714068f..777103059c 100644 --- a/tests/boundary/cli/jebInputDiagnostics.test.ts +++ b/tests/boundary/cli/jebInputDiagnostics.test.ts @@ -1,4 +1,4 @@ -import { Cli } from "incur"; +import { createCommandCli } from "../../support/cli/commandCli.js"; import { Ajv2020 } from "ajv/dist/2020.js"; import { expect, it } from "vitest"; @@ -43,7 +43,7 @@ const invoke = async (argv: readonly string[]) => { ); }, }; - const cli = Cli.create("rea-jeb-input-test", { sync: false }); + const cli = createCommandCli(); registerJebCommands(cli, silentLogger, {}, provider); let stdout = ""; let exitCode = 0; diff --git a/tests/boundary/cli/jsonInputSchema.test.ts b/tests/boundary/cli/jsonInputSchema.test.ts index 76e899975b..af0383b2d0 100644 --- a/tests/boundary/cli/jsonInputSchema.test.ts +++ b/tests/boundary/cli/jsonInputSchema.test.ts @@ -41,7 +41,7 @@ import { jsonInputContentSchema, } from "../../../src/cli/jsonInputArgument.js"; import { cliJsonCallerPathSchema } from "../../../src/cli/cliJsonInput.js"; -import { visitRegisteredCommands } from "../../../src/cli/visitRegisteredCommands.js"; +import { cliCommands } from "../../../src/cli/commandRegistry.js"; import type { CliInstance } from "../../../src/cli/types.js"; const frame = (schema: z.ZodType): z.ZodType => @@ -185,7 +185,7 @@ interface InputJsonSchema { const jsonInputCommands = (cli: CliInstance): string[] => { const names: string[] = []; - visitRegisteredCommands(cli, (command, path) => { + cliCommands(cli).forEach(({ definition: command, name: path }) => { if ( command.args instanceof z.ZodObject && Object.hasOwn(command.args.shape, "inputJson") diff --git a/tests/boundary/cli/jsonLinesOutput.test.ts b/tests/boundary/cli/jsonLinesOutput.test.ts index 51d779b511..35f5f94e32 100644 --- a/tests/boundary/cli/jsonLinesOutput.test.ts +++ b/tests/boundary/cli/jsonLinesOutput.test.ts @@ -1,14 +1,12 @@ import { Writable } from "node:stream"; -import { Cli } from "incur"; +import { createCommandCli } from "../../support/cli/commandCli.js"; +import { registerCliCommand } from "../../../src/cli/commandRegistry.js"; import { z } from "zod"; import { estimateTokenCount } from "tokenx"; import { describe, expect, it } from "vitest"; -import { - createCliResultOutput, - streamCliCommandResults, -} from "../../../src/cli/cliResultOutput.js"; +import { createCliResultOutput } from "../../../src/cli/cliResultOutput.js"; import { jsonLinesErrorRecord } from "../../../src/cli/jsonLines.js"; import { parseCliOutputArguments } from "../../../src/cliOutput.js"; import { logCliCommand } from "../../../src/cliLogging.js"; @@ -467,25 +465,23 @@ describe("JSON Lines counting and transport", () => { }, ]; const stream = capture(["--format", "jsonl"]); - const cli = Cli.create("explicit-success", { sync: false }).command( - "rows", - { - run: () => - logCliCommand( - silentLogger, - "rows", - async () => value, - () => false, - ), - }, - ); - streamCliCommandResults(cli, stream.output); + const cli = createCommandCli(stream.output); + registerCliCommand(cli, "rows", { + run: () => + logCliCommand( + silentLogger, + "rows", + async () => value, + () => false, + ), + }); + await cli.serve(["rows", "--format", "jsonl"], { stdout: () => undefined }); expect(lines(stream.text())).toEqual(value); }); }); -describe("SDK-owned JSON Lines parser diagnostics", () => { +describe("Command-owned JSON Lines parser diagnostics", () => { it.each([false, true])( "retains counted parser diagnostics (full: %s)", async (full) => { @@ -498,21 +494,22 @@ describe("SDK-owned JSON Lines parser diagnostics", () => { ]; for (const extra of [[], ["--zzz-bogus"]]) { const stream = capture(args); - const cli = Cli.create("sdk-count", { sync: false }).command("rows", { + const cli = createCommandCli(stream.output); + registerCliCommand(cli, "rows", { args: z.object({ required: z.string() }), run: () => [{ id: "row" }], }); - streamCliCommandResults(cli, stream.output); + let status = 0; await cli.serve([...args, ...extra], { stdout: (text) => { - stream.output.captureSdkOutput(text); + stream.destination.write(text); }, exit: (code) => { status = code; }, }); - await stream.output.finishSdkOutput(status); + await stream.output.finish(); expect(status).toBe(1); const diagnostic = { code: extra.length === 0 ? "VALIDATION_ERROR" : "UNKNOWN", @@ -537,27 +534,27 @@ describe("SDK-owned JSON Lines parser diagnostics", () => { ); }); -describe("SDK-owned JSON Lines outcomes", () => { - it("uses SDK status to frame validation errors and resets ownership between invocations", async () => { +describe("Command-owned JSON Lines outcomes", () => { + it("frames parsed validation failures and resets output ownership between invocations", async () => { const stream = capture(["--format", "jsonl"]); - const cli = Cli.create("sdk-status", { sync: false }).command("rows", { + const cli = createCommandCli(stream.output); + registerCliCommand(cli, "rows", { args: z.object({ required: z.string() }), run: () => [{ id: "row" }], }); - streamCliCommandResults(cli, stream.output); + const serve = async (args: string[]) => { let status = 0; stream.output.begin(parseCliOutputArguments(args)); await cli.serve(args, { stdout: (text) => { - if (!stream.output.handled && !stream.output.captureSdkOutput(text)) - throw new Error("Unexpected delegation"); + stream.destination.write(text); }, exit: (code) => { status = code; }, }); - await stream.output.finishSdkOutput(status); + await stream.output.finish(); return status; }; expect(await serve(["rows", "--format", "jsonl"])).toBe(1); @@ -570,87 +567,4 @@ describe("SDK-owned JSON Lines outcomes", () => { expect(lines(stream.text())[1]).toEqual({ id: "row" }); expect(stream.output.error).toBeUndefined(); }); - - it.each([ - { failure: false, count: false }, - { failure: true, count: false }, - { failure: false, count: true }, - { failure: true, count: true }, - ])( - "preserves sentinel outcomes under counting (%j)", - async ({ failure, count }) => { - const args = [ - "result", - "--format", - "jsonl", - ...(count ? ["--token-count"] : []), - ]; - const stream = capture(args); - const cli = Cli.create("sdk-sentinel", { sync: false }).command( - "result", - { - run: (context) => - failure - ? context.error({ - code: "EXPLICIT_FAILURE", - message: "Caller-owned error", - }) - : context.ok({ - code: "EXPLICIT_FAILURE", - message: "Successful data", - }), - }, - ); - streamCliCommandResults(cli, stream.output); - let status = 0; - await cli.serve(args, { - stdout: (text) => { - stream.output.captureSdkOutput(text); - }, - exit: (code) => { - status = code; - }, - }); - expect(stream.text()).toBe(""); - await stream.output.finishSdkOutput(status); - expect(lines(stream.text())[0]).toEqual( - count && !failure - ? estimateTokenCount( - JSON.stringify({ - code: "EXPLICIT_FAILURE", - message: "Successful data", - }) + "\n", - ) - : failure - ? jsonLinesErrorRecord({ - code: "EXPLICIT_FAILURE", - message: "Caller-owned error", - }) - : { code: "EXPLICIT_FAILURE", message: "Successful data" }, - ); - }, - ); - - it("delegates generator events immediately without retaining the stream", async () => { - const stream = capture(["--format", "jsonl"]); - const delegated: string[] = []; - const cli = Cli.create("sdk-stream", { sync: false }).command("events", { - run: async function* () { - yield { text: "first" }; - expect(delegated.length).toBeGreaterThan(0); - yield { text: "second" }; - }, - }); - streamCliCommandResults(cli, stream.output); - await cli.serve(["events", "--format", "jsonl"], { - stdout: (text) => { - expect(stream.output.captureSdkOutput(text)).toBe(false); - delegated.push(text); - }, - }); - await stream.output.finishSdkOutput(0); - expect(stream.text()).toBe(""); - expect(delegated.join("")).toContain("first"); - expect(delegated.join("")).toContain("second"); - }); }); diff --git a/tests/boundary/cli/jsonOutput.test.ts b/tests/boundary/cli/jsonOutput.test.ts index bc202be1b5..78179f74a4 100644 --- a/tests/boundary/cli/jsonOutput.test.ts +++ b/tests/boundary/cli/jsonOutput.test.ts @@ -1,18 +1,16 @@ +import { registerCliCommand } from "../../../src/cli/commandRegistry.js"; +import { createCommandCli } from "../../support/cli/commandCli.js"; import { constants } from "node:buffer"; import { createHash } from "node:crypto"; import { Writable } from "node:stream"; -import { Cli } from "incur"; import { estimateTokenCount } from "tokenx"; import { parse as parseYaml } from "yaml"; import { describe, expect, it } from "vitest"; import { writeJsonOutput } from "../../../src/cli/jsonOutput.js"; import { parseCliOutputArguments } from "../../../src/cliOutput.js"; -import { - createCliResultOutput, - streamCliCommandResults, -} from "../../../src/cli/cliResultOutput.js"; +import { createCliResultOutput } from "../../../src/cli/cliResultOutput.js"; import { logCliCommand } from "../../../src/cliLogging.js"; import { registerManagedCommands } from "../../../src/cli/managedCommands.js"; import { analysisErrorProjectionSchema } from "../../../src/domain/analysisErrorProjectionSchema.js"; @@ -44,7 +42,7 @@ const collect = async ( return Buffer.concat(chunks).toString("utf8"); }; -describe("SDK output completion", () => { +describe("CLI output completion", () => { it.each(["json", "toon"])( "waits for pending raw %s writes before exit", async (format) => { @@ -66,7 +64,7 @@ describe("SDK output completion", () => { }); }, }); - // Terminal JSON stays with Incur; only pipes buffer for compact rewrite. + // Both layouts retain the caller-owned destination until its writes drain. if (format === "json") Object.defineProperty(destination, "isTTY", { value: true }); const output = createCliResultOutput( @@ -75,113 +73,13 @@ describe("SDK output completion", () => { ); if (output === undefined) throw new Error("Expected valid output controls"); - expect(output.captureSdkOutput(document)).toBe(false); destination.write(document); expect(complete).toBe(false); - await output.finishSdkOutput(1); + await output.finish(); expect(complete).toBe(true); expect(destination.writableEnded).toBe(false); }, ); - - it("rewrites piped SDK JSON diagnostics compactly", async () => { - const value = { - code: "VALIDATION_ERROR", - message: "REA could not read the command arguments.", - fieldErrors: [{ path: "symbols", missing: true, expected: "array" }], - }; - const indented = `${JSON.stringify(value, null, 2)}\n`; - const chunks: Buffer[] = []; - const destination = new Writable({ - write(chunk: unknown, _encoding, callback) { - if (!Buffer.isBuffer(chunk)) { - callback(new TypeError("Expected a UTF-8 output buffer")); - return; - } - chunks.push(chunk); - callback(); - }, - }); - const output = createCliResultOutput( - parseCliOutputArguments(["--json"]), - destination, - ); - if (output === undefined) throw new Error("Expected valid output controls"); - expect(output.captureSdkOutput(indented)).toBe(true); - expect(Buffer.concat(chunks).toString("utf8")).toBe(""); - await output.finishSdkOutput(1); - const text = Buffer.concat(chunks).toString("utf8"); - expect(text).toBe(`${JSON.stringify(value)}\n`); - expect(text).not.toContain("\n "); - expect(JSON.parse(text)).toEqual(value); - }); - - it("counts tokens for piped SDK JSON documents instead of rewriting them", async () => { - const value = { - version: "incur.v1", - commands: [{ name: "inspect-devicetree" }], - }; - const indented = `${JSON.stringify(value, null, 2)}\n`; - const compact = `${JSON.stringify(value)}\n`; - const chunks: Buffer[] = []; - const destination = new Writable({ - write(chunk: unknown, _encoding, callback) { - if (!Buffer.isBuffer(chunk)) { - callback(new TypeError("Expected a UTF-8 output buffer")); - return; - } - chunks.push(chunk); - callback(); - }, - }); - const output = createCliResultOutput( - parseCliOutputArguments([ - "--llms-full", - "--format", - "json", - "--token-count", - ]), - destination, - ); - if (output === undefined) throw new Error("Expected valid output controls"); - expect( - output.sdkArguments(["--llms-full", "--format", "json", "--token-count"]), - ).toEqual(expect.any(Array)); - expect(output.captureSdkOutput(indented)).toBe(true); - await output.finishSdkOutput(0); - expect(Buffer.concat(chunks).toString("utf8")).toBe( - `${estimateTokenCount(compact)}\n`, - ); - }); - - it("preserves non-JSON piped --json output under --token-count (completion hooks)", async () => { - const hook = "# bash completion hook\ncomplete -F _rea rea\n"; - const chunks: Buffer[] = []; - const destination = new Writable({ - write(chunk: unknown, _encoding, callback) { - if (!Buffer.isBuffer(chunk)) { - callback(new TypeError("Expected a UTF-8 output buffer")); - return; - } - chunks.push(chunk); - callback(); - }, - }); - const output = createCliResultOutput( - parseCliOutputArguments([ - "completions", - "bash", - "--json", - "--token-count", - ]), - destination, - ); - if (output === undefined) throw new Error("Expected valid output controls"); - output.sdkArguments(["completions", "bash", "--json", "--token-count"]); - expect(output.captureSdkOutput(hook)).toBe(true); - await output.finishSdkOutput(0); - expect(Buffer.concat(chunks).toString("utf8")).toBe(hook); - }); }); describe("incremental CLI JSON", () => { @@ -308,7 +206,7 @@ describe("incremental CLI JSON", () => { }); describe("CLI command output wrapping", () => { - it("wraps a mounted group root reached through its alias", async () => { + it("delivers a registered command through the result owner", async () => { const chunks: Buffer[] = []; const destination = new Writable({ write(chunk: Buffer, _encoding, callback) { @@ -323,17 +221,13 @@ describe("CLI command output wrapping", () => { if (output === undefined) throw new Error("Missing structured output surface"); - const group = Cli.create("nested", { - aliases: ["nested-alias"], - run: () => ({ kind: "group-root" }), - }).command("child", { run: () => ({ kind: "child" }) }); - const cli = Cli.create("rea-output-group-test", { sync: false }).command( - group, - ); - streamCliCommandResults(cli, output); + const cli = createCommandCli(output); + registerCliCommand(cli, "fixture", { + run: () => ({ kind: "command-result" }), + }); let fallback = ""; - await cli.serve(["nested-alias", "--format", "json"], { + await cli.serve(["fixture", "--format", "json", "--full-output"], { stdout: (text) => { if (!output.handled) fallback += text; }, @@ -343,8 +237,8 @@ describe("CLI command output wrapping", () => { expect(fallback).toBe(""); expect(JSON.parse(Buffer.concat(chunks).toString("utf8"))).toMatchObject({ ok: true, - data: { kind: "group-root" }, - meta: { command: "nested" }, + data: { kind: "command-result" }, + meta: { command: "fixture" }, }); }); }); @@ -386,12 +280,11 @@ describe("CLI result output surface", () => { ); if (output === undefined) throw new Error("Missing structured output surface"); - const cli = Cli.create("rea-output-test", { sync: false }); + const cli = createCommandCli(output); registerManagedCommands(cli, silentLogger, { runProviderAnalysis: async () => ({ ok: false, error: failure }), runManagedProviderEvidence: unusedManagedEvidence, }); - streamCliCommandResults(cli, output); let fallback = ""; const previousExitCode = process.exitCode; try { @@ -468,8 +361,8 @@ describe("CLI result output surface", () => { destination, ); if (output === undefined) throw new Error("Missing JSON output surface"); - const cli = Cli.create("rea-output-test", { sync: false }); - cli.command("fixture", { + const cli = createCommandCli(output); + registerCliCommand(cli, "fixture", { run: () => logCliCommand( silentLogger, @@ -478,7 +371,6 @@ describe("CLI result output surface", () => { scenario.isFailure, ), }); - streamCliCommandResults(cli, output); const previousExitCode = process.exitCode; try { await cli.serve(argv, { stdout: () => undefined }); @@ -516,7 +408,7 @@ describe("full-output token windows", () => { destination, ); if (output === undefined) throw new Error("Missing TOON output surface"); - const cli = Cli.create("rea-output-test", { sync: false }); + const cli = createCommandCli(output); registerManagedCommands(cli, silentLogger, { runProviderAnalysis: async () => ({ ok: false, @@ -531,7 +423,6 @@ describe("full-output token windows", () => { }), runManagedProviderEvidence: unusedManagedEvidence, }); - streamCliCommandResults(cli, output); const previousExitCode = process.exitCode; try { await cli.serve(argv, { stdout: () => undefined }); @@ -571,8 +462,8 @@ describe("logger classification handoff", () => { destination, ); if (output === undefined) throw new Error("Missing JSON output surface"); - const cli = Cli.create("rea-output-test", { sync: false }); - cli.command("fixture", { + const cli = createCommandCli(output); + registerCliCommand(cli, "fixture", { run: () => logCliCommand( silentLogger, @@ -581,7 +472,6 @@ describe("logger classification handoff", () => { () => false, ), }); - streamCliCommandResults(cli, output); const previousExitCode = process.exitCode; try { await cli.serve(argv, { stdout: () => undefined }); @@ -630,7 +520,6 @@ describe("full-output token counts", () => { await output.write(failure, { command: "inspect-managed-artifact", duration: "0ms", - format: "json", }); expect(output.handled).toBe(true); expect(Buffer.concat(chunks).toString("utf8")).toBe( @@ -638,7 +527,7 @@ describe("full-output token counts", () => { ); }); it("counts the exact emitted JSON representation and selected document", async () => { - const metadata = { command: "fixture", duration: "0ms", format: "json" }; + const metadata = { command: "fixture", duration: "0ms" }; for (const terminal of [false, true]) { for (const flags of [ [], @@ -664,12 +553,21 @@ describe("full-output token counts", () => { destination, ); if (output === undefined) throw new Error("Missing output surface"); - await output.write({ value: ["hello", "雪😀"] }, metadata); + await output.write({ rows: ["hello", "雪😀"] }, metadata); return Buffer.concat(chunks).toString("utf8"); }; - expect(Number((await render(true)).trim())).toBe( - estimateTokenCount(await render(false)), - ); + const document = await render(false); + // JSONL counts each emitted line independently, including metadata. + const expected = flags.includes("jsonl") + ? document + .split("\n") + .filter(Boolean) + .reduce( + (total, line) => total + estimateTokenCount(`${line}\n`), + 0, + ) + : estimateTokenCount(document); + expect(Number((await render(true)).trim())).toBe(expected); } } }); @@ -704,7 +602,7 @@ describe("full-output token counts", () => { retryable: false, remediation: { action: "Select an available target." }, }, - { command: "fixture", duration: "0ms", format: "toon" }, + { command: "fixture", duration: "0ms" }, ); const text = Buffer.concat(chunks).toString("utf8"); expect(text).toMatch(/showing tokens (\d+)–\1 of \1/); @@ -741,7 +639,7 @@ describe("CLI result output surface", () => { await expect( output.write( { result: "small" }, - { command: "fixture", duration: "1ms", format: "json" }, + { command: "fixture", duration: "1ms" }, ), ).rejects.toBe(cause); expect(output.handled).toBe(true); @@ -779,15 +677,6 @@ describe("CLI result output surface", () => { callback(); }, }); - const cli = Cli.create("rea-output-test", { sync: false }); - registerManagedCommands(cli, silentLogger, { - runProviderAnalysis: async (...[path, operation]) => { - expect(path).toBe("fixture.dll"); - expect(operation).toBe("inspect_managed_members"); - return { ok: false, error: value }; - }, - runManagedProviderEvidence: unusedManagedEvidence, - }); // A terminal destination exercises the indented encoding past the limit. Object.defineProperty(destination, "isTTY", { value: true }); const argv = ["inspect-managed-members", "fixture.dll", "--json"]; @@ -796,7 +685,15 @@ describe("CLI result output surface", () => { destination, ); if (output === undefined) throw new Error("Missing JSON output surface"); - streamCliCommandResults(cli, output); + const cli = createCommandCli(output); + registerManagedCommands(cli, silentLogger, { + runProviderAnalysis: async (...[path, operation]) => { + expect(path).toBe("fixture.dll"); + expect(operation).toBe("inspect_managed_members"); + return { ok: false, error: value }; + }, + runManagedProviderEvidence: unusedManagedEvidence, + }); let exitCode = 0; let fallbackBytes = 0; await cli.serve(argv, { @@ -825,12 +722,11 @@ describe("CLI result output surface", () => { ); if (tokenOutput === undefined) throw new Error("Missing token-count output surface"); - const tokenCli = Cli.create("rea-output-test", { sync: false }); + const tokenCli = createCommandCli(tokenOutput); registerManagedCommands(tokenCli, silentLogger, { runProviderAnalysis: async () => ({ ok: false, error: value }), runManagedProviderEvidence: unusedManagedEvidence, }); - streamCliCommandResults(tokenCli, tokenOutput); await tokenCli.serve(tokenArgv, { stdout: (text) => { if (!tokenOutput.handled) fallbackBytes += text.length; @@ -900,7 +796,7 @@ describe("streamed CLI filtered selections", () => { if (output === undefined) throw new Error("Missing JSON output surface"); await output.write( { raw_result: null, nested: { value: null }, count: 0, enabled: false }, - { command: "fixture", duration: "1ms", format }, + { command: "fixture", duration: "1ms" }, ); const text = Buffer.concat(chunks).toString("utf8"); if (expected === "JSONL_BOUNDARY_ERROR") diff --git a/tests/boundary/cli/markdownArgumentErrors.test.ts b/tests/boundary/cli/markdownArgumentErrors.test.ts index 647bf16990..5cf73cf1ed 100644 --- a/tests/boundary/cli/markdownArgumentErrors.test.ts +++ b/tests/boundary/cli/markdownArgumentErrors.test.ts @@ -1,4 +1,8 @@ -import { Cli, Errors } from "incur"; +import { + registerCliCommand, + cliCommand, +} from "../../../src/cli/commandRegistry.js"; +import { createCommandCli } from "../../support/cli/commandCli.js"; import { z } from "zod"; import { parseFragment, type DefaultTreeAdapterTypes } from "parse5"; import { estimateTokenCount } from "tokenx"; @@ -6,14 +10,12 @@ import { createMarkdownRenderer, disposeMdItInstance } from "vitepress"; import { afterAll, expect, it } from "vitest"; import { - encodeCliArgumentErrors, - presentCliArgumentErrors, + redactCliCommandFailure, + renderCliCommandFailure, } from "../../../src/cli/argumentErrors.js"; -import { - excludeDeclaredSensitiveArguments, - explicitSensitiveValueOptions, -} from "../../../src/cli/explicitSensitiveArguments.js"; +import { explicitSensitiveValueOptions } from "../../../src/cli/explicitSensitiveArguments.js"; +import { readCliOutputArguments } from "../../../src/cliOutput.js"; import { parseCliGlobalArguments } from "../../../src/cliBuiltinArguments.js"; import { cliTest } from "../../support/cli/cliFixture.js"; @@ -62,17 +64,17 @@ cliTest( const renderer = await createMarkdownRenderer(process.cwd(), { linkify: false, }); + const visibleText = (node: DefaultTreeAdapterTypes.Node): string => + node.nodeName === "#text" && "value" in node + ? node.value + : "childNodes" in node + ? node.childNodes.map(visibleText).join("") + : ""; const renderedCells = (output: string): string[] => { const cells: string[] = []; const visit = (node: DefaultTreeAdapterTypes.Node): void => { if ("tagName" in node && node.tagName === "td") { - const text = (child: DefaultTreeAdapterTypes.Node): string => - child.nodeName === "#text" && "value" in child - ? child.value - : "childNodes" in child - ? child.childNodes.map(text).join("") - : ""; - cells.push(text(node)); + cells.push(visibleText(node)); } else if ("childNodes" in node) node.childNodes.forEach(visit); }; visit(parseFragment(renderer.render(output))); @@ -83,7 +85,9 @@ cliTest( expect(Number(count.stdout.trim())).toBe( estimateTokenCount(markdown.stdout.trimEnd()), ); - expect(window.stdout).toContain("[truncated: showing tokens 0–20 of "); + expect( + visibleText(parseFragment(renderer.render(window.stdout))), + ).toContain("[truncated: showing tokens 0–20 of "); expect(window.stdout).toContain("nextOffset"); // A different parser error has a much longer enum. Compare the visible @@ -143,6 +147,50 @@ cliTest( }, ); +// Exercise literal field facts at the presentation boundary; shipped schemas +// cannot manufacture all punctuation/whitespace combinations as issue fields. +const fixtureDiagnostic = ( + value: string, + secret: string, + format: string, + sensitive: boolean, +): string => { + const cli = createCommandCli(); + registerCliCommand(cli, "inspect", { + options: z.object({ ...explicitSensitiveValueOptions }), + run: () => undefined, + }); + const entry = cliCommand(cli, "inspect")!; + return renderCliCommandFailure( + redactCliCommandFailure( + { + code: "VALIDATION_ERROR", + message: "fixture", + fieldErrors: [ + { + code: "invalid_value", + missing: false, + path: "input", + expected: "", + received: value, + message: `Value ${value} is invalid`, + }, + ], + }, + sensitive ? [secret] : [], + ), + { + cli: cli.name, + entry, + duration: "0ms", + stdoutIsTerminal: false, + controls: readCliOutputArguments( + parseCliGlobalArguments(["--format", format]), + ), + }, + ); +}; + it("redacts Markdown punctuation in validation fields before presentation", async () => { for (const secret of [ "left|right", @@ -150,54 +198,8 @@ it("redacts Markdown punctuation in validation fields before presentation", asyn "left\\right", "&value", ]) { - const cli = Cli.create("sensitive-fixture", { sync: false }); - cli.command("inspect", { - options: z.object({ ...explicitSensitiveValueOptions }), - run: () => { - throw new Errors.ValidationError({ - message: "fixture", - fieldErrors: [ - { - code: "invalid_value", - missing: false, - path: "input", - expected: "", - received: secret, - message: `Value ${secret} is invalid`, - }, - ], - }); - }, - }); - presentCliArgumentErrors(cli); - const declared = excludeDeclaredSensitiveArguments(cli); - encodeCliArgumentErrors(cli); - const original = cli.serve.bind(cli); - const run = async (format: string, sensitive: boolean) => { - let stdout = ""; - let exitCode = 0; - const global = parseCliGlobalArguments([ - "inspect", - ...(sensitive ? ["--sensitive-value", secret] : []), - "--format", - format, - ]); - await declared( - global, - { - env: {}, - stdout: (text) => { - stdout += text; - }, - exit: (code) => { - exitCode = code; - }, - }, - (options) => original([...global.arguments], options), - ); - expect(exitCode).toBe(1); - return stdout; - }; + const run = (format: string, sensitive: boolean) => + fixtureDiagnostic(secret, secret, format, sensitive); const md = await run("md", true); const json = JSON.parse(await run("json", true)); const control = JSON.parse(await run("json", false)); @@ -217,54 +219,8 @@ it("redacts Markdown punctuation in validation fields before presentation", asyn it("retains upstream Markdown literal-cell protections after redaction", async () => { const value = "\u00a0\t:smile: secret|token # {x}\t\u202f"; const secret = "secret|token"; - const cli = Cli.create("literal-validation-fixture", { sync: false }); - cli.command("inspect", { - options: z.object({ ...explicitSensitiveValueOptions }), - run: () => { - throw new Errors.ValidationError({ - message: "fixture", - fieldErrors: [ - { - code: "invalid_value", - missing: false, - path: "input", - expected: "", - received: value, - message: `Value ${value} is invalid`, - }, - ], - }); - }, - }); - presentCliArgumentErrors(cli); - const declared = excludeDeclaredSensitiveArguments(cli); - encodeCliArgumentErrors(cli); - const original = cli.serve.bind(cli); - const run = async (format: string, sensitive: boolean) => { - let stdout = ""; - let exitCode = 0; - const global = parseCliGlobalArguments([ - "inspect", - ...(sensitive ? ["--sensitive-value", secret] : []), - "--format", - format, - ]); - await declared( - global, - { - env: {}, - stdout: (text) => { - stdout += text; - }, - exit: (code) => { - exitCode = code; - }, - }, - (options) => original([...global.arguments], options), - ); - expect(exitCode).toBe(1); - return stdout; - }; + const run = (format: string, sensitive: boolean) => + fixtureDiagnostic(value, secret, format, sensitive); const md = await run("md", false); const redactedMd = await run("md", true); const json = JSON.parse(await run("json", false)); diff --git a/tests/boundary/cli/markdownNestedFacts.test.ts b/tests/boundary/cli/markdownNestedFacts.test.ts index d5d9daaffc..5019b322b2 100644 --- a/tests/boundary/cli/markdownNestedFacts.test.ts +++ b/tests/boundary/cli/markdownNestedFacts.test.ts @@ -1,6 +1,7 @@ +import { registerCliCommand } from "../../../src/cli/commandRegistry.js"; +import { createCommandCli } from "../../support/cli/commandCli.js"; import { join } from "node:path"; import { Writable } from "node:stream"; -import { Cli } from "incur"; import { expect, it } from "vitest"; import { createMarkdownRenderer } from "vitepress"; import { parseFragment, type DefaultTreeAdapterTypes } from "parse5"; @@ -9,10 +10,7 @@ import { parseCliOutputArguments, renderCliDocument, } from "../../../src/cliOutput.js"; -import { - createCliResultOutput, - streamCliCommandResults, -} from "../../../src/cli/cliResultOutput.js"; +import { createCliResultOutput } from "../../../src/cli/cliResultOutput.js"; import { writeOrderedZip } from "../../fixtures/artifactEntryOrder.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { workspaceCliTest } from "../../support/cli/workspaceCliFixture.js"; @@ -30,8 +28,6 @@ it("keeps source keys literal in Markdown headings through CLI result output", a plain: Object.freeze({ nested: Object.freeze({ value: false }) }), }); const original = JSON.stringify(value); - const cli = Cli.create("heading-facts-test", { sync: false }); - cli.command("facts", { run: () => value }); const args = ["facts", "--format", "md"]; const chunks: Buffer[] = []; const output = createCliResultOutput( @@ -44,7 +40,8 @@ it("keeps source keys literal in Markdown headings through CLI result output", a }), ); if (output === undefined) throw new Error("Missing CLI result output owner"); - streamCliCommandResults(cli, output); + const cli = createCommandCli(output); + registerCliCommand(cli, "facts", { run: () => value }); let fallback = ""; await cli.serve(args, { exit: (code) => expect(code).toBe(0), diff --git a/tests/boundary/cli/nativeFeatureTraceDelivery.test.ts b/tests/boundary/cli/nativeFeatureTraceDelivery.test.ts index 0f7316eea6..5fd5df42de 100644 --- a/tests/boundary/cli/nativeFeatureTraceDelivery.test.ts +++ b/tests/boundary/cli/nativeFeatureTraceDelivery.test.ts @@ -1,7 +1,7 @@ +import { createCommandCli } from "../../support/cli/commandCli.js"; import { unknownTarget } from "../../../src/domain/targetIdentity.js"; import { readFile, stat, writeFile } from "node:fs/promises"; import { join } from "node:path"; -import { Cli } from "incur"; import pino from "pino"; import { expect, it } from "vitest"; import { @@ -31,7 +31,7 @@ const effects = { }; const verifyReplay = async ( - cli: ReturnType, + cli: ReturnType, path: string, snapshot: string, root: string, @@ -155,7 +155,7 @@ it.each([ createNativeBinarySession: createSession, createManagedBinarySession: createSession, }; - const cli = Cli.create("rea-native-trace-cli-source", { sync: false }); + const cli = createCommandCli(); registerCoreBinaryCommands( cli, pino({ enabled: false }), diff --git a/tests/boundary/cli/nativeLoadImageSummaryCli.test.ts b/tests/boundary/cli/nativeLoadImageSummaryCli.test.ts index 76db77590c..ebf2e9223c 100644 --- a/tests/boundary/cli/nativeLoadImageSummaryCli.test.ts +++ b/tests/boundary/cli/nativeLoadImageSummaryCli.test.ts @@ -1,4 +1,4 @@ -import { Cli } from "incur"; +import { createCommandCli } from "../../support/cli/commandCli.js"; import pino from "pino"; import { readFile } from "node:fs/promises"; import { join } from "node:path"; @@ -32,7 +32,7 @@ it("preserves the relative request path in a load-image CLI summary and its comp selectedPath, ); const run = vi.fn(async () => ({ ok: true as const, value: parent })); - const cli = Cli.create("rea-load-image-cli-test", { sync: false }); + const cli = createCommandCli(); registerCoreNativeCommands(cli, pino({ enabled: false }), run); let stdout = ""; await cli.serve( diff --git a/tests/boundary/cli/overnightBatch1CliSchemas.test.ts b/tests/boundary/cli/overnightBatch1CliSchemas.test.ts index 6d32a4142a..a84de30f59 100644 --- a/tests/boundary/cli/overnightBatch1CliSchemas.test.ts +++ b/tests/boundary/cli/overnightBatch1CliSchemas.test.ts @@ -1,7 +1,7 @@ +import { createCommandCli } from "../../support/cli/commandCli.js"; import { join } from "node:path"; import { Ajv2020 } from "ajv/dist/2020.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; -import { Cli } from "incur"; import { z } from "zod"; import { expect, it, vi } from "vitest"; import { createAnalysisExecution } from "../../../src/ports/AnalysisProvider.js"; @@ -12,7 +12,7 @@ import { registerAdbCommands } from "../../../src/cli/adbCommands.js"; import { registerApktoolCommands } from "../../../src/cli/apktoolCommands.js"; import { registerCoreBinaryCommands } from "../../../src/cli/coreBinaryCommands.js"; import { registerSqliteCommands } from "../../../src/cli/sqliteCommands.js"; -import { visitRegisteredCommands } from "../../../src/cli/visitRegisteredCommands.js"; +import { cliCommands } from "../../../src/cli/commandRegistry.js"; import { silentLogger } from "../../../src/logger.js"; const registry = () => { @@ -48,7 +48,7 @@ const registry = () => { close: async () => {}, execute: apktoolExecute, }; - const cli = Cli.create("overnight-batch1-cli-schemas", { sync: false }); + const cli = createCommandCli(); registerAdbCommands(cli, silentLogger, {}, adbProvider); registerApktoolCommands(cli, silentLogger, {}, apktoolProvider); registerCoreBinaryCommands(cli, silentLogger, runDirectAnalysis, {}); @@ -213,7 +213,7 @@ it.each([ it("rejects an empty column array in the inspect-sqlite-database options schema", () => { const { cli } = registry(); let options: unknown; - visitRegisteredCommands(cli, (command, path) => { + cliCommands(cli).forEach(({ definition: command, name: path }) => { if (path === "inspect-sqlite-database") options = command.options; }); expect(options).toBeInstanceOf(z.ZodObject); diff --git a/tests/boundary/cli/procedureReferencesDelivery.test.ts b/tests/boundary/cli/procedureReferencesDelivery.test.ts index 64306a32c5..81322a050e 100644 --- a/tests/boundary/cli/procedureReferencesDelivery.test.ts +++ b/tests/boundary/cli/procedureReferencesDelivery.test.ts @@ -1,7 +1,7 @@ +import { createCommandCli } from "../../support/cli/commandCli.js"; import { unknownTarget } from "../../../src/domain/targetIdentity.js"; import { readFile, stat, writeFile } from "node:fs/promises"; import { join } from "node:path"; -import { Cli } from "incur"; import pino from "pino"; import { expect, it } from "vitest"; import { @@ -90,7 +90,7 @@ it.each([false, true])( createNativeBinarySession: createSession, createManagedBinarySession: createSession, }; - const cli = Cli.create("procedure-references", { sync: false }); + const cli = createCommandCli(); registerCoreNativeCommands( cli, pino({ enabled: false }), diff --git a/tests/boundary/cli/reverseEngineeringCommands.test.ts b/tests/boundary/cli/reverseEngineeringCommands.test.ts index 7a43f072a1..5498dba1dd 100644 --- a/tests/boundary/cli/reverseEngineeringCommands.test.ts +++ b/tests/boundary/cli/reverseEngineeringCommands.test.ts @@ -1,6 +1,7 @@ +import { cliCommand } from "../../../src/cli/commandRegistry.js"; +import { createCommandCli } from "../../support/cli/commandCli.js"; import { unknownTarget } from "../../../src/domain/targetIdentity.js"; import pino from "pino"; -import { Cli } from "incur"; import { z } from "zod"; import { afterEach, expect, it, vi } from "vitest"; import { rm } from "node:fs/promises"; @@ -64,39 +65,7 @@ const runObjdump = async ( maxOutputBytes?: number; } = {}, ) => { - const commands = new Map< - string, - { - run(input: { - args: { path: string; operation: string }; - options: { - followDebugLinks: boolean; - symbol?: string; - commandTimeoutMs?: number; - maxOutputBytes?: number; - }; - }): Promise; - } - >(); - const cli = { - command: ( - name: string, - definition: { - run(input: { - args: { path: string; operation: string }; - options: { - followDebugLinks: boolean; - symbol?: string; - commandTimeoutMs?: number; - maxOutputBytes?: number; - }; - }): Promise; - }, - ) => { - commands.set(name, definition); - return cli; - }, - } as unknown as CliInstance; + const cli = createCommandCli(); registerReverseEngineeringCommands( cli, pino({ enabled: false }), @@ -104,10 +73,14 @@ const runObjdump = async ( undefined, () => service as ReverseEngineeringService, ); - const command = commands.get(cliCommandFor("inspect_with_objdump")); + const command = cliCommand( + cli, + cliCommandFor("inspect_with_objdump"), + )?.definition; if (command === undefined) throw new Error("objdump CLI command was not registered"); return command.run({ + formatExplicit: false, args: { path, operation: selection.operation ?? "file_headers" }, options: { followDebugLinks: false, @@ -166,27 +139,8 @@ it("forwards selected objdump resource budgets and preserves omission", async () it("lists objdump architectures without inventing an artifact path", async () => { const evidence = observation("complete"); const inspectWithObjdump = vi.fn(async (_input: unknown) => ok(evidence)); - const commands = new Map< - string, - { - readonly args?: { safeParse(input: unknown): { success: boolean } }; - run(input: { args?: unknown; options?: unknown }): Promise; - } - >(); - const cli = { - command: (_name: string, definition: unknown) => { - commands.set( - _name, - definition as { - readonly args?: { - safeParse(input: unknown): { success: boolean }; - }; - run(input: { args?: unknown; options?: unknown }): Promise; - }, - ); - return cli; - }, - } as unknown as CliInstance; + + const cli = createCommandCli(); registerReverseEngineeringCommands( cli, pino({ enabled: false }), @@ -198,18 +152,28 @@ it("lists objdump architectures without inventing an artifact path", async () => close: vi.fn(async () => undefined), }) as unknown as ReverseEngineeringService, ); - const command = commands.get(CLI_COMMANDS.listObjdumpArchitectures); + const command = cliCommand( + cli, + CLI_COMMANDS.listObjdumpArchitectures, + )?.definition; if (command === undefined) throw new Error("architecture command was not registered"); - const result = await command.run({ options: { detail: "complete" } }); + const result = await command.run({ + formatExplicit: false, + args: {}, + options: { detail: "complete" }, + }); expect(result).toEqual(evidence); expect(inspectWithObjdump).toHaveBeenCalledWith( { operation: "architectures" }, expect.objectContaining({ signal: expect.any(AbortSignal) }), ); - const artifactCommand = commands.get(cliCommandFor("inspect_with_objdump")); + const artifactCommand = cliCommand( + cli, + cliCommandFor("inspect_with_objdump"), + )?.definition; expect( artifactCommand?.args?.safeParse({ path: "/tmp/sample", @@ -477,29 +441,8 @@ it.each([false, true])( "passes the Rizin TTY and uses final cleanup outcome (retry=%s)", async (retryClose) => { process.exitCode = 0; - const commands = new Map< - string, - { - run(input: { - args: Record; - options: Record; - }): Promise; - } - >(); - const cli = { - command: ( - name: string, - definition: { - run(input: { - args: Record; - options: Record; - }): Promise; - }, - ) => { - commands.set(name, definition); - return cli; - }, - } as unknown as CliInstance; + + const cli = createCommandCli(); const evidence = createEvidence( unknownTarget("not-observed"), { id: "rizin.debugger", name: "Rizin debugger", version: null }, @@ -550,11 +493,12 @@ it.each([false, true])( undefined, ); registerReverseEngineeringCommands(cli, pino({ enabled: false }), {}); - const command = commands.get(CLI_COMMANDS.debugWithRizin); + const command = cliCommand(cli, CLI_COMMANDS.debugWithRizin)?.definition; if (command === undefined) throw new Error("Rizin CLI command was not registered"); await command.run({ + formatExplicit: false, args: { path: "./sample.bin", command: "dr" }, options: { inferiorTty: "/dev/pts/7" }, }); @@ -570,15 +514,16 @@ it.each([false, true])( expect.any(AbortSignal), ); - const parserCli = Cli.create("rea-test", { version: "1.0.0", sync: false }); + const parserCli = createCommandCli(); registerReverseEngineeringCommands( parserCli as unknown as CliInstance, pino({ enabled: false }), {}, ); - const commandContract = Cli.toCommands - .get(parserCli) - ?.get(CLI_COMMANDS.debugWithRizin); + const commandContract = cliCommand( + parserCli, + CLI_COMMANDS.debugWithRizin, + )?.definition; expect(commandContract).toBeDefined(); const argsSchema = commandContract === undefined @@ -612,19 +557,7 @@ const retainedRizinCleanup = { it.each(["incomplete", "interrupt", "control"] as const)( "reports final Rizin cleanup %s as a typed outcome", async (mode) => { - const commands = new Map< - string, - { run(input: unknown): Promise } - >(); - const cli = { - command( - name: string, - definition: { run(input: unknown): Promise }, - ) { - commands.set(name, definition); - return cli; - }, - } as unknown as CliInstance; + const cli = createCommandCli(); const previous = process.exitCode; const evidence = createEvidence( unknownTarget("not-observed"), @@ -712,12 +645,13 @@ it.each(["incomplete", "interrupt", "control"] as const)( ); }); registerReverseEngineeringCommands(cli, pino({ enabled: false }), {}); - const command = commands.get(CLI_COMMANDS.debugWithRizin); + const command = cliCommand(cli, CLI_COMMANDS.debugWithRizin)?.definition; if (command === undefined) throw new Error("Rizin CLI command was not registered"); try { process.exitCode = 0; const result = await command.run({ + formatExplicit: false, args: { path: "./sample.bin", command: "dr" }, options: { inferiorTty: "/dev/pts/7" }, }); diff --git a/tests/boundary/cli/routedCommand.test.ts b/tests/boundary/cli/routedCommand.test.ts index 3d34c1b998..3774090846 100644 --- a/tests/boundary/cli/routedCommand.test.ts +++ b/tests/boundary/cli/routedCommand.test.ts @@ -1,4 +1,5 @@ -import { Cli } from "incur"; +import { cliCommand } from "../../../src/cli/commandRegistry.js"; +import { createCommandCli } from "../../support/cli/commandCli.js"; import { z } from "zod"; import pino from "pino"; import { expect, it } from "vitest"; @@ -13,7 +14,7 @@ import { absoluteLocalPathStringSchema } from "../../../src/domain/localPath.js" /** Two synthetic contracts routed by whether the target names an archive. */ const harness = () => { const calls: { route: string; cliOptions: unknown; input: unknown }[] = []; - const cli = Cli.create("rea-routed-test", { version: "1", sync: false }); + const cli = createCommandCli(); const command = { command: "probe", description: "Probe" }; registerRoutedCommand( cli as unknown as CliInstance, @@ -61,7 +62,7 @@ const harness = () => { ), ], ); - const registered = Cli.toCommands.get(cli)?.get("probe"); + const registered = cliCommand(cli, "probe")?.definition; if (registered === undefined) throw new Error("probe was not registered"); const execute = Reflect.get(registered, "run") as ( value: unknown, @@ -145,10 +146,7 @@ it("advertises each option's default without supplying it to routing", async () }); it("refuses routes that check a shared JSON input differently", () => { - const cli = Cli.create("rea-routed-check-test", { - version: "1", - sync: false, - }); + const cli = createCommandCli(); const command = { command: "probe", description: "Probe" }; const route = (name: string, check: () => { ok: true; value: string }) => commandRoute( diff --git a/tests/boundary/cli/scenarioManifestCoverage.test.ts b/tests/boundary/cli/scenarioManifestCoverage.test.ts index 78cbd581f8..1f188f88e5 100644 --- a/tests/boundary/cli/scenarioManifestCoverage.test.ts +++ b/tests/boundary/cli/scenarioManifestCoverage.test.ts @@ -1,4 +1,4 @@ -import { Cli } from "incur"; +import { createCommandCli } from "../../support/cli/commandCli.js"; import { expect, it } from "vitest"; import { registerAnalysisViewCommands } from "../../../src/cli/analysisViewCommands.js"; @@ -49,7 +49,7 @@ const manifest = async ( }), }, }); - const cli = Cli.create("scenario-coverage", { sync: false }); + const cli = createCommandCli(); registerAnalysisViewCommands(cli, silentLogger); let stdout = ""; let exitCode = 0; @@ -144,7 +144,7 @@ it("does not derive a tool from conflicting header-only MIME evidence through th })), }, ]); - const cli = Cli.create("scenario-mime", { sync: false }); + const cli = createCommandCli(); registerAnalysisViewCommands(cli, silentLogger); let stdout = ""; let exitCode = 0; diff --git a/tests/boundary/cli/searchBytesAdmission.test.ts b/tests/boundary/cli/searchBytesAdmission.test.ts index 98a2eff205..6588ed00b3 100644 --- a/tests/boundary/cli/searchBytesAdmission.test.ts +++ b/tests/boundary/cli/searchBytesAdmission.test.ts @@ -1,4 +1,4 @@ -import { Cli } from "incur"; +import { createCommandCli } from "../../support/cli/commandCli.js"; import pino from "pino"; import { expect, it, vi } from "vitest"; import { registerCoreNativeCommands } from "../../../src/cli/coreNativeCommands.js"; @@ -8,7 +8,7 @@ const registry = () => { ok: false as const, error: { code: "invalid_request", message: "Admitted query control" }, })); - const cli = Cli.create("byte-admission", { sync: false }); + const cli = createCommandCli(); registerCoreNativeCommands(cli, pino({ enabled: false }), run); return { cli, run }; }; diff --git a/tests/boundary/cli/signalCleanup.test.ts b/tests/boundary/cli/signalCleanup.test.ts index f9681ef23f..6f378a8607 100644 --- a/tests/boundary/cli/signalCleanup.test.ts +++ b/tests/boundary/cli/signalCleanup.test.ts @@ -1,5 +1,5 @@ +import { createCommandCli } from "../../support/cli/commandCli.js"; import { unknownTarget } from "../../../src/domain/targetIdentity.js"; -import { Cli } from "incur"; import { expect, it } from "vitest"; import { registerSignalCommands } from "../../../src/cli/signalCommands.js"; import { silentLogger } from "../../../src/logger.js"; @@ -24,7 +24,7 @@ it.each([ ])( "rejects invalid selections before invoking the CLI service: $message", async ({ flags, message }) => { - const cli = Cli.create("signal-selection-test", { sync: false }); + const cli = createCommandCli(); let called = false; registerSignalCommands( cli, @@ -82,7 +82,7 @@ it.each([false, true])( { operation: "decode_signal_recording", partialObservation: evidence }, ); let closed = false; - const cli = Cli.create("signal-cleanup-test", { sync: false }); + const cli = createCommandCli(); registerSignalCommands( cli, silentLogger, diff --git a/tests/boundary/cli/strictPositionals.test.ts b/tests/boundary/cli/strictPositionals.test.ts index 0321e6b96f..1f5e1d82d3 100644 --- a/tests/boundary/cli/strictPositionals.test.ts +++ b/tests/boundary/cli/strictPositionals.test.ts @@ -1,20 +1,16 @@ +import { registerCliCommand } from "../../../src/cli/commandRegistry.js"; +import { createCommandCli } from "../../support/cli/commandCli.js"; import { EVIDENCE_FORMAT_REVISION } from "../../../src/domain/evidenceFormat.js"; import { writeFile } from "node:fs/promises"; import { join } from "node:path"; -import { Cli } from "incur"; import { z } from "zod"; import { expect, it } from "vitest"; import { createCli } from "../../../src/cli.js"; -import { validateCliArguments } from "../../../src/cli/strictPositionals.js"; -import { parseCliGlobalArguments } from "../../../src/cliBuiltinArguments.js"; -import { - excludeDeclaredSensitiveArguments, - explicitSensitiveValueOptions, -} from "../../../src/cli/explicitSensitiveArguments.js"; +import { explicitSensitiveValueOptions } from "../../../src/cli/explicitSensitiveArguments.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; -type CliInstance = ReturnType; +type CliInstance = ReturnType; const serve = async (cli: CliInstance, argv: string[]) => { let stdout = ""; let exitCode = 0; @@ -29,19 +25,6 @@ const serve = async (cli: CliInstance, argv: string[]) => { }); return { stdout, exitCode }; }; -const installAdmission = (cli: CliInstance) => { - const strict = validateCliArguments(cli); - const declared = excludeDeclaredSensitiveArguments(cli); - const original = cli.serve.bind(cli); - cli.serve = (argv = [], options = {}) => { - const global = parseCliGlobalArguments(argv); - return strict(global, options, (selected) => - declared(global, selected, (declaredOptions) => - original([...global.arguments], declaredOptions), - ), - ); - }; -}; it("rejects surplus public CLI inputs before importing and retains the one-path control", async () => { const directory = await createTestTempDirectory( @@ -88,8 +71,8 @@ it("keeps parser-owned aliases, option values and optional arguments without rer let runs = 0; let transforms = 0; let defaults = 0; - const cli = Cli.create("strict-fixture", { sync: false }); - cli.command("scalar", { + const cli = createCommandCli(); + registerCliCommand(cli, "scalar", { args: z.object({ first: z.string().transform((value) => { transforms++; @@ -113,7 +96,6 @@ it("keeps parser-owned aliases, option values and optional arguments without rer return { args, options }; }, }); - installAdmission(cli); const valid = await serve(cli, [ "scalar", "one", @@ -156,28 +138,19 @@ it("keeps parser-owned aliases, option values and optional arguments without rer ).toBe(0); }); -it("uses resolved group and alias paths and preserves declared variadic inputs", async () => { - const group = Cli.create("group", { sync: false }); - group.command("scalar", { - aliases: ["alias"], +it("enforces a scalar's arity and preserves declared variadic inputs", async () => { + const cli = createCommandCli(); + registerCliCommand(cli, "scalar", { args: z.object({ value: z.string() }), run: ({ args }) => args, }); - group.command("many", { + registerCliCommand(cli, "many", { args: z.object({ values: z.array(z.string()) }), run: ({ args }) => args, }); - const cli = Cli.create("strict-groups", { sync: false }).command(group); - installAdmission(cli); - expect((await serve(cli, ["group", "scalar", "one"])).exitCode).toBe(0); - expect((await serve(cli, ["group", "scalar", "one", "extra"])).exitCode).toBe( - 1, - ); - expect((await serve(cli, ["group", "alias", "one"])).exitCode).toBe(0); - expect((await serve(cli, ["group", "alias", "one", "extra"])).exitCode).toBe( - 1, - ); - const many = await serve(cli, ["group", "many", "one", "two", "three"]); + expect((await serve(cli, ["scalar", "one"])).exitCode).toBe(0); + expect((await serve(cli, ["scalar", "one", "extra"])).exitCode).toBe(1); + const many = await serve(cli, ["many", "one", "two", "three"]); expect(many.exitCode).toBe(0); expect(JSON.parse(many.stdout)).toMatchObject({ values: ["one", "two", "three"], @@ -186,8 +159,8 @@ it("uses resolved group and alias paths and preserves declared variadic inputs", it("preserves counted aliases and negated booleans while checking the positional tail", async () => { let runs = 0; - const cli = Cli.create("strict-counted-flags", { sync: false }); - cli.command("capture", { + const cli = createCommandCli(); + registerCliCommand(cli, "capture", { args: z.object({ path: z.string() }), options: z.object({ enabled: z.boolean().default(true), @@ -199,7 +172,6 @@ it("preserves counted aliases and negated booleans while checking the positional return { args, options }; }, }); - installAdmission(cli); const valid = await serve(cli, ["capture", "one", "--no-enabled", "-vvv"]); expect(valid.exitCode).toBe(0); expect(JSON.parse(valid.stdout)).toMatchObject({ @@ -221,9 +193,8 @@ it("preserves counted aliases and negated booleans while checking the positional it("validates every dry-run literal before lossy coercion while retaining bare and negated controls", async () => { let runs = 0; let defaults = 0; - const cli = Cli.create("dry-run-fixture", { sync: false }); - cli.command("setup", { - aliases: ["plan"], + const cli = createCommandCli(); + registerCliCommand(cli, "setup", { options: z.object({ dryRun: z.boolean().default(false), selected: z.string().default(() => { @@ -236,10 +207,9 @@ it("validates every dry-run literal before lossy coercion while retaining bare a return options; }, }); - installAdmission(cli); for (const literal of ["", "abc", "1", "True", "ab\ncd"]) { const result = await serve(cli, [ - "plan", + "setup", `--dry-run=${literal}`, "--dryRun=false", ]); @@ -262,8 +232,8 @@ it("validates every dry-run literal before lossy coercion while retaining bare a }); it("keeps flag-shaped option data untouched while validating only bound dry-run values", async () => { - const cli = Cli.create("dry-run-data", { sync: false }); - cli.command("setup", { + const cli = createCommandCli(); + registerCliCommand(cli, "setup", { options: z.object({ dryRun: z.boolean().default(false), selected: z.string(), @@ -271,11 +241,10 @@ it("keeps flag-shaped option data untouched while validating only bound dry-run alias: { selected: "s" }, run: ({ options }) => options, }); - cli.command("text", { + registerCliCommand(cli, "text", { options: z.object({ dryRun: z.string() }), run: ({ options }) => options, }); - installAdmission(cli); for (const value of ["--dry-run=abc", "--dry-run", "--no-dryRun"]) { const result = await serve(cli, ["setup", "-s", value, "--dry-run=true"]); expect(result.exitCode, result.stdout).toBe(0); @@ -291,8 +260,8 @@ it("keeps flag-shaped option data untouched while validating only bound dry-run it("validates dry-run on variadic commands without losing their declared tail", async () => { let runs = 0; - const cli = Cli.create("dry-run-tail", { sync: false }); - cli.command("many", { + const cli = createCommandCli(); + registerCliCommand(cli, "many", { args: z.object({ values: z.array(z.string()), }), @@ -302,7 +271,6 @@ it("validates dry-run on variadic commands without losing their declared tail", return { args, options }; }, }); - installAdmission(cli); const rejected = await serve(cli, ["many", "one", "two", "--dry-run=abc"]); expect(rejected.exitCode).toBe(1); expect(runs).toBe(0); diff --git a/tests/boundary/cli/textUnicodeOutput.test.ts b/tests/boundary/cli/textUnicodeOutput.test.ts index 6097dc16a4..732937c649 100644 --- a/tests/boundary/cli/textUnicodeOutput.test.ts +++ b/tests/boundary/cli/textUnicodeOutput.test.ts @@ -28,7 +28,6 @@ it("refuses TOON values or keys that UTF-8 cannot preserve", async () => { await output.write(value, { command: "fixture", duration: "1ms", - format: "toon", }), ).toBe(true); expect(output.error).toMatchObject({ code: "invalid_request" }); @@ -65,7 +64,6 @@ it.each([false, true])( await output.write(value, { command: "fixture", duration: "1ms", - format: "toon", }), ).toBe(true); expect(output.error).toMatchObject({ @@ -87,10 +85,12 @@ it.each([false, true])( ); it("keeps valid supplementary characters and an authored replacement character", async () => { + const chunks: Buffer[] = []; const output = createCliResultOutput( parseCliOutputArguments(["--format", "toon"]), new Writable({ - write(_chunk, _encoding, done) { + write(chunk: Buffer, _encoding, done) { + chunks.push(chunk); done(); }, }), @@ -99,9 +99,13 @@ it("keeps valid supplementary characters and an authored replacement character", expect( await output.write( { value: "😀�" }, - { command: "fixture", duration: "1ms", format: "toon" }, + { command: "fixture", duration: "1ms" }, ), - ).toBe(false); + ).toBe(true); + expect(output.error).toBeUndefined(); + expect(decode(Buffer.concat(chunks).toString("utf8"))).toEqual({ + value: "😀�", + }); }); it("only refuses malformed code units in selected TOON output", async () => { @@ -119,7 +123,7 @@ it("only refuses malformed code units in selected TOON output", async () => { expect( await output.write( { safe: "retained", other: "\ud800" }, - { command: "fixture", duration: "1ms", format: "toon" }, + { command: "fixture", duration: "1ms" }, ), ).toBe(true); expect(output.error).toBeUndefined(); @@ -141,7 +145,7 @@ it("refuses malformed code units retained in a TOON token window", async () => { expect( await output.write( { value: "\ud800" }, - { command: "fixture", duration: "1ms", format: "toon" }, + { command: "fixture", duration: "1ms" }, ), ).toBe(true); expect(output.error).toMatchObject({ code: "invalid_request" }); @@ -168,10 +172,7 @@ it.each(["\ud800", "\u0000"])( ); if (output === undefined) throw new Error("invalid output settings"); expect( - await output.write( - { value }, - { command: "fixture", duration: "1ms", format: "md" }, - ), + await output.write({ value }, { command: "fixture", duration: "1ms" }), ).toBe(true); expect(output.error).toMatchObject({ code: "invalid_request" }); expect(Buffer.concat(chunks).toString("utf8")).not.toContain("�"); diff --git a/tests/boundary/cli/traceNativeValuesCompletenessCli.test.ts b/tests/boundary/cli/traceNativeValuesCompletenessCli.test.ts index 916b26df1a..5b7f2ea663 100644 --- a/tests/boundary/cli/traceNativeValuesCompletenessCli.test.ts +++ b/tests/boundary/cli/traceNativeValuesCompletenessCli.test.ts @@ -1,6 +1,6 @@ +import { createCommandCli } from "../../support/cli/commandCli.js"; import { readFile, writeFile } from "node:fs/promises"; import { join } from "node:path"; -import { Cli } from "incur"; import pino from "pino"; import { expect, it } from "vitest"; import { z } from "zod"; @@ -85,7 +85,7 @@ const serveTraceCli = async ( createNativeBinarySession: createSession, createManagedBinarySession: createSession, }; - const cli = Cli.create("rea-value-trace-cli-test", { sync: false }); + const cli = createCommandCli(); registerCoreNativeCommands( cli, pino({ enabled: false }), diff --git a/tests/boundary/cli/traceNativeValuesEvidenceCli.test.ts b/tests/boundary/cli/traceNativeValuesEvidenceCli.test.ts index 3afe1e08f7..32f1a767e9 100644 --- a/tests/boundary/cli/traceNativeValuesEvidenceCli.test.ts +++ b/tests/boundary/cli/traceNativeValuesEvidenceCli.test.ts @@ -1,6 +1,6 @@ +import { createCommandCli } from "../../support/cli/commandCli.js"; import { readFile } from "node:fs/promises"; import { join } from "node:path"; -import { Cli } from "incur"; import pino from "pino"; import { expect, it, vi } from "vitest"; @@ -87,10 +87,7 @@ const createTraceFixture = () => { type DirectAnalysisRunner = Parameters[2]; const createTraceCli = (run: DirectAnalysisRunner) => { - const cli = Cli.create("rea-trace-evidence-test", { - version: "1", - sync: false, - }); + const cli = createCommandCli(); registerCoreNativeCommands( cli as unknown as CliInstance, pino({ enabled: false }), @@ -100,7 +97,7 @@ const createTraceCli = (run: DirectAnalysisRunner) => { }; const runJsonCli = async ( - cli: ReturnType, + cli: ReturnType, args: string[], ) => { let stdout = ""; diff --git a/tests/boundary/cli/webScriptSelectionCli.test.ts b/tests/boundary/cli/webScriptSelectionCli.test.ts index 5438d0fa3b..b1ca387c6c 100644 --- a/tests/boundary/cli/webScriptSelectionCli.test.ts +++ b/tests/boundary/cli/webScriptSelectionCli.test.ts @@ -1,3 +1,5 @@ +import { createCommandCli } from "../../support/cli/commandCli.js"; +import { cliCommand } from "../../../src/cli/commandRegistry.js"; import { access, mkdir, readdir, symlink, writeFile } from "node:fs/promises"; import { join } from "node:path"; @@ -18,18 +20,9 @@ import { import { cliTest } from "../../support/cli/cliFixture.js"; const registeredExportCommand = () => { - const commands = new Map }>(); - const cli = { - command: ( - name: string, - definition: { run(input: unknown): Promise }, - ) => { - commands.set(name, definition); - return cli; - }, - } as unknown as Parameters[0]; + const cli = createCommandCli(); registerWebScriptCommands(cli, pino({ enabled: false })); - return commands.get(cliCommandFor("export_web_scripts"))!; + return cliCommand(cli, cliCommandFor("export_web_scripts"))!.definition; }; it("forwards an interrupt into the export workflow and reports cancellation", async () => { @@ -47,6 +40,8 @@ it("forwards an interrupt into the export workflow and reports cancellation", as const previousExitCode = process.exitCode; try { const output = await command.run({ + formatExplicit: false, + options: {}, args: { capturePath: "/unused/capture.json", outputDirectory: "/unused/out", @@ -78,6 +73,8 @@ it.each(["cleanup failure", "cancellation during cleanup"] as const)( const previousExitCode = process.exitCode; try { const output = await command.run({ + formatExplicit: false, + options: {}, args: { capturePath: "/unused/capture.json", outputDirectory: "/unused/out", @@ -108,6 +105,8 @@ it("closes export resources when the operation throws", async () => { .mockResolvedValue(); try { const output = await command.run({ + formatExplicit: false, + options: {}, args: { capturePath: "/unused/capture.json", outputDirectory: "/unused/out", diff --git a/tests/boundary/mcp/syntheticContractSurfaces.test.ts b/tests/boundary/mcp/syntheticContractSurfaces.test.ts index 2a71df61be..a4f2614350 100644 --- a/tests/boundary/mcp/syntheticContractSurfaces.test.ts +++ b/tests/boundary/mcp/syntheticContractSurfaces.test.ts @@ -1,4 +1,5 @@ -import { Cli } from "incur"; +import { cliCommand } from "../../../src/cli/commandRegistry.js"; +import { createCommandCli } from "../../support/cli/commandCli.js"; import { expect } from "vitest"; import { z } from "zod"; @@ -71,10 +72,7 @@ mcpTest( expect(cliCommandNames(contracts)).toContain("inspect-synthetic-fixture"); // CLI: the contract's own command runs its handler with the admitted input. - const cli = Cli.create("rea-synthetic-contract", { - version: "1", - sync: false, - }); + const cli = createCommandCli(); const cliReceived: unknown[] = []; registerContractCommand( cli as unknown as CliInstance, @@ -86,7 +84,7 @@ mcpTest( return {}; }, ); - const command = Cli.toCommands.get(cli)?.get("inspect-synthetic-fixture"); + const command = cliCommand(cli, "inspect-synthetic-fixture")?.definition; if (command === undefined) throw new Error("inspect-synthetic-fixture is not registered"); const parse = (key: "args" | "options", value: unknown) => diff --git a/tests/boundary/providers/RizinDebugSessionInferiorStdin.test.ts b/tests/boundary/providers/RizinDebugSessionInferiorStdin.test.ts index 72220187cd..49debeeb17 100644 --- a/tests/boundary/providers/RizinDebugSessionInferiorStdin.test.ts +++ b/tests/boundary/providers/RizinDebugSessionInferiorStdin.test.ts @@ -1,3 +1,5 @@ +import { createCommandCli } from "../../support/cli/commandCli.js"; +import { cliCommand } from "../../../src/cli/commandRegistry.js"; import { execFileSync, type ChildProcess } from "node:child_process"; import { rizinDebugMcpServer } from "../../fixtures/debuggerMcp.js"; import { once } from "node:events"; @@ -10,7 +12,6 @@ import pino from "pino"; import { expect, it, onTestFinished } from "vitest"; import { registerReverseEngineeringCommands } from "../../../src/cli/reverseEngineeringCommands.js"; -import type { CliInstance } from "../../../src/cli/types.js"; import { CLI_COMMANDS } from "../../../src/contracts/cliCommandNames.js"; import { toolContract } from "../../../src/contracts/toolContracts.js"; import type { AnalysisError } from "../../../src/domain/analysisErrorBase.js"; @@ -279,27 +280,13 @@ const expectRunningOnTerminal = async ( expect([stdin.dev, stdin.ino]).toEqual([selected.dev, selected.ino]); }; -const registerCliCommand = (launcher: string) => { - const commands = new Map< - string, - { - run(input: { - args: { path: string; command: string }; - options: { inferiorTty: string }; - }): Promise; - } - >(); - const cli = { - command: (name: string, definition: never) => { - commands.set(name, definition); - return cli; - }, - } as unknown as CliInstance; +const rizinCommand = (launcher: string) => { + const cli = createCommandCli(); registerReverseEngineeringCommands(cli, pino({ enabled: false }), { ...process.env, REA_RIZIN_COMMAND: launcher, }); - return commands.get(CLI_COMMANDS.debugWithRizin)!; + return cliCommand(cli, CLI_COMMANDS.debugWithRizin)!.definition; }; it.skipIf(process.platform === "win32")( @@ -420,7 +407,8 @@ linuxIt("completes the one-shot CLI on a target that reads stdin", async () => { const previousExitCode = process.exitCode; process.exitCode = 0; try { - const result = await registerCliCommand(current.launcher).run({ + const result = await rizinCommand(current.launcher).run({ + formatExplicit: false, args: { path: "/usr/bin/cat", command: "dr" }, options: { inferiorTty: current.terminal.path }, }); @@ -498,7 +486,8 @@ linuxIt( const previousExitCode = process.exitCode; process.exitCode = 0; try { - const result = await registerCliCommand(current.launcher).run({ + const result = await rizinCommand(current.launcher).run({ + formatExplicit: false, args: { path: "/usr/bin/cat", command: "dr" }, options: { inferiorTty: current.terminal.path }, }); diff --git a/tests/boundary/signals/recordingProvider.test.ts b/tests/boundary/signals/recordingProvider.test.ts index f48bdbc524..520e897a42 100644 --- a/tests/boundary/signals/recordingProvider.test.ts +++ b/tests/boundary/signals/recordingProvider.test.ts @@ -1,3 +1,4 @@ +import { createCommandCli } from "../../support/cli/commandCli.js"; import { spawnFailure } from "../../support/process/spawnFailure.js"; import { AnalysisOutputError, @@ -24,7 +25,6 @@ import { createDeferred } from "../../fixtures/binarySession.js"; import { analysisErrorRemediationAction } from "../../../src/domain/analysisErrorPresentation.js"; import { createApplicationMcpHarness } from "../../fixtures/applicationMcpHarness.js"; import { parseMcpToolError } from "../../fixtures/mcpToolError.js"; -import { Cli } from "incur"; import { registerSignalCommands } from "../../../src/cli/signalCommands.js"; import { silentLogger } from "../../../src/logger.js"; @@ -579,7 +579,7 @@ it.each([ "fixture: selected input format was not forwarded", ); - const cli = Cli.create("signal-input-format-refusal-test", { sync: false }); + const cli = createCommandCli(); registerSignalCommands(cli, silentLogger, {}, f.service); let stdout = ""; let commandExitCode: typeof process.exitCode; @@ -743,7 +743,7 @@ it("projects sigrok's zero-exit missing-channel refusal through CLI and MCP with const previousExitCode = process.exitCode; process.exitCode = 0; try { - const cli = Cli.create("signal-channel-refusal-test", { sync: false }); + const cli = createCommandCli(); registerSignalCommands(cli, silentLogger, {}, f.service); let stdout = ""; await cli.serve( @@ -793,7 +793,7 @@ it("projects a missing bare channel target as invalid decoder input through the const previousExitCode = process.exitCode; process.exitCode = 0; try { - const cli = Cli.create("signal-channel-target-test", { sync: false }); + const cli = createCommandCli(); registerSignalCommands(cli, silentLogger, {}, f.service); let stdout = ""; await cli.serve( @@ -956,7 +956,7 @@ it("reports an unknown decoder help selection as CLI invalid input", async () => const previousExitCode = process.exitCode; process.exitCode = 0; try { - const cli = Cli.create("signal-refusal-test", { sync: false }); + const cli = createCommandCli(); registerSignalCommands(cli, silentLogger, {}, f.service); let stdout = ""; await cli.serve( diff --git a/tests/boundary/sqlite/sqliteDatabaseDescriptorCleanup.test.ts b/tests/boundary/sqlite/sqliteDatabaseDescriptorCleanup.test.ts index 91636524bd..a006e5d55c 100644 --- a/tests/boundary/sqlite/sqliteDatabaseDescriptorCleanup.test.ts +++ b/tests/boundary/sqlite/sqliteDatabaseDescriptorCleanup.test.ts @@ -1,4 +1,4 @@ -import { Cli } from "incur"; +import { createCommandCli } from "../../support/cli/commandCli.js"; import { access, readFile, writeFile } from "node:fs/promises"; import { createHash } from "node:crypto"; import type { FileHandle } from "node:fs/promises"; @@ -170,7 +170,7 @@ const serveInspection = async ( vi.mocked(createSqliteDatabaseService).mockReturnValue( new SqliteDatabaseService(provider), ); - const cli = Cli.create("rea-sqlite-cleanup-test", { sync: false }); + const cli = createCommandCli(); registerSqliteCommands(cli, silentLogger, {}); let stdout = ""; await cli.serve(["inspect-sqlite-database", path, "--json"], { diff --git a/tests/fixtures/managedComparisonCommand.ts b/tests/fixtures/managedComparisonCommand.ts index 169b964d54..43b8a0e6bf 100644 --- a/tests/fixtures/managedComparisonCommand.ts +++ b/tests/fixtures/managedComparisonCommand.ts @@ -1,8 +1,11 @@ import { registerManagedCommands } from "../../src/cli/managedCommands.js"; +import { cliCommand } from "../../src/cli/commandRegistry.js"; import { cliCommandFor } from "../../src/contracts/cliCommandNames.js"; import { createDirectAnalysis } from "../../src/composition/directAnalysis.js"; import type { DirectAnalysis } from "../../src/composition/directAnalysis.js"; import { silentLogger } from "../../src/logger.js"; +import { isRecord } from "../../src/kernel/isRecord.js"; +import { createCommandCli } from "../support/cli/commandCli.js"; type ManagedEvidenceRunner = DirectAnalysis["runManagedProviderEvidence"]; @@ -14,33 +17,32 @@ export const managedComparisonCommand = ( runManagedProviderEvidence: ManagedEvidenceRunner = createDirectAnalysis({}) .runManagedProviderEvidence, ) => { - let registered: - | { run(input: unknown): Promise> } - | undefined; - const cli = { - command: ( - name: string, - definition: { run(input: unknown): Promise> }, - ) => { - if (name === cliCommandFor("compare_managed_members")) - registered = definition; - return cli; - }, - } as unknown as Parameters[0]; + const cli = createCommandCli(); registerManagedCommands(cli, silentLogger, { runProviderAnalysis: () => { throw new Error("Comparison runs only managed Evidence"); }, runManagedProviderEvidence, }); - const command = registered; + const command = cliCommand( + cli, + cliCommandFor("compare_managed_members"), + )?.definition; if (command === undefined) throw new Error("compare-managed-members is not registered"); /** Run the command as argv would select it, returning its JSON output. */ - return ( + return async ( leftPath: string, rightPath: string, options: Readonly> = {}, - ): Promise> => - command.run({ args: { leftPath, rightPath }, options }); + ): Promise> => { + const value = await command.run({ + args: { leftPath, rightPath }, + options, + formatExplicit: false, + }); + if (!isRecord(value)) + throw new Error("Managed comparison did not return a document"); + return value; + }; }; diff --git a/tests/process-global/browserScenarioCleanup.test.ts b/tests/process-global/browserScenarioCleanup.test.ts index 531f25b766..91cfbc7e00 100644 --- a/tests/process-global/browserScenarioCleanup.test.ts +++ b/tests/process-global/browserScenarioCleanup.test.ts @@ -1,5 +1,5 @@ +import { createCommandCli } from "../support/cli/commandCli.js"; import { EventEmitter } from "node:events"; -import { Cli } from "incur"; import { resolve } from "node:path"; import { expect, it, vi } from "vitest"; @@ -158,7 +158,7 @@ it("waits for a slow but successful browser close before removing its profile", }); const serveScenario = async () => { - const cli = Cli.create("browser-cleanup-test", { sync: false }); + const cli = createCommandCli(); registerBrowserScenarioCommands(cli, silentLogger, {}); let stdout = ""; let exitCode = 0; diff --git a/tests/process-global/cliUpdateAlias.test.ts b/tests/process-global/cliUpdateAlias.test.ts index 9a755521ef..5b29924193 100644 --- a/tests/process-global/cliUpdateAlias.test.ts +++ b/tests/process-global/cliUpdateAlias.test.ts @@ -98,8 +98,22 @@ it.each(["json", "jsonl", "yaml", "toon", "md"])( const expected = await serve(cli, ["update", "--format", format]); const actual = await serve(cli, ["--format", format, "--update"]); expect(actual).toEqual(expected); - expect(actual.exitCode).toBe(0); - expect(actual.stdout).toContain(PRODUCT_IDENTITY.packageVersion); + if (format === "jsonl") { + // Direct serve follows the public writer's record-collection contract. + expect(actual.exitCode).toBe(1); + expect(JSON.parse(actual.stdout)).toMatchObject({ + $rea: "jsonl/v1", + type: "error", + ok: false, + result: { + code: "invalid_request", + remediation: { action: expect.stringContaining("--format json") }, + }, + }); + } else { + expect(actual.exitCode).toBe(0); + expect(actual.stdout).toContain(PRODUCT_IDENTITY.packageVersion); + } expect(mocks.run).toHaveBeenCalledTimes(2); expect(mocks.run).toHaveBeenLastCalledWith( PRODUCT_IDENTITY.packageVersion, diff --git a/tests/process-global/commandFinalizationCancellation.test.ts b/tests/process-global/commandFinalizationCancellation.test.ts index 4b48474309..507659323e 100644 --- a/tests/process-global/commandFinalizationCancellation.test.ts +++ b/tests/process-global/commandFinalizationCancellation.test.ts @@ -1,7 +1,7 @@ +import { createCommandCli } from "../support/cli/commandCli.js"; import { readdir, writeFile } from "node:fs/promises"; import { join } from "node:path"; -import { Cli } from "incur"; import { afterEach, expect, it, vi } from "vitest"; import * as analysisViewService from "../../src/application/analysisView/AnalysisViewService.js"; @@ -158,9 +158,7 @@ it.each([ closed = true; if (failsCleanup) throw cleanup; }); - const cli = Cli.create("cutter-discovery-finalization-test", { - sync: false, - }); + const cli = createCommandCli(); registerCutterCommands(cli, silentLogger, {}); let output = ""; let settled = false; @@ -284,7 +282,7 @@ it.each([ }, }); vi.spyOn(wasmArtifactModule, "create").mockReturnValue(service); - const cli = Cli.create("finalization-test", { sync: false }); + const cli = createCommandCli(); registerWasmCommands(cli, silentLogger, {}); let output = ""; const previousExitCode = process.exitCode; @@ -481,7 +479,7 @@ it.each([ if (signal !== "control" && phase === "close") interrupt(); if (phase.startsWith("authentication")) queueInterrupt(); }); - const cli = Cli.create("analysis-view-finalization-test", { sync: false }); + const cli = createCommandCli(); registerAnalysisViewCommands(cli, silentLogger); let output = ""; const previousExitCode = process.exitCode; diff --git a/tests/process-global/flutterCliCleanup.test.ts b/tests/process-global/flutterCliCleanup.test.ts index c13144a4e1..684360cd9d 100644 --- a/tests/process-global/flutterCliCleanup.test.ts +++ b/tests/process-global/flutterCliCleanup.test.ts @@ -1,4 +1,4 @@ -import { Cli } from "incur"; +import { createCommandCli } from "../support/cli/commandCli.js"; import { expect, it, onTestFinished, vi } from "vitest"; import { registerFlutterCommands } from "../../src/cli/flutterCommands.js"; import { aotFixtureImage } from "../../src/flutter/FlutterBuild.fixture.js"; @@ -39,7 +39,7 @@ const serveWithCleanupRetry = async ( }); const provider = new FlutterBuildProvider(); onTestFinished(() => provider.close()); - const cli = Cli.create("flutter-cleanup-retry-test", { sync: false }); + const cli = createCommandCli(); registerFlutterCommands(cli, silentLogger, provider); let stdout = ""; await cli.serve([command, apk, "--format", "json"], { diff --git a/tests/process-global/javascriptRuntimeObservationCli.test.ts b/tests/process-global/javascriptRuntimeObservationCli.test.ts index 50c7976103..e151079e1e 100644 --- a/tests/process-global/javascriptRuntimeObservationCli.test.ts +++ b/tests/process-global/javascriptRuntimeObservationCli.test.ts @@ -1,8 +1,8 @@ +import { createCommandCli } from "../support/cli/commandCli.js"; import { writeFile } from "node:fs/promises"; import { join } from "node:path"; import { pathToFileURL } from "node:url"; -import { Cli } from "incur"; import { afterEach, describe, expect, test, vi } from "vitest"; import { observeJavaScriptRuntime } from "../../src/application/javascript/JavaScriptRuntimeObservationService.js"; @@ -149,7 +149,7 @@ describe("JavaScript runtime observation CLI parity", () => { const previousExitCode = process.exitCode; process.exitCode = 0; try { - const cli = Cli.create("rea-runtime-cleanup-test", { sync: false }); + const cli = createCommandCli(); registerJavaScriptRuntimeObservationCommands(cli, silentLogger, {}); let stdout = ""; await cli.serve( diff --git a/tests/process-global/oneShotSourceClosure.test.ts b/tests/process-global/oneShotSourceClosure.test.ts index a2d8cceaa4..8f895d834c 100644 --- a/tests/process-global/oneShotSourceClosure.test.ts +++ b/tests/process-global/oneShotSourceClosure.test.ts @@ -1,8 +1,8 @@ +import { createCommandCli } from "../support/cli/commandCli.js"; import { unknownTarget } from "../../src/domain/targetIdentity.js"; import { readdir, readFile, writeFile } from "node:fs/promises"; import { join } from "node:path"; -import { Cli } from "incur"; import { afterEach, expect, it, vi } from "vitest"; import type { UndeliveredSourceClosure } from "../../src/application/AnalysisEvidenceSources.js"; @@ -148,7 +148,7 @@ const runMatching = async ( { operation: "match_native_functions" }, ); }); - const cli = Cli.create("one-shot-source-closure-test", { sync: false }); + const cli = createCommandCli(); registerNativeFunctionMatchingCommands( cli, silentLogger, diff --git a/tests/support/cli/apktoolCli.ts b/tests/support/cli/apktoolCli.ts index 78feedd2e7..63f952c075 100644 --- a/tests/support/cli/apktoolCli.ts +++ b/tests/support/cli/apktoolCli.ts @@ -1,4 +1,4 @@ -import { Cli } from "incur"; +import { createCommandCli } from "./commandCli.js"; import pino from "pino"; import type { ApktoolResourceAnalysisPort } from "../../../src/application/apktool/ApktoolResourceAnalysisPort.js"; @@ -26,7 +26,7 @@ export const invokeApktoolCli = async (argv: readonly string[]) => { ); }, }; - const cli = Cli.create("rea", { sync: false }); + const cli = createCommandCli(); registerApktoolCommands(cli, pino({ level: "silent" }), {}, provider); presentOmittableDefaults(cli); diff --git a/tests/support/cli/commandCli.ts b/tests/support/cli/commandCli.ts new file mode 100644 index 0000000000..394b627fc1 --- /dev/null +++ b/tests/support/cli/commandCli.ts @@ -0,0 +1,6 @@ +import { createCliShell } from "../../../src/cli/cliShell.js"; +import type { CliResultOutput } from "../../../src/cli/cliResultOutput.js"; + +/** The real command dispatcher with fixture-owned command definitions and output. */ +export const createCommandCli = (resultOutput?: CliResultOutput) => + createCliShell({ selectedEnvironment: {}, registrations: [], resultOutput }); diff --git a/tests/support/cli/processComparisonCli.ts b/tests/support/cli/processComparisonCli.ts index 0ba56ec561..f3ae37177a 100644 --- a/tests/support/cli/processComparisonCli.ts +++ b/tests/support/cli/processComparisonCli.ts @@ -1,4 +1,4 @@ -import { Cli } from "incur"; +import { createCommandCli } from "./commandCli.js"; import pino from "pino"; import { registerProcessCommands } from "../../../src/cli/processCommands.js"; @@ -13,7 +13,7 @@ export const compareProcessCaptureFiles = async ( right: string, traceSpecification?: string, ): Promise => { - const cli = Cli.create("rea", { sync: false }); + const cli = createCommandCli(); registerProcessCommands(cli, pino({ level: "silent" }), {}); const { stdout } = await serveInProcessCli(cli, [ "compare-process-captures",