From 212f00d6700614fff2c048e1320d60689ade92ab Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Fri, 21 Aug 2026 08:39:36 -0700 Subject: [PATCH 1/4] Add diligence-brief workflow: research a company and draft a cited brief Ports scout's diligence-brief pipeline (workflows/diligence-brief) as a single-step, mail-triggered @intx/workflow definition, following code-review's shape. Scout's own tools cannot be pinned here (CL-5179), so every call is rebound: web research to @corbits/web-search-tools, firm memory to @corbits/memory-tools, and artifact persistence to @corbits/artifacts-hub's workflow-artifacts surface (via a duplicated finalize-tool/artifact-client, same convention every sibling workflow package uses). The brief is trimmed to five prose sections with no per-dimension scoring, since scout's parallel per-section step graph assumes an `action` primitive this repo's execution host has never wired (see src/index.ts's header comment for the full account of what did and did not port). Persisting is gated by human approval. --- bun.lock | 20 +- workflows/diligence-brief/LICENSE | 176 +++++++++++ workflows/diligence-brief/package.json | 32 ++ .../src/artifact-client.test.ts | 60 ++++ .../diligence-brief/src/artifact-client.ts | 68 ++++ .../diligence-brief/src/finalize-tool.test.ts | 200 ++++++++++++ .../diligence-brief/src/finalize-tool.ts | 160 ++++++++++ workflows/diligence-brief/src/index.ts | 298 ++++++++++++++++++ .../diligence-brief/test/boundary.test.ts | 54 ++++ .../diligence-brief/test/definition.test.ts | 160 ++++++++++ workflows/diligence-brief/tsconfig.json | 7 + 11 files changed, 1231 insertions(+), 4 deletions(-) create mode 100644 workflows/diligence-brief/LICENSE create mode 100644 workflows/diligence-brief/package.json create mode 100644 workflows/diligence-brief/src/artifact-client.test.ts create mode 100644 workflows/diligence-brief/src/artifact-client.ts create mode 100644 workflows/diligence-brief/src/finalize-tool.test.ts create mode 100644 workflows/diligence-brief/src/finalize-tool.ts create mode 100644 workflows/diligence-brief/src/index.ts create mode 100644 workflows/diligence-brief/test/boundary.test.ts create mode 100644 workflows/diligence-brief/test/definition.test.ts create mode 100644 workflows/diligence-brief/tsconfig.json diff --git a/bun.lock b/bun.lock index 6fc7a0622..0e2cafd92 100644 --- a/bun.lock +++ b/bun.lock @@ -1653,6 +1653,20 @@ "typescript": "catalog:", }, }, + "workflows/diligence-brief": { + "name": "@corbits/diligence-brief-workflow", + "version": "0.0.1", + "dependencies": { + "@intx/agent": "0.3.0", + "@intx/types": "0.3.0", + "@intx/workflow": "workspace:*", + "arktype": "catalog:", + }, + "devDependencies": { + "@types/bun": "catalog:", + "typescript": "catalog:", + }, + }, "workflows/echo": { "name": "@corbits/echo-workflow", "version": "0.0.1", @@ -1969,6 +1983,8 @@ "@corbits/credential-providers": ["@corbits/credential-providers@workspace:packages/credential-providers"], + "@corbits/diligence-brief-workflow": ["@corbits/diligence-brief-workflow@workspace:workflows/diligence-brief"], + "@corbits/docker-provisioner": ["@corbits/docker-provisioner@workspace:packages/docker-provisioner"], "@corbits/e2b-sandbox-sidecar": ["@corbits/e2b-sandbox-sidecar@workspace:packages/e2b-sandbox-sidecar"], @@ -3357,8 +3373,6 @@ "@babel/helper-compilation-targets/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="], - "@corbits/memory-hub/@corbits/memory": ["@corbits/memory@github:corbitsdev/corbits-memory#9e6f213", { "dependencies": { "@intx/agent": "0.2.2", "@intx/authz": "0.2.2", "@intx/hub-api": "0.2.2", "@intx/log": "0.2.2", "@intx/workflow": "0.2.2", "arktype": "^2.1.29", "drizzle-orm": "^0.45.1", "hono": "^4.9.0", "hono-openapi": "^1.3.1", "postgres": "^3.4.7" } }, "corbitsdev-corbits-memory-9e6f213", "sha512-utnM4ZT2zmslcPXYWAAqxlDNLcpGsXFiTOtj8h7+OXnhCP0Eaw8yl25+yCTyHpvt3jcdeG4h5uFsSj7ou0BZCA=="], - "@esbuild-kit/core-utils/esbuild": ["esbuild@0.18.20", "", { "optionalDependencies": { "@esbuild/android-arm": "0.18.20", "@esbuild/android-arm64": "0.18.20", "@esbuild/android-x64": "0.18.20", "@esbuild/darwin-arm64": "0.18.20", "@esbuild/darwin-x64": "0.18.20", "@esbuild/freebsd-arm64": "0.18.20", "@esbuild/freebsd-x64": "0.18.20", "@esbuild/linux-arm": "0.18.20", "@esbuild/linux-arm64": "0.18.20", "@esbuild/linux-ia32": "0.18.20", "@esbuild/linux-loong64": "0.18.20", "@esbuild/linux-mips64el": "0.18.20", "@esbuild/linux-ppc64": "0.18.20", "@esbuild/linux-riscv64": "0.18.20", "@esbuild/linux-s390x": "0.18.20", "@esbuild/linux-x64": "0.18.20", "@esbuild/netbsd-x64": "0.18.20", "@esbuild/openbsd-x64": "0.18.20", "@esbuild/sunos-x64": "0.18.20", "@esbuild/win32-arm64": "0.18.20", "@esbuild/win32-ia32": "0.18.20", "@esbuild/win32-x64": "0.18.20" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-ceqxoedUrcayh7Y7ZX6NdbbDzGROiyVBgC4PriJThBKSVPWnnFHZAkfI1lJT8QFkOwH4qOS2SJkS4wvpGl8BpA=="], "@eslint-community/eslint-utils/eslint-visitor-keys": ["eslint-visitor-keys@3.4.3", "", {}, "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag=="], @@ -3381,8 +3395,6 @@ "@typescript-eslint/eslint-plugin/ignore": ["ignore@7.0.6", "", {}, "sha512-BAg6QkE8W+TuQLrrw0Ugr7HegXduRuuj8/ti2kSOc+jz1dmx8/WNcjr6XGnq5YpDWxFwwaavqD0+jIUOKelTsw=="], - "@workbench/hub/@corbits/memory": ["@corbits/memory@github:corbitsdev/corbits-memory#9e6f213", { "dependencies": { "@intx/agent": "0.2.2", "@intx/authz": "0.2.2", "@intx/hub-api": "0.2.2", "@intx/log": "0.2.2", "@intx/workflow": "0.2.2", "arktype": "^2.1.29", "drizzle-orm": "^0.45.1", "hono": "^4.9.0", "hono-openapi": "^1.3.1", "postgres": "^3.4.7" } }, "corbitsdev-corbits-memory-9e6f213", "sha512-utnM4ZT2zmslcPXYWAAqxlDNLcpGsXFiTOtj8h7+OXnhCP0Eaw8yl25+yCTyHpvt3jcdeG4h5uFsSj7ou0BZCA=="], - "ajv-formats/ajv": ["ajv@8.20.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="], "better-call/@better-auth/utils": ["@better-auth/utils@0.5.0", "", { "dependencies": { "@noble/hashes": "^2.0.1" } }, "sha512-BL8W4EfIZFwlu0r54m3v1ztjDhu6dDe/amLTm0xybmbZaNgYUqhD3SjpAsnq0q8YD6/ki4iwIgxJNLP/N3TxiA=="], diff --git a/workflows/diligence-brief/LICENSE b/workflows/diligence-brief/LICENSE new file mode 100644 index 000000000..c6487f4fd --- /dev/null +++ b/workflows/diligence-brief/LICENSE @@ -0,0 +1,176 @@ +GNU LESSER GENERAL PUBLIC LICENSE + +Version 2.1, February 1999 + +Copyright (C) 1991, 1999 Free Software Foundation, Inc. +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] + +Preamble + +The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. + +This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. + +When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. + +To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. + +For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. + +We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. + +To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. + +Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. + +Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. + +When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. + +We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. + +For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. + +In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. + +Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. + +The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. + +GNU LESSER GENERAL PUBLIC LICENSE +TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + +0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". + +A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. + +The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) + +"Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. + +Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. + +1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. + +You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. + +2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. + +(For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. + +3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. + +Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. + +This option is useful when you wish to copy part of the code of the Library into a program that is not a library. + +4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. + +If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. + +5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. + +However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. + +When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. + +If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) + +Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. + +6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. + +You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: + + a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. + + e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. + +For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. + +It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. + +7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. + + b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. + +8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. + +9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. + +10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. + +11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. + +This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. + +12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. + +13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. + +14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. + +NO WARRANTY + +15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +END OF TERMS AND CONDITIONS + +How to Apply These Terms to Your New Libraries + +If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). + +To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. + + one line to give the library's name and an idea of what it does. + Copyright (C) year name of author + + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: + +Yoyodyne, Inc., hereby disclaims all copyright interest in +the library `Frob' (a library for tweaking knobs) written +by James Random Hacker. + +signature of Ty Coon, 1 April 1990 +Ty Coon, President of Vice +That's all there is to it! diff --git a/workflows/diligence-brief/package.json b/workflows/diligence-brief/package.json new file mode 100644 index 000000000..af9783c6d --- /dev/null +++ b/workflows/diligence-brief/package.json @@ -0,0 +1,32 @@ +{ + "name": "@corbits/diligence-brief-workflow", + "private": true, + "description": "Single-step, mail-triggered workflow that researches a company and writes a cited diligence brief, held for approval", + "version": "0.0.1", + "license": "LGPL-2.1-or-later", + "type": "module", + "corbits": { + "workflow": { + "assetName": "diligence-brief", + "displayName": "Diligence brief", + "automatable": false + } + }, + "exports": { + ".": "./src/index.ts" + }, + "scripts": { + "typecheck": "tsc --noEmit", + "test": "bun test" + }, + "dependencies": { + "@intx/agent": "0.3.0", + "@intx/types": "0.3.0", + "@intx/workflow": "workspace:*", + "arktype": "catalog:" + }, + "devDependencies": { + "@types/bun": "catalog:", + "typescript": "catalog:" + } +} diff --git a/workflows/diligence-brief/src/artifact-client.test.ts b/workflows/diligence-brief/src/artifact-client.test.ts new file mode 100644 index 000000000..d5484d742 --- /dev/null +++ b/workflows/diligence-brief/src/artifact-client.test.ts @@ -0,0 +1,60 @@ +import { expect, test } from "bun:test"; + +import { createWorkflowArtifact } from "./artifact-client"; + +const CONFIG = { + hubArtifactsUrl: "https://hub.example.com", + sidecarToken: "sc-token", + runAddress: "run_1@workflow", +}; + +test("posts to the workflow-artifacts endpoint and returns id/version", async () => { + const captured: { url: string; init: RequestInit | undefined } = { + url: "", + init: undefined, + }; + const fetchImpl = (async (input: URL | string, init?: RequestInit) => { + captured.url = String(input); + captured.init = init; + return new Response(JSON.stringify({ data: { id: "art_1", version: 1 } }), { + status: 201, + }); + }) as unknown as typeof fetch; + + const result = await createWorkflowArtifact( + { ...CONFIG, fetchImpl }, + { title: "Acme Corp", kind: "text", content: "# Diligence brief" }, + ); + + expect(result).toEqual({ id: "art_1", version: 1 }); + expect(captured.url).toBe("https://hub.example.com/api/workflow-artifacts/"); + const headers = captured.init?.headers as Record; + expect(headers["authorization"]).toBe("Bearer sc-token"); + expect(headers["x-workflow-run-address"]).toBe("run_1@workflow"); +}); + +test("throws on a non-ok HTTP response", async () => { + const fetchImpl = (async () => + new Response("nope", { status: 500 })) as unknown as typeof fetch; + + await expect( + createWorkflowArtifact( + { ...CONFIG, fetchImpl }, + { title: "Acme Corp", kind: "text", content: "# Diligence brief" }, + ), + ).rejects.toThrow(/500/); +}); + +test("throws when the response doesn't match the expected shape", async () => { + const fetchImpl = (async () => + new Response(JSON.stringify({ data: {} }), { + status: 201, + })) as unknown as typeof fetch; + + await expect( + createWorkflowArtifact( + { ...CONFIG, fetchImpl }, + { title: "Acme Corp", kind: "text", content: "# Diligence brief" }, + ), + ).rejects.toThrow(/did not match the expected shape/); +}); diff --git a/workflows/diligence-brief/src/artifact-client.ts b/workflows/diligence-brief/src/artifact-client.ts new file mode 100644 index 000000000..ca798faad --- /dev/null +++ b/workflows/diligence-brief/src/artifact-client.ts @@ -0,0 +1,68 @@ +// A minimal client for the sanctioned workflow-artifacts HTTP surface +// (`@corbits/artifacts-hub`'s `createWorkflowArtifactRoutes`, CL-6000). +// Deliberately duplicated from `@corbits/artifact-tools`' `client.ts` +// (and from every sibling workflow package's own copy, e.g. +// `last-30-days-research`) rather than imported: this package ships as +// installable data on the native workflow contract (see `./index.ts`'s +// header comment and `test/boundary.test.ts`), so its shipped sources +// import only `@intx/*`, `arktype`, and relative specifiers — never +// another `@corbits/*` package. Authenticates with the sidecar's own +// bearer token plus the run's own mailbox address (both already reach a +// workflow-process child's tool env), never a database handle. +import { type } from "arktype"; + +export interface WorkflowArtifactClientConfig { + readonly hubArtifactsUrl: string; + readonly sidecarToken: string; + readonly runAddress: string; + /** Override for tests; defaults to the global `fetch`. */ + readonly fetchImpl?: typeof fetch; +} + +export type CreateWorkflowArtifactInput = { + readonly title: string; + readonly kind: string; + readonly content: string; +}; + +export type CreatedWorkflowArtifact = { + readonly id: string; + readonly version: number; +}; + +const CreatedWorkflowArtifactResponse = type({ + data: { id: "string", version: "number" }, +}); + +/** Persists one artifact. Throws on any transport, HTTP, or shape failure. */ +export async function createWorkflowArtifact( + config: WorkflowArtifactClientConfig, + input: CreateWorkflowArtifactInput, +): Promise { + const doFetch = config.fetchImpl ?? fetch; + const response = await doFetch( + `${config.hubArtifactsUrl}/api/workflow-artifacts/`, + { + method: "POST", + headers: { + authorization: `Bearer ${config.sidecarToken}`, + "x-workflow-run-address": config.runAddress, + "content-type": "application/json", + }, + body: JSON.stringify(input), + }, + ); + if (!response.ok) { + throw new Error( + `Workflow artifact create failed: ${response.status} ${response.statusText}`, + ); + } + const body: unknown = await response.json(); + const parsed = CreatedWorkflowArtifactResponse(body); + if (parsed instanceof type.errors) { + throw new Error( + `Workflow artifact create response did not match the expected shape: ${parsed.summary}`, + ); + } + return parsed.data; +} diff --git a/workflows/diligence-brief/src/finalize-tool.test.ts b/workflows/diligence-brief/src/finalize-tool.test.ts new file mode 100644 index 000000000..c6f1f5e21 --- /dev/null +++ b/workflows/diligence-brief/src/finalize-tool.test.ts @@ -0,0 +1,200 @@ +import { expect, test } from "bun:test"; + +import { + DILIGENCE_BRIEF_FINALIZE_TOOL, + DILIGENCE_BRIEF_FINALIZE_TOOL_NAME, + buildArtifactPayload, + type WorkflowArtifactEnv, +} from "./finalize-tool"; + +test("the tool's definition marks itself approval-gated", () => { + expect(DILIGENCE_BRIEF_FINALIZE_TOOL.definitions).toEqual([ + { name: DILIGENCE_BRIEF_FINALIZE_TOOL_NAME, approval: "ask" }, + ]); +}); + +test("the tool is namespaced under this workflow package, not a shared one", () => { + expect(DILIGENCE_BRIEF_FINALIZE_TOOL.id).toBe( + "@corbits/workflow-diligence-brief/finalize", + ); +}); + +test("requires the sanctioned workflow-artifacts env keys", () => { + expect(DILIGENCE_BRIEF_FINALIZE_TOOL.requires).toEqual([ + "hubArtifactsUrl", + "sidecarToken", + "address", + ]); +}); + +test("buildArtifactPayload marks a real brief as a text artifact", () => { + const payload = buildArtifactPayload({ + outcome: "brief", + title: "Diligence brief: Acme Corp", + content: "## Overview\n\nAcme Corp sells widgets", + }); + expect(payload).toEqual({ + title: "Diligence brief: Acme Corp", + kind: "text", + content: "## Overview\n\nAcme Corp sells widgets", + }); +}); + +test("buildArtifactPayload marks a no-data teaching payload as status-note, not text", () => { + const payload = buildArtifactPayload({ + outcome: "status-note", + title: "Diligence brief: Acme Corp — no results yet", + content: "`exa` is not connected yet.", + }); + expect(payload).toEqual({ + title: "Diligence brief: Acme Corp — no results yet", + kind: "status-note", + content: "`exa` is not connected yet.", + }); +}); + +function testEnv(): WorkflowArtifactEnv { + return { + hubArtifactsUrl: "https://hub.example.com", + sidecarToken: "sc-token", + address: "run_1@workflow", + } as unknown as WorkflowArtifactEnv; +} + +test("run persists the artifact on real invocation (i.e. after approval re-dispatches the call) and reports it persisted", async () => { + const originalFetch = globalThis.fetch; + globalThis.fetch = (async () => + new Response(JSON.stringify({ data: { id: "art_1", version: 1 } }), { + status: 201, + })) as unknown as typeof fetch; + + try { + const bundle = DILIGENCE_BRIEF_FINALIZE_TOOL(testEnv()); + const result = await bundle.run( + { + id: "call_1", + name: DILIGENCE_BRIEF_FINALIZE_TOOL_NAME, + arguments: { + outcome: "brief", + title: "Diligence brief: Acme Corp", + content: "## Overview\n\nAcme Corp sells widgets", + }, + }, + new AbortController().signal, + ); + + expect(result.isError).toBe(false); + const parsed = JSON.parse(String(result.content)) as { + id: string; + version: number; + title: string; + kind: string; + persisted: boolean; + }; + expect(parsed).toEqual({ + id: "art_1", + version: 1, + title: "Diligence brief: Acme Corp", + kind: "text", + persisted: true, + }); + } finally { + globalThis.fetch = originalFetch; + } +}); + +test("run persists a teaching payload on the no-data path with a status-note kind, distinct from a real brief", async () => { + const originalFetch = globalThis.fetch; + globalThis.fetch = (async () => + new Response(JSON.stringify({ data: { id: "art_2", version: 1 } }), { + status: 201, + })) as unknown as typeof fetch; + + try { + const bundle = DILIGENCE_BRIEF_FINALIZE_TOOL(testEnv()); + const result = await bundle.run( + { + id: "call_2", + name: DILIGENCE_BRIEF_FINALIZE_TOOL_NAME, + arguments: { + outcome: "status-note", + title: "Diligence brief: Acme Corp — no results yet", + content: + "This brief would have searched the web (`exa`) and firm " + + "memory for this company. `exa` is not connected yet — " + + "connect it in Settings to get a real brief next time.", + }, + }, + new AbortController().signal, + ); + + expect(result.isError).toBe(false); + const parsed = JSON.parse(String(result.content)) as { + persisted: boolean; + kind: string; + }; + expect(parsed.persisted).toBe(true); + expect(parsed.kind).toBe("status-note"); + } finally { + globalThis.fetch = originalFetch; + } +}); + +test("run returns an honest error result when persistence fails, never fabricating persisted: true", async () => { + const originalFetch = globalThis.fetch; + globalThis.fetch = (async () => + new Response("nope", { status: 500 })) as unknown as typeof fetch; + + try { + const bundle = DILIGENCE_BRIEF_FINALIZE_TOOL(testEnv()); + const result = await bundle.run( + { + id: "call_1", + name: DILIGENCE_BRIEF_FINALIZE_TOOL_NAME, + arguments: { + outcome: "brief", + title: "Diligence brief: Acme Corp", + content: "## Overview\n\nAcme Corp sells widgets", + }, + }, + new AbortController().signal, + ); + + expect(result.isError).toBe(true); + expect(result.content).toContain("Failed to persist"); + } finally { + globalThis.fetch = originalFetch; + } +}); + +test("run rejects malformed arguments without throwing", async () => { + const bundle = DILIGENCE_BRIEF_FINALIZE_TOOL(testEnv()); + const result = await bundle.run( + { + id: "call_1", + name: DILIGENCE_BRIEF_FINALIZE_TOOL_NAME, + arguments: {}, + }, + new AbortController().signal, + ); + expect(result.isError).toBe(true); + expect(result.content).toContain("Invalid arguments"); +}); + +test("run rejects an outcome value outside the two structural kinds", async () => { + const bundle = DILIGENCE_BRIEF_FINALIZE_TOOL(testEnv()); + const result = await bundle.run( + { + id: "call_1", + name: DILIGENCE_BRIEF_FINALIZE_TOOL_NAME, + arguments: { + outcome: "summary", + title: "Diligence brief: Acme Corp", + content: "## Overview\n\nAcme Corp sells widgets", + }, + }, + new AbortController().signal, + ); + expect(result.isError).toBe(true); + expect(result.content).toContain("Invalid arguments"); +}); diff --git a/workflows/diligence-brief/src/finalize-tool.ts b/workflows/diligence-brief/src/finalize-tool.ts new file mode 100644 index 000000000..df7365be8 --- /dev/null +++ b/workflows/diligence-brief/src/finalize-tool.ts @@ -0,0 +1,160 @@ +// The one piece of this workflow gated by human approval: finalizing the +// diligence brief. Kept inside the workflow package rather than a shared +// tool package — same "workflow-specific logic lives in the definition" +// convention `pain-point-collateral`'s `finalize-tool.ts` established — +// this is not a reusable integration on its own. +// +// Approval mechanics: identical to `pain-point-collateral`'s and +// `last-30-days-research`'s `finalize-tool.ts` — `definitions` marks +// this tool's one definition `approval: "ask"`, the platform's native +// tool-approval gate. Calling it suspends the run and creates a real +// `approval` row; only executes once a human approves it. +// +// Persistence: `run` below calls `createWorkflowArtifact` +// (`./artifact-client.ts`, duplicated from `@corbits/artifact-tools`' +// client rather than imported — see that file's header for why this +// installable-data package never imports another `@corbits/*` package) +// against the sanctioned workflow-artifacts HTTP surface — authenticated +// with the sidecar's own bearer token and this run's own mailbox +// address, both already present on `env`, never a database handle. The +// persisted artifact's content is markdown, so the sibling Gotenberg +// PDF-rendering lane can turn it into a document without this workflow +// needing to know anything about PDF generation. +// +// The finalized content is not always a "real" brief: when research +// turns up nothing usable (no wired source returns anything for the +// company) this workflow's system prompt (see `./index.ts`) still calls +// this same tool with a teaching payload — what it searched for and +// which connectors are missing — so a run always ends in a persisted, +// chip-visible artifact rather than silence. + +import { type } from "arktype"; +import { defineTool, type BaseEnv } from "@intx/agent"; +import { createWorkflowArtifact } from "./artifact-client"; + +export const DILIGENCE_BRIEF_FINALIZE_TOOL_NAME = "diligence_brief_finalize"; + +export const DILIGENCE_BRIEF_FINALIZE_DESCRIPTION = + "Finalizes the diligence brief, pending human approval, and persists it as a Library artifact."; + +const FinalizeArgs = type({ + /** + * Which of the two shapes this call is: `"brief"` for a real, populated + * brief; `"status-note"` for the no-data path's teaching payload. This + * is what fixes the persisted artifact's `kind` — the model names the + * outcome, but never supplies `kind` directly, so a run can never + * accidentally (or by prompt drift) mislabel a teaching payload as a + * real brief or vice versa. + */ + outcome: "'brief'|'status-note'", + /** Short, human-facing title — doubles as the inbox/approve-card headline. */ + title: "string > 0", + /** The finished brief's markdown body — a real brief, or an honest teaching payload on the no-data path. */ + content: "string > 0", +}); + +export type FinalizeArgs = typeof FinalizeArgs.infer; + +export type ArtifactPayload = { + title: string; + kind: "text" | "status-note"; + content: string; +}; + +/** + * The payload `createWorkflowArtifact` persists (`{ title, kind, + * content }`). Built here so the persist call is a straight pass-through + * of this object, not a payload assembled at the call site. `kind` comes + * from `args.outcome`, never from free-text the model could drift on. + */ +export function buildArtifactPayload(args: FinalizeArgs): ArtifactPayload { + return { + title: args.title, + kind: args.outcome === "status-note" ? "status-note" : "text", + content: args.content, + }; +} + +/** + * The env this tool needs beyond `BaseEnv`: the sanctioned + * workflow-artifacts credential trio, populated for every workflow step + * (`apps/sidecar/src/workflow-substrate-factory/step-env.ts`) — the same + * three keys `@corbits/artifact-tools`' read-side bundle declares. + */ +export interface WorkflowArtifactEnv extends BaseEnv { + readonly hubArtifactsUrl: string; + readonly sidecarToken: string; + readonly address: string; +} + +/** + * `defineTool`'s env-DI factory shape. Needs the sanctioned + * workflow-artifacts credential trio beyond `BaseEnv`. + */ +export const DILIGENCE_BRIEF_FINALIZE_TOOL = defineTool({ + id: "@corbits/workflow-diligence-brief/finalize", + requires: ["hubArtifactsUrl", "sidecarToken", "address"], + definitions: [ + { + name: DILIGENCE_BRIEF_FINALIZE_TOOL_NAME, + approval: "ask", + }, + ], + factory: (env) => ({ + definitions: [ + { + name: DILIGENCE_BRIEF_FINALIZE_TOOL_NAME, + description: DILIGENCE_BRIEF_FINALIZE_DESCRIPTION, + inputSchema: { + type: "object", + properties: { + outcome: { type: "string", enum: ["brief", "status-note"] }, + title: { type: "string" }, + content: { type: "string" }, + }, + required: ["outcome", "title", "content"], + }, + }, + ], + run: async (call) => { + const parsed = FinalizeArgs(call.arguments); + if (parsed instanceof type.errors) { + return { + callId: call.id, + isError: true, + content: `Invalid arguments for ${DILIGENCE_BRIEF_FINALIZE_TOOL_NAME}: ${parsed.summary}`, + }; + } + const artifact = buildArtifactPayload(parsed); + try { + const created = await createWorkflowArtifact( + { + hubArtifactsUrl: env.hubArtifactsUrl, + sidecarToken: env.sidecarToken, + runAddress: env.address, + }, + artifact, + ); + return { + callId: call.id, + isError: false, + content: JSON.stringify({ + id: created.id, + version: created.version, + title: artifact.title, + kind: artifact.kind, + persisted: true, + }), + }; + } catch (err) { + return { + callId: call.id, + isError: true, + content: `Failed to persist "${artifact.title}" as a Library artifact: ${ + err instanceof Error ? err.message : String(err) + }`, + }; + } + }, + }), +}); diff --git a/workflows/diligence-brief/src/index.ts b/workflows/diligence-brief/src/index.ts new file mode 100644 index 000000000..4cd914a86 --- /dev/null +++ b/workflows/diligence-brief/src/index.ts @@ -0,0 +1,298 @@ +// The diligence-brief workflow (CL-6499): a single-step, mail-triggered +// definition that researches a company and writes a cited diligence +// brief as a markdown Library artifact, held for one human approval. +// +// ## Where this comes from +// +// Ported from scout's `workflows/diligence-brief` — a real multi-step +// pipeline there: an outline step plus one PARALLEL step per section +// (team, product, revenue, capital, growth, market, risks), each scored +// against seven weighted dimensions, deterministically assembled into a +// structured `DiligenceBrief` object by a pure-code `assemble-brief` +// action, then rendered. None of that machinery ports as-is: +// +// - Scout's tools (its own artifact/knowledge-search/web-research +// bundles from `@corbits/scout`) compile into scout's own sidecar and +// cannot be pinned here (`packages/scout/README.md`, CL-5179). Every +// tool call is rebound below to a workbench-published package instead: +// web research -> `@corbits/web-search-tools` (Exa-backed), firm +// memory -> `@corbits/memory-tools`. Nothing scout-specific is +// imported. +// - Scout's per-section parallel steps and pure-code assembler assume a +// deterministic `action` primitive this repo's execution host +// (`apps/sidecar`) has never wired (the same gap +// `last-30-days-research`'s header documents at length). Rather than +// fold seven parallel section steps into seven serial reasoning +// steps (which would multiply run time and per-step timeout risk for +// a first port), this port follows `code-review`'s and +// `collateral-generation`'s single-step shape: one agent, one +// reasoning turn, tools called inside it. +// - Scout's seven-dimension weighted scoring (`SCORE_WEIGHTS`, +// `dims`/`dimensionReads`) is cut entirely for this port. It is real +// product value scout's teammates rely on, and cutting it is an +// honest scope trim, not an oversight: a scored, per-dimension brief +// needs the parallel-section machinery above to stay within a single +// turn's output budget, and that machinery isn't proven on this +// host yet. This port ships a narrower, PROSE-ONLY brief across five +// fixed sections (see `DILIGENCE_BRIEF_SECTIONS` below) instead of a +// 500 on every run. +// +// ## What this port keeps faithful +// +// The evidence discipline scout's prompts commit to: ground every claim +// in a tool result, never invent a fact, and say "insufficient evidence" +// plainly rather than filling a section with prose that sounds +// confident but is not sourced. Firm memory is checked first (so a +// second brief on the same company builds on the first), then the web, +// exactly the order scout's own "tool policy" section commits to +// (`artifact refs first... then check knowledge-search... then +// webResearchTool`, minus the artifact-refs step this deployment has no +// equivalent trigger for yet). +// +// ## Delivery +// +// Persisting is gated by human approval, same as every other +// artifact-producing workflow in this catalog (AGENTS.md: "every +// external side effect sits behind human approval") — scout's own +// pipeline has no such gate (CL-6000 predates this repo's Library +// engine), so this is a deliberate policy addition, not a missing +// feature. The persisted artifact is markdown (`kind: "text"`), the +// same shape the sibling Gotenberg PDF-rendering lane already expects +// to render, so this workflow needs no PDF logic of its own. +// +// This package is installable data. It imports only published platform +// packages, and nothing imports it statically: a host publishes the +// serialized definition as a workflow asset and deploys it through the +// platform's deploy machinery; the execution host materializes it at +// runtime from the deploy alone. + +import type { AgentDefinition, InferencePreference } from "@intx/agent"; +import { defineWorkflow, step } from "@intx/workflow"; +import type { WorkflowDefinition } from "@intx/workflow"; +import type { CredentialBinding } from "@intx/types"; +import type { ToolPackagePin } from "@intx/types/tool-packages"; + +import { DILIGENCE_BRIEF_FINALIZE_TOOL_NAME } from "./finalize-tool"; + +export const DILIGENCE_BRIEF_WORKFLOW_ID = "wf_diligence_brief"; +export const DILIGENCE_BRIEF_STEP_ID = "diligence-brief"; + +/** + * The brief's fixed section outline (trimmed from scout's seven + * separately-scored sections — see this file's header comment). Team & + * Founders and Product & Market each keep their own heading since + * founder/product evidence rarely overlaps; Traction & Funding folds + * scout's separate revenue/capital-runway/growth-traction sections into + * one, since a single-turn brief cannot sustain three sections' worth of + * distinct evidence without either padding or fabricating. + */ +export const DILIGENCE_BRIEF_SECTIONS = [ + "Overview", + "Team & Founders", + "Product & Market", + "Traction & Funding", + "Risks & Open Questions", +] as const; + +export const DILIGENCE_BRIEF_WIRED_SOURCES = ["Web search", "Firm memory"] as const; + +/** + * Tool packages this definition pins (CL-5999 shape, matching + * `code-review`/`collateral-generation`/`assistant`'s precedent): + * `@corbits/web-search-tools` for live research, `@corbits/memory-tools` + * so a brief can check (and later inform) the tenant's firm memory. + */ +export const DILIGENCE_BRIEF_TOOL_PACKAGE_PINS: readonly ToolPackagePin[] = [ + { name: "@corbits/web-search-tools", version: "0.0.3" }, + { name: "@corbits/memory-tools", version: "0.0.4" }, +]; + +/** + * Binds the pinned web-search package's "exa" handle to the tenant's + * connection — `@corbits/memory-tools` needs no credential binding of + * its own; its env keys (`hubMemoryUrl`/`sidecarToken`/`address`) are + * populated for every workflow step directly, the same as + * `@corbits/artifact-tools`' trio. + */ +export const DILIGENCE_BRIEF_CREDENTIAL_BINDINGS: readonly CredentialBinding[] = [ + { + package: "@corbits/web-search-tools", + handle: "exa", + provider: "exa", + locator: "tenant", + }, +]; + +const SECTION_LINES = DILIGENCE_BRIEF_SECTIONS.map( + (heading, index) => `${String(index + 1)}. ${heading}`, +).join("\n"); + +export const DILIGENCE_BRIEF_SYSTEM_PROMPT = + "You research a company and write one cited diligence brief for the " + + "sender's own review, then finalize it pending a human's approval.\n" + + "\n" + + "## Reading the request\n" + + "The triggering mail names a `company` (the subject of the brief) and " + + "an optional `focus` narrowing which angle to dig into (e.g. \"go-to-" + + "market\" or \"founder track record\"). If no company is named, say so " + + "in one plain sentence and stop — never draft a brief with no subject.\n" + + "\n" + + "## Research order\n" + + "First call memory_search for the company name: firm memory may " + + "already hold notes from an earlier brief or conversation. Then call " + + "web_search (at least twice, with distinct queries — e.g. the company " + + "name alone, and the company name plus \"funding\" or \"founders\") to " + + "gather current, public information. A tool call that comes back as " + + "an error (missing credential, rate limit, failed request) means that " + + "source is not reachable right now — note it plainly and move on; " + + "never fail the whole run because one source is unavailable, and " + + "never invent results for a source you could not reach. If BOTH " + + "memory_search and every web_search call come back empty or " + + "unreachable, you have nothing to draft from.\n" + + "\n" + + "## Writing the brief\n" + + `Structure the brief under these five headings, in order:\n${SECTION_LINES}\n` + + "Ground every claim in a specific tool result — cite it inline (e.g. " + + "\"per web_search: ...\") rather than asserting facts with no source. " + + "Where evidence is thin or absent for a section, say so plainly " + + "(\"insufficient evidence in the sources gathered\") rather than " + + "padding it with generic industry prose. Never fabricate a founder " + + "name, a funding round, a metric, or a competitor that no source " + + "actually named.\n" + + "\n" + + "## Finalizing\n" + + `Once you have written the brief, call \`${DILIGENCE_BRIEF_FINALIZE_TOOL_NAME}\` ` + + 'exactly once with outcome "brief", a short title (e.g. "Diligence ' + + 'brief: "), and the full markdown brief as content. This ' + + "call requires a human's approval before it completes. If research " + + "turned up nothing (the no-data case above), still call " + + `\`${DILIGENCE_BRIEF_FINALIZE_TOOL_NAME}\` once with outcome ` + + '"status-note", a teaching title (e.g. "Diligence brief: — ' + + 'no results yet"), and content that honestly explains what was ' + + "searched for, names the missing or unreachable connectors by id " + + "(`exa` for web search), and says what to do next. Never end a run " + + "without finalizing — a plain reply with no artifact is not an " + + "acceptable outcome, even on the no-data path.\n" + + "\n" + + "If the finalize call succeeds, present the finalized brief as your " + + "reply exactly as written, with no commentary about the approval " + + "mechanism itself. If the call is denied, reply with one calm, plain " + + "sentence that the brief was not approved and no action was taken; " + + "never present a denial as an error, and never apologize as if " + + "something broke."; + +/** + * Everything the definition needs that is per-deployment data. The + * trigger address names a specific deployment's inbox — for this + * workflow, the address a human messages with a company name to start + * a run — so a definition built here is per-deployment by construction. + */ +export interface DiligenceBriefWorkflowInput { + /** The deployment's mail address; each inbound mail is one run. */ + readonly triggerAddress: string; + /** Provider/model preferences, in order; resolved at deploy time. */ + readonly inferencePreferences: readonly InferencePreference[]; + /** Per-turn timeout in milliseconds, enforced on the single step. */ + readonly turnTimeoutMs: number; +} + +/** + * Builds the diligence-brief definition. Exactly one step, matching the + * shape every other definition in this catalog commits to (`code-review` + * is the closest reference). Tools are never inlined on the definition: + * they arrive as packages on the deploy, keeping the definition pure + * data. + */ +export function buildDiligenceBriefWorkflow( + input: DiligenceBriefWorkflowInput, +): WorkflowDefinition { + if (input.triggerAddress === "") { + throw new Error( + "buildDiligenceBriefWorkflow requires a non-empty triggerAddress", + ); + } + if (!Number.isInteger(input.turnTimeoutMs) || input.turnTimeoutMs <= 0) { + throw new Error( + "buildDiligenceBriefWorkflow requires turnTimeoutMs to be a positive integer", + ); + } + return defineWorkflow({ + id: DILIGENCE_BRIEF_WORKFLOW_ID, + trigger: { type: "mail", to: input.triggerAddress }, + credentialBindings: DILIGENCE_BRIEF_CREDENTIAL_BINDINGS, + steps: { + [DILIGENCE_BRIEF_STEP_ID]: step({ + agent: { + id: DILIGENCE_BRIEF_STEP_ID, + description: + "Researches a company and writes a cited diligence brief, " + + "finalized pending human approval", + systemPrompt: DILIGENCE_BRIEF_SYSTEM_PROMPT, + toolFactories: [], + capabilities: [], + inference: { sources: input.inferencePreferences }, + toolPackagePins: DILIGENCE_BRIEF_TOOL_PACKAGE_PINS, + } satisfies AgentDefinition, + timeout: input.turnTimeoutMs, + }), + }, + }); +} + +/** + * Serializes a definition to the JSON a workflow asset carries. The + * definition must survive the asset round-trip byte-faithfully, so + * anything JSON would silently drop or mangle — functions, undefined, + * symbols, bigints, non-finite numbers, class instances — is a loud + * error naming the offending path instead of a corrupted asset. + */ +export function serializeDiligenceBriefWorkflow( + definition: WorkflowDefinition, +): string { + assertJsonPortable(definition, "definition"); + return JSON.stringify(definition); +} + +function assertJsonPortable(value: unknown, path: string): void { + if (value === null) return; + switch (typeof value) { + case "string": + case "boolean": + return; + case "number": + if (!Number.isFinite(value)) { + throw new Error(`${path} is a non-finite number; JSON drops it`); + } + return; + case "object": + break; + default: + throw new Error( + `${path} is a ${typeof value}, which does not survive JSON ` + + "serialization", + ); + } + if (Array.isArray(value)) { + value.forEach((element, index) => { + assertJsonPortable(element, `${path}[${index}]`); + }); + return; + } + const proto: unknown = Object.getPrototypeOf(value); + if (proto !== Object.prototype && proto !== null) { + throw new Error( + `${path} is a non-plain object; JSON would flatten it lossily`, + ); + } + for (const [key, entry] of Object.entries(value)) { + assertJsonPortable(entry, `${path}.${key}`); + } +} + +export { + DILIGENCE_BRIEF_FINALIZE_TOOL, + DILIGENCE_BRIEF_FINALIZE_TOOL_NAME, + DILIGENCE_BRIEF_FINALIZE_DESCRIPTION, + buildArtifactPayload, +} from "./finalize-tool"; +export type { ArtifactPayload, FinalizeArgs } from "./finalize-tool"; diff --git a/workflows/diligence-brief/test/boundary.test.ts b/workflows/diligence-brief/test/boundary.test.ts new file mode 100644 index 000000000..1874d3d43 --- /dev/null +++ b/workflows/diligence-brief/test/boundary.test.ts @@ -0,0 +1,54 @@ +// This package is installable data on the native workflow contract: +// its shipped sources import only published platform packages, so the +// source tree plus the package manifest deploys on any Interchange +// instance without a wrapper contract. Tool packages this workflow +// expects at deploy time (@corbits/web-search-tools, @corbits/memory-tools) +// are pinned by the deployer, never imported here — see src/index.ts's +// header comment. + +import { readFile, readdir } from "node:fs/promises"; +import path from "node:path"; +import { expect, test } from "bun:test"; + +const ALLOWED_IMPORT_PREFIXES = ["@intx/", "arktype", "./", "../"]; + +async function listFiles(dir: string): Promise { + const entries = await readdir(dir, { withFileTypes: true }); + const files: string[] = []; + for (const entry of entries) { + const full = path.join(dir, entry.name); + if (entry.isDirectory()) { + files.push(...(await listFiles(full))); + } else { + files.push(full); + } + } + return files; +} + +async function shippedFiles(): Promise { + const packageRoot = path.join(import.meta.dir, ".."); + return [ + ...(await listFiles(path.join(packageRoot, "src"))), + path.join(packageRoot, "package.json"), + ]; +} + +test("shipped sources import only published platform packages", async () => { + const importPattern = /from\s+"([^"]+)"/g; + const violations: string[] = []; + for (const file of await shippedFiles()) { + if (!file.endsWith(".ts") || file.endsWith(".test.ts")) continue; + const content = await readFile(file, "utf8"); + for (const match of content.matchAll(importPattern)) { + const specifier = match[1] ?? ""; + const allowed = ALLOWED_IMPORT_PREFIXES.some((prefix) => + specifier.startsWith(prefix), + ); + if (!allowed) { + violations.push(`${path.basename(file)}: ${specifier}`); + } + } + } + expect(violations).toEqual([]); +}); diff --git a/workflows/diligence-brief/test/definition.test.ts b/workflows/diligence-brief/test/definition.test.ts new file mode 100644 index 000000000..726366bd2 --- /dev/null +++ b/workflows/diligence-brief/test/definition.test.ts @@ -0,0 +1,160 @@ +// Tests for this package's own contract: the shape our factory +// commits to, its serialization guarantees, and its boundary. The +// platform's own normalization and validation are its business, not +// re-proven here. + +import { expect, test } from "bun:test"; +import type { StepPrimitive, WorkflowDefinition } from "@intx/workflow"; + +import { + DILIGENCE_BRIEF_CREDENTIAL_BINDINGS, + DILIGENCE_BRIEF_FINALIZE_TOOL_NAME, + DILIGENCE_BRIEF_SECTIONS, + DILIGENCE_BRIEF_STEP_ID, + DILIGENCE_BRIEF_TOOL_PACKAGE_PINS, + DILIGENCE_BRIEF_WIRED_SOURCES, + DILIGENCE_BRIEF_WORKFLOW_ID, + buildDiligenceBriefWorkflow, + serializeDiligenceBriefWorkflow, +} from "../src/index"; + +const INPUT = { + triggerAddress: "diligence-brief@example.test", + inferencePreferences: [{ provider: "anthropic", model: "claude-test" }], + turnTimeoutMs: 600000, +} as const; + +function briefStep(definition: WorkflowDefinition): StepPrimitive { + const primitive = definition.steps[DILIGENCE_BRIEF_STEP_ID]; + if (primitive === undefined || primitive.kind !== "step") { + throw new Error( + `definition has no step named ${DILIGENCE_BRIEF_STEP_ID}`, + ); + } + return primitive; +} + +test("the definition is one mail-triggered step", () => { + const definition = buildDiligenceBriefWorkflow(INPUT); + expect(definition.id).toBe(DILIGENCE_BRIEF_WORKFLOW_ID); + expect(definition.stepOrder).toEqual([DILIGENCE_BRIEF_STEP_ID]); + expect(definition.triggers).toEqual([ + { type: "mail", to: INPUT.triggerAddress }, + ]); +}); + +test("the step pins web-search and memory tool packages and sets an explicit turn timeout", () => { + const primitive = briefStep(buildDiligenceBriefWorkflow(INPUT)); + expect(primitive.timeout).toBe(INPUT.turnTimeoutMs); + expect(primitive.agent.toolPackagePins).toEqual( + DILIGENCE_BRIEF_TOOL_PACKAGE_PINS, + ); + expect(DILIGENCE_BRIEF_TOOL_PACKAGE_PINS).toEqual([ + { name: "@corbits/web-search-tools", version: "0.0.3" }, + { name: "@corbits/memory-tools", version: "0.0.4" }, + ]); + expect(primitive.agent.toolFactories).toEqual([]); +}); + +test("the definition binds the web-search package's exa handle to the tenant's connection", () => { + const definition = buildDiligenceBriefWorkflow(INPUT); + expect(definition.credentialBindings).toEqual( + DILIGENCE_BRIEF_CREDENTIAL_BINDINGS, + ); + expect(DILIGENCE_BRIEF_CREDENTIAL_BINDINGS).toEqual([ + { + package: "@corbits/web-search-tools", + handle: "exa", + provider: "exa", + locator: "tenant", + }, + ]); +}); + +test("the prompt names the fixed five-section outline, in order", () => { + const definition = buildDiligenceBriefWorkflow(INPUT); + const prompt = briefStep(definition).agent.systemPrompt; + expect(DILIGENCE_BRIEF_SECTIONS).toEqual([ + "Overview", + "Team & Founders", + "Product & Market", + "Traction & Funding", + "Risks & Open Questions", + ]); + let lastIndex = -1; + for (const heading of DILIGENCE_BRIEF_SECTIONS) { + const index = prompt.indexOf(heading); + expect(index).toBeGreaterThan(lastIndex); + lastIndex = index; + } +}); + +test("the prompt commits to checking memory before the web, and to the two wired sources", () => { + const definition = buildDiligenceBriefWorkflow(INPUT); + const prompt = briefStep(definition).agent.systemPrompt; + expect(DILIGENCE_BRIEF_WIRED_SOURCES).toEqual(["Web search", "Firm memory"]); + expect(prompt).toContain("memory_search"); + expect(prompt).toContain("web_search"); + expect(prompt.indexOf("memory_search")).toBeLessThan( + prompt.indexOf("web_search"), + ); + expect(prompt).toMatch(/never invent results/i); + expect(prompt).toMatch(/never fabricate/i); +}); + +test("the prompt names the exact approval-gated finalize tool and commits to always finalizing", () => { + const definition = buildDiligenceBriefWorkflow(INPUT); + const prompt = briefStep(definition).agent.systemPrompt; + expect(prompt).toContain(DILIGENCE_BRIEF_FINALIZE_TOOL_NAME); + expect(prompt).toMatch(/never end a run without finalizing/i); + expect(prompt).toContain("exa"); +}); + +test("the prompt commits to a calm terminal reply on denial, not an error", () => { + const definition = buildDiligenceBriefWorkflow(INPUT); + const prompt = briefStep(definition).agent.systemPrompt; + expect(prompt).toMatch(/not approved/i); + expect(prompt).toMatch(/never present a denial as an error/i); +}); + +test("the definition survives the workflow-asset round trip", () => { + const definition = buildDiligenceBriefWorkflow(INPUT); + const round = JSON.parse( + serializeDiligenceBriefWorkflow(definition), + ) as WorkflowDefinition; + expect(round).toEqual(definition); +}); + +test("serialization fails loud on a function-valued field, naming its path", () => { + const poisoned = { + id: DILIGENCE_BRIEF_WORKFLOW_ID, + triggers: [{ type: "manual" }], + stepOrder: [DILIGENCE_BRIEF_STEP_ID], + steps: { + [DILIGENCE_BRIEF_STEP_ID]: { + kind: "step", + id: DILIGENCE_BRIEF_STEP_ID, + drainBehavior: "cancel", + agent: { + id: DILIGENCE_BRIEF_STEP_ID, + systemPrompt: "x", + toolFactories: [() => []], + capabilities: [], + inference: { sources: [] }, + }, + }, + }, + } as unknown as WorkflowDefinition; + expect(() => serializeDiligenceBriefWorkflow(poisoned)).toThrow( + new RegExp(`steps\\.${DILIGENCE_BRIEF_STEP_ID}\\.agent\\.toolFactories\\[0\\]`), + ); +}); + +test("a blank trigger address or a bad timeout is refused at build time", () => { + expect(() => + buildDiligenceBriefWorkflow({ ...INPUT, triggerAddress: "" }), + ).toThrow(/triggerAddress/); + expect(() => + buildDiligenceBriefWorkflow({ ...INPUT, turnTimeoutMs: 0 }), + ).toThrow(/turnTimeoutMs/); +}); diff --git a/workflows/diligence-brief/tsconfig.json b/workflows/diligence-brief/tsconfig.json new file mode 100644 index 000000000..e956ddd88 --- /dev/null +++ b/workflows/diligence-brief/tsconfig.json @@ -0,0 +1,7 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "types": ["bun"] + }, + "include": ["src", "test"] +} From 22c8d673eb2e576e04df282361dcad931e100c0e Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Fri, 21 Aug 2026 08:39:44 -0700 Subject: [PATCH 2/4] Register diligence-brief in the workflow catalog and connector pin map MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds a WORKFLOW_CATALOG entry (asset name diligence-brief, company/focus trigger fields, automatable: false — gated behind a per-run company name, same as last-30-days-research) so the workflow is deployable and shows up in the web Routines picker, and adds it to the exa connector's pinned-workflows list alongside the other Exa-backed workflows. --- .../src/connections-pinned-by.test.ts | 3 +- .../settings-ui/src/connections-pinned-by.ts | 2 +- packages/workflow-catalog/src/index.ts | 34 +++++++++++++++++++ 3 files changed, 37 insertions(+), 2 deletions(-) diff --git a/packages/settings-ui/src/connections-pinned-by.test.ts b/packages/settings-ui/src/connections-pinned-by.test.ts index 341591782..b07ed95d1 100644 --- a/packages/settings-ui/src/connections-pinned-by.test.ts +++ b/packages/settings-ui/src/connections-pinned-by.test.ts @@ -37,10 +37,11 @@ describe("connections pinned-by", () => { ); }); - test("exa pins both web-search workflows", () => { + test("exa pins every web-search workflow", () => { expect(CONNECTOR_PINNED_WORKFLOWS.exa).toEqual([ "last-30-days-research", "exa-topic-watch", + "diligence-brief", ]); }); diff --git a/packages/settings-ui/src/connections-pinned-by.ts b/packages/settings-ui/src/connections-pinned-by.ts index 9434de55b..8c6d73534 100644 --- a/packages/settings-ui/src/connections-pinned-by.ts +++ b/packages/settings-ui/src/connections-pinned-by.ts @@ -18,7 +18,7 @@ export const CONNECTOR_PINNED_WORKFLOWS: Readonly< "collateral-generation", ], linear: ["morning-brief", "collateral-generation"], - exa: ["last-30-days-research", "exa-topic-watch"], + exa: ["last-30-days-research", "exa-topic-watch", "diligence-brief"], attio: ["attio-task-agent"], scrapecreators: ["reddit-opportunity-scanner"], github: ["code-review"], diff --git a/packages/workflow-catalog/src/index.ts b/packages/workflow-catalog/src/index.ts index 6d4cb421e..99bf58d06 100644 --- a/packages/workflow-catalog/src/index.ts +++ b/packages/workflow-catalog/src/index.ts @@ -343,6 +343,40 @@ export const WORKFLOW_CATALOG: readonly WorkflowCatalogEntry[] = [ }, ], }, + { + assetName: "diligence-brief", + displayName: "Diligence brief", + automatable: false, + conversational: false, + deliveryMode: "workbench", + whatItDoes: + "Researches a company across web search and firm memory, and writes a cited diligence brief across five fixed sections, held for approval before it's saved.", + requiredConnections: ["exa"], + exampleOutput: "Diligence brief: 5 sections, 2 flagged as insufficient evidence", + typicalDuration: "1-2 minutes, plus review and approval time", + // Mirrors workflows/diligence-brief/src/index.ts's system prompt + // exactly: "the trigger carries a `company` and an optional `focus`" — + // company is required (the prompt refuses to draft with no subject), + // focus narrows which angle to dig into and is skippable. + triggerFields: [ + { + key: "company", + kind: "text", + label: "Company", + placeholder: "Acme Corp", + required: true, + help: "The company this brief is about.", + }, + { + key: "focus", + kind: "text", + label: "Focus", + placeholder: "Founder track record", + required: false, + help: "Optional — narrows which angle to dig into.", + }, + ], + }, { assetName: "exa-topic-watch", displayName: "Web topic watch", From 8b2f1cd9c8a2b82294cdd9af00d9ce44caccc3e5 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Fri, 21 Aug 2026 08:39:49 -0700 Subject: [PATCH 3/4] Add diligence-brief workflow docs Documents what ported cleanly from scout, what got rebound to workbench tool packages and why, and the specific trims (no per-section parallel steps, five sections instead of seven, no dimension scoring, no source-artifact intake) so a reader comparing this to scout's original knows exactly where the gap is. --- workflows/diligence-brief/README.md | 128 ++++++++++++++++++++++++++++ 1 file changed, 128 insertions(+) create mode 100644 workflows/diligence-brief/README.md diff --git a/workflows/diligence-brief/README.md b/workflows/diligence-brief/README.md new file mode 100644 index 000000000..4e100a05b --- /dev/null +++ b/workflows/diligence-brief/README.md @@ -0,0 +1,128 @@ +# @corbits/diligence-brief-workflow + +A single-step, mail-triggered workflow that researches a company and +writes a cited diligence brief as a markdown Library artifact, held for +one human approval (CL-6499, ported from scout's +`workflows/diligence-brief`). + +## What ported cleanly + +The evidence discipline: ground every claim in a specific tool result, +never invent a founder, funding round, metric, or competitor, and say +"insufficient evidence" plainly rather than padding a thin section. The +research order — firm memory first, then the live web — mirrors scout's +own "tool policy" (artifact refs, then knowledge-search, then web +research), minus the artifact-refs step (this deployment has no +per-brief source-artifact trigger yet). The finalize-then-approve +delivery shape is the same one every other artifact-producing workflow +in this catalog uses (`last-30-days-research`, `pain-point-collateral`, +`collateral-generation`). + +## What did not port, and what this rebinds to instead + +Scout's tools compile into scout's own sidecar and cannot be pinned here +(`packages/scout/README.md`, CL-5179), so every tool call is rebound to +a workbench-published package: + +- Web research -> `@corbits/web-search-tools` (`web_search`, Exa-backed) +- Firm memory -> `@corbits/memory-tools` (`memory_search`) +- Artifact persistence -> `@corbits/artifacts-hub`'s workflow-artifacts + surface (`createWorkflowArtifact`, via this package's own + `finalize-tool.ts`/`artifact-client.ts` — duplicated rather than + imported, same convention every sibling workflow package uses). + That surface offers create + list-recent only, no search-by-field or + read-by-id — the same limit the sibling `@corbits/scout-agent` port + hit — so this workflow only ever writes one artifact per run; it + never reads a prior brief back by id. + +Scout's own artifact-read/knowledge-search tools (reading a founder deck +or prior source document by locator) have no workbench equivalent yet: +this port has no source-artifact input at all, so that gap is moot for +now rather than silently dropped. + +## What was trimmed, and why (read before comparing to scout's original) + +This is a materially narrower brief than scout's. Be blunt about this +with anyone who has used the original: + +- **No per-section parallel steps.** Scout drafts the brief as one + outline step plus one PARALLEL step per section (team, product, + revenue, capital, growth, market, risks), each well under a safe + output-token ceiling, then deterministically assembles them + (`assemble-brief`). This repo's execution host has never wired the + `action` primitive that parallel/assembled step graph assumes (the + same gap `last-30-days-research`'s own header documents). Folding + seven sections into seven *serial* reasoning steps would multiply run + time and per-step timeout risk for a first port, so this port instead + follows `code-review`'s single-step shape: one agent, one turn, + everything — research, drafting, all five sections — in one pass. +- **Five sections, not seven.** `DILIGENCE_BRIEF_SECTIONS` folds scout's + separate Revenue & Business Model / Capital & Runway / Growth & + Traction sections into one "Traction & Funding" section, and Market & + Competition into "Product & Market" — a single-turn brief cannot + sustain three sections' worth of genuinely distinct evidence without + either padding or fabricating. +- **No scoring.** Scout scores seven weighted dimensions + (`SCORE_WEIGHTS`, `dims`/`dimensionReads`) and produces a structured + `DiligenceBrief` object. This port produces prose-only markdown, no + scores, no structured JSON. Scoring is real product value and cutting + it is a deliberate scope trim, not an oversight — restoring it is the + natural next step once the parallel-step machinery above lands here. +- **No source-artifact intake.** Scout's research step opens every + `sourceArtifactRefs` locator with artifact-read before searching the + web. This port has no equivalent trigger field, so research starts + from firm memory and the open web only. + +## Verified end to end + +`bun test` (package-scoped, stubbing every tool call — no live Exa, no +live inference) passes: the finalize tool persists a stubbed artifact +and returns `persisted: true` on success, returns an honest `isError: +true` naming the failure on a broken persist call rather than a +fabricated success or a silent empty brief, and rejects malformed +arguments without throwing. The definition itself is asserted to name +the exact approval-gated finalize tool, commit to always finalizing +(even on the no-data path), and survive the workflow-asset JSON +round-trip. `bun run typecheck` passes clean. + +## Registration + +Registered in `packages/workflow-catalog`'s `WORKFLOW_CATALOG` (asset +name `diligence-brief`) alongside this package's own `corbits.workflow` +block, so it shows up wherever that catalog is read: the seed step and +the web Routines picker. See [`workflows/README.md`](../README.md#status-note) +for what registration/automatable/seeded mean — this one is +`automatable: false` (gated behind a human-supplied company name per +run, same as `last-30-days-research`) and not seeded by default. + +## Usage + +```ts +import { + buildDiligenceBriefWorkflow, + serializeDiligenceBriefWorkflow, +} from "@corbits/diligence-brief-workflow"; + +const definition = buildDiligenceBriefWorkflow({ + triggerAddress: "diligence-brief@tenant.example", + inferencePreferences: [{ provider: "anthropic", model: "claude-sonnet-5" }], + turnTimeoutMs: 600_000, +}); + +const json = serializeDiligenceBriefWorkflow(definition); +``` + +Pin `@corbits/web-search-tools` (needs an Exa key, handle `exa`) and +`@corbits/memory-tools` on the deployment for research to reach real +data; without them the brief honestly reports both as unreachable and +finalizes a status-note instead of a real brief. + +### Trigger fields (`company`, `focus`) + +Every run is triggered by mail to the deployment's address +(`triggerAddress` above); the one reasoning step reads two fields off +the trigger payload: + +- `company` (required) — the company the brief is about. +- `focus` (optional) — narrows which angle to dig into (e.g. + "go-to-market" or "founder track record"). From 11e4d4c953963509df213c1b9e50cb66d7006c96 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Fri, 21 Aug 2026 11:34:06 -0700 Subject: [PATCH 4/4] Format diligence workflow sources --- packages/workflow-catalog/src/index.ts | 3 +- workflows/diligence-brief/README.md | 2 +- workflows/diligence-brief/src/index.ts | 32 +++++++++++-------- .../diligence-brief/test/definition.test.ts | 8 ++--- 4 files changed, 25 insertions(+), 20 deletions(-) diff --git a/packages/workflow-catalog/src/index.ts b/packages/workflow-catalog/src/index.ts index 99bf58d06..d039a9370 100644 --- a/packages/workflow-catalog/src/index.ts +++ b/packages/workflow-catalog/src/index.ts @@ -352,7 +352,8 @@ export const WORKFLOW_CATALOG: readonly WorkflowCatalogEntry[] = [ whatItDoes: "Researches a company across web search and firm memory, and writes a cited diligence brief across five fixed sections, held for approval before it's saved.", requiredConnections: ["exa"], - exampleOutput: "Diligence brief: 5 sections, 2 flagged as insufficient evidence", + exampleOutput: + "Diligence brief: 5 sections, 2 flagged as insufficient evidence", typicalDuration: "1-2 minutes, plus review and approval time", // Mirrors workflows/diligence-brief/src/index.ts's system prompt // exactly: "the trigger carries a `company` and an optional `focus`" — diff --git a/workflows/diligence-brief/README.md b/workflows/diligence-brief/README.md index 4e100a05b..028afa46d 100644 --- a/workflows/diligence-brief/README.md +++ b/workflows/diligence-brief/README.md @@ -52,7 +52,7 @@ with anyone who has used the original: (`assemble-brief`). This repo's execution host has never wired the `action` primitive that parallel/assembled step graph assumes (the same gap `last-30-days-research`'s own header documents). Folding - seven sections into seven *serial* reasoning steps would multiply run + seven sections into seven _serial_ reasoning steps would multiply run time and per-step timeout risk for a first port, so this port instead follows `code-review`'s single-step shape: one agent, one turn, everything — research, drafting, all five sections — in one pass. diff --git a/workflows/diligence-brief/src/index.ts b/workflows/diligence-brief/src/index.ts index 4cd914a86..b4ad88681 100644 --- a/workflows/diligence-brief/src/index.ts +++ b/workflows/diligence-brief/src/index.ts @@ -94,7 +94,10 @@ export const DILIGENCE_BRIEF_SECTIONS = [ "Risks & Open Questions", ] as const; -export const DILIGENCE_BRIEF_WIRED_SOURCES = ["Web search", "Firm memory"] as const; +export const DILIGENCE_BRIEF_WIRED_SOURCES = [ + "Web search", + "Firm memory", +] as const; /** * Tool packages this definition pins (CL-5999 shape, matching @@ -114,14 +117,15 @@ export const DILIGENCE_BRIEF_TOOL_PACKAGE_PINS: readonly ToolPackagePin[] = [ * populated for every workflow step directly, the same as * `@corbits/artifact-tools`' trio. */ -export const DILIGENCE_BRIEF_CREDENTIAL_BINDINGS: readonly CredentialBinding[] = [ - { - package: "@corbits/web-search-tools", - handle: "exa", - provider: "exa", - locator: "tenant", - }, -]; +export const DILIGENCE_BRIEF_CREDENTIAL_BINDINGS: readonly CredentialBinding[] = + [ + { + package: "@corbits/web-search-tools", + handle: "exa", + provider: "exa", + locator: "tenant", + }, + ]; const SECTION_LINES = DILIGENCE_BRIEF_SECTIONS.map( (heading, index) => `${String(index + 1)}. ${heading}`, @@ -133,15 +137,15 @@ export const DILIGENCE_BRIEF_SYSTEM_PROMPT = "\n" + "## Reading the request\n" + "The triggering mail names a `company` (the subject of the brief) and " + - "an optional `focus` narrowing which angle to dig into (e.g. \"go-to-" + - "market\" or \"founder track record\"). If no company is named, say so " + + 'an optional `focus` narrowing which angle to dig into (e.g. "go-to-' + + 'market" or "founder track record"). If no company is named, say so ' + "in one plain sentence and stop — never draft a brief with no subject.\n" + "\n" + "## Research order\n" + "First call memory_search for the company name: firm memory may " + "already hold notes from an earlier brief or conversation. Then call " + "web_search (at least twice, with distinct queries — e.g. the company " + - "name alone, and the company name plus \"funding\" or \"founders\") to " + + 'name alone, and the company name plus "funding" or "founders") to ' + "gather current, public information. A tool call that comes back as " + "an error (missing credential, rate limit, failed request) means that " + "source is not reachable right now — note it plainly and move on; " + @@ -153,9 +157,9 @@ export const DILIGENCE_BRIEF_SYSTEM_PROMPT = "## Writing the brief\n" + `Structure the brief under these five headings, in order:\n${SECTION_LINES}\n` + "Ground every claim in a specific tool result — cite it inline (e.g. " + - "\"per web_search: ...\") rather than asserting facts with no source. " + + '"per web_search: ...") rather than asserting facts with no source. ' + "Where evidence is thin or absent for a section, say so plainly " + - "(\"insufficient evidence in the sources gathered\") rather than " + + '("insufficient evidence in the sources gathered") rather than ' + "padding it with generic industry prose. Never fabricate a founder " + "name, a funding round, a metric, or a competitor that no source " + "actually named.\n" + diff --git a/workflows/diligence-brief/test/definition.test.ts b/workflows/diligence-brief/test/definition.test.ts index 726366bd2..d97b47bea 100644 --- a/workflows/diligence-brief/test/definition.test.ts +++ b/workflows/diligence-brief/test/definition.test.ts @@ -27,9 +27,7 @@ const INPUT = { function briefStep(definition: WorkflowDefinition): StepPrimitive { const primitive = definition.steps[DILIGENCE_BRIEF_STEP_ID]; if (primitive === undefined || primitive.kind !== "step") { - throw new Error( - `definition has no step named ${DILIGENCE_BRIEF_STEP_ID}`, - ); + throw new Error(`definition has no step named ${DILIGENCE_BRIEF_STEP_ID}`); } return primitive; } @@ -146,7 +144,9 @@ test("serialization fails loud on a function-valued field, naming its path", () }, } as unknown as WorkflowDefinition; expect(() => serializeDiligenceBriefWorkflow(poisoned)).toThrow( - new RegExp(`steps\\.${DILIGENCE_BRIEF_STEP_ID}\\.agent\\.toolFactories\\[0\\]`), + new RegExp( + `steps\\.${DILIGENCE_BRIEF_STEP_ID}\\.agent\\.toolFactories\\[0\\]`, + ), ); });