The Docs app, as a repo of its own: the files of the mind's repos, written together
Jonas Templestein, 2026-11-27 14:40 UTC · 8463f4182da0b0b64488af0d59a38057ac434cf2 · the first commit
21 files changed
- A .gitignore
- A LICENSE
- A README.md
- A app.ts
- A index.html
- A notes.ts
- A package.json
- A pnpm-lock.yaml
- A processors/anchor.ts
- A processors/classes.ts
- A processors/comments.ts
- A processors/doc.ts
- A processors/frames.ts
- A processors/merge.ts
- A processors/root.ts
- A public/app.css
- A public/app.js
- A public/manifest.webmanifest
- A tests/merge.test.mjs
- A tests/notes.test.mjs
- A tsconfig.json
A .gitignore
@@ -0,0 +1,1 @@ +node_modules/
A LICENSE
@@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, 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 +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If 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 convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero 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 +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "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 PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM 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 PROGRAM (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 PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state 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 program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program 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 Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +<https://www.gnu.org/licenses/>.
A README.md
@@ -0,0 +1,21 @@ +# docs + +The Docs app of a mind, on `docs.<domain>` for members: the files of the mind's repos, written +together in a browser. The bar's switcher at the top chooses the repo. Several people type in one +file at once, comment on its text, and what they type is saved as commits to that repo. + +- `app.ts` serves the page. `config/worker.ts` mounts it: `docsApp({ icon })`. +- `public/app.js` is the page. Everything it draws is a component of `@iterate-com/ui`, loaded + through the import map in `index.html`. +- `processors/` holds the two Durable Object classes that keep an open doc + (`processors/classes.ts` says how). The page starts them from THIS repo's files when a doc first + opens, with the three packages that `package.json` lists (`yjs`, `diff`, `node-diff3`). The + mind's worker never loads them, so a package that cannot be fetched breaks Docs alone. + `main` in `package.json` names their module: the loader asks every source for an entry. +- The Tasks app's task sheet edits a task's file with the same editor and the same processors + (`processorsAnswer` in `app.ts`), so a file that is open in both is one doc. +- `notes.ts`: `docs.<domain>/notes/<name>.html` answers the mind's file of that path inline, + fenced so that it cannot act as the member. + +Check it with `pnpm install`, `pnpm typecheck` and `pnpm test`, with `stdlib` and `kernel` in the +folders beside this one.
A app.ts
@@ -0,0 +1,87 @@ +// app.ts — THE DOCS APP, as config/worker.ts mounts it on docs.<domain>: the files of the mind's +// repos, written together in a browser. public/app.js says what the page does. This file serves +// the page and answers where the editor's processors are (processors/classes.ts) and which version +// of them this commit holds. One more path, /notes/<name>.html, answers a stored HTML note inline +// (notes.ts). +import { type AppDescription, serveFiles, type IterateConfigEntrypoint } from "iterate/sdk"; +import { openFile } from "@repos/stdlib/open-files.ts"; +import theme from "@repos/stdlib/theme.css"; +import index from "./index.html"; +import { isNotePath, noteResponse } from "./notes.ts"; +import processors from "./processors/"; +import files from "./public/"; + +/** What Docs says of itself to anyone: the mind's sign-in pages show its name and icon. */ +const DOCS: AppDescription = { name: "Docs", icon: "/icon.svg", for: "members" }; + +/** The repo of the mind that holds the processors' code: this one. A page starts a doc's + * processors from that repo's own files, with the packages that its package.json lists. */ +const PROCESSORS_REPO = "/repos/docs"; +/** The module that exports the processors' classes, as a path in that repo. */ +const PROCESSORS_MODULE = "processors/classes.ts"; + +// The processors' source as TEXT (a folder import hands files over, it does not load them), for +// one thing: a name for this version of it. The page starts a doc's processor from this repo's +// files under that name, so a commit that changes the processors starts them anew, and a commit +// that changes anything else leaves them running. +let version: Promise<string> | undefined; + +/** Where the processors' classes are and which version of them this commit holds: what + * /processors.json answers. Another app of the mind that opens a doc (the Tasks app, its task + * sheet) answers the same, so that both pages start a doc's processors under ONE name. */ +export async function processorsAnswer() { + return { + repo: PROCESSORS_REPO, + mainModule: PROCESSORS_MODULE, + version: await (version ||= versionOf(processors)), + }; +} + +/** `icon`: the answer for the mind's icon, which every app serves as its own (open-files.ts of + * /repos/stdlib). */ +export function docsApp({ icon }: { icon: () => Response }) { + return { + /** The app's description and icon, for anyone: worker.ts asks this before its guard. */ + open: (request: Request) => openFile(request, DOCS, icon), + /** Every request on the app's host. worker.ts guards it, so a member alone gets here. */ + async fetch(request: Request, host: Pick<IterateConfigEntrypoint, "auth" | "getItx">) { + const url = new URL(request.url); + // A stored HTML note, read in the browser: /notes/<name>.html is the mind's file of that + // path, fenced so that it cannot act as the member (notes.ts). + if (isNotePath(url.pathname)) { + using itx = host.getItx(); + return await noteResponse(request, (path) => itx.files.get(path).bytes()); + } + // Where the processors' classes are and which version of them this commit holds. + if (url.pathname === "/processors.json") return Response.json(await processorsAnswer()); + // The page's own socket (/itx) and what @iterate-com/ui's shell asks of its host + // (/.auth/session.json, /.auth/minds.json, /.auth/logout). + const page = host.auth.memberPage(request); + if (page) return page; + // the app's own files, and the theme that every app of this mind shares + return serveFiles(request, { index, files: { ...files, "theme.css": theme } }); + }, + }; +} + +/** A short name for the processors' source: a hash of every file's path and content. */ +async function versionOf(source: Record<string, string | Uint8Array>): Promise<string> { + const encoder = new TextEncoder(); + const parts = Object.keys(source) + .sort() + .flatMap((path) => { + const content = source[path]!; + return [ + encoder.encode(`\0${path}\0`), + typeof content === "string" ? encoder.encode(content) : content, + ]; + }); + const bytes = new Uint8Array(parts.reduce((sum, part) => sum + part.byteLength, 0)); + let at = 0; + for (const part of parts) { + bytes.set(part, at); + at += part.byteLength; + } + const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)); + return [...digest.slice(0, 12)].map((byte) => byte.toString(16).padStart(2, "0")).join(""); +}
A index.html
@@ -0,0 +1,53 @@ +<!doctype html> +<html lang="en"> + <head> + <meta charset="utf-8" /> + <meta name="viewport" content="width=device-width, initial-scale=1" /> + <title>Docs</title> + <!-- What the app is called and its icon: the mind's sign-in pages show both. --> + <link rel="manifest" href="/manifest.webmanifest" /> + <link rel="icon" href="/icon.svg" type="image/svg+xml" /> + <!-- iterate's components, pinned to one release of iterate's UI host (the version is a + commit of the branch `dist` of git.iterate.com/repos/ui). To upgrade, change the commit + here, in every line that names it. --> + <script type="importmap"> + { + "imports": { + "@iterate-com/ui/": "https://ui.iterate.com/@iterate-com/ui@113924454d6ae84a3194625bd4c88892430fb678/", + "react": "https://ui.iterate.com/@iterate-com/ui@113924454d6ae84a3194625bd4c88892430fb678/react", + "react/": "https://ui.iterate.com/@iterate-com/ui@113924454d6ae84a3194625bd4c88892430fb678/react/", + "react-dom": "https://ui.iterate.com/@iterate-com/ui@113924454d6ae84a3194625bd4c88892430fb678/react-dom", + "react-dom/": "https://ui.iterate.com/@iterate-com/ui@113924454d6ae84a3194625bd4c88892430fb678/react-dom/", + "lucide-react": "https://esm.iterate.com/lucide-react@1.48.0?external=react,react-dom" + } + } + </script> + <!-- THE PAGE'S SESSION, asked for here and not when the app's modules have loaded, which is + a second later: app.js takes the answer (the mind's address) from `__session`. Without + this line the app asks for it itself when it runs. It stands before the stylesheets, + because a script after a stylesheet waits for it. --> + <script> + window.__session = fetch("/.auth/session.json").then((answer) => answer.json()); + </script> + <!-- The kit's stylesheet for a page with the docs editor: everything styles.css holds, and + the editor's own classes and its live preview's look. It takes the place of styles.css: + a page links one of the two, never both (the two would disagree about which rule wins). --> + <link + rel="stylesheet" + href="https://ui.iterate.com/@iterate-com/ui@113924454d6ae84a3194625bd4c88892430fb678/docs-editor.css" + /> + <!-- The look of this mind's apps: theme.css of /repos/stdlib, one file for every app. One + line there makes them all dark. shadcn's components also ask for the class `dark`, so the script + puts it on <html> when the file says dark. --> + <link rel="stylesheet" href="/theme.css" /> + <script> + if (getComputedStyle(document.documentElement).colorScheme === "dark") + document.documentElement.classList.add("dark"); + </script> + <link rel="stylesheet" href="/app.css" /> + </head> + <body> + <div id="root"><p class="p-4 text-sm text-muted-foreground">Connecting…</p></div> + <script type="module" src="/app.js"></script> + </body> +</html>
A notes.ts
@@ -0,0 +1,50 @@ +// notes.ts — A STORED HTML NOTE, READ IN A MEMBER'S BROWSER: docs.<domain>/notes/<name>.html answers +// the mind's file /notes/<name>.html inline. A stored file's own link is a download; this is the +// link "that I can open in a browser". worker.ts guards the docs app, so a member alone gets here. +// +// THE NOTE MUST NOT ACT AS THE MEMBER. Anyone who can write a file under /notes/ (an agent, with a +// stranger's words in its context) writes this page, and it opens on a host where the member is +// signed in. So the answer carries a sandbox with no `allow-scripts` and no `allow-same-origin`: +// no script runs, and the page has no origin, no cookie and no storage. Nothing loads from +// anywhere: styles are the note's own, images are data: URLs. A link to an anchor of the same page +// still works; a link out and a form do nothing. + +/** The one shape of a note's address: lower-case letters, digits and hyphens, then `.html`. */ +const NOTE = /^\/notes\/[a-z0-9][a-z0-9-]{0,99}\.html$/; + +export const NOTE_HEADERS = { + "content-type": "text/html; charset=utf-8", + "content-security-policy": "sandbox; default-src 'none'; style-src 'unsafe-inline'; img-src data:", + "x-content-type-options": "nosniff", + "cache-control": "private, no-store", + "x-robots-tag": "noindex, nofollow", + "referrer-policy": "no-referrer", +}; + +/** Whether the docs app answers this path as a note (`fetch` asks before anything else). */ +export const isNotePath = (pathname: string) => pathname.startsWith("/notes/"); + +/** The answer for a path under /notes/: the file inline, or a 404 for a name outside the pattern, + * another method, or a file that is not there. `read` hands back the file's bytes and throws when + * there is none (`itx.files.get(path).bytes()`). */ +export async function noteResponse( + request: Request, + read: (path: string) => Promise<ArrayBuffer | Uint8Array>, +): Promise<Response> { + const { pathname } = new URL(request.url); + const none = () => + new Response("No such note.", { + status: 404, + headers: { ...NOTE_HEADERS, "content-type": "text/plain; charset=utf-8" }, + }); + if ((request.method !== "GET" && request.method !== "HEAD") || !NOTE.test(pathname)) return none(); + let bytes: ArrayBuffer | Uint8Array; + try { + bytes = await read(pathname); + } catch (error) { + // the platform's words for a path with no file; anything else is a fault and is thrown on + if (/nothing at/.test(String(error instanceof Error ? error.message : error))) return none(); + throw error; + } + return new Response(request.method === "HEAD" ? null : bytes, { headers: NOTE_HEADERS }); +}
A package.json
@@ -0,0 +1,22 @@ +{ + "name": "@repos/docs", + "private": true, + "type": "module", + "main": "processors/classes.ts", + "scripts": { + "typecheck": "tsc -p .", + "test": "node --test tests/*.test.mjs" + }, + "dependencies": { + "@repos/stdlib": "../stdlib", + "diff": "8.0.4", + "node-diff3": "3.2.1", + "yjs": "13.6.33" + }, + "devDependencies": { + "@cloudflare/workers-types": "^5.20261103.1", + "iterate": "link:../kernel/core/lib", + "typescript": "^7.0.2", + "zod": "4.6.5" + } +}
A pnpm-lock.yaml
@@ -0,0 +1,291 @@ +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +importers: + + .: + dependencies: + '@repos/stdlib': + specifier: ../stdlib + version: link:../stdlib + diff: + specifier: 8.0.4 + version: 8.0.4 + node-diff3: + specifier: 3.2.1 + version: 3.2.1 + yjs: + specifier: 13.6.33 + version: 13.6.33 + devDependencies: + '@cloudflare/workers-types': + specifier: ^5.20261103.1 + version: 5.20261125.1 + iterate: + specifier: link:../kernel/core/lib + version: link:../kernel/core/lib + typescript: + specifier: ^7.0.2 + version: 7.0.2 + zod: + specifier: 4.6.5 + version: 4.6.5 + +packages: + + '@cloudflare/workers-types@5.20261125.1': + resolution: {integrity: sha512-FBFIY/srJZZtZjxyH56AerZ0ZDbhr6Ifa5O707q0f7YzHmzqd+2zD3vG6d8cAcSDL/heJvsP7eEAsYRLFd7jpw==} + + '@typescript/typescript-aix-ppc64@7.0.2': + resolution: {integrity: sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==} + engines: {node: '>=16.20.0'} + cpu: [ppc64] + os: [aix] + + '@typescript/typescript-darwin-arm64@7.0.2': + resolution: {integrity: sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [darwin] + + '@typescript/typescript-darwin-x64@7.0.2': + resolution: {integrity: sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [darwin] + + '@typescript/typescript-freebsd-arm64@7.0.2': + resolution: {integrity: sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [freebsd] + + '@typescript/typescript-freebsd-x64@7.0.2': + resolution: {integrity: sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [freebsd] + + '@typescript/typescript-linux-arm64@7.0.2': + resolution: {integrity: sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [linux] + + '@typescript/typescript-linux-arm@7.0.2': + resolution: {integrity: sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==} + engines: {node: '>=16.20.0'} + cpu: [arm] + os: [linux] + + '@typescript/typescript-linux-loong64@7.0.2': + resolution: {integrity: sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==} + engines: {node: '>=16.20.0'} + cpu: [loong64] + os: [linux] + + '@typescript/typescript-linux-mips64el@7.0.2': + resolution: {integrity: sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==} + engines: {node: '>=16.20.0'} + cpu: [mips64el] + os: [linux] + + '@typescript/typescript-linux-ppc64@7.0.2': + resolution: {integrity: sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==} + engines: {node: '>=16.20.0'} + cpu: [ppc64] + os: [linux] + + '@typescript/typescript-linux-riscv64@7.0.2': + resolution: {integrity: sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==} + engines: {node: '>=16.20.0'} + cpu: [riscv64] + os: [linux] + + '@typescript/typescript-linux-s390x@7.0.2': + resolution: {integrity: sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==} + engines: {node: '>=16.20.0'} + cpu: [s390x] + os: [linux] + + '@typescript/typescript-linux-x64@7.0.2': + resolution: {integrity: sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [linux] + + '@typescript/typescript-netbsd-arm64@7.0.2': + resolution: {integrity: sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [netbsd] + + '@typescript/typescript-netbsd-x64@7.0.2': + resolution: {integrity: sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [netbsd] + + '@typescript/typescript-openbsd-arm64@7.0.2': + resolution: {integrity: sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [openbsd] + + '@typescript/typescript-openbsd-x64@7.0.2': + resolution: {integrity: sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [openbsd] + + '@typescript/typescript-sunos-x64@7.0.2': + resolution: {integrity: sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [sunos] + + '@typescript/typescript-win32-arm64@7.0.2': + resolution: {integrity: sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [win32] + + '@typescript/typescript-win32-x64@7.0.2': + resolution: {integrity: sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [win32] + + diff@8.0.4: + resolution: {integrity: sha512-DPi0FmjiSU5EvQV0++GFDOJ9ASQUVFh5kD+OzOnYdi7n3Wpm9hWWGfB/O2blfHcMVTL5WkQXSnRiK9makhrcnw==} + engines: {node: '>=0.3.1'} + + isomorphic.js@0.2.5: + resolution: {integrity: sha512-PIeMbHqMt4DnUP3MA/Flc0HElYjMXArsw1qwJZcm9sqR8mq3l8NYizFMty0pWwE/tzIGH3EKK5+jes5mAr85yw==} + + lib0@0.2.120: + resolution: {integrity: sha512-/a2eRImR8sZbmMVKe2we1/KukDQkuPyPf8yol6epvCu2PH6hurjcRI3mdGFFAi0uGoRJGyns99JquZgxwW1tQg==} + engines: {node: '>=16'} + hasBin: true + + node-diff3@3.2.1: + resolution: {integrity: sha512-eKZcJ8RtMQ3cIaA15EgmtwG927fYnRlhtdA4Q9HAcCpAZPQhhU2XptnTH9GeAkMiX2bAXxlJSAFa9shFbztPgw==} + engines: {bun: '>=1.3.10'} + + typescript@7.0.2: + resolution: {integrity: sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==} + engines: {node: '>=16.20.0'} + hasBin: true + + yjs@13.6.33: + resolution: {integrity: sha512-q/UYvr1gOk4XII+Cu1CW2dINjYqJJFifTzogEaIARznrvX7uOlHsdTEXcnOBMuIsrCGEEKdNxi74kyMLZlKVfw==} + engines: {node: '>=16.0.0', npm: '>=8.0.0'} + + zod@4.6.5: + resolution: {integrity: sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q==} + +snapshots: + + '@cloudflare/workers-types@5.20261125.1': {} + + '@typescript/typescript-aix-ppc64@7.0.2': + optional: true + + '@typescript/typescript-darwin-arm64@7.0.2': + optional: true + + '@typescript/typescript-darwin-x64@7.0.2': + optional: true + + '@typescript/typescript-freebsd-arm64@7.0.2': + optional: true + + '@typescript/typescript-freebsd-x64@7.0.2': + optional: true + + '@typescript/typescript-linux-arm64@7.0.2': + optional: true + + '@typescript/typescript-linux-arm@7.0.2': + optional: true + + '@typescript/typescript-linux-loong64@7.0.2': + optional: true + + '@typescript/typescript-linux-mips64el@7.0.2': + optional: true + + '@typescript/typescript-linux-ppc64@7.0.2': + optional: true + + '@typescript/typescript-linux-riscv64@7.0.2': + optional: true + + '@typescript/typescript-linux-s390x@7.0.2': + optional: true + + '@typescript/typescript-linux-x64@7.0.2': + optional: true + + '@typescript/typescript-netbsd-arm64@7.0.2': + optional: true + + '@typescript/typescript-netbsd-x64@7.0.2': + optional: true + + '@typescript/typescript-openbsd-arm64@7.0.2': + optional: true + + '@typescript/typescript-openbsd-x64@7.0.2': + optional: true + + '@typescript/typescript-sunos-x64@7.0.2': + optional: true + + '@typescript/typescript-win32-arm64@7.0.2': + optional: true + + '@typescript/typescript-win32-x64@7.0.2': + optional: true + + diff@8.0.4: {} + + isomorphic.js@0.2.5: {} + + lib0@0.2.120: + dependencies: + isomorphic.js: 0.2.5 + + node-diff3@3.2.1: {} + + typescript@7.0.2: + optionalDependencies: + '@typescript/typescript-aix-ppc64': 7.0.2 + '@typescript/typescript-darwin-arm64': 7.0.2 + '@typescript/typescript-darwin-x64': 7.0.2 + '@typescript/typescript-freebsd-arm64': 7.0.2 + '@typescript/typescript-freebsd-x64': 7.0.2 + '@typescript/typescript-linux-arm': 7.0.2 + '@typescript/typescript-linux-arm64': 7.0.2 + '@typescript/typescript-linux-loong64': 7.0.2 + '@typescript/typescript-linux-mips64el': 7.0.2 + '@typescript/typescript-linux-ppc64': 7.0.2 + '@typescript/typescript-linux-riscv64': 7.0.2 + '@typescript/typescript-linux-s390x': 7.0.2 + '@typescript/typescript-linux-x64': 7.0.2 + '@typescript/typescript-netbsd-arm64': 7.0.2 + '@typescript/typescript-netbsd-x64': 7.0.2 + '@typescript/typescript-openbsd-arm64': 7.0.2 + '@typescript/typescript-openbsd-x64': 7.0.2 + '@typescript/typescript-sunos-x64': 7.0.2 + '@typescript/typescript-win32-arm64': 7.0.2 + '@typescript/typescript-win32-x64': 7.0.2 + + yjs@13.6.33: + dependencies: + lib0: 0.2.120 + + zod@4.6.5: {}
A processors/anchor.ts
@@ -0,0 +1,75 @@ +// anchor.ts — WHERE A COMMENT POINTS: a quote of the text it's about, never a position. A +// position goes stale with every edit before it; a quote is found again in whatever the text is now +// (a reload, an agent's rewrite, a commit made in git), the way a reader would find it. The page +// finds each thread's quote to highlight it; the doc's processor finds them again after each save and +// refreshes a quote that only matched loosely (doc.ts, `docs/comment-reanchored`), so the +// stored quote never drifts far from the text. +// +// FINDING a quote, in order: +// 1. the exact text: where it's once, there; where it's several times, the one whose surroundings +// match the quote's prefix and suffix best; +// 2. its surroundings: the quote's prefix and then its suffix, close together, bracket what's there +// now (the typo "teh" fixed to "the" between the same words) — a loose match; +// 3. neither: the quote is detached (null). The text it was about is gone or reworded around it. + +/** What a comment points at: the text, and up to `CONTEXT` characters either side of it. */ +export type Quote = { exact: string; prefix: string; suffix: string }; + +/** Where a quote is in a text now; `exact` false for a match by its surroundings alone. */ +export type Found = { from: number; to: number; exact: boolean }; + +/** How much of each side a quote keeps: enough to tell repeats apart and to bracket an edit. */ +const context = 32; + +/** The quote of `text` between `from` and `to`. */ +export function quoteAt(text: string, from: number, to: number): Quote { + return { + exact: text.slice(from, to), + prefix: text.slice(Math.max(0, from - context), from), + suffix: text.slice(to, to + context), + }; +} + +/** Where `quote` is in `text` now, or null (detached). */ +export function findQuote(text: string, quote: Quote): Found | null { + const exact = occurrences(text, quote.exact); + if (exact.length > 0) { + const best = exact.reduce((a, b) => (fit(text, quote, b) > fit(text, quote, a) ? b : a)); + return { from: best, to: best + quote.exact.length, exact: true }; + } + return bracketed(text, quote); +} + +/** How well the text around `at` matches the quote's surroundings: characters in common, reading + * outward from the quote on each side. */ +function fit(text: string, quote: Quote, at: number) { + let score = 0; + for (let i = 1; i <= quote.prefix.length && text[at - i] === quote.prefix.at(-i); i++) score++; + const after = at + quote.exact.length; + for (let i = 0; i < quote.suffix.length && text[after + i] === quote.suffix[i]; i++) score++; + return score; +} + +/** The text between the quote's prefix and suffix, where both are still there, in order and close + * (no further apart than the quote was long, plus room for the edit), and something is between. */ +function bracketed(text: string, quote: Quote): Found | null { + // at the start or end of the text, a side has nothing to find: its edge stands in + const prefixes = quote.prefix + ? occurrences(text, quote.prefix).map((at) => at + quote.prefix.length) + : [0]; + const room = quote.exact.length * 2 + 16; + let best: Found | null = null; + for (const from of prefixes) { + const to = quote.suffix ? text.indexOf(quote.suffix, from) : text.length; + if (to < 0 || to - from > room || to === from) continue; + // the nearest bracket wins: the least text between prefix and suffix + if (!best || to - from < best.to - best.from) best = { from, to, exact: false }; + } + return best; +} + +function occurrences(text: string, part: string) { + const found: number[] = []; + for (let at = text.indexOf(part); at >= 0; at = text.indexOf(part, at + 1)) found.push(at); + return found; +}
A processors/classes.ts
@@ -0,0 +1,51 @@ +// processors/classes.ts — THE DOCS APP'S PROCESSORS: two Durable Object classes that let people co-edit a +// markdown file of one of this mind's repos in the browser, with comments, and save it as commits. +// +// - `DocDurableObject` is ONE OPEN DOC: the facet `doc` on the context `/docs/<repo name>/<path>` +// (/repos/config's notes/plan.md is /docs/config/notes/plan.md). It holds the text as a Yjs +// document in its own storage, takes the edits the open tabs send, and commits the text a minute +// after the first unsaved edit, or at once when the last tab leaves (doc.ts). A tab +// joins with `sync`. It also keeps the doc's comments (comments.ts). +// - `DocsDurableObject` is the processor `docs` on `/`: it remembers which docs were opened and +// tells each one when a commit to its repo changed it, so an agent's commit reaches the open +// tabs (root.ts). +// +// What the page and the processors say to each other is frames.ts. +// +// WHY THE MIND'S WORKER NEVER LOADS THIS FOLDER. The classes need three packages (`yjs`, `diff` +// and `node-diff3`, in this repo's package.json). What config/worker.ts imports is resolved with +// its packages each time the mind is published, so a package that cannot be fetched there would +// stop the whole mind from publishing. So worker.ts never imports this code (../app.ts takes the +// folder as text, to tell one version of it from the next). The page starts both processors as a +// doc opens and names where their code is: this file, in this repo's own files, loaded then with +// this repo's package.json. So the packages are fetched when a doc first opens, and a package +// that fails breaks Docs alone. +import { StreamProcessorDurableObject } from "iterate/sdk"; +import type { ProcessorState } from "iterate/stream/processor"; +import { DocContract, DocProcessor } from "./doc.ts"; +import { DocsContract, DocsProcessor } from "./root.ts"; + +export class DocDurableObject extends StreamProcessorDurableObject< + ProcessorState<typeof DocContract> +> { + static override publicMethods = [...super.publicMethods, "sync"]; + + processor = new DocProcessor({ + sql: this.ctx.storage.sql, + getItx: () => this.getItx(), + publishLiveState: () => this.publishLiveState(), + // a minute after the first unsaved edit, however much typing follows (or sooner: the last tab + // leaving); each commit to /repos/config publishes the mind again + autosave: { idleMs: 60_000, maxMs: 60_000 }, + }); + + sync(stateVector: string, client: number) { + return this.processor.sync(stateVector, client); + } +} + +export class DocsDurableObject extends StreamProcessorDurableObject< + ProcessorState<typeof DocsContract> +> { + processor = new DocsProcessor(() => this.getItx()); +}
A processors/comments.ts
@@ -0,0 +1,212 @@ +// comments.ts — COMMENTS ON A DOC: durable events on the doc's own context (frames.ts), never +// text in the file. A thread points at the text it's about by quoting it (anchor.ts), or at the +// whole doc; its comments are the events that added and replied to it. Any member of the mind may +// resolve or reopen a thread; only a comment's author may edit or delete it. The author is the +// event's `source`, which the platform stamps: a person's email, or the context an agent wrote from. +// A comment an agent wrote for a person (Claude Code over MCP, as that person) says so in `via`, the +// agent's own word for itself; the event's `source.grant` is the connection it really came through. +// +// docs/comment-added a new thread: its id, its quote (or none, for the whole doc), its first comment +// docs/comment-replied a comment on a thread +// docs/comment-edited a comment's new body, by its author +// docs/comment-deleted a comment gone, by its author (the thread goes with its last comment) +// docs/comment-resolved a thread done; docs/comment-reopened undoes it +// docs/comment-routed the context a thread's comments go to (an agent that answers them), so +// the page can show what that context is doing; a later one replaces it +// docs/comment-reanchored the doc's processor, after a save: the thread's quote refreshed from +// the text it now matches loosely, or null when nothing matches (detached) +import { z } from "zod"; +import type { StreamEvent } from "iterate/stream/processor"; + +export const COMMENT_ADDED = "docs/comment-added"; +export const COMMENT_REPLIED = "docs/comment-replied"; +export const COMMENT_EDITED = "docs/comment-edited"; +export const COMMENT_DELETED = "docs/comment-deleted"; +export const COMMENT_RESOLVED = "docs/comment-resolved"; +export const COMMENT_REOPENED = "docs/comment-reopened"; +export const COMMENT_REANCHORED = "docs/comment-reanchored"; +export const COMMENT_ROUTED = "docs/comment-routed"; + +/** Every comment event, as a doc's processor consumes them. */ +export const commentEvents = [ + COMMENT_ADDED, + COMMENT_REPLIED, + COMMENT_EDITED, + COMMENT_DELETED, + COMMENT_RESOLVED, + COMMENT_REOPENED, + COMMENT_REANCHORED, + COMMENT_ROUTED, +]; + +export const Quote = z.object({ exact: z.string().min(1), prefix: z.string(), suffix: z.string() }); + +/** The agent that wrote a comment on its person's behalf, as it names itself ("Claude Code"). */ +const Via = z.string().trim().min(1).max(40).optional(); + +export const CommentAdded = z.object({ + thread: z.string().min(1), + quote: Quote.nullable(), + body: z.string().min(1), + via: Via, +}); +export const CommentReplied = z.object({ + thread: z.string(), + comment: z.string().min(1), + body: z.string().min(1), + via: Via, +}); +export const CommentEdited = z.object({ + thread: z.string(), + comment: z.string(), + body: z.string().min(1), +}); +export const CommentDeleted = z.object({ thread: z.string(), comment: z.string() }); +export const ThreadRef = z.object({ thread: z.string() }); +export const CommentReanchored = z.object({ thread: z.string(), quote: Quote.nullable() }); +/** `to`: a context's path (`/agents/assistant/2026-10-31-comment-4ae622dc`), or null for nowhere. */ +export const CommentRouted = z.object({ thread: z.string(), to: z.string().min(1).nullable() }); + +export const Comment = z.object({ + /** the thread's id for its first comment */ + id: z.string(), + author: z.string(), + /** the agent that wrote it for its author, when one did; absent in a build before it, whose + * live state a newer page still reads */ + via: z.string().nullable().default(null), + body: z.string(), + at: z.string(), + edited: z.boolean(), +}); +export type Comment = z.infer<typeof Comment>; + +export const CommentThread = z.object({ + id: z.string(), + /** what it's about; null for the whole doc */ + quote: Quote.nullable(), + /** its quote matches nothing in the text as last saved */ + detached: z.boolean(), + resolved: z.object({ by: z.string(), at: z.string() }).nullable(), + /** the context its comments go to (`docs/comment-routed`); absent in a build before it */ + routedTo: z.string().nullable().default(null), + comments: z.array(Comment), +}); +export type CommentThread = z.infer<typeof CommentThread>; + +/** Who wrote an event: the person, or the person a script ran for (an agent over MCP, as them), + * else the context it was written from (an agent's own). */ +export function authorOf(event: Pick<StreamEvent, "source">) { + const person = event.source.principal || event.source.onBehalfOf?.principal; + return person?.email || person?.actor || event.source.origin; +} + +/** The threads after `event`; the same array when it changes nothing (not a comment event, a + * payload that doesn't parse, an edit by someone else). */ +export function reduceComments(threads: CommentThread[], event: StreamEvent): CommentThread[] { + const author = authorOf(event); + const update = (id: string, change: (thread: CommentThread) => CommentThread | null) => { + const index = threads.findIndex((thread) => thread.id === id); + if (index < 0) return threads; + const next = change(threads[index]!); + if (next === threads[index]) return threads; + return next + ? threads.map((thread, i) => (i === index ? next : thread)) + : threads.filter((_, i) => i !== index); + }; + switch (event.type) { + case COMMENT_ADDED: { + const added = CommentAdded.safeParse(event.payload); + if (!added.success || threads.some((thread) => thread.id === added.data.thread)) + return threads; + const { thread, quote, body, via } = added.data; + return [ + ...threads, + { + id: thread, + quote, + detached: false, + resolved: null, + routedTo: null, + comments: [ + { id: thread, author, via: via || null, body, at: event.createdAt, edited: false }, + ], + }, + ]; + } + case COMMENT_REPLIED: { + const reply = CommentReplied.safeParse(event.payload); + if (!reply.success) return threads; + const { comment, body, via } = reply.data; + return update(reply.data.thread, (thread) => + thread.comments.some((each) => each.id === comment) + ? thread + : { + ...thread, + comments: [ + ...thread.comments, + { + id: comment, + author, + via: via || null, + body, + at: event.createdAt, + edited: false, + }, + ], + }, + ); + } + case COMMENT_EDITED: { + const edit = CommentEdited.safeParse(event.payload); + if (!edit.success) return threads; + return update(edit.data.thread, (thread) => { + const target = thread.comments.find((each) => each.id === edit.data.comment); + if (!target || target.author !== author) return thread; + return { + ...thread, + comments: thread.comments.map((each) => + each === target ? { ...each, body: edit.data.body, edited: true } : each, + ), + }; + }); + } + case COMMENT_DELETED: { + const deletion = CommentDeleted.safeParse(event.payload); + if (!deletion.success) return threads; + return update(deletion.data.thread, (thread) => { + const target = thread.comments.find((each) => each.id === deletion.data.comment); + if (!target || target.author !== author) return thread; + const comments = thread.comments.filter((each) => each !== target); + return comments.length > 0 ? { ...thread, comments } : null; + }); + } + case COMMENT_RESOLVED: + case COMMENT_REOPENED: { + const ref = ThreadRef.safeParse(event.payload); + if (!ref.success) return threads; + return update(ref.data.thread, (thread) => ({ + ...thread, + resolved: event.type === COMMENT_RESOLVED ? { by: author, at: event.createdAt } : null, + })); + } + case COMMENT_REANCHORED: { + const anchor = CommentReanchored.safeParse(event.payload); + if (!anchor.success) return threads; + // detached keeps the old quote, to show what the thread was about + return update(anchor.data.thread, (thread) => + anchor.data.quote + ? { ...thread, quote: anchor.data.quote, detached: false } + : { ...thread, detached: true }, + ); + } + case COMMENT_ROUTED: { + const routed = CommentRouted.safeParse(event.payload); + if (!routed.success) return threads; + return update(routed.data.thread, (thread) => + thread.routedTo === routed.data.to ? thread : { ...thread, routedTo: routed.data.to }, + ); + } + default: + return threads; + } +}
A processors/doc.ts
@@ -0,0 +1,416 @@ +// doc.ts — ONE OPEN DOC (frames.ts): its text as a Y.Doc, the edits its browsers send, and its +// autosave. Git stays the source of truth; the Y.Doc is the session's buffer, and an edit is safe +// once it's here (the table below), so commits can be few. +// +// THE Y.DOC lives in this facet's own SQLite: every update appended to `doc_updates` as it lands, +// folded into one after each save; `doc_meta` holds the commit the text was last saved as or read +// at (`base`) and who has edited since. A facet reset or an eviction loses nothing: the next call +// replays the table. The first open of a doc (no rows) reads the file at the repo's tip. The text +// is too big and changes too often for the engine's reduce checkpoint, which is written only after +// durable events anyway; the comments are in the reduced state (`DocContract`). +// +// AUTOSAVE: a minute after the first unsaved edit (classes.ts), or at once when the last open +// tab leaves (`docs/left`; a tab is here from its `sync` or its first edit), a commit to the doc's +// repo whose parent is `base`, authored by the first person who edited since the last save, the +// others as `Co-authored-by:`. A commit to /repos/config publishes the mind, so a burst of typing +// is one commit, not one per pause. The repo refuses a parent that isn't its tip; then the tip's +// copy is merged in like git (merge.ts), the merge goes to every open browser as an edit frame, and +// the save is tried again. The same catch-up runs when a browser joins (`sync`) and when the root's +// docs processor says a commit changed the doc (`docs/commit-noticed`, root.ts), so a commit an +// agent made reaches the open editors without a reload. +// +// COMMENTS (comments.ts) are reduced into the processor's state, and so into its live state. After +// each save and each catch-up the processor finds every thread's quote in the new text (anchor.ts) +// and appends `docs/comment-reanchored` for one that now matches only loosely (the quote refreshed +// to the text it matches), matches nothing (detached), or matches again after being detached. +import * as Y from "yjs"; +import type { IterateContextApi } from "iterate/api"; +import { z } from "zod"; +import { + defineProcessorContract, + StreamProcessor, + type ProcessEventArgs, + type ProcessorState, + type ReduceArgs, +} from "iterate/stream/processor"; +import { findQuote, quoteAt } from "./anchor.ts"; +import { COMMENT_REANCHORED, CommentThread, commentEvents, reduceComments } from "./comments.ts"; +import { + COMMIT_NOTICED, + DOC_LEFT, + DocLeft, + docOf, + EDIT_FRAME, + EditFrame, + fromBase64, + toBase64, + type DocLiveState, + type DocRef, +} from "./frames.ts"; +import { mergeText, textEdits } from "./merge.ts"; + +export const DocContract = defineProcessorContract({ + slug: "doc", + // the reduce's version (comments.ts): at another one, the engine reduces the log again from 0 + version: "3", + description: + "Holds an open doc's text as Yjs, applies its editors' edits, autosaves it to its repo, and reduces its comments.", + stateSchema: z.object({ threads: z.array(CommentThread).default([]) }), + consumes: [EDIT_FRAME, COMMIT_NOTICED, DOC_LEFT, ...commentEvents], + emits: [EDIT_FRAME, COMMENT_REANCHORED], +}); + +type DocState = ProcessorState<typeof DocContract>; + +type DocDeps = { + sql: SqlStorage; + /** The doc's context, `/docs/<repo name>/<path>` (its `whoami()` names the doc). The repos + * are the root's (`itx.cd("/").repos`), which loaded code reaches from anywhere in its mind. */ + getItx: () => IterateContextApi & Disposable; + /** Re-project the live state after a change outside a batch (the host's `publishLiveState`). */ + publishLiveState: () => void; + /** When to save: `idleMs` after the last edit, and at most `maxMs` after the first unsaved one. */ + autosave: { idleMs: number; maxMs: number }; +}; + +export class DocProcessor extends StreamProcessor<DocState> { + contract = DocContract; + readonly #deps: DocDeps; + #doc: Y.Doc | null = null; + /** The doc's repo and path, from the context's own path as the doc loads. */ + #ref: DocRef = { repo: "", path: "" }; + /** The tabs with the doc open, by Yjs client id; when the last one leaves, the doc saves. */ + #present = new Set<number>(); + #loading: Promise<Y.Doc> | null = null; + /** The commit the text last matched, and its copy of the doc. */ + #base = { oid: "", text: "" }; + /** Who has edited since the last save, by email, in the order they started. */ + #editors = new Set<string>(); + #savedBy: string[] = []; + #saveError: string | null = null; + /** The threads as last reduced, for re-anchoring after a save. */ + #threads: CommentThread[] = []; + #firstEditAt = 0; + #lastEditAt = 0; + #saveScheduled = false; + /** Saves and catch-ups run one at a time: each reads `base` before an await and writes it after. */ + #serial: Promise<unknown> = Promise.resolve(); + + constructor(deps: DocDeps) { + super(); + this.#deps = deps; + deps.sql.exec( + "CREATE TABLE IF NOT EXISTS doc_updates (seq INTEGER PRIMARY KEY AUTOINCREMENT, data BLOB NOT NULL)", + ); + deps.sql.exec( + "CREATE TABLE IF NOT EXISTS doc_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)", + ); + } + + override reduce({ event, state }: ReduceArgs<DocState>): DocState | undefined { + const threads = reduceComments(state.threads, event); + if (threads !== state.threads) return { ...state, threads }; + } + + override projectLiveState(state: DocState): DocLiveState { + return { + commitOid: this.#base.oid || null, + dirty: this.#dirty(), + savedBy: this.#savedBy, + saveError: this.#saveError, + threads: state.threads, + }; + } + + override processEvent({ + event, + state, + delivery, + blockProcessorWhile, + runInBackground, + }: ProcessEventArgs<DocState>): undefined { + this.#threads = state.threads; + // At the head (the eventless pass, or the last event of a batch that reaches it), after a + // reset or a revive: the doc loaded, so the live state has its commit even when only comments + // arrive, and what the last incarnation hadn't saved yet is saved. + if (delivery.caughtUp) + blockProcessorWhile(async () => { + await this.#load(); + // an edit's own timer stands: this isn't an edit + if (this.#dirty() && !this.#saveScheduled) this.#scheduleSave(runInBackground); + }); + if (!event) return; + if (event.type === COMMIT_NOTICED) { + blockProcessorWhile(async () => { + await this.#load(); + await this.#exclusive(() => this.#catchUp()); + }); + return; + } + if (event.type === DOC_LEFT) { + const left = DocLeft.safeParse(event.payload); + if (!left.success) return; + this.#present.delete(left.data.client); + // the last tab gone: what's unsaved is saved now, not a minute from now + if (this.#present.size === 0) + runInBackground(async () => { + await this.#load(); + await this.#exclusive(() => this.#save()); + }); + return; + } + if (event.type !== EDIT_FRAME) return; + const frame = EditFrame.safeParse(event.payload); + // the processor's own frames come back to it: already applied + if (!frame.success || frame.data.client === "processor") return; + this.#present.add(frame.data.client); + const editor = event.source.principal?.email; + blockProcessorWhile(async () => { + const doc = await this.#load(); + Y.applyUpdate(doc, fromBase64(frame.data.update), "browser"); + if (!this.#dirty()) return; + if (editor && !this.#editors.has(editor)) { + this.#editors.add(editor); + this.#writeMeta(); + } + this.#scheduleSave(runInBackground); + }); + } + + /** A browser joining, or syncing again: `client` (its Yjs client id) is here until it sends + * `docs/left`. Answers the processor's state past `stateVector` (base64), after taking in any + * commit made since the last sync, and its own state vector, for the browser to send back what + * the processor lacks. */ + async sync(stateVector: string, client: number) { + this.#present.add(client); + const doc = await this.#load(); + await this.#exclusive(() => this.#catchUp()); + return { + update: toBase64(Y.encodeStateAsUpdate(doc, fromBase64(stateVector))), + stateVector: toBase64(Y.encodeStateVector(doc)), + commitOid: this.#base.oid, + }; + } + + #text() { + return this.#doc ? this.#doc.getText("file").toString() : this.#base.text; + } + + #dirty() { + return this.#text() !== this.#base.text; + } + + #load(): Promise<Y.Doc> { + this.#loading ||= this.#loadOnce(); + return this.#loading; + } + + async #loadOnce() { + const { sql } = this.#deps; + { + using itx = this.#deps.getItx(); + this.#ref = docOf((await itx.whoami()).path); + } + const doc = new Y.Doc(); + const updates = sql + .exec<{ data: ArrayBuffer }>("SELECT data FROM doc_updates ORDER BY seq") + .toArray(); + for (const row of updates) Y.applyUpdate(doc, new Uint8Array(row.data)); + // from here on every update is kept, the first read's included + doc.on("update", (update: Uint8Array) => { + sql.exec("INSERT INTO doc_updates (data) VALUES (?)", update); + }); + const meta = Object.fromEntries( + sql + .exec<{ key: string; value: string }>("SELECT key, value FROM doc_meta") + .toArray() + .map((row) => [row.key, row.value]), + ); + if (updates.length > 0) { + this.#base = { oid: meta.baseOid || "", text: meta.baseText || "" }; + this.#editors = new Set(JSON.parse(meta.editors || "[]")); + this.#savedBy = JSON.parse(meta.savedBy || "[]"); + } else { + using itx = this.#deps.getItx(); + const repo = itx.cd("/").repos.get(this.#ref.repo); + const tip = await repo.tip(); + const text = tip ? await repo.readFile(this.#ref.path, { commitOid: tip }) : null; + this.#base = { oid: tip || "", text: text || "" }; + doc.getText("file").insert(0, this.#base.text); + this.#writeMeta(); + } + this.#doc = doc; + return doc; + } + + #writeMeta() { + const entries = { + baseOid: this.#base.oid, + baseText: this.#base.text, + editors: JSON.stringify([...this.#editors]), + savedBy: JSON.stringify(this.#savedBy), + }; + for (const [key, value] of Object.entries(entries)) + this.#deps.sql.exec( + "INSERT INTO doc_meta (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value", + key, + value, + ); + } + + #exclusive<T>(work: () => Promise<T>): Promise<T> { + const run = this.#serial.then(work); + this.#serial = run.catch(() => {}); + return run; + } + + #scheduleSave(runInBackground: (work: () => Promise<unknown>) => void) { + const now = Date.now(); + this.#lastEditAt = now; + this.#firstEditAt ||= now; + if (this.#saveScheduled) return; + this.#saveScheduled = true; + this.#deps.publishLiveState(); + runInBackground(async () => { + const { idleMs, maxMs } = this.#deps.autosave; + try { + for ( + let wait = idleMs; + wait > 0; + wait = Math.min(this.#lastEditAt + idleMs, this.#firstEditAt + maxMs) - Date.now() + ) + await new Promise((resolve) => setTimeout(resolve, wait)); + } finally { + this.#saveScheduled = false; + this.#firstEditAt = 0; + } + await this.#exclusive(() => this.#save()); + }); + } + + /** Commit the text with `base` as its parent; refused because someone else committed, take + * their commit in and commit the merge on top of it. */ + async #save(): Promise<void> { + const text = this.#text(); + if (text === this.#base.text) return; + const editors = [...this.#editors]; + const { repo, path } = this.#ref; + try { + using itx = this.#deps.getItx(); + const result = await itx + .cd("/") + .repos.get(repo) + .commitFiles({ + // git's trailers, after a blank line: everyone but the author + message: [ + `docs: edit ${path}`, + ...(editors.length > 1 ? [""] : []), + ...editors.slice(1).map((editor) => `Co-authored-by: ${editor} <${editor}>`), + ].join("\n"), + changes: [{ path, content: text }], + parent: this.#base.oid || null, + author: editors[0] ? { name: editors[0], email: editors[0] } : undefined, + }); + this.#base = { oid: result.commitOid || this.#base.oid, text }; + this.#savedBy = editors; + this.#saveError = null; + for (const editor of editors) this.#editors.delete(editor); + this.#compact(); + } catch (error) { + // anything but main having moved is a real failure; the next edit or at-head pass retries + if (!(await this.#catchUp())) { + this.#saveError = error instanceof Error ? error.message : String(error); + throw error; + } + return this.#save(); + } finally { + this.#writeMeta(); + this.#deps.publishLiveState(); + } + await this.#reanchor(text); + } + + /** Take in the repo's tip when it moved past `base`: ours (the live text) and theirs (the tip's + * copy) merged over base, applied as small edits and sent to the open browsers. False when the + * tip is `base`. */ + async #catchUp(): Promise<boolean> { + const { path } = this.#ref; + let tip: string | null; + let theirs: string | null = null; + { + using itx = this.#deps.getItx(); + const repo = itx.cd("/").repos.get(this.#ref.repo); + tip = await repo.tip(); + if (tip && tip !== this.#base.oid) theirs = await repo.readFile(path, { commitOid: tip }); + } + if (!tip || tip === this.#base.oid) return false; + const ours = this.#text(); + const unsaved = ours !== this.#base.text; + // the file deleted at the tip: the live text stays in the open tabs; a delete of a doc with no + // unsaved edits stands (until someone edits it again), and unsaved edits are dirty against a + // base of nothing, so the next save writes the doc back with them + // oxlint-disable-next-line iterate/simple-truthiness-check -- only a deleted file is null; an emptied one is "" and merges like any edit + const deleted = theirs === null; + const theirsText = deleted ? ours : theirs || ""; + const merged = unsaved ? mergeText(ours, this.#base.text, theirsText).text : theirsText; + const update = this.#replaceText(ours, merged); + this.#base = { oid: tip, text: deleted && unsaved ? "" : theirsText }; + this.#writeMeta(); + if (update) { + using itx = this.#deps.getItx(); + await itx.append({ + type: EDIT_FRAME, + ephemeral: true, + payload: { update: toBase64(update), client: "processor" }, + }); + } + this.#deps.publishLiveState(); + await this.#reanchor(merged); + return true; + } + + /** Each thread's quote found in `text`: refreshed where only its surroundings matched, detached + * where nothing did, attached again where a detached one matches. An exact match changes nothing. */ + async #reanchor(text: string) { + const events = this.#threads.flatMap((thread) => { + if (!thread.quote) return []; + const found = findQuote(text, thread.quote); + if (found?.exact && !thread.detached) return []; + if (!found && thread.detached) return []; + // a repeat (two saves before the first's event is reduced) sets the same quote again + const quote = found && quoteAt(text, found.from, found.to); + return [{ type: COMMENT_REANCHORED, payload: { thread: thread.id, quote } }]; + }); + if (events.length === 0) return; + using itx = this.#deps.getItx(); + await itx.append(...events); + } + + /** Turn the live text from `from` into `to` in one transaction; the update it made, if any. */ + #replaceText(from: string, to: string): Uint8Array | null { + const doc = this.#doc!; + const text = doc.getText("file"); + const edits = textEdits(from, to); + if (edits.length === 0) return null; + let made: Uint8Array | null = null; + const keep = (update: Uint8Array) => { + made = update; + }; + doc.on("update", keep); + doc.transact(() => { + for (const edit of edits) { + if ("insert" in edit) text.insert(edit.at, edit.insert); + else text.delete(edit.at, edit.delete); + } + }, "processor"); + doc.off("update", keep); + return made; + } + + /** After a save: the updates table as one update, the whole doc. */ + #compact() { + const state = Y.encodeStateAsUpdate(this.#doc!); + this.#deps.sql.exec("DELETE FROM doc_updates"); + this.#deps.sql.exec("INSERT INTO doc_updates (data) VALUES (?)", state); + } +}
A processors/frames.ts
@@ -0,0 +1,86 @@ +// frames.ts — HOW A DOC IS CO-EDITED: what the Docs app's browsers and the doc's processor +// (doc.ts) say to each other on the doc's own context. A doc is a markdown file in one of the +// mind's repos, and each open doc is one context, `/docs/<repo name>/<path in the repo>` +// (/repos/config's tasks/plan.md is /docs/config/tasks/plan.md). Its text is one Yjs `Y.Text` +// ("file", the file's bytes); every edit is a Yjs update, and each update travels as an EPHEMERAL +// event: nothing durable per keystroke, and a browser's existing socket carries it (facets take no +// WebSocket of their own). +// +// docs/edit-frame a Yjs update, from a browser or from the processor (a merged commit) +// docs/awareness-frame who is here and where their cursor is (y-protocols awareness); browsers only +// docs/left a browser closed the doc: when it was the last, the processor saves now +// docs/commit-noticed the repo moved and the doc changed: the processor takes the commit in +// +// On the mind's root, the docs processor (root.ts) keeps which docs have been opened +// (`docs/opened`, durable, one per doc) and turns each commit to a repo into a +// `docs/commit-noticed` on the opened docs it changed, so a commit an agent makes reaches the open +// editors, and a doc no one has opened gets no context. +// +// An ephemeral push can be dropped under load, and nothing redelivers it. Yjs updates can be applied +// in any order and more than once, so a browser syncs again with the processor (`sync`, by state +// vector, both ways) when an update arrives that needs one it never got, after each save, and after +// a send failed: when asked to try again, and before it leaves the doc. +import { z } from "zod"; +import { CommentThread } from "./comments.ts"; + +export const EDIT_FRAME = "docs/edit-frame"; +export const AWARENESS_FRAME = "docs/awareness-frame"; +export const COMMIT_NOTICED = "docs/commit-noticed"; +export const DOC_LEFT = "docs/left"; +export const DOC_OPENED = "docs/opened"; + +/** `update`: the Yjs update, base64. `client`: the sender's Yjs client id ("processor" for the + * processor's own), so a sender can skip the echo of its own frames. */ +export const EditFrame = z.object({ + update: z.string(), + client: z.union([z.number(), z.literal("processor")]), +}); +export const AwarenessFrame = z.object({ update: z.string(), client: z.number() }); +/** `client`: the Yjs client id of the tab that closed the doc. */ +export const DocLeft = z.object({ client: z.number() }); + +/** A doc: its repo (`/repos/<name>`) and its path in the repo, `.md` included. */ +export type DocRef = { repo: string; path: string }; + +/** The context that co-edits `doc`. */ +export function docContextPath(doc: DocRef) { + const name = /^\/repos\/([^/]+)$/.exec(doc.repo)?.[1]; + if (!name) throw new Error(`not a repo Docs edits: ${doc.repo} (a repo is /repos/<name>)`); + return `/docs/${name}/${doc.path}`; +} + +/** The doc a context co-edits. */ +export function docOf(contextPath: string): DocRef { + const [, name, path] = /^\/docs\/([^/]+)\/(.+)$/.exec(contextPath) || []; + if (!name || !path) throw new Error(`not a doc's context: ${contextPath}`); + return { repo: `/repos/${name}`, path }; +} + +/** The processor's live state, what the page shows around the editor. `commitOid`: the commit the + * text was last saved as (or read at); `dirty`: edits since then are waiting to be saved; + * `savedBy`: whose edits the last save committed; `saveError`: why the last save failed, when it + * did (the text is kept, and the next edit saves again); `threads`: the doc's comments + * (comments.ts), in the order they were started. */ +export const DocLiveState = z.object({ + commitOid: z.string().nullable(), + dirty: z.boolean(), + savedBy: z.array(z.string()), + saveError: z.string().nullable(), + threads: z.array(CommentThread), +}); +export type DocLiveState = z.infer<typeof DocLiveState>; + +export function toBase64(bytes: Uint8Array) { + let binary = ""; + // in chunks: a spread of a big array overflows the call stack + for (let i = 0; i < bytes.length; i += 0x8000) + binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000)); + return btoa(binary); +} + +export function fromBase64(base64: string) { + const binary = atob(base64); + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i); + return bytes; +}
A processors/merge.ts
@@ -0,0 +1,102 @@ +// merge.ts — MERGING a commit someone else made into the text being edited, the way git merges: +// ours and theirs both changed base. The result goes into the live text as small edits, so people +// typing elsewhere in the doc, even in the same sentence, keep their keystrokes. `diff3Merge` is +// node-diff3's (https://github.com/bhousel/node-diff3), `diffChars` is jsdiff's +// (https://github.com/kpdecker/jsdiff). +import { diffChars, diffLines } from "diff"; +import * as nodeDiff3 from "node-diff3"; +import { z } from "zod"; + +// WHERE THE PACKAGE'S FUNCTIONS ARE depends on who loaded it, so they are looked for in each place: +// - Node and a bundler give them as named exports; +// - esm.sh may serve them as a single `default`, an object of its functions; +// - esm.sh's browser build has an EMPTY `default`, and puts them on `globalThis.Diff3`. +// Looked for at the first merge, not when this module loads: a doc that needs no merge opens +// whatever the package looks like. +/** A place that holds node-diff3's functions: one of the places above. */ +const Diff3 = z.object({ + diff3Merge: z.custom<typeof nodeDiff3.diff3Merge>((value) => typeof value === "function"), +}); +type Diff3 = z.infer<typeof Diff3>; + +/** node-diff3's functions from the first of `places` that holds them; the places are the + * package's named exports, its `default` and `globalThis.Diff3`, unless a test names others. */ +export function diff3( + places: unknown[] = [ + nodeDiff3, + Reflect.get(nodeDiff3, "default"), + Reflect.get(globalThis, "Diff3"), + ], +): Diff3 { + const found = places + .map((place) => Diff3.safeParse(place)) + .find((parsed) => parsed.success)?.data; + if (!found) + throw new Error( + "docs: the package node-diff3 has no diff3Merge as a named export, on its default or on globalThis.Diff3 (processors/merge.ts of /repos/docs)", + ); + return found; +} + +/** ours + theirs over base, line by line. Where both changed the same lines, ours stays: a doc + * never shows conflict markers. `conflicts` says how many places that happened. */ +export function mergeText(ours: string, base: string, theirs: string) { + const regions = diff3().diff3Merge(ours.split("\n"), base.split("\n"), theirs.split("\n"), { + excludeFalseConflicts: true, + }); + return { + text: regions.flatMap((region) => region.ok || region.conflict!.a).join("\n"), + conflicts: regions.filter((region) => region.conflict).length, + }; +} + +/** The edits that turn `from` into `to`, in order, each position in the text as the edits before + * it left it: what a `Y.Text` applies one by one. The texts are compared by line, and only the + * lines that changed by character: a character diff of two whole files costs seconds of CPU once + * they differ in many places (26,000 characters, 50 changed groups of lines: 1.8 s), and the + * processor's invocation has no seconds. */ +export function textEdits(from: string, to: string) { + const edits: ({ at: number; insert: string } | { at: number; delete: number })[] = []; + let at = 0; + const parts = diffLines(from, to); + for (let index = 0; index < parts.length; index++) { + const part = parts[index]!; + const next = parts[index + 1]; + if (part.removed && next?.added) { + // lines that were replaced: the characters that changed in them + for (const edit of replacedTextEdits(part.value, next.value)) { + if ("insert" in edit) { + edits.push({ at, insert: edit.insert }); + at += edit.insert.length; + } else if ("delete" in edit) edits.push({ at, delete: edit.delete }); + else at += edit.keep; + } + index++; + } else if (part.removed) edits.push({ at, delete: part.value.length }); + else if (part.added) { + edits.push({ at, insert: part.value }); + at += part.value.length; + } else at += part.value.length; + } + return edits; +} + +/** How many characters two replaced groups of lines may differ by and still be compared by + * character. Past it the group is replaced whole: the cost of the comparison grows with the square + * of this number, and at 1,000 it is under 100 ms. */ +const MOST_CHANGED_CHARACTERS = 1_000; + +function replacedTextEdits( + from: string, + to: string, +): ({ insert: string } | { delete: number } | { keep: number })[] { + const changes = diffChars(from, to, { maxEditLength: MOST_CHANGED_CHARACTERS }); + if (!changes) return [{ delete: from.length }, { insert: to }]; + return changes.map((change) => + change.added + ? { insert: change.value } + : change.removed + ? { delete: change.value.length } + : { keep: change.value.length }, + ); +}
A processors/root.ts
@@ -0,0 +1,78 @@ +// root.ts — THE DOCS PROCESSOR on the mind's root (frames.ts): which docs have been opened, by +// their contexts' paths, and a `docs/commit-noticed` to each one a commit to its repo changed. The +// doc's processor reads the commit itself (doc.ts); the notice only says to look. Its own saves +// come back through here too, and the doc's catch-up finds nothing new. +import { z } from "zod"; +import type { IterateContextApi } from "iterate/api"; +import { + defineProcessorContract, + StreamProcessor, + type ProcessEventArgs, + type ProcessorState, + type ReduceArgs, +} from "iterate/stream/processor"; +import { COMMIT_NOTICED, DOC_OPENED, docContextPath } from "./frames.ts"; + +export const DocsContract = defineProcessorContract({ + slug: "docs", + version: "1", + description: "Tells each opened doc's processor when a commit to its repo changed its doc.", + stateSchema: z.object({ opened: z.array(z.string()).default([]) }), + consumes: ["events.iterate.com/repo/commit-completed", DOC_OPENED], + emits: [COMMIT_NOTICED], +}); + +type DocsState = ProcessorState<typeof DocsContract>; + +const DocOpened = z.object({ repo: z.string(), path: z.string() }); +const CommitCompleted = z.object({ + path: z.string(), + commitOid: z.string(), + changedPaths: z.array(z.string()), +}); + +export class DocsProcessor extends StreamProcessor<DocsState> { + contract = DocsContract; + readonly #getItx: () => IterateContextApi & Disposable; + constructor(getItx: () => IterateContextApi & Disposable) { + super(); + this.#getItx = getItx; + } + + override reduce({ event, state }: ReduceArgs<DocsState>): DocsState | undefined { + if (event.type !== DOC_OPENED) return; + const opened = DocOpened.safeParse(event.payload); + if (!opened.success) return; + const context = docContextPath(opened.data); + if (!state.opened.includes(context)) return { opened: [...state.opened, context] }; + } + + override processEvent({ + event, + state, + blockProcessorWhile, + }: ProcessEventArgs<DocsState>): undefined { + if (event?.type !== "events.iterate.com/repo/commit-completed") return; + const commit = CommitCompleted.safeParse(event.payload); + // a repo Docs never opened a doc in (or nested deeper than /repos/<name>) has nothing to tell + if (!commit.success || !/^\/repos\/[^/]+$/.test(commit.data.path)) return; + const repo = commit.data.path; + const opened = new Set(state.opened); + const changed = commit.data.changedPaths + .map((path) => docContextPath({ repo, path })) + .filter((context) => opened.has(context)); + if (changed.length === 0) return; + blockProcessorWhile(async () => { + using itx = this.#getItx(); + await Promise.all( + changed.map((context) => + itx.cd(context).append({ + type: COMMIT_NOTICED, + ephemeral: true, + payload: { commitOid: commit.data.commitOid }, + }), + ), + ); + }); + } +}
A public/app.css
@@ -0,0 +1,15 @@ +/* app.css — the page's own layout. @iterate-com/ui's stylesheets hold the classes its own + components use and no others, so what this page adds is written here as plain CSS, on the + theme's variables (theme.css of /repos/stdlib). */ +html, +body, +#root { + height: 100%; +} + +/* a line in place of a doc: it is being read, it is not text, it is not there */ +.docs-note { + padding: 1rem; + color: var(--muted-foreground); + font-size: 0.875rem; +}
A public/app.js
@@ -0,0 +1,373 @@ +// app.js — THE DOCS APP'S PAGE: the files of this mind's repos, written together. The sidebar is +// a repo's files as a tree. Beside it is one file in a live editor: several people type in it at +// once and see each other, comment on its text, and what they type is saved as commits. With no +// file open, the page lists the repo's docs and makes a new one. +// +// Everything it draws is a component of @iterate-com/ui, loaded through the import map in +// index.html: `DocEditor`, `DocTree` and `DocListPanel` are that package's docs editor. This file +// is the wiring: the member's itx, the URL, and where the editor's processors are (processors/). +import { + html, + render, + useCallback, + useEffect, + useMemo, + useState, + useSyncExternalStore, +} from "@iterate-com/ui/page"; +import { AppShell, AppShellBrand } from "@iterate-com/ui/components/app-shell"; +import { + commitAuthorOf, + cursorColor, + DocEditor, + DocList, + DocListPanel, + DocSession, + DocTree, + fileKind, +} from "@iterate-com/ui/components/docs-editor/docs-editor"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuGroup, + DropdownMenuItem, + DropdownMenuLabel, + DropdownMenuTrigger, +} from "@iterate-com/ui/components/ui/dropdown-menu"; +import { + SidebarGroup, + SidebarGroupContent, + SidebarGroupLabel, + SidebarMenu, + SidebarMenuButton, + SidebarMenuItem, + useSidebar, +} from "@iterate-com/ui/components/ui/sidebar"; +import { CheckIcon, ChevronDownIcon } from "@iterate-com/ui/icons"; +import { newWebSocketRpcSession } from "@iterate-com/ui/live"; + +// ── the member's itx ── +// As @iterate-com/ui/live's `memberItx` (the Dash's page): one WebSocket to this host's /itx, a +// capnweb session whose root is the mind's itx, as the member the platform signed in on this +// host. The platform ends it when the sign-in ends; a reload signs in again. Three closes in a +// minute stop the reloads. +const socket = new WebSocket(new URL("/itx", location.href.replace(/^http/, "ws"))); +socket.addEventListener("open", () => performance.mark("iterate:itx-open"), { once: true }); +const itx = newWebSocketRpcSession(socket); +socket.addEventListener("close", () => { + const now = Date.now(); + let closes = []; + try { + closes = JSON.parse(sessionStorage.getItem("itx-closes") || "[]").filter( + (at) => now - at < 60_000, + ); + sessionStorage.setItem("itx-closes", JSON.stringify([...closes, now])); + } catch { + // no storage: one reload is still right + } + if (closes.length < 3) setTimeout(() => location.reload(), 1000); + else document.getElementById("root").textContent = "Disconnected. Reload the page to connect."; +}); + +const { principal } = await itx.whoami(); +// Who types, as the others see them, and who a commit made here is by. +const me = principal?.email || principal?.actor || "someone"; +const user = { name: me, email: me, color: cursorColor(me) }; +const author = principal ? commitAuthorOf(principal) : undefined; + +// The mind's address is its control-plane hostname, where its sign-in is: this host says it +// (`/.auth/session.json`, ../app.ts). The page never works it out from its own hostname, which +// may be in any zone of the mind. +// index.html asks for it in its head, while the modules load. +const hostSession = + window.__session ?? fetch("/.auth/session.json").then((answer) => answer.json()); +const mind = new URL((await hostSession).issuer).hostname; +// The sidebar's head: the mind's icon above its address, as in the Dash. The app's own +// `/icon.svg` is the mind's icon (open-files.ts of /repos/stdlib), so the page asks its own host +// for it. +// This app serves one mind, so it shows the plain head, with no list of minds to switch to. +const MIND_ICON = html`<img src="/icon.svg" alt="" className="size-8 rounded-md" />`; + +// ── where the editor's processors are ── +// The page starts a doc's processors (../processors/classes.ts says why from here) under a name +// for their version: the source's, which ../app.ts answers with the repo that holds them, and the +// pins of the three packages in that repo's package.json, so a changed pin starts them anew too. +const PROCESSOR_PACKAGES = ["yjs", "diff", "node-diff3"]; +const processorsAnswer = await fetch("/processors.json"); +// a refusal is said as it is: its body is no list of processors +if (!processorsAnswer.ok) + throw new Error(`Docs cannot start: /processors.json answered ${processorsAnswer.status}`); +const processors = await processorsAnswer.json(); +const manifest = JSON.parse( + (await itx.repos.get(processors.repo).readFile("package.json")) || "{}", +); +const pins = PROCESSOR_PACKAGES.map((name) => `${name}@${manifest.dependencies?.[name] || "none"}`); +const missingPackages = PROCESSOR_PACKAGES.filter((name) => !manifest.dependencies?.[name]); +const facetSpec = (className) => ({ + className, + mainModule: processors.mainModule, + source: ["itx", ["cd", "/"], "repos", ["get", processors.repo], ["modules"]], + cacheKey: `docs-processors:${processors.version}:${pins.join(",")}`, +}); + +/** What the editor says, in this page's words, when a doc cannot be opened for editing: what the + * Docs repo needs. The editor shows the platform's own reason above it. */ +/** One sentence when the repo's package.json lacks one of the packages, else nothing. */ +function whatIsMissing() { + if (missingPackages.length === 0) return null; + return html` + This repo's <code>package.json</code> does not list <code> ${missingPackages.join(", ")}</code>. + `; +} +const whatDocsNeeds = html` + <div> + <p> + Docs edits a file through two classes in this mind's repo <code>${processors.repo}</code>, + the folder <code>processors/</code>, and three packages in its <code>package.json</code>. + ${whatIsMissing()} + </p> + <p> + To set it up, ask an agent of this mind to "bring the repo ${processors.repo} up to + iterate's", or add them by hand: the folder <code>processors/</code> and, under + <code>"dependencies"</code>, the packages <code>yjs</code>, <code>diff</code> and + <code>node-diff3</code>, as in + <a href="https://git.iterate.com/repos/docs" target="_blank" rel="noreferrer">iterate's Docs repo</a + >. The file below is shown as it was read. + </p> + </div> +`; + +// ── the URL ── +// THE PAGE IS A LINK: `?repo=<name>` is the repo (none: config), `?doc=<path>` the open file, and +// `?mode=comment` opens it to read and comment on, not to edit. +const subscribeToUrl = (listener) => { + addEventListener("popstate", listener); + return () => removeEventListener("popstate", listener); +}; + +const hrefOf = (change) => { + const next = new URLSearchParams(location.search); + for (const [key, value] of Object.entries(change)) + if (value === undefined) next.delete(key); + else next.set(key, value); + const query = next.toString(); + return query ? `?${query}` : "./"; +}; + +const go = (href) => { + history.pushState(null, "", href); + dispatchEvent(new PopStateEvent("popstate")); +}; + +/** The repos' names, sorted: `config` is /repos/config. */ +const repoNames = (repos) => + repos + .map((repo) => /^\/repos\/([^/]+)$/.exec(repo.path)?.[1]) + .filter(Boolean) + .sort(); + +// ── reads ── + +/** What a promise came to, for the `key` it was asked with: `{ key, value }`, `{ key, error }`, or + * undefined while it runs. A newer key drops the older answer. */ +function useRead(key, read) { + const [answer, setAnswer] = useState(); + useEffect(() => { + let current = true; + read().then( + (value) => current && setAnswer({ key, value }), + (error) => + current && + setAnswer({ key, error: error instanceof Error ? error.message : String(error) }), + ); + return () => { + current = false; + }; + // `read` is made anew each render: `key` says when to read again + }, [key]); + return answer?.key === key ? answer : undefined; +} + +// ── the page ── + +function App() { + const search = useSyncExternalStore(subscribeToUrl, () => location.search); + const params = useMemo(() => new URLSearchParams(search), [search]); + const repo = params.get("repo") || "config"; + const path = params.get("doc") || undefined; + const commentOnly = params.get("mode") === "comment"; + const repos = useRead("repos", async () => repoNames(await itx.repos.list())); + const names = repos?.value || []; + // one list per repo: the tree and the doc list read the same one + const list = useMemo(() => new DocList(itx, `/repos/${repo}`), [repo]); + const open = useCallback((file) => go(hrefOf({ doc: file, mode: undefined })), []); + return html` + <${AppShell} + app="Docs" + mind=${mind} + switcher=${html`<${RepoSwitcher} repo=${repo} repos=${names} />`} + nav=${html`<${Files} repo=${repo} list=${list} path=${path} open=${open} />`} + account=${principal} + locationKey=${location.pathname + search} + > + <${Page} repo=${repo} path=${path} commentOnly=${commentOnly} list=${list} open=${open} /> + <//> + `; +} + +/** The sidebar's head: Docs + the active repo, with a dropdown to switch repos when the mind has + * more than one, or a plain brand when it has one. */ +function RepoSwitcher({ repo, repos }) { + const { isMobile, setOpenMobile } = useSidebar(); + const repoPath = `/repos/${repo}`; + if (repos.length <= 1) { + return html` + <${AppShellBrand} + app="Docs" + line=${html`<span className="font-mono">${repoPath}</span>`} + logo=${MIND_ICON} + href="./" + /> + `; + } + return html` + <${SidebarMenu}> + <${SidebarMenuItem}> + <${DropdownMenu}> + <${DropdownMenuTrigger} + render=${html` + <${SidebarMenuButton} + size="lg" + className="data-popup-open:bg-sidebar-accent data-popup-open:text-sidebar-accent-foreground" + aria-label=${`Repo: ${repoPath}`} + > + <span className="flex aspect-square size-8 items-center justify-center rounded-md bg-black"> + ${MIND_ICON} + </span> + <span className="grid flex-1 text-left text-sm leading-tight"> + <span className="truncate font-medium">Docs</span> + <span className="truncate font-mono text-xs text-muted-foreground">${repoPath}</span> + </span> + <${ChevronDownIcon} className="ml-auto" /> + <//> + `} + /> + <${DropdownMenuContent} + align="start" + side=${isMobile ? "bottom" : "right"} + sideOffset=${4} + className="min-w-56 rounded-lg" + > + <${DropdownMenuGroup}> + <${DropdownMenuLabel}>Repos<//> + ${repos.map( + (name) => html` + <${DropdownMenuItem} + key=${name} + className="gap-2" + onClick=${() => { + if (name !== repo) go(hrefOf({ repo: name, doc: undefined, mode: undefined })); + if (isMobile) setOpenMobile(false); + }} + > + <span className="truncate font-mono">${`/repos/${name}`}</span> + ${name === repo ? html`<${CheckIcon} className="ml-auto" />` : null} + <//> + `, + )} + <//> + <//> + <//> + <//> + <//> + `; +} + +/** Beside the sidebar: the open file, or with none the repo's docs and "New doc". */ +function Page({ repo, path, commentOnly, list, open }) { + if (!path) + return html` + <${DocListPanel} + list=${list} + author=${author} + docHref=${(file) => hrefOf({ doc: file, mode: undefined })} + onOpen=${open} + /> + `; + return html` + <${Doc} + key=${`${repo}:${path}:${commentOnly}`} + repo=${repo} + path=${path} + commentOnly=${commentOnly} + /> + `; +} + +/** The sidebar: the repo's path and its files as a tree. */ +function Files({ repo, list, path, open }) { + return html` + <${SidebarGroup}> + <${SidebarGroupLabel} className="font-mono">${`/repos/${repo}`}<//> + <${SidebarGroupContent}> + <${DocTree} list=${list} openPath=${path} onOpen=${open} author=${author} /> + <//> + <//> + `; +} + +/** One file of the repo: read once, then live in the editor. A file that is not text has no + * editor. */ +function Doc({ repo, path, commentOnly }) { + const kind = fileKind(path); + const file = useRead(`${repo}:${path}`, () => + kind === "binary" ? Promise.resolve(null) : itx.repos.get(`/repos/${repo}`).readFile(path), + ); + if (kind === "binary") + return html`<p class="docs-note">${path} is not text, so it has no editor here.</p>`; + if (!file) return html`<p class="docs-note">Reading ${path}…</p>`; + if (file.error) + return html`<p class="docs-note" role="alert">Couldn't read ${path}: ${file.error}</p>`; + if (typeof file.value !== "string") + return html`<p class="docs-note">${repo} has no file ${path}.</p>`; + return html` + <${LiveDoc} + repo=${repo} + path=${path} + kind=${kind} + text=${file.value} + commentOnly=${commentOnly} + /> + `; +} + +function LiveDoc({ repo, path, kind, text, commentOnly }) { + // one session per doc and person: it opens the doc's context when the editor mounts and lets it + // go when it unmounts + const session = useMemo( + () => + new DocSession({ + itx, + repo: `/repos/${repo}`, + path, + kind, + text, + user, + facetSpec, + commentOnly, + }), + [repo, path, kind, text, commentOnly], + ); + return html` + <${DocEditor} + session=${session} + listHref=${hrefOf({ doc: undefined, mode: undefined })} + listLabel=${repo} + editHref=${hrefOf({ mode: undefined })} + onNavigate=${go} + unavailable=${whatDocsNeeds} + /> + `; +} + +render(html`<${App} />`, document.getElementById("root"));
A public/manifest.webmanifest
@@ -0,0 +1,17 @@ +{ + "name": "Docs", + "short_name": "Docs", + "description": "The files of the mind's repos, written together.", + "start_url": "/", + "display": "browser", + "icons": [ + { + "src": "/icon.svg", + "sizes": "any", + "type": "image/svg+xml" + } + ], + "iterate": { + "for": "members" + } +}
A tests/merge.test.mjs
@@ -0,0 +1,51 @@ +// merge.test.mjs — `node --test tests/merge.test.mjs`. The edits that take a commit into a +// doc's live text (processors/merge.ts `textEdits`): they give the new text, a small change is a +// small edit, and a large file costs milliseconds of CPU, not the seconds that ended the doc +// facet's invocation on /docs/config/AGENTS.md. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { textEdits } from "../processors/merge.ts"; + +/** `from` after `edits`, applied one by one as a `Y.Text` applies them. */ +const applied = (from, edits) => + edits.reduce( + (text, edit) => + "insert" in edit + ? text.slice(0, edit.at) + edit.insert + text.slice(edit.at) + : text.slice(0, edit.at) + text.slice(edit.at + edit.delete), + from, + ); + +test("a typo fixed in one line is an edit of that word, so a person typing in the same line keeps their keystrokes", () => { + const from = "# Plan\n\nWe fly in on Wendesday.\n\n## Agenda\n"; + const to = "# Plan\n\nWe fly in on Wednesday.\n\n## Agenda\n"; + const edits = textEdits(from, to); + assert.equal(applied(from, edits), to); + assert.ok(edits.every((edit) => ("insert" in edit ? edit.insert.length : edit.delete) <= 2)); +}); + +test("a commit that changes 50 places of a 30,000-character file costs milliseconds of CPU", () => { + const lines = Array.from({ length: 400 }, (_, index) => `- line ${index}: ${"words ".repeat(9)}`); + const from = lines.join("\n"); + const to = lines + .flatMap((line, index) => + index % 8 === 0 ? [`- line ${index}, rewritten: ${"other words ".repeat(12)}`, ""] : [line], + ) + .join("\n"); + const before = process.cpuUsage(); + const edits = textEdits(from, to); + const spent = process.cpuUsage(before); + assert.equal(applied(from, edits), to); + assert.ok((spent.user + spent.system) / 1000 < 500); +}); + +test("lines replaced by wholly different text are replaced whole: the comparison by character has a bound", () => { + const from = `intro\n${"a".repeat(3_000)}\noutro\n`; + const to = `intro\n${"b".repeat(3_000)}\noutro\n`; + const edits = textEdits(from, to); + assert.equal(applied(from, edits), to); + assert.deepEqual(edits, [ + { at: 6, delete: 3_001 }, + { at: 6, insert: `${"b".repeat(3_000)}\n` }, + ]); +});
A tests/notes.test.mjs
@@ -0,0 +1,84 @@ +// notes.test.mjs — `node --test tests/notes.test.mjs`. The docs app's notes route (notes.ts): which paths +// it answers, the headers that keep a note from acting as the member, and what a missing file gets. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { NOTE_HEADERS, isNotePath, noteResponse } from "../notes.ts"; + +const files = { "/notes/onboarding-map-2026-11-17.html": "<!doctype html><title>map</title><a href=\"#a\">a</a>" }; +const asked = []; +const read = async (path) => { + asked.push(path); + if (!(path in files)) throw new Error(`files: nothing at ${JSON.stringify(path)}`); + return new TextEncoder().encode(files[path]); +}; +const get = (path, init) => noteResponse(new Request(`https://docs.example.com${path}`, init), read); + +test("a stored note is answered inline as HTML, with the headers that fence it", async () => { + const answer = await get("/notes/onboarding-map-2026-11-17.html"); + assert.equal(answer.status, 200); + assert.equal(await answer.text(), files["/notes/onboarding-map-2026-11-17.html"]); + assert.equal(answer.headers.get("content-type"), "text/html; charset=utf-8"); + assert.equal(answer.headers.get("content-disposition"), null); + const policy = answer.headers.get("content-security-policy"); + assert.match(policy, /^sandbox;/); + assert.doesNotMatch(policy, /allow-scripts|allow-same-origin|script-src/); + assert.match(policy, /default-src 'none'/); + assert.equal(answer.headers.get("x-content-type-options"), "nosniff"); + assert.equal(answer.headers.get("cache-control"), "private, no-store"); + assert.match(answer.headers.get("x-robots-tag"), /noindex/); +}); + +test("a HEAD has the headers and no body", async () => { + const answer = await get("/notes/onboarding-map-2026-11-17.html", { method: "HEAD" }); + assert.equal(answer.status, 200); + assert.equal(await answer.text(), ""); +}); + +test("only a strict name under /notes/ that ends in .html is read", async () => { + for (const path of [ + "/notes/", + "/notes/a.md", + "/notes/a.html.md", + "/notes/A.html", + "/notes/a_b.html", + "/notes/a.b.html", + "/notes/-a.html", + "/notes/sub/a.html", + "/notes/%2e%2e/secrets.html", + "/notes/..%2fsecrets.html", + "/notes/a.html/", + `/notes/${"a".repeat(101)}.html`, + ]) { + asked.length = 0; + const answer = await get(path); + assert.equal(answer.status, 404, path); + assert.deepEqual(asked, [], `${path} must not reach the files`); + assert.equal(answer.headers.get("content-type"), "text/plain; charset=utf-8"); + } +}); + +test("a note that is not there is a 404, and another fault is thrown on", async () => { + assert.equal((await get("/notes/no-such-note.html")).status, 404); + await assert.rejects( + noteResponse(new Request("https://docs.example.com/notes/a.html"), async () => { + throw new Error("the files did not answer"); + }), + /did not answer/, + ); +}); + +test("a write to a note's address reads nothing", async () => { + asked.length = 0; + const answer = await get("/notes/onboarding-map-2026-11-17.html", { method: "POST", body: "x" }); + assert.equal(answer.status, 404); + assert.deepEqual(asked, []); +}); + +test("the docs app asks the route for every path under /notes/ and for no other", () => { + assert.equal(isNotePath("/notes/a.html"), true); + assert.equal(isNotePath("/notes/../x"), true); + assert.equal(isNotePath("/notes"), false); + assert.equal(isNotePath("/"), false); + assert.equal(isNotePath("/itx"), false); + assert.equal(Object.keys(NOTE_HEADERS).length, 6); +});
A tsconfig.json
@@ -0,0 +1,4 @@ +{ + "extends": "@repos/stdlib/tsconfig.base.json", + "include": ["**/*.ts"] +}