From 8013ea00508f7910b1d01e317ebe7df9d91de6ae Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Fri, 25 Sep 2026 20:14:42 -0700 Subject: [PATCH 1/4] chore: use the Interchange LICENSE text and add the CLA --- .github/workflows/cla.yml | 53 +++ CLA.md | 64 ++++ LICENSE | 673 ++++++++++---------------------------- 3 files changed, 291 insertions(+), 499 deletions(-) create mode 100644 .github/workflows/cla.yml create mode 100644 CLA.md diff --git a/.github/workflows/cla.yml b/.github/workflows/cla.yml new file mode 100644 index 0000000..a03ad39 --- /dev/null +++ b/.github/workflows/cla.yml @@ -0,0 +1,53 @@ +name: CLA Assistant + +on: + issue_comment: + types: [created] + pull_request_target: + types: [opened, synchronize] + +permissions: + actions: write + contents: write + pull-requests: write + statuses: write + +concurrency: + group: cla-${{ github.event.pull_request.number || github.event.issue.number || github.run_id }} + cancel-in-progress: true + +jobs: + cla: + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - name: Maintainer fast path + if: >- + github.event_name == 'pull_request_target' && + (contains(fromJSON('["TheGreatAxios","brianjfox"]'), github.event.pull_request.user.login) || + endsWith(github.event.pull_request.user.login, '[bot]')) + run: echo "Maintainer or bot pull request; CLA not required." + - name: CLA Assistant + if: >- + ((github.event.comment.body == 'recreate-signatures' || + github.event.comment.body == 'I have read the CLA Document and I hereby sign the CLA') || + github.event_name == 'pull_request_target') && + !(github.event_name == 'pull_request_target' && + (contains(fromJSON('["TheGreatAxios","brianjfox"]'), github.event.pull_request.user.login) || + endsWith(github.event.pull_request.user.login, '[bot]'))) + # corbitsdev/cla-assistant-action v2.6.1-node24: upstream v2.6.1 on node24. + uses: corbitsdev/cla-assistant-action@ef6d3e51db8232fe93090810f13bde30497c1d74 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + path-to-document: "https://github.com/${{ github.repository }}/blob/main/CLA.md" + path-to-signatures: "signatures/version1/cla.json" + branch: "cla-signatures" + allowlist: TheGreatAxios,brianjfox,*[bot] + custom-notsigned-prcomment: >- + Thank you for your contribution. Before it can be merged, please read our + [Contributor License Agreement](https://github.com/${{ github.repository }}/blob/main/CLA.md) + and sign it by posting a new comment on this pull request containing + exactly the line below (nothing else): + custom-pr-sign-comment: "I have read the CLA Document and I hereby sign the CLA" + custom-allsigned-prcomment: "All contributors have signed the CLA." diff --git a/CLA.md b/CLA.md new file mode 100644 index 0000000..201eec8 --- /dev/null +++ b/CLA.md @@ -0,0 +1,64 @@ +# Contributor License Agreement (CLA) + +Version 1.0 + +This Contributor License Agreement ("Agreement") is entered into between the contributor ("Contributor") and ABK Labs, Inc. ("Maintainer"). + +By submitting any Contribution to a project maintained by Maintainer, the Contributor agrees to the following terms. + +## 1. Definitions + +"Contribution" means any source code, object code, documentation, test cases, designs, specifications, bug fixes, enhancements, comments, pull requests, commits, issues containing code, or other materials intentionally submitted to a project maintained by Maintainer. + +## 2. Copyright Ownership + +The Contributor retains ownership of the Contributor's copyrights in the Contribution. + +No transfer of copyright ownership is required by this Agreement. + +## 3. License Grant to Maintainer + +The Contributor grants Maintainer a perpetual, worldwide, non-exclusive, irrevocable, royalty-free license to: + +- use, reproduce, modify, distribute, display, perform, and sublicense the Contribution; +- combine the Contribution with other software and works; +- distribute the Contribution under the project's current license; +- distribute the Contribution under future versions of the project's license; +- distribute the Contribution under alternative open-source, source-available, commercial, proprietary, or dual-license terms. + +## 4. License Grant to the Public + +The Contributor agrees that the Contribution may be distributed as part of the applicable project under the project's then-current license terms, including LGPL-2.1 or any successor license adopted by Maintainer. + +## 5. Contributor Representations + +The Contributor represents and warrants that: + +1. The Contributor created the Contribution or otherwise has sufficient rights to submit it. +2. The Contributor has the legal authority to grant the rights described in this Agreement. +3. To the best of the Contributor's knowledge, the Contribution does not knowingly infringe the intellectual property rights of any third party. +4. Any third-party material included in the Contribution has been properly disclosed and is compatible with the rights granted under this Agreement. + +## 6. Corporate Contributions + +If a Contribution is submitted on behalf of an employer or other legal entity, the person accepting this Agreement represents that they are authorized to bind that entity to this Agreement. + +## 7. No Obligation + +Maintainer is not obligated to use, distribute, maintain, support, or accept any Contribution. + +## 8. Disclaimer + +Except as expressly stated in this Agreement, the Contribution is provided "AS IS" without warranties or conditions of any kind. + +## 9. Electronic Acceptance + +The Contributor agrees that electronic acceptance of this Agreement, including acceptance through a website, source-control platform, click-through process, pull-request workflow, or similar mechanism, shall have the same force and effect as a handwritten signature. + +## 10. Governing Law + +This Agreement shall be governed by the laws of the State of California, excluding its conflict-of-law provisions. + +--- + +By submitting a Contribution, the Contributor acknowledges that they have read and agree to this Agreement. diff --git a/LICENSE b/LICENSE index f6683e7..c6487f4 100644 --- a/LICENSE +++ b/LICENSE @@ -1,501 +1,176 @@ - GNU LESSER GENERAL PUBLIC LICENSE - Version 2.1, February 1999 - - Copyright (C) 1991, 1999 Free Software Foundation, Inc. - - 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. - - - Copyright (C) - - 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, see . - -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. - - , 1 April 1990 - Moe Ghoul, President of Vice +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! From 7adbf82670ddc60703501a8807fd4d220a5e7b34 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Fri, 25 Sep 2026 20:14:42 -0700 Subject: [PATCH 2/4] build: align package.json and tsconfig with the package standard --- .gitignore | 14 +++----------- bun.lock | 16 +++------------- e2e/list.test.ts | 12 ++++++------ e2e/reference-host.test.ts | 2 +- examples/reference-host/src/index.ts | 2 +- package.json | 27 ++++++++++----------------- tsconfig.build.json | 7 ++----- tsconfig.json | 16 +++++++++++----- 8 files changed, 37 insertions(+), 59 deletions(-) diff --git a/.gitignore b/.gitignore index 388079f..6f17218 100644 --- a/.gitignore +++ b/.gitignore @@ -1,16 +1,8 @@ node_modules/ dist/ -.env -.env.local *.tsbuildinfo +*.tgz coverage/ +.env +.env.* .DS_Store - -# npm pack output -*.tgz -.worktrees/ - -# Dispatch orchestration artifacts (local agent runs) -dispatch/ -.agent-state/ -.intercode/ diff --git a/bun.lock b/bun.lock index d26328d..ba5664c 100644 --- a/bun.lock +++ b/bun.lock @@ -17,8 +17,7 @@ "@intx/hub-common": "0.4.0", "@intx/hub-sessions": "0.4.0", "@intx/types": "0.4.0", - "@types/bun": "1.1.14", - "@types/node": "22.10.5", + "@types/bun": "1.3.9", "drizzle-orm": "0.45.2", "hono": "4.12.32", "hono-openapi": "1.2.0", @@ -42,9 +41,6 @@ ], }, }, - "overrides": { - "drizzle-orm": "0.45.2", - }, "packages": { "@ark/schema": ["@ark/schema@0.56.4", "", { "dependencies": { "@ark/util": "0.56.4" } }, "sha512-nd4OqaWdKZJeGF5zNmZysDQO7NyyJ1ycl4S7i16Hj1VxqL+x72Z66lOn7ErpsoMUZtCtslAMHMjqJhuQSxciyw=="], @@ -210,14 +206,12 @@ "@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="], - "@types/bun": ["@types/bun@1.1.14", "", { "dependencies": { "bun-types": "1.1.37" } }, "sha512-opVYiFGtO2af0dnWBdZWlioLBoxSdDO5qokaazLhq8XQtGZbY4pY3/JxY8Zdf/hEwGubbp7ErZXoN1+h2yesxA=="], + "@types/bun": ["@types/bun@1.3.9", "", { "dependencies": { "bun-types": "1.3.9" } }, "sha512-KQ571yULOdWJiMH+RIWIOZ7B2RXQGpL1YQrBtLIV3FqDcCu6FsbFUBwhdKUlCKUpS3PJDsHlJ1QKlpxoVR+xtw=="], "@types/json-schema": ["@types/json-schema@7.0.15", "", {}, "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA=="], "@types/node": ["@types/node@22.10.5", "", { "dependencies": { "undici-types": "~6.20.0" } }, "sha512-F8Q+SeGimwOo86fiovQh8qiXfFEh2/ocYv7tU5pJ3EXMSSxk1Joj5wefpFK2fHTf/N6HKGSxIDBT9f3gCxXPkQ=="], - "@types/ws": ["@types/ws@8.5.14", "", { "dependencies": { "@types/node": "*" } }, "sha512-bd/YFLW+URhBzMXurx7lWByOu+xzU9+kb3RboOteXYDfW+tr+JZa99OyNmPINEGB/ahzKrEuc8rcv4gnpJmxTw=="], - "abort-controller": ["abort-controller@3.0.0", "", { "dependencies": { "event-target-shim": "^5.0.0" } }, "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg=="], "agent-base": ["agent-base@7.1.4", "", {}, "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ=="], @@ -242,7 +236,7 @@ "buffer": ["buffer@6.0.3", "", { "dependencies": { "base64-js": "^1.3.1", "ieee754": "^1.2.1" } }, "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA=="], - "bun-types": ["bun-types@1.1.37", "", { "dependencies": { "@types/node": "~20.12.8", "@types/ws": "~8.5.10" } }, "sha512-C65lv6eBr3LPJWFZ2gswyrGZ82ljnH8flVE03xeXxKhi2ZGtFiO4isRKTKnitbSqtRAcaqYSR6djt1whI66AbA=="], + "bun-types": ["bun-types@1.3.9", "", { "dependencies": { "@types/node": "*" } }, "sha512-+UBWWOakIP4Tswh0Bt0QD0alpTY8cb5hvgiYeWCMet9YukHbzuruIEeXC2D7nMJPB12kbh8C7XJykSexEqGKJg=="], "cacache": ["cacache@20.0.4", "", { "dependencies": { "@npmcli/fs": "^5.0.0", "fs-minipass": "^3.0.0", "glob": "^13.0.0", "lru-cache": "^11.1.0", "minipass": "^7.0.3", "minipass-collect": "^2.0.1", "minipass-flush": "^1.0.5", "minipass-pipeline": "^1.2.4", "p-map": "^7.0.2", "ssri": "^13.0.0" } }, "sha512-M3Lab8NPYlZU2exsL3bMVvMrMqgwCnMWfdZbK28bn3pK6APT/Te/I8hjRPNu1uwORY9a1eEQoifXbKPQMfMTOA=="], @@ -472,8 +466,6 @@ "@npmcli/agent/lru-cache": ["lru-cache@11.5.2", "", {}, "sha512-4pfM1Ff0x50o0tQwb5ucw/RzNyD0/YJME6IVcStalZuMWxdt3sR3huStTtxz4PUmvZfRguvDejasvQ2kifR11g=="], - "bun-types/@types/node": ["@types/node@20.12.14", "", { "dependencies": { "undici-types": "~5.26.4" } }, "sha512-scnD59RpYD91xngrQQLGkE+6UrHUPzeKZWhhjBSa3HSkwjbQc38+q3RoIVEwxQGRw3M+j5hpNAM+lgV3cVormg=="], - "cacache/lru-cache": ["lru-cache@11.5.2", "", {}, "sha512-4pfM1Ff0x50o0tQwb5ucw/RzNyD0/YJME6IVcStalZuMWxdt3sR3huStTtxz4PUmvZfRguvDejasvQ2kifR11g=="], "cacache/ssri": ["ssri@13.0.1", "", { "dependencies": { "minipass": "^7.0.3" } }, "sha512-QUiRf1+u9wPTL/76GTYlKttDEBWV1ga9ZXW8BG6kfdeyyM8LGPix9gROyg9V2+P0xNyF3X2Go526xKFdMZrHSQ=="], @@ -492,8 +484,6 @@ "path-scurry/lru-cache": ["lru-cache@11.5.2", "", {}, "sha512-4pfM1Ff0x50o0tQwb5ucw/RzNyD0/YJME6IVcStalZuMWxdt3sR3huStTtxz4PUmvZfRguvDejasvQ2kifR11g=="], - "bun-types/@types/node/undici-types": ["undici-types@5.26.5", "", {}, "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA=="], - "minipass-flush/minipass/yallist": ["yallist@4.0.0", "", {}, "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A=="], "minipass-pipeline/minipass/yallist": ["yallist@4.0.0", "", {}, "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A=="], diff --git a/e2e/list.test.ts b/e2e/list.test.ts index 8cf7a15..c2524f2 100644 --- a/e2e/list.test.ts +++ b/e2e/list.test.ts @@ -186,13 +186,13 @@ describe("list paging", () => { } const first = await listArtifacts(db, "acme", { sort: "oldest", limit: 2 }); - expect(first.rows.map((r) => r.id)).toEqual([ids[0], ids[1]]); + expect(first.rows.map((r) => r.id)).toEqual([ids[0]!, ids[1]!]); const second = await listArtifacts( db, "acme", parseQuery({ sort: "oldest", limit: "2", cursor: first.nextCursor! }), ); - expect(second.rows.map((r) => r.id)).toEqual([ids[2]]); + expect(second.rows.map((r) => r.id)).toEqual([ids[2]!]); }); test("a malformed cursor is rejected by the query schema", () => { @@ -302,7 +302,7 @@ describe("list paging", () => { const first = await listArtifacts(db, "acme", { limit: 1 }); // Newest first: 2026-01-03 12:00 UTC — not the LA wall clock 04:00 with a // lying Z suffix. - expect(first.rows.map((r) => r.id)).toEqual([ids[2]]); + expect(first.rows.map((r) => r.id)).toEqual([ids[2]!]); expect(first.nextCursor).toBe(`2026-01-03T12:00:00.000000Z__${ids[2]}`); const second = await listArtifacts( @@ -310,7 +310,7 @@ describe("list paging", () => { "acme", parseQuery({ limit: "1", cursor: first.nextCursor! }), ); - expect(second.rows.map((r) => r.id)).toEqual([ids[1]]); + expect(second.rows.map((r) => r.id)).toEqual([ids[1]!]); expect(second.nextCursor).toBe(`2026-01-02T12:00:00.000000Z__${ids[1]}`); const third = await listArtifacts( @@ -318,7 +318,7 @@ describe("list paging", () => { "acme", parseQuery({ limit: "1", cursor: second.nextCursor! }), ); - expect(third.rows.map((r) => r.id)).toEqual([ids[0]]); + expect(third.rows.map((r) => r.id)).toEqual([ids[0]!]); expect(third.nextCursor).toBeNull(); // Date filters must also compare absolute instants, not session walls. @@ -330,7 +330,7 @@ describe("list paging", () => { createdBefore: "2026-01-02T23:59:59Z", }), ); - expect(filtered.rows.map((r) => r.id)).toEqual([ids[1]]); + expect(filtered.rows.map((r) => r.id)).toEqual([ids[1]!]); } finally { await db.execute(sql`SET TimeZone = 'UTC'`); } diff --git a/e2e/reference-host.test.ts b/e2e/reference-host.test.ts index d75249e..eb074c4 100644 --- a/e2e/reference-host.test.ts +++ b/e2e/reference-host.test.ts @@ -16,7 +16,7 @@ import { runArtifactMigrations, UnsupportedUploadTypeError, type ContentStore, -} from "@corbits/artifacts"; +} from "../src/index.js"; import { createReferenceHost, type ReferenceHost, diff --git a/examples/reference-host/src/index.ts b/examples/reference-host/src/index.ts index 1147f55..12f2e89 100644 --- a/examples/reference-host/src/index.ts +++ b/examples/reference-host/src/index.ts @@ -48,7 +48,7 @@ import { type ResolvedPrincipal, type ContentStore, type SerializedArtifactBase, -} from "@corbits/artifacts"; +} from "../../../src/index.js"; import { databaseConfig, DATABASE_URL } from "../../../e2e/helpers.js"; const EPOCH = new Date(0); diff --git a/package.json b/package.json index 6d46544..b87dbb1 100644 --- a/package.json +++ b/package.json @@ -26,13 +26,11 @@ "files": [ "dist", "migrations", - "LICENSE", - "README.md" + "README.md", + "LICENSE" ], "type": "module", "sideEffects": false, - "main": "./dist/index.js", - "types": "./dist/index.d.ts", "exports": { ".": { "types": "./dist/index.d.ts", @@ -47,15 +45,16 @@ "access": "public" }, "scripts": { - "typecheck": "tsc --noEmit", "build": "rm -rf dist && tsc -p tsconfig.build.json", "prepack": "bun run build", - "test": "bun test src", - "test:e2e": "bun test e2e", - "test:coverage": "bun test --coverage src e2e", + "typecheck": "tsc --noEmit", "lint": "oxlint", "format": "oxfmt", - "format:check": "oxfmt --check" + "format:check": "oxfmt --check", + "test": "bun test src --pass-with-no-tests", + "test:e2e": "bun test e2e", + "check": "bun run typecheck && bun run lint && bun run format:check && bun run test", + "test:coverage": "bun test --coverage src e2e" }, "dependencies": { "@hono/standard-validator": "^0.2.3", @@ -70,8 +69,7 @@ "@intx/hub-common": "0.4.0", "@intx/hub-sessions": "0.4.0", "@intx/types": "0.4.0", - "@types/bun": "1.1.14", - "@types/node": "22.10.5", + "@types/bun": "1.3.9", "drizzle-orm": "0.45.2", "hono": "4.12.32", "hono-openapi": "1.2.0", @@ -95,13 +93,8 @@ "optional": true } }, - "overrides": { - "drizzle-orm": "0.45.2" - }, "engines": { + "bun": ">=1.2.0", "node": ">=24" - }, - "corbits": { - "minimumIntxVersion": "0.4.0" } } diff --git a/tsconfig.build.json b/tsconfig.build.json index 9998a21..af6694f 100644 --- a/tsconfig.build.json +++ b/tsconfig.build.json @@ -1,15 +1,12 @@ { "extends": "./tsconfig.json", "compilerOptions": { - "types": ["node"], - "module": "NodeNext", - "moduleResolution": "NodeNext", - "allowImportingTsExtensions": false, - "composite": false, "noEmit": false, "declaration": true, "declarationMap": false, "sourceMap": false, + "module": "NodeNext", + "moduleResolution": "NodeNext", "outDir": "dist", "rootDir": "src" }, diff --git a/tsconfig.json b/tsconfig.json index aeb030c..dda942c 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,15 +1,21 @@ { "compilerOptions": { - "strict": true, - "exactOptionalPropertyTypes": true, + "esModuleInterop": true, + "skipLibCheck": true, "target": "ESNext", "module": "ESNext", "moduleResolution": "bundler", + "moduleDetection": "force", + "isolatedModules": true, "verbatimModuleSyntax": true, - "skipLibCheck": true, + "resolveJsonModule": true, + "strict": true, + "noUncheckedIndexedAccess": true, + "noImplicitOverride": true, + "exactOptionalPropertyTypes": true, "noEmit": true, - "types": ["node", "@types/bun"], - "paths": { "@corbits/artifacts": ["./src/index.ts"] } + "lib": ["ESNext"], + "types": ["bun"] }, "include": ["src", "e2e"] } From 84b19fdcd8e28462b951cf860a9fdf4c05424560 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Fri, 25 Sep 2026 20:14:43 -0700 Subject: [PATCH 3/4] ci: run check and a Node pack smoke --- .github/workflows/ci.yml | 38 +++++++++++++++++++ .github/workflows/test.yml | 75 -------------------------------------- e2e/helpers.ts | 2 +- 3 files changed, 39 insertions(+), 76 deletions(-) create mode 100644 .github/workflows/ci.yml delete mode 100644 .github/workflows/test.yml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..3729e10 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,38 @@ +name: ci + +on: + pull_request: + push: + branches: [main] + +jobs: + check: + runs-on: ubuntu-latest + timeout-minutes: 15 + services: + postgres: + image: postgres:16 + env: { POSTGRES_PASSWORD: postgres, POSTGRES_DB: artifact_core } + ports: ["5432:5432"] + options: >- + --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 + env: + ARTIFACT_DATABASE_URL: postgres://postgres:postgres@localhost:5432/artifact_core + ALLOW_DESTRUCTIVE_ARTIFACT_TESTS: "1" + steps: + - uses: actions/checkout@v5 + - uses: actions/setup-node@v4 + with: + node-version: 24 + - uses: oven-sh/setup-bun@v2 + - run: bun install --frozen-lockfile + - run: bun run check + - run: bun run test:coverage + - name: node consumer smoke + run: | + set -euo pipefail + TARBALL="$PWD/$(npm pack --silent)" + mkdir -p "$RUNNER_TEMP/c" && cd "$RUNNER_TEMP/c" + npm init -y >/dev/null && npm pkg set type=module >/dev/null + npm install "$TARBALL" + node -e 'import("@corbits/artifacts").then((m) => { for (const n of ["createArtifactRoutes", "runArtifactMigrations"]) if (typeof m[n] !== "function") throw new Error("missing export: " + n); })' diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml deleted file mode 100644 index 2b7beb4..0000000 --- a/.github/workflows/test.yml +++ /dev/null @@ -1,75 +0,0 @@ -name: test - -on: - push: - branches: [main] - pull_request: - -jobs: - test: - runs-on: ubuntu-latest - strategy: - matrix: - node-version: [24] - - services: - postgres: - image: postgres:16 - env: - POSTGRES_PASSWORD: postgres - POSTGRES_DB: artifact_core - ports: ["5457:5432"] - options: >- - --health-cmd pg_isready - --health-interval 10s - --health-timeout 5s - --health-retries 5 - - env: - ARTIFACT_DATABASE_URL: postgres://postgres:postgres@localhost:5457/artifact_core - # Package suite TRUNCATEs tables / some migration tests DROP SCHEMA — both - # refuse unless opted in against an allowlisted ephemeral database name. - ALLOW_DESTRUCTIVE_ARTIFACT_TESTS: "1" - - steps: - - uses: actions/checkout@v4 - - uses: oven-sh/setup-bun@v2 - with: - bun-version: 1.3.14 - - - run: bun install --frozen-lockfile - - run: bun run lint - - run: bun run format:check - - - name: typecheck - run: bun run typecheck - - - name: unit, integration and reference-host acceptance tests - run: bun run test:coverage - - - name: build - run: bun run build - - # A consumer on plain Node must be able to install and import the - # tarball; Node cannot strip types, so a src-pointing manifest would die - # here rather than after publish. - - name: Set up Node ${{ matrix.node-version }} - uses: actions/setup-node@v4 - with: - node-version: ${{ matrix.node-version }} - - name: node consumer smoke test - run: | - set -euo pipefail - TARBALL="$(npm pack --silent)" - TARBALL="$PWD/$TARBALL" - mkdir -p "$RUNNER_TEMP/consumer" && cd "$RUNNER_TEMP/consumer" - npm init -y >/dev/null && npm pkg set type=module >/dev/null - npm install "$TARBALL" - node -e ' - import("@corbits/artifacts").then((m) => { - for (const name of ["createArtifactRoutes", "runArtifactMigrations"]) { - if (typeof m[name] !== "function") throw new Error(`missing export: ${name}`); - } - console.log("node consumer ok"); - }); - ' diff --git a/e2e/helpers.ts b/e2e/helpers.ts index 81b69d7..4e317d3 100644 --- a/e2e/helpers.ts +++ b/e2e/helpers.ts @@ -26,7 +26,7 @@ import type { Actor } from "./fixtures.js"; export const DATABASE_URL = process.env.ARTIFACT_DATABASE_URL ?? - "postgres://postgres:postgres@localhost:5457/artifact_core"; + "postgres://postgres:postgres@localhost:5432/artifact_core"; /** `DATABASE_URL` in the shape Interchange's `runMigrations` takes. */ export function databaseConfig(connectionString: string): DBConfig { From 2a5fc435caec9c56ffcd6f3bb8b9cc96ea071215 Mon Sep 17 00:00:00 2001 From: Sawyer Cutler Date: Fri, 25 Sep 2026 20:14:43 -0700 Subject: [PATCH 4/4] docs: trim CONTRIBUTING, add AGENTS.md, drop SECURITY.md --- .github/SECURITY.md | 6 - AGENTS.md | 321 +++++++++++++++++++++++++++++++++++ CHANGELOG.md | 103 ----------- CONTRIBUTING.md | 404 ++------------------------------------------ README.md | 4 - 5 files changed, 339 insertions(+), 499 deletions(-) delete mode 100644 .github/SECURITY.md create mode 100644 AGENTS.md delete mode 100644 CHANGELOG.md diff --git a/.github/SECURITY.md b/.github/SECURITY.md deleted file mode 100644 index a0725a6..0000000 --- a/.github/SECURITY.md +++ /dev/null @@ -1,6 +0,0 @@ -# Security - -Report vulnerabilities privately to **sawyer@abklabs.com**. Please do not open -public issues for security reports. - -Supported version: the latest 0.x release. diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..a96626b --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,321 @@ +# AGENTS.md + +## Purpose + +`@corbits/artifacts` stores artifacts, their versions and uploads for an +Interchange host. It owns the three tables and their migrations, the HTTP +surface with its validation and status codes, the version and archive +semantics, the upload gate (`createFileArtifact` refuses anything outside its +required `policy` before the `ContentStore` is touched) and the download path +with its `nosniff`/`attachment` behaviour. The host supplies the +`Hono` app and database handle, the authenticated tenant and +principal, `RequireGrant`, display-only provenance decoration and a +`ContentStore`. + +## Layout + +- `src/mount.ts` — `createArtifactRoutes`: parsing, validation, status codes; wires the host's `requireGrant`. +- `src/workflow-mount.ts` — `createWorkflowArtifactRoutes`, the run-scoped routes for callers with no browser session. +- `src/artifacts.ts` — the core domain: create, revise, find-or-version, list, get, archive, serialize. +- `src/uploads.ts` — `createFileArtifact`, the MIME policies and the size caps. +- `src/download.ts` — one download path over the three storage conventions. +- `src/preview.ts`, `src/counts.ts` — previews and segment counts over the list query. +- `src/content-store.ts` — the two shipped `ContentStore` implementations. +- `src/tools.ts` — agent-facing tool definitions and windowed reads (caller tenant only). +- `src/sidecar-bundle.ts` — the `./sidecar-bundle` entry the tool-package loader invokes. +- `src/ports.ts` — the `ContentStore` type and the shared `ResolvedPrincipal` shape. +- `src/schema.ts`, `src/migrations.ts` — the three tables and `runArtifactMigrations`. +- `src/db.ts`, `src/arktype.ts` — the db handle type and arktype config. +- `src/index.ts` — the package entry. +- `e2e/` — real-Postgres suites; `e2e/reference-host.test.ts` runs the acceptance scenarios against `examples/reference-host`. + +## Rules + +- Nothing is mocked at the database boundary. Destructive test paths refuse to run unless `ALLOW_DESTRUCTIVE_ARTIFACT_TESTS=1` and the database is allowlisted (`artifact_core`, or a name ending in `_test`). +- The coverage floor is 80% of lines and functions per file (`bunfig.toml`); `bun run test:coverage` enforces it. +- A change to the route factory, a port or host wiring is shown working in `examples/reference-host`. +- No `@workbench/*` imports: it is an unpublished scope. +- A new `ContentStore` passes the same suite the shipped ones do, with no special cases. +- `schema.ts` and `migrations/` change together; every migration statement is idempotent and every backfill is cheap once it has run. +- One 404 covers never minted, malformed and another tenant's id; never add an existence oracle. +- Every `any` or cast carries a comment saying why the type system leaves no alternative. + +## Internals + +### Where the routes are served + +The core registers root-relative paths (`/artifacts*`) and takes no base path, so the _mount point_ +is the host's decision. The convention every `@corbits/*-core` package +documents, and every example here demonstrates, is **`/api`** — the same prefix +Interchange serves its own routes under (`app.route("/api/me", …)`, +`app.route("/api/tenants", …)`). No `/v1` segment, no vendor prefix. + +```ts +// Host middleware has already placed `tenant` and `principal` on the context. +app.route("/api", createArtifactRoutes({ db, contentStore, requireGrant })); +``` + +which serves `/api/artifacts`, `/api/artifacts/:id`, +`/api/artifacts/:id/versions`, and `/api/artifacts/:id/download`. Returning a sub-app rather than +taking a base path keeps the factory free of a configurable base path. + +Everything else it needs arrives through `deps` or the host's request context. +Nothing is reached for. + +### The route factory + +`createArtifactRoutes(deps): Hono` returns a sub-app typed with +Interchange's `TenantEnv`, built the way hub-api's `createGrantRoutes` is, so it +composes beneath Interchange auth + tenant middleware. The host places full +`tenant` and `principal` rows on the context; this package reads them natively +and never invents a second principal resolution path. + +Three options have no sensible default — `db`, `contentStore`, `requireGrant` — +and the rest degrade a _feature_, never safety, when omitted. The README's option +tables are the reference; what matters architecturally is +that optional seams **fail closed**: no `decorate` means no decoration. + +What the package does **not** require of a host: no session library, no UI, no +directory, no owner/admin policy callback. What it DOES require: Interchange's +control plane — `public.tenant` and `public.principal` must exist before the +migrations run, because the tables carry hard foreign keys into them — and a +host that puts the authenticated principal on `TenantEnv` and hands in its +`RequireGrant`. + +The principal's tenant is authoritative — there is no caller-supplied tenant +override anywhere in the route or tool surface. Tool reads always stay inside +`scope.tenantId`. + +**This is a decision, not an oversight.** The prior `Identity` port let +`readArtifact` / `readArtifactChunk` take a `tenantId` argument and cross into +it when `identity.ownerIsMemberOfTenant(scope, tenantId)` said the caller's +owner belonged there — a membership check this package invented and owned. +That is exactly the kind of policy this PR removes. It is not replaced by a +grant check, and won't be by a later one either: Interchange's `GrantStore` +resolves a principal's grants **within one tenant** +(`collectGrants(principalId, tenantId)`; `@intx/db`'s implementation filters +`grant` rows by `tenant_id`, and a principal is itself a row scoped to one +tenant). There is no platform primitive for "principal P, home tenant A, holds +a grant readable from tenant B" to check — inventing one here would mean this +package building a second, bespoke cross-tenant authorization concept on top +of the platform's, which is the precise failure mode "authorization is the +host's job" is meant to prevent. If a real product need for cross-tenant +artifact reads shows up, it belongs in Interchange's grant model, not +re-derived per package. + +### Three custom seams + +Beyond the host's native context and grants, this package exposes **three** +extension seams: the substrate (`ContentStore`), a display-only decorator +(`decorate` / provenance), and a grant-provisioning hook (`onArtifactCreated`). +Authorization is not a custom seam — it is the host's Interchange `RequireGrant`; +`onArtifactCreated` is not authorization either, it is the write side of the +same idea — the host deciding what makes its grant model true, this package +only handing it the row and the scope that made it. + +### Row decoration + +`decorate`'s display-only status is a contract, not a convention: it may add +fields to rows on their way out and must never affect _what_ is returned or +_who_ may see it. Joining a host's workflow tables inside this package would +couple it to a schema it must not know, so the host supplies the decorator. +Clients that need an owner display name resolve `ownerPrincipalId` themselves; +this package never ships directory names on the wire. + +### Grant provisioning (`onArtifactCreated`) + +Checking a grant (`requireGrant`) and minting one (`onArtifactCreated`) are the +same host responsibility looked at from both ends: this package neither +invents authorization policy nor decides who a newly created row belongs to +for grant purposes — it hands the host the row, inside the transaction that +made it durable, and the host decides. + +Creating needs its own grant, `create` on `artifact:*`, checked before the +body is read; the reference host seeds it for every principal in its tenant. +`examples/reference-host` then provisions a real `creator`-origin grant on create — +`write` and `archive` on `artifact:` for the creating principal, inserted +into Interchange's own `grant` table via `@intx/db`'s schema, in the same +transaction as the artifact row. Its `buildApp`'s default `requireGrant` is the +platform's real `createRequireGrant` over that same table (via +`createGrantStore`), not a stub — a principal with no matching row is refused, +exactly as in production. See `grantOwnership` in +`examples/reference-host/src/index.ts` and the "ownership-derived grants" +scenarios in its acceptance suite for the end-to-end proof: the creator +succeeds, a co-tenant with no grant does not. + +### ContentStore + +`ContentStore` is the substrate seam: + +- `put(tx, scope, blob)` persists bytes **inside the caller's transaction** and + returns the two artifact-row fields a stored file determines (`content` and + `source`). Taking the transaction rather than the handle is what makes "bytes, + artifact row, and version 1" a single atomic write — a failure anywhere leaves + no orphan bytes and no orphan artifact. +- `get(db, artifact)` resolves **out-of-band** bytes, or `null` when the store + keeps content in the row itself. It is tenant-scoped: a reference resolving to + another tenant's bytes must return `null`. + +Two implementations ship and both pass the same suite: `InlineContentStore` +(bytes in a tenant-owned `upload` row, referenced by `source.upload.id`) and +`DataUrlContentStore` (bytes inline in `content` as a base64 `data:` URL, no +side-table row, so its `get` returns `null`). A third backend — object storage, +say — is a third implementation, not a rewrite. The single download path +resolves the storage conventions in precedence order rather than branching on +which store is installed. + +### Data model + +Three physical tables — `artifact`, `artifact_version`, `upload`. + +**Hard control-plane foreign keys, by design.** `tenant_id` is `NOT NULL` and +references the host's `tenant(id)` (`ON DELETE CASCADE` — a deleted tenant takes its +artifacts with it) and `principal_id` / `owner_principal_id` reference +the host's `principal(id)` (`ON DELETE SET NULL` — a removed principal detaches its +artifacts rather than destroying them). This package is coupled to Interchange: +it mounts on Interchange-shaped hosts only, and the host's own migrations must +have run before `runArtifactMigrations`. The internal key — +`artifact_version.artifact_id` — cascades with its artifact. + +**Cheap row-local CHECKs.** `artifact.version` and `artifact_version.version` +must be ≥ 1; `upload.size` must be ≥ 0. These are +single-column constraints — free at write time. + +**Principal↔tenant alignment is host-owned.** The package FKs each column into +the control plane independently; it does **not** enforce that `principal_id` (or +`owner_principal_id`) belongs to the same tenant as `tenant_id`. A multi-table +trigger or composite FK into `public.principal` would couple every write to a +control-plane lookup and is deliberately out of scope. The host's middleware and +context are the authority: routes stamp the `(tenantId, principalId)` pair from +the Interchange `principal` already on `TenantEnv`, so a correctly mounted host +never plants a cross-tenant principal. Operators cleaning legacy rows before the +`tenant_id NOT NULL` migration must assign a valid tenant or delete orphans — +the migration fails with an explicit message if null `tenant_id` rows remain. + +**`kind` is free-form text, not a pg enum,** validated at the application edge. +New kinds cost no migration. What is _not_ free-form is the import allowlist: +`POST /api/artifacts` may only mint `link` or `document`, so an untrusted caller +cannot stamp a file-shaped, downloadable kind onto a row whose content is a URL +or a pasted body. + +**History is append-only.** Every create and every revision writes an +`artifact_version` row — including version 1, written eagerly with the artifact — +so a version-pinned read always resolves. The version bump has a double guard: +`SELECT ... FOR UPDATE` serializes writers, and the `(artifact_id, version)` +unique constraint makes a racing writer that somehow computed the same next +version fail loudly rather than corrupt history. + +**Archival is a soft hide.** `archived_at` null means visible; a timestamp means +hidden from discovery. Deep links to archived artifacts still load. + +**Find-or-version is a package primitive, not a constraint.** The only +uniqueness the schema enforces is `(artifact_id, version)` — there is no +constraint on `(tenant_id, title, kind)`, so "find by title, create if +absent, add a version if present" is not naturally atomic: a plain +read-then-write of that pattern races, and two concurrent callers can both +observe NOT FOUND and both create, leaving two artifacts with the same +title. + +A uniqueness constraint on `(tenant_id, title, kind)` was considered and +rejected — not just for now, but structurally. `createArtifact` is a +public, unconditional insert with no title lookup of its own, called +directly by the import route, the upload path, and `artifact_link_file`. +Two independent creates sharing a title is normal, intended behavior on +every one of those paths — a coworker uploading `report.pdf` twice, or two +agents each linking a file named `notes.md`, are not bugs. A hard +`UNIQUE(tenant_id, title, kind)` constraint would reject those ordinary +inserts outright, not just gate on a one-time backfill of legacy +duplicates. Uniqueness on that triple is a property of the _find-or-version +pattern specifically_, not an invariant of the table, so it does not belong +in the schema — it belongs exactly where it now lives, inside the one code +path that promises it. + +Separately, this package also has no way to confirm existing tenants are +already free of duplicate `(title, kind)` rows, which would make even a +scoped constraint risky to backfill. That is not the main reason for +rejecting the constraint, and it is not by itself decisive. + +Instead, `findOrVersionArtifact(db, args)` (in `artifacts.ts`) closes the +race with a transaction-scoped advisory lock keyed by +`hashtext(tenantId, kind, title)`, in its own lock-space namespace (the +two-`int4`-argument form of `pg_advisory_xact_lock`, disjoint from the +single-`bigint` form `runArtifactMigrations` uses). Collision semantics: +whichever concurrent caller acquires the lock first creates the artifact; +every other caller for the identical `(tenantId, kind, title)` blocks, then +finds the row the winner just committed and revises it. Two overlapping +callers always converge on ONE artifact with two versions, never two rows — +callers for a different tenant, kind, or title never contend with each +other. This guarantee holds only for callers that go through +`findOrVersionArtifact`; a caller that instead calls `createArtifact` +directly is unconstrained by design, as above, and a caller that hand-rolls +its own find-then-create against a _different_ lock is not serialized +against this one — the primitive closes the race for its own call path, not +for every possible way to write an artifact. + +**`upload` is never a standalone resource.** There is no `POST /uploads`; every +upload eagerly mints its artifact, and the row is reachable only through +`source.upload.id`. + +The list index is `(tenant_id, updated_at, id)`. The `id` is the list's +tie-break and must be _in_ the index, or the keyset cursor's row-value +comparison falls out of the index condition into a filter and drags a sort +behind it. + +### Migration runner + +`runArtifactMigrations(config, { schema })` takes the same arguments as +Interchange's `runMigrations`, and a host calls it right after that, with the +same values. `schema` is where the host's `tenant` and `principal` tables live; +the runner rewrites the `"public".` foreign-key references in the SQL files to +it. It is idempotent and safe to call on every boot of every replica. + +- The whole run is one transaction whose first statement takes a + **transaction-scoped** advisory lock, so the lock releases on commit or + rollback and there is no unlock call to lose on an error path. + `CREATE TABLE IF NOT EXISTS` is not itself race-safe, so the lock — not the + `IF NOT EXISTS` — is what makes concurrent cold starts safe. +- The runner opens its own single-connection client and discards NOTICEs, so a + re-run, where Postgres answers every `IF NOT EXISTS` with a NOTICE, prints + nothing. +- Event timestamps (`created_at`, `updated_at`, `archived_at`) are + **`timestamptz`**. List keyset cursors project through `AT TIME ZONE 'UTC'` + and compare with `::timestamptz`, so paging and date filters stay on the + absolute instant under any session `TimeZone`. +- Releases up to 0.1.0 kept a checksum ledger in `artifacts.migrations`. + `0002_drop_migration_ledger.sql` removes it; a database migrated by 0.1.0 + already has the shape `0001_artifacts.sql` creates, so its statements no-op. + +**The package owns its own Postgres schema.** Every table and index lives in +`artifacts`, created by the runner and qualified in every DDL statement and +every query — nothing resolves through `search_path`, so the package shares a +database with the host's control plane without ever being able to collide with +(or silently adopt) a host table of the same name. The coupling to the host is +explicit instead: `tenant_id` and the principal columns are hard FKs into the +host schema's `tenant` / `principal` (see the data model). + +### Known limits + +- **No file parsing, ever.** No PDF parser, no spreadsheet parser, no text + extractor, and none is planned. An extractor is a heavyweight, fast-moving + native dependency, and what the extracted text is _for_ is the host's product. + The contract the package offers a parsing host instead is **parse before you + store**: `createFileArtifact` is the only way a file becomes an artifact, so a + host that parses first and fails leaves nothing orphaned. +- **Two of the three MIME allowlists are host-owned surfaces.** This package + ships all three constants but only owns the gallery import route; spreadsheet + ingest and attachment divert are the host's routes calling this package's gate. +- **Upload caps are fixed constants,** not configuration: 10 MB per file, 50 + files and 100 MB per request. +- **`InlineContentStore` keeps bytes in Postgres.** That is a deliberate + zero-dependency default, not a recommendation at scale; a large corpus wants a + `ContentStore` over object storage. +- **List paging caps at 100** rows (default 20). +- **One 404 covers three causes** for a resolved caller — never minted, + malformed, or another tenant's. Distinguishing them would be + an existence oracle. Expect no more detail than that from the API. + +## Local development + +```sh +bun install && bun run check +``` diff --git a/CHANGELOG.md b/CHANGELOG.md deleted file mode 100644 index 99b4cda..0000000 --- a/CHANGELOG.md +++ /dev/null @@ -1,103 +0,0 @@ -# Changelog - -All notable changes to `@corbits/artifacts` are documented here. The format -follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this -package follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - -Until 1.0, a minor bump may contain a breaking change; breaking changes are -always called out under their own heading. - -## [0.2.0] — 2026-09-25 - -### Added - -- `POST /api/artifacts/:id/versions` revises an uploaded file with new bytes - when sent as `multipart/form-data` with one `file` field and an optional - `expectedVersion`. The bytes go through the configured `ContentStore` and - upload policy (`415` for a refused type, `413` over `MAX_UPLOAD_BYTES`), - and are stored only after the version check passes. The title carries - forward; the version downloads under the new file's name. - `reviseFileArtifact` is the underlying function. -- Upload bytes are versioned. Each version records its own content - reference in `artifact_version.source` (added by `0004_version_source`, - which backfills existing versions), so `GET .../download?version=N` and - `GET .../versions/:version` return that version's file after a revision. - -### Changed - -- `@intx/agent` is an optional peer. Only `@corbits/artifacts/sidecar-bundle` - imports it. -- `arktype` is a regular dependency instead of a peer. -- `@intx/db` is a new peer. The minimum `@intx/*` is **0.4.0**. - -### Breaking - -- `mountArtifacts(app, opts)` is replaced by `createArtifactRoutes(deps)`, - which returns a `Hono` sub-app the host mounts with - `app.route(...)`. `MountArtifactsOpts` is renamed `CreateArtifactRoutesDeps`. -- `mountWorkflowArtifacts(app, opts)` is replaced by - `createWorkflowArtifactRoutes(deps)`, a sub-app the host mounts at - `/api/workflow-artifacts`. `MountWorkflowArtifactsOpts` is renamed - `CreateWorkflowArtifactRoutesDeps`. -- `POST /artifacts` and `POST /artifacts/upload` require - `requireGrant("artifact:*", "create")`. On upgrade from 0.1.0, the - migrations grant `create` on `artifact:*` to every principal that has - already created an artifact in its tenant, in the host's `grant` table. - New principals need the grant from the host. An unauthenticated caller now gets - `{ "error": "Forbidden" }` instead of `{ "error": "Tenant not accessible" }`. -- `runArtifactMigrations(config, { schema })` takes the same arguments as - Interchange's `runMigrations`: a `DBConfig` and the host schema holding - `tenant` and `principal`. It applies the idempotent SQL files shipped under - `migrations/` with no ledger. The `adopt` option, - `RunArtifactMigrationsOptions`, `MigrationChecksumError` and - `MigrationAdoptError` are removed. -- The first 0.2.0 boot drops the `artifacts.migrations` ledger, so a - database cannot go back to 0.1.0. Do not run 0.1.0 and 0.2.0 replicas - against the same database. -- The drizzle tables (`artifact`, `artifactVersion`, `upload`, - `mailAttachmentRef`) are no longer exported. `ARTIFACTS_SCHEMA` and the - `*Row` types stay public. -- `SKILL_DRAFT_KIND` is removed. `skill-draft` is an ordinary `kind`. -- `web_site` handling is removed: content is stored as given, `readArtifact` - no longer takes `path`, and every `WEB_SITE_*` constant and web-site - helper and type is no longer exported. -- Mail attachment references are removed: the - `/instances/:instanceId/mail-attachments` routes, `saveMailAttachmentRefs`, - `listMailAttachmentRefs`, `MAIL_ATTACHABLE_KINDS`, - `MailAttachmentKindError`, `MAX_MAIL_ATTACHMENT_BYTES`, - `MAX_MAIL_ATTACHMENTS_PER_MAIL` and `MailAttachmentRefRow`. - `0003_drop_mail_attachment_ref` drops the table and its rows. -- `windowContent` is no longer exported. -- Node 24 or newer is required (0.1.0 accepted Node 22). - -## [0.1.0] — first release - -Initial public release. Nothing has been published before this, so everything is -new; the list below is what the surface consists of rather than what changed. - -- `mountArtifacts(app, opts)` — mounts artifacts, versions and uploads on a - host's existing Hono app: tenant-scoped list with keyset paging and - query/kind/owner/date filters, human import of a link or pasted text, - multipart upload, deep-link detail, version history and revision, idempotent - soft archive and unarchive, a single download path, and artifact↔message - attachment refs. Every route carries OpenAPI metadata. -- `runArtifactMigrations(db)` — idempotent, advisory-locked, checksum-guarded, - with its own ledger table (`artifacts.migrations`) and silent re-runs. Safe to - call on every boot of every replica. All tables live in the package-owned - `artifacts` Postgres schema; nothing resolves through `search_path`. -- Four tables — `artifact`, `artifact_version`, `upload`, `mail_attachment_ref` - — with hard foreign keys into Interchange's `public.tenant` / - `public.principal` and append-only version history. -- `ContentStore` port with two shipped implementations, `InlineContentStore` - (bytea side-table) and `DataUrlContentStore` (inline `data:` URL), both - passing the same suite. -- Host options: required `db`, `contentStore`, and `requireGrant`, plus optional - display-only `decorate` and `uploadPolicy` behavior. -- Agent-facing tool definitions with tenant-confined windowed artifact reads, - and the `web_site` artifact kind. -- Requires `@intx/*` 0.2.2 or newer, Node 22+ or Bun 1.1+, and Postgres 13+. - (`@intx/*` 0.1.2 does not install — its deps pin the unpublished - `@intx/*@0.0.0` — and ships raw TypeScript.) - -[0.2.0]: https://github.com/corbitsdev/corbits-artifacts -[0.1.0]: https://github.com/corbitsdev/corbits-artifacts diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 274310e..f12e59a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,402 +1,21 @@ # Contributing -A small, deliberately boring codebase: strict TypeScript, arktype at the boundaries, -drizzle for data access, no magic. - ## Development ```sh -git clone https://github.com/corbitsdev/corbits-artifacts.git -cd corbits-artifacts bun install -docker run -d --name corbits-artifact-pg -p 5457:5432 \ - -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=artifact_core postgres:16 -export ALLOW_DESTRUCTIVE_ARTIFACT_TESTS=1 - -bun run typecheck -bun run test # unit -bun run test:e2e # real-Postgres and reference-host acceptance -bun run build # dist/ (JS + .d.ts) +bun run check ``` -Tests expect `postgres://postgres:postgres@localhost:5457/artifact_core` (override with -`ARTIFACT_DATABASE_URL`). - -`bun run typecheck` must be clean — it is its own CI step, and `any` is not a way past it. The -few escapes in the tree each carry a comment explaining why the type system leaves no -alternative; new ones need the same. - -## Most of the suite needs a real Postgres - -Nothing is mocked at the database boundary. Migrations, indexes, keyset cursors, the -version-bump race and tenant scoping are asserted against a live server, because that is -the only place they are true. - -The harness truncates package tables between tests and drops the package schema in a -couple of migration cases. Those paths are fail-closed: set -`ALLOW_DESTRUCTIVE_ARTIFACT_TESTS=1` and point `ARTIFACT_DATABASE_URL` at an allowlisted -ephemeral database (`artifact_core`, or any name ending in `_test`). Without both, the -suite throws before mutating. - -End-to-end suites live in `e2e/`. `e2e/helpers.ts` creates a fresh -`artifact__test` database per suite on the `ARTIFACT_DATABASE_URL` server, -applies Interchange's `runMigrations` and `runArtifactMigrations`, and drops it -afterwards. `artifactApp` mounts `createArtifactRoutes` for a seeded tenant -principal, authorized by the platform's real `createRequireGrant` over the -database's `grant` table. `bun run test` runs `src/`; `bun run test:e2e` runs `e2e/`. - -## The reference host is the acceptance suite, not a demo - -`examples/reference-host` mounts the package on a real `@intx/hub-api` app against a -live Postgres. `e2e/reference-host.test.ts` asserts the end-to-end scenarios against -it as part of `bun run test:e2e`; the example imports `@corbits/artifacts`, which the -root `tsconfig.json` maps to `src/`. CI's Node consumer smoke test covers the built -`dist/` a consumer installs. +`bun run check` runs typecheck, lint, format check and unit tests. `bun run format` rewrites the tree. -If you change the route factory, a port, or anything about how a host wires this up, the -reference host is where that change has to be shown working. +Contributors sign the [CLA](CLA.md) on their first PR; the CLA bot explains how. -## Dependency rule - -No `@workbench/*` imports anywhere — it is an unpublished scope, and importing it would -make this package uninstallable outside the project that defines it. - -## Tests - -- **Red first.** A bug fix starts with a test that fails for the reason you believe, and - you should watch it fail. A test that was green before the fix proved nothing. -- **Coverage floor is 80% of lines and functions**, set by `coverageThreshold` in the - package's `bunfig.toml` and applied by Bun **per file** — one badly covered new file - fails the run even when the average looks fine. It is a floor, not a target. -- Assert **behavior a consumer can observe** — a status code, a returned shape, a row in - the database — over internal call shapes. -- A new `ContentStore` implementation is expected to pass the same suite the two shipped - ones do. If it needs a special case in a test, that is a signal about the port, not - about the test. +`bun run test:e2e` and `bun run test:coverage` need Postgres. Start one with `docker run -d --name corbits-artifact-pg -p 5432:5432 -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=artifact_core postgres:16`, then run with `ARTIFACT_DATABASE_URL=postgres://postgres:postgres@localhost:5432/artifact_core ALLOW_DESTRUCTIVE_ARTIFACT_TESTS=1`. The harness truncates tables and drops schemas, so it refuses to run without that flag and an allowlisted database name (`artifact_core`, or any name ending in `_test`). Each e2e suite creates and drops its own `artifact__test` database. `bun run test:coverage` runs `src/` and `e2e/` and fails below the 80% per-file floor in `bunfig.toml`; CI runs it. ## Migrations -Migrations are SQL files under `migrations/`, applied in filename order on every -boot, so every statement must be idempotent (`IF NOT EXISTS`, `IF EXISTS`). There -is no ledger: a schema change is a new file whose statements are safe to re-run, -never an edit that assumes it runs once. - -Because every file re-runs on every boot, a data backfill must be cheap once it has -run: guard it so an already-migrated database does no work beyond a quick check. - -`schema.ts` and `migrations/` must agree — every query goes through the drizzle -table objects, and the route suites fail when a column they write is missing. -Change one, change the other, in the same commit. - -## Pull requests - -- Keep commits focused, and keep the diff to the change you are describing. -- Explain _why_ in the commit message; the code already says what. -- CI must be green: typecheck, unit + integration, build, reference-host - acceptance, and a Node consumer smoke test that installs the packed tarball. -- Contributions are accepted under the repository's LGPL-2.1-only licence. - -## Internals - -How the package is put together and why. Mount options and snippets are in the -[README](./README.md). - -### Where the routes are served - -The core registers root-relative paths (`/artifacts*`) and takes no base path, so the _mount point_ -is the host's decision. The convention every `@corbits/*-core` package -documents, and every example here demonstrates, is **`/api`** — the same prefix -Interchange serves its own routes under (`app.route("/api/me", …)`, -`app.route("/api/tenants", …)`). No `/v1` segment, no vendor prefix. - -```ts -// Host middleware has already placed `tenant` and `principal` on the context. -app.route("/api", createArtifactRoutes({ db, contentStore, requireGrant })); -``` - -which serves `/api/artifacts`, `/api/artifacts/:id`, -`/api/artifacts/:id/versions`, and `/api/artifacts/:id/download`. Returning a sub-app rather than -taking a base path keeps the factory free of a configurable base path. - -Everything else it needs arrives through `deps` or the host's request context. -Nothing is reached for. - -### The route factory - -`createArtifactRoutes(deps): Hono` returns a sub-app typed with -Interchange's `TenantEnv`, built the way hub-api's `createGrantRoutes` is, so it -composes beneath Interchange auth + tenant middleware. The host places full -`tenant` and `principal` rows on the context; this package reads them natively -and never invents a second principal resolution path. - -Three options have no sensible default — `db`, `contentStore`, `requireGrant` — -and the rest degrade a _feature_, never safety, when omitted. The README's option -tables are the reference; what matters architecturally is -that optional seams **fail closed**: no `decorate` means no decoration. - -What the package does **not** require of a host: no session library, no UI, no -directory, no owner/admin policy callback. What it DOES require: Interchange's -control plane — `public.tenant` and `public.principal` must exist before the -migrations run, because the tables carry hard foreign keys into them — and a -host that puts the authenticated principal on `TenantEnv` and hands in its -`RequireGrant`. - -The principal's tenant is authoritative — there is no caller-supplied tenant -override anywhere in the route or tool surface. Tool reads always stay inside -`scope.tenantId`. - -**This is a decision, not an oversight.** The prior `Identity` port let -`readArtifact` / `readArtifactChunk` take a `tenantId` argument and cross into -it when `identity.ownerIsMemberOfTenant(scope, tenantId)` said the caller's -owner belonged there — a membership check this package invented and owned. -That is exactly the kind of policy this PR removes. It is not replaced by a -grant check, and won't be by a later one either: Interchange's `GrantStore` -resolves a principal's grants **within one tenant** -(`collectGrants(principalId, tenantId)`; `@intx/db`'s implementation filters -`grant` rows by `tenant_id`, and a principal is itself a row scoped to one -tenant). There is no platform primitive for "principal P, home tenant A, holds -a grant readable from tenant B" to check — inventing one here would mean this -package building a second, bespoke cross-tenant authorization concept on top -of the platform's, which is the precise failure mode "authorization is the -host's job" is meant to prevent. If a real product need for cross-tenant -artifact reads shows up, it belongs in Interchange's grant model, not -re-derived per package. - -### Three custom seams - -Beyond the host's native context and grants, this package exposes **three** -extension seams: the substrate (`ContentStore`), a display-only decorator -(`decorate` / provenance), and a grant-provisioning hook (`onArtifactCreated`). -Authorization is not a custom seam — it is the host's Interchange `RequireGrant`; -`onArtifactCreated` is not authorization either, it is the write side of the -same idea — the host deciding what makes its grant model true, this package -only handing it the row and the scope that made it. - -### Row decoration - -`decorate`'s display-only status is a contract, not a convention: it may add -fields to rows on their way out and must never affect _what_ is returned or -_who_ may see it. Joining a host's workflow tables inside this package would -couple it to a schema it must not know, so the host supplies the decorator. -Clients that need an owner display name resolve `ownerPrincipalId` themselves; -this package never ships directory names on the wire. - -### Grant provisioning (`onArtifactCreated`) - -Checking a grant (`requireGrant`) and minting one (`onArtifactCreated`) are the -same host responsibility looked at from both ends: this package neither -invents authorization policy nor decides who a newly created row belongs to -for grant purposes — it hands the host the row, inside the transaction that -made it durable, and the host decides. - -Creating needs its own grant, `create` on `artifact:*`, checked before the -body is read; the reference host seeds it for every principal in its tenant. -`examples/reference-host` then provisions a real `creator`-origin grant on create — -`write` and `archive` on `artifact:` for the creating principal, inserted -into Interchange's own `grant` table via `@intx/db`'s schema, in the same -transaction as the artifact row. Its `buildApp`'s default `requireGrant` is the -platform's real `createRequireGrant` over that same table (via -`createGrantStore`), not a stub — a principal with no matching row is refused, -exactly as in production. See `grantOwnership` in -`examples/reference-host/src/index.ts` and the "ownership-derived grants" -scenarios in its acceptance suite for the end-to-end proof: the creator -succeeds, a co-tenant with no grant does not. - -### ContentStore - -`ContentStore` is the substrate seam: - -- `put(tx, scope, blob)` persists bytes **inside the caller's transaction** and - returns the two artifact-row fields a stored file determines (`content` and - `source`). Taking the transaction rather than the handle is what makes "bytes, - artifact row, and version 1" a single atomic write — a failure anywhere leaves - no orphan bytes and no orphan artifact. -- `get(db, artifact)` resolves **out-of-band** bytes, or `null` when the store - keeps content in the row itself. It is tenant-scoped: a reference resolving to - another tenant's bytes must return `null`. - -Two implementations ship and both pass the same suite: `InlineContentStore` -(bytes in a tenant-owned `upload` row, referenced by `source.upload.id`) and -`DataUrlContentStore` (bytes inline in `content` as a base64 `data:` URL, no -side-table row, so its `get` returns `null`). A third backend — object storage, -say — is a third implementation, not a rewrite. The single download path -resolves the storage conventions in precedence order rather than branching on -which store is installed. - -### Modules - -| File | Role | -| ----------------------------- | -------------------------------------------------------------------------------------------------------- | -| `mount.ts` | HTTP surface: parsing, validation, status codes; reads `TenantEnv` principal; wires host `requireGrant`. | -| `artifacts.ts` | The core domain — create, revise, find-or-version, list, get, archive, serialize. | -| `uploads.ts` | `createFileArtifact`, the MIME policies, and the size caps. | -| `download.ts` | One download path over the three storage conventions. | -| `content-store.ts` | The two shipped `ContentStore` implementations. | -| `tools.ts` | Agent-facing tool definitions and windowed artifact reads (caller tenant only). | -| `ports.ts` | The `ContentStore` type and the shared `ResolvedPrincipal` shape. | -| `schema.ts` / `migrations.ts` | The three tables, and the DDL that creates them. | - -### Data model - -Three physical tables — `artifact`, `artifact_version`, `upload`. - -**Hard control-plane foreign keys, by design.** `tenant_id` is `NOT NULL` and -references the host's `tenant(id)` (`ON DELETE CASCADE` — a deleted tenant takes its -artifacts with it) and `principal_id` / `owner_principal_id` reference -the host's `principal(id)` (`ON DELETE SET NULL` — a removed principal detaches its -artifacts rather than destroying them). This package is coupled to Interchange: -it mounts on Interchange-shaped hosts only, and the host's own migrations must -have run before `runArtifactMigrations`. The internal key — -`artifact_version.artifact_id` — cascades with its artifact. - -**Cheap row-local CHECKs.** `artifact.version` and `artifact_version.version` -must be ≥ 1; `upload.size` must be ≥ 0. These are -single-column constraints — free at write time. - -**Principal↔tenant alignment is host-owned.** The package FKs each column into -the control plane independently; it does **not** enforce that `principal_id` (or -`owner_principal_id`) belongs to the same tenant as `tenant_id`. A multi-table -trigger or composite FK into `public.principal` would couple every write to a -control-plane lookup and is deliberately out of scope. The host's middleware and -context are the authority: routes stamp the `(tenantId, principalId)` pair from -the Interchange `principal` already on `TenantEnv`, so a correctly mounted host -never plants a cross-tenant principal. Operators cleaning legacy rows before the -`tenant_id NOT NULL` migration must assign a valid tenant or delete orphans — -the migration fails with an explicit message if null `tenant_id` rows remain. - -**`kind` is free-form text, not a pg enum,** validated at the application edge. -New kinds cost no migration. What is _not_ free-form is the import allowlist: -`POST /api/artifacts` may only mint `link` or `document`, so an untrusted caller -cannot stamp a file-shaped, downloadable kind onto a row whose content is a URL -or a pasted body. - -**History is append-only.** Every create and every revision writes an -`artifact_version` row — including version 1, written eagerly with the artifact — -so a version-pinned read always resolves. The version bump has a double guard: -`SELECT ... FOR UPDATE` serializes writers, and the `(artifact_id, version)` -unique constraint makes a racing writer that somehow computed the same next -version fail loudly rather than corrupt history. - -**Archival is a soft hide.** `archived_at` null means visible; a timestamp means -hidden from discovery. Deep links to archived artifacts still load. - -**Find-or-version is a package primitive, not a constraint.** The only -uniqueness the schema enforces is `(artifact_id, version)` — there is no -constraint on `(tenant_id, title, kind)`, so "find by title, create if -absent, add a version if present" is not naturally atomic: a plain -read-then-write of that pattern races, and two concurrent callers can both -observe NOT FOUND and both create, leaving two artifacts with the same -title. - -A uniqueness constraint on `(tenant_id, title, kind)` was considered and -rejected — not just for now, but structurally. `createArtifact` is a -public, unconditional insert with no title lookup of its own, called -directly by the import route, the upload path, and `artifact_link_file`. -Two independent creates sharing a title is normal, intended behavior on -every one of those paths — a coworker uploading `report.pdf` twice, or two -agents each linking a file named `notes.md`, are not bugs. A hard -`UNIQUE(tenant_id, title, kind)` constraint would reject those ordinary -inserts outright, not just gate on a one-time backfill of legacy -duplicates. Uniqueness on that triple is a property of the _find-or-version -pattern specifically_, not an invariant of the table, so it does not belong -in the schema — it belongs exactly where it now lives, inside the one code -path that promises it. - -Separately, this package also has no way to confirm existing tenants are -already free of duplicate `(title, kind)` rows, which would make even a -scoped constraint risky to backfill. That is not the main reason for -rejecting the constraint, and it is not by itself decisive. - -Instead, `findOrVersionArtifact(db, args)` (in `artifacts.ts`) closes the -race with a transaction-scoped advisory lock keyed by -`hashtext(tenantId, kind, title)`, in its own lock-space namespace (the -two-`int4`-argument form of `pg_advisory_xact_lock`, disjoint from the -single-`bigint` form `runArtifactMigrations` uses). Collision semantics: -whichever concurrent caller acquires the lock first creates the artifact; -every other caller for the identical `(tenantId, kind, title)` blocks, then -finds the row the winner just committed and revises it. Two overlapping -callers always converge on ONE artifact with two versions, never two rows — -callers for a different tenant, kind, or title never contend with each -other. This guarantee holds only for callers that go through -`findOrVersionArtifact`; a caller that instead calls `createArtifact` -directly is unconstrained by design, as above, and a caller that hand-rolls -its own find-then-create against a _different_ lock is not serialized -against this one — the primitive closes the race for its own call path, not -for every possible way to write an artifact. - -**`upload` is never a standalone resource.** There is no `POST /uploads`; every -upload eagerly mints its artifact, and the row is reachable only through -`source.upload.id`. - -The list index is `(tenant_id, updated_at, id)`. The `id` is the list's -tie-break and must be _in_ the index, or the keyset cursor's row-value -comparison falls out of the index condition into a filter and drags a sort -behind it. - -### Migration runner - -`runArtifactMigrations(config, { schema })` takes the same arguments as -Interchange's `runMigrations`, and a host calls it right after that, with the -same values. `schema` is where the host's `tenant` and `principal` tables live; -the runner rewrites the `"public".` foreign-key references in the SQL files to -it. It is idempotent and safe to call on every boot of every replica. - -- The whole run is one transaction whose first statement takes a - **transaction-scoped** advisory lock, so the lock releases on commit or - rollback and there is no unlock call to lose on an error path. - `CREATE TABLE IF NOT EXISTS` is not itself race-safe, so the lock — not the - `IF NOT EXISTS` — is what makes concurrent cold starts safe. -- The runner opens its own single-connection client and discards NOTICEs, so a - re-run, where Postgres answers every `IF NOT EXISTS` with a NOTICE, prints - nothing. -- Event timestamps (`created_at`, `updated_at`, `archived_at`) are - **`timestamptz`**. List keyset cursors project through `AT TIME ZONE 'UTC'` - and compare with `::timestamptz`, so paging and date filters stay on the - absolute instant under any session `TimeZone`. -- Releases up to 0.1.0 kept a checksum ledger in `artifacts.migrations`. - `0002_drop_migration_ledger.sql` removes it; a database migrated by 0.1.0 - already has the shape `0001_artifacts.sql` creates, so its statements no-op. - -**The package owns its own Postgres schema.** Every table and index lives in -`artifacts`, created by the runner and qualified in every DDL statement and -every query — nothing resolves through `search_path`, so the package shares a -database with the host's control plane without ever being able to collide with -(or silently adopt) a host table of the same name. The coupling to the host is -explicit instead: `tenant_id` and the principal columns are hard FKs into the -host schema's `tenant` / `principal` (see the data model). - -### Boundaries - -Owned by this package: the three tables and their migrations; the HTTP surface, -its validation and its status codes; the version and archive semantics; the -upload **gate** (`createFileArtifact` takes `policy` as a required argument and -refuses anything outside it before the `ContentStore` is touched); and the -download path with its `nosniff`/`attachment` behaviour. - -Supplied by the host: the `Hono` app and the database handle; the -authenticated `tenant`/`principal` on the request context; the host's -`RequireGrant`; display-only provenance decoration; and a `ContentStore`. - -### Known limits - -- **No file parsing, ever.** No PDF parser, no spreadsheet parser, no text - extractor, and none is planned. An extractor is a heavyweight, fast-moving - native dependency, and what the extracted text is _for_ is the host's product. - The contract the package offers a parsing host instead is **parse before you - store**: `createFileArtifact` is the only way a file becomes an artifact, so a - host that parses first and fails leaves nothing orphaned. -- **Two of the three MIME allowlists are host-owned surfaces.** This package - ships all three constants but only owns the gallery import route; spreadsheet - ingest and attachment divert are the host's routes calling this package's gate. -- **Upload caps are fixed constants,** not configuration: 10 MB per file, 50 - files and 100 MB per request. -- **`InlineContentStore` keeps bytes in Postgres.** That is a deliberate - zero-dependency default, not a recommendation at scale; a large corpus wants a - `ContentStore` over object storage. -- **List paging caps at 100** rows (default 20). -- **One 404 covers three causes** for a resolved caller — never minted, - malformed, or another tenant's. Distinguishing them would be - an existence oracle. Expect no more detail than that from the API. +Migrations are SQL files under `migrations/`, applied in filename order on every boot, so every statement must be idempotent (`IF NOT EXISTS`, `IF EXISTS`). There is no ledger: a schema change is a new file whose statements are safe to re-run. A data backfill must be cheap once it has run. `schema.ts` and `migrations/` change together, in the same commit. ## Commit messages @@ -404,3 +23,16 @@ Commit subjects and PR titles follow [Conventional Commits](https://www.conventi Add `!` only for public API breaks: removed or renamed exports, changed signatures, newly required params. Peer and dependency range changes are `build(deps):` with no `!`. Keep subjects imperative, lowercase after the colon, 72 characters or less, and free of ticket IDs. Every PR links its issue with a `Closes ` line in the PR body. + +## Releasing + +Releases are manual. On a clean, up-to-date `main`: + +```sh +npm version -m "chore(release): %s" +git push --follow-tags +gh release create "v$(node -p 'require("./package.json").version')" --generate-notes +npm publish +``` + +Bump minor only for breaking API changes; everything else is a patch. `prepack` builds `dist/` from the tagged commit. diff --git a/README.md b/README.md index c389b67..29affef 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,5 @@ # @corbits/artifacts -[![npm](https://img.shields.io/npm/v/@corbits/artifacts.svg)](https://www.npmjs.com/package/@corbits/artifacts) [![License: LGPL-2.1](https://img.shields.io/badge/license-LGPL--2.1-green.svg)](https://github.com/corbitsdev/corbits-artifacts/blob/main/LICENSE) - Versioned documents and files for Interchange agents and their users: a Corbits hub module that mounts grant-gated Hono routes on `@intx/hub-api`, keeps versions in Postgres and bytes in a pluggable `ContentStore`, and ships agent tools for the sidecar. ## Why @corbits/artifacts? @@ -178,8 +176,6 @@ export function buildAssistant(sources: readonly InferencePreference[]) { - The drizzle tables, the `web_site` helpers, `SKILL_DRAFT_KIND`, `windowContent` and the mail-attachment routes and helpers are removed. The `mail_attachment_ref` table is dropped. - Node 24 or newer is required. -See the [changelog](https://github.com/corbitsdev/corbits-artifacts/blob/main/CHANGELOG.md) for the full list. - ## License [LGPL-2.1-only](https://github.com/corbitsdev/corbits-artifacts/blob/main/LICENSE)